I want the entry to be autocompleted in the PHP class

57 Views Asked by At

My PhpStorm PHP autocomplete works but I can't customize it for modded inputs.

This is my method in the PHP class:

public function orientation($orientation = 'landscape')
{

}

First, I want this method to accept only the following values as input:

$orientation = 'landscape' , 'portrait' , 'square' , 'panoramic'

I want PhpStorm to suggest these values for input - that's the main problem.

1

There are 1 best solutions below

0
Martin Komischke On

In PHP 5.6 I suggest to turn the argument type into a value object instead of plain strings. This is how it looks like:

class Camera
{
    /** @param Orientation $orientation */
    public function orientation($orientation)
    {
        var_dump($orientation->getValue());
    }
}

class Service
{
    public function useCamera()
    {
        $camera = new Camera();
        $camera->orientation(
            Orientation::/* This is when your IDE kicks in with suggestions. */Landscape()
        );
    }
}

class Orientation
{
    private $orientation;

    /** @param string $value */
    private function __construct($value)
    {
        $this->orientation = $value;
    }

    /** @return string */
    public function getValue()
    {
        return $this->orientation;
    }

    public static function Landscape()
    {
        return new self('landscape');
    }

    public static function Portrait()
    {
        return new self('portrait');
    }

    public static function Square()
    {
        return new self('square');
    }

    public static function Panoramic()
    {
        return new self('panoramic');
    }
}

Note the private constructor and the factory functions taking care of proper initialization of the value object $orientation. This way you have an easy approach to narrow the available orientation options.

With later versions of PHP I suggest to use string backed enums instead. See: https://www.php.net/manual/en/language.enumerations.backed.php