Symfony 3 - Auto generate BOOLEAN getters and setters - isActive vs getActive Symfony 3 - Auto generate BOOLEAN getters and setters - isActive vs getActive symfony symfony

Symfony 3 - Auto generate BOOLEAN getters and setters - isActive vs getActive


I've played with the code a bit and unfortunately there is no way to generate it differently with the existent setup. All classes are hardcoded and there is no way to override it with command or Symfony settings.

So I've extended generator classes a bit and created extended command that accepts generator as a parameter. I've also created sample generator that created 'is...' methods for setting booleans.

Unfortunately there are some copy-paste from existent classes because it is not possible to extend it.

Answering 2nd question I think that it is more personal preference using fluent interface. I'm old school developer and I'm not used to fluent interface in PHP. I do not see any major performance impact with it.

For the 3rd question. The difference between bool and boolean is that bool is a scalar type declaration while the boolean is a variable type. See the 'Warning' in the documentation. It explains a lot.

<?php// src/AppBundle/Command/GenerateDoctrineEntityExtendedCommand.phpnamespace AppBundle\Command;use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineEntityCommand;use Sensio\Bundle\GeneratorBundle\Generator\Generator;use Symfony\Component\Console\Input\InputInterface;use Symfony\Component\Console\Input\InputOption;use Symfony\Component\Console\Output\OutputInterface;class GenerateDoctrineEntityExtendedCommand extends GenerateDoctrineEntityCommand{    /** @var Generator */    private $generator;    protected function configure()    {        parent::configure();        $this->setName('doctrine:generate:entity:extended');        $this->setDescription($this->getDescription() . " Allows specifying generator class.");        $this->addOption('generator', null, InputOption::VALUE_REQUIRED, "The generator class to create entity.", 'Sensio\Bundle\GeneratorBundle\Generator\DoctrineEntityGenerator');    }    protected function initialize(InputInterface $input, OutputInterface $output)    {        parent::initialize($input, $output);        if ($class = $input->getOption('generator')) {            if (!class_exists($class)) {                throw new \Exception('Class ' . $class . 'does not exist.');            }            $this->generator = new $class($this->getContainer()->get('filesystem'), $this->getContainer()->get('doctrine'));        }    }    protected function createGenerator()    {        return $this->generator;    }}

DoctrineEntityGenerator replacement:

<?php// src/AppBundle/Generator/IsDoctrineEntityGenerator.phpnamespace AppBundle\Generator;use Sensio\Bundle\GeneratorBundle\Generator\DoctrineEntityGenerator;class IsDoctrineEntityGenerator extends DoctrineEntityGenerator{    protected function getEntityGenerator()    {        // This is the place where customized entity generator is instantiated instead of default        $entityGenerator = new IsEntityGenerator();        $entityGenerator->setGenerateAnnotations(false);        $entityGenerator->setGenerateStubMethods(true);        $entityGenerator->setRegenerateEntityIfExists(false);        $entityGenerator->setUpdateEntityIfExists(true);        $entityGenerator->setNumSpaces(4);        $entityGenerator->setAnnotationPrefix('ORM\\');        return $entityGenerator;    }}

EntityGenerator replacement:

<?php// src/AppBundle/Generator/IsEntityGenerator.phpnamespace AppBundle\Generator;use Doctrine\Common\Inflector\Inflector;use Doctrine\ORM\Mapping\ClassMetadataInfo;use Doctrine\ORM\Tools\EntityGenerator;use Doctrine\DBAL\Types\Type;class IsEntityGenerator extends EntityGenerator{    protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null)    {        //        // This is the only line I've added compared to the original method        //        $methodPrefix = ($type == 'get' && $typeHint == 'boolean') ? 'is' : $type;        $methodName = $methodPrefix . Inflector::classify($fieldName);        $variableName = Inflector::camelize($fieldName);        if (in_array($type, array("add", "remove"))) {            $methodName = Inflector::singularize($methodName);            $variableName = Inflector::singularize($variableName);        }        if ($this->hasMethod($methodName, $metadata)) {            return '';        }        $this->staticReflection[$metadata->name]['methods'][] = strtolower($methodName);        $var = sprintf('%sMethodTemplate', $type);        $template = static::$$var;        $methodTypeHint = null;        $types = Type::getTypesMap();        $variableType = $typeHint ? $this->getType($typeHint) : null;        if ($typeHint && !isset($types[$typeHint])) {            $variableType = '\\' . ltrim($variableType, '\\');            $methodTypeHint = '\\' . $typeHint . ' ';        }        $replacements = array(            '<description>' => ucfirst($type) . ' ' . $variableName,            '<methodTypeHint>' => $methodTypeHint,            '<variableType>' => $variableType,            '<variableName>' => $variableName,            '<methodName>' => $methodName,            '<fieldName>' => $fieldName,            '<variableDefault>' => ($defaultValue !== null) ? (' = ' . $defaultValue) : '',            '<entity>' => $this->getClassName($metadata)        );        $method = str_replace(            array_keys($replacements),            array_values($replacements),            $template        );        return $this->prefixCodeWithSpaces($method);    }}

So that's I'm afraid the only option for what you want so far.


Stepashka correctly answered.

But I think there is a better, simplified and more conventional way to help you to use PhpStorm auto generate Getters and Setters methods with Symfony.

You can customize PhpStorm Getters and Setters generation methods!

You just have to go to : Preferences/Editor/File and Code Templates/Code

Then for Getter, to modify isActive to getActive you have to change "PHP Getter Method" to :

/* * @return ${TYPE_HINT} */public ${STATIC} function get${NAME}()#if(${RETURN_TYPE}): ${RETURN_TYPE}#else#end{#if (${STATIC} == "static")    return self::$${FIELD_NAME};#else    return $this->${FIELD_NAME};#end}

for Setter, to add "return $this" you have to change "PHP Setter Method" to:

/* * @param ${TYPE_HINT} $${PARAM_NAME} * @return ${CLASS_NAME} */public ${STATIC} function set${NAME}(#if (${SCALAR_TYPE_HINT})(${SCALAR_TYPE_HINT} #else#end$${PARAM_NAME}){#if (${STATIC} == "static")    self::$${FIELD_NAME} = $${PARAM_NAME};#else    $this->${FIELD_NAME} = $${PARAM_NAME};#end    return $this;}

Finally, don't forget to Apply changes.