zendframework / zend-code

BSD 3-Clause "New" or "Revised" License
1.68k stars 78 forks source link

Name of dynamic methods are added quotation marks #159

Closed rorteg closed 6 years ago

rorteg commented 6 years ago

My code:

require_once 'vendor/autoload.php';

use Zend\Code\Generator\ClassGenerator;
use Zend\Code\Reflection\ClassReflection;
use Zend\Code\Generator\MethodGenerator;

$generator = ClassGenerator::fromReflection(
    new ClassReflection(\Rorteg\CodeGeneratorTool\Api\TestInterface::class)
);

$generator->setName('Test');
$generator->setNamespaceName('Rorteg\\CodeGeneratorTool\\Model');
$constants = $generator->getConstants();
$generator->setImplementedInterfaces([\Rorteg\CodeGeneratorTool\Api\TestInterface::class]);

foreach ($constants as $constant) {
    $array = explode('_', $constant->getDefaultValue());
    $parts = array_map('ucwords', $array);
    $camelCase = implode('', $parts);
    $methodName = lcfirst($camelCase);

    $generator->addMethodFromGenerator(MethodGenerator::fromArray([
        'name' => "set{$methodName}",
        'body' => '$this->_' . $camelCase . ' = $' . $camelCase . ';',
        'parameters' => [$camelCase]
    ]));

    $generator->removeConstant($constant->getName());
}

echo $generator->generate();

Output:

namespace Rorteg\CodeGeneratorTool\Model;

class Test implements \Rorteg\CodeGeneratorTool\Api\TestInterface
{

    public function set'testconstant';($'testconstant';)
    {
        $this->_'testconstant'; = $'testconstant';;
    }

    public function set'testOkConstant';($'testOkConstant';)
    {
        $this->_'testOkConstant'; = $'testOkConstant';;
    }

}
Ocramius commented 6 years ago

That's normal, because $constant->getDefaultValue() will give you the var_export()-ed version of the variable.

Closing as invalid.