setParameters() public method

public setParameters ( array $parameters ) : MethodGenerator
$parameters array
return MethodGenerator
Beispiel #1
0
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $managerName
  */
 protected function addCreateServiceMethod($className, $managerName)
 {
     // set action body
     $body = array('/** @var ServiceLocatorAwareInterface $' . $managerName . ' */', '$serviceLocator = $' . $managerName . '->getServiceLocator();', '', '$instance = new ' . $className . '();', '', 'return $instance;');
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters(array(new ParameterGenerator($managerName, 'ServiceLocatorInterface')));
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, array(new ParamTag($managerName, array('ServiceLocatorInterface')), new ReturnTag(array($className)))));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 /**
  * Generate a filter method
  */
 protected function addFilterMethod()
 {
     // set action body
     $body = ['// add filter code here', 'return $value;'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('filter');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('value', 'mixed')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Called when filter is executed', null, [new ParamTag('value', ['mixed']), new ReturnTag(['mixed'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $moduleName
  * @param string $tableName
  */
 protected function addCreateServiceMethod($className, $moduleName, $tableName)
 {
     $managerName = 'serviceLocator';
     $tableGatewayName = ucfirst($tableName) . 'TableGateway';
     $tableGatewayService = $moduleName . '\\' . $this->config['namespaceTableGateway'] . '\\' . ucfirst($tableName);
     // set action body
     $body = ['/** @var ' . $tableGatewayName . ' $tableGateway */', '$tableGateway = $serviceLocator->get(\'' . $tableGatewayService . '\');', '', '$instance = new ' . $className . '($tableGateway);', '', 'return $instance;'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator($managerName, 'ServiceLocatorInterface')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag($managerName, ['ServiceLocatorInterface']), new ReturnTag([$className])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 public function transform()
 {
     $classGenerator = $this->getService()->getClassGenerator();
     if ($createContactBatch = $classGenerator->getMethod('CreateContactBatch')) {
         $newMethod = new CodeGenerator\MethodGenerator();
         $newMethod->setName($createContactBatch->getName());
         $docblock = $createContactBatch->getDocBlock();
         $docblock->setTag((new CodeGenerator\DocBlock\Tag\ParamTag())->setParamName('id')->setDataType('int'));
         $newMethod->setDocBlock($docblock);
         $parameters = $createContactBatch->getParameters();
         $idParameter = new CodeGenerator\ParameterGenerator();
         $idParameter->setName('id');
         $createContactBatch->setParameter($idParameter);
         $newMethod->setParameters(array("id" => $idParameter, "CreateContactBatch" => $parameters['CreateContactBatch']));
         $body = $createContactBatch->getBody();
         $body = str_replace('array()', 'array($id)', $body);
         $newMethod->setBody($body);
         $classGenerator->removeMethod('CreateContactBatch');
         $classGenerator->addMethodFromGenerator($newMethod);
     }
 }
 public function fixPathParameters($classGenerator, $method, $newParameters)
 {
     $oldMethod = $classGenerator->getMethod($method);
     $newMethod = new CodeGenerator\MethodGenerator();
     $newMethod->setName($oldMethod->getName());
     $docblock = $oldMethod->getDocBlock();
     $parameters = $oldMethod->getParameters();
     $body = $oldMethod->getBody();
     $newParameterSpec = array();
     foreach ($newParameters as $name => $type) {
         $docblock->setTag((new CodeGenerator\DocBlock\Tag\ParamTag())->setParamName($name)->setDataType($type));
         $newParameter = new CodeGenerator\ParameterGenerator();
         $newParameter->setName($name);
         $newMethod->setParameter($newParameter);
         $newParameterSpec[$name] = $newParameter;
     }
     $newMethod->setParameters(array_merge($newParameterSpec, array($method => $parameters[$method])));
     $body = str_replace('array()', 'array($' . implode(', $', array_keys($newParameters)) . ')', $body);
     $newMethod->setDocBlock($docblock);
     $newMethod->setBody($body);
     $classGenerator->removeMethod($method);
     $classGenerator->addMethodFromGenerator($newMethod);
 }
 /**
  * Generate an hydrate method
  */
 protected function addHydrateMethod()
 {
     // set action body
     $body = ['// add extended hydrator logic here', 'return parent::hydrate($data, $object);'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('hydrate');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('data', 'array'), new ParameterGenerator('object', 'object')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Hydrate an object by populating data', null, [new ParamTag('data', ['array']), new ParamTag('object', ['object']), new ReturnTag(['object'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Beispiel #7
0
 /**
  * Construct, configure, and return a PHP class file code generation object
  *
  * Creates a Zend\Code\Generator\FileGenerator object that has
  * created the specified class and service locator methods.
  *
  * @param  null|string                         $filename
  * @throws \Zend\Di\Exception\RuntimeException
  * @return FileGenerator
  */
 public function getCodeGenerator($filename = null)
 {
     $injector = $this->injector;
     $im = $injector->instanceManager();
     $indent = '    ';
     $aliases = $this->reduceAliases($im->getAliases());
     $caseStatements = array();
     $getters = array();
     $definitions = $injector->definitions();
     $fetched = array_unique(array_merge($definitions->getClasses(), $im->getAliases()));
     foreach ($fetched as $name) {
         $getter = $this->normalizeAlias($name);
         $meta = $injector->get($name);
         $params = $meta->getParams();
         // Build parameter list for instantiation
         foreach ($params as $key => $param) {
             if (null === $param || is_scalar($param) || is_array($param)) {
                 $string = var_export($param, 1);
                 if (strstr($string, '::__set_state(')) {
                     throw new Exception\RuntimeException('Arguments in definitions may not contain objects');
                 }
                 $params[$key] = $string;
             } elseif ($param instanceof GeneratorInstance) {
                 /* @var $param GeneratorInstance */
                 $params[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName()));
             } else {
                 $message = sprintf('Unable to use object arguments when building containers. Encountered with "%s", parameter of type "%s"', $name, get_class($param));
                 throw new Exception\RuntimeException($message);
             }
         }
         // Strip null arguments from the end of the params list
         $reverseParams = array_reverse($params, true);
         foreach ($reverseParams as $key => $param) {
             if ('NULL' === $param) {
                 unset($params[$key]);
                 continue;
             }
             break;
         }
         // Create instantiation code
         $constructor = $meta->getConstructor();
         if ('__construct' != $constructor) {
             // Constructor callback
             $callback = var_export($constructor, 1);
             if (strstr($callback, '::__set_state(')) {
                 throw new Exception\RuntimeException('Unable to build containers that use callbacks requiring object instances');
             }
             if (count($params)) {
                 $creation = sprintf('$object = call_user_func(%s, %s);', $callback, implode(', ', $params));
             } else {
                 $creation = sprintf('$object = call_user_func(%s);', $callback);
             }
         } else {
             // Normal instantiation
             $className = '\\' . ltrim($name, '\\');
             $creation = sprintf('$object = new %s(%s);', $className, implode(', ', $params));
         }
         // Create method call code
         $methods = '';
         foreach ($meta->getMethods() as $methodData) {
             if (!isset($methodData['name']) && !isset($methodData['method'])) {
                 continue;
             }
             $methodName = isset($methodData['name']) ? $methodData['name'] : $methodData['method'];
             $methodParams = $methodData['params'];
             // Create method parameter representation
             foreach ($methodParams as $key => $param) {
                 if (null === $param || is_scalar($param) || is_array($param)) {
                     $string = var_export($param, 1);
                     if (strstr($string, '::__set_state(')) {
                         throw new Exception\RuntimeException('Arguments in definitions may not contain objects');
                     }
                     $methodParams[$key] = $string;
                 } elseif ($param instanceof GeneratorInstance) {
                     $methodParams[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName()));
                 } else {
                     $message = sprintf('Unable to use object arguments when generating method calls. Encountered with class "%s", method "%s", parameter of type "%s"', $name, $methodName, get_class($param));
                     throw new Exception\RuntimeException($message);
                 }
             }
             // Strip null arguments from the end of the params list
             $reverseParams = array_reverse($methodParams, true);
             foreach ($reverseParams as $key => $param) {
                 if ('NULL' === $param) {
                     unset($methodParams[$key]);
                     continue;
                 }
                 break;
             }
             $methods .= sprintf("\$object->%s(%s);\n", $methodName, implode(', ', $methodParams));
         }
         // Generate caching statement
         $storage = '';
         if ($im->hasSharedInstance($name, $params)) {
             $storage = sprintf("\$this->services['%s'] = \$object;\n", $name);
         }
         // Start creating getter
         $getterBody = '';
         // Create fetch of stored service
         if ($im->hasSharedInstance($name, $params)) {
             $getterBody .= sprintf("if (isset(\$this->services['%s'])) {\n", $name);
             $getterBody .= sprintf("%sreturn \$this->services['%s'];\n}\n\n", $indent, $name);
         }
         // Creation and method calls
         $getterBody .= sprintf("%s\n", $creation);
         $getterBody .= $methods;
         // Stored service
         $getterBody .= $storage;
         // End getter body
         $getterBody .= "return \$object;\n";
         $getterDef = new MethodGenerator();
         $getterDef->setName($getter);
         $getterDef->setBody($getterBody);
         $getters[] = $getterDef;
         // Get cases for case statements
         $cases = array($name);
         if (isset($aliases[$name])) {
             $cases = array_merge($aliases[$name], $cases);
         }
         // Build case statement and store
         $statement = '';
         foreach ($cases as $value) {
             $statement .= sprintf("%scase '%s':\n", $indent, $value);
         }
         $statement .= sprintf("%sreturn \$this->%s();\n", str_repeat($indent, 2), $getter);
         $caseStatements[] = $statement;
     }
     // Build switch statement
     $switch = sprintf("switch (%s) {\n%s\n", '$name', implode("\n", $caseStatements));
     $switch .= sprintf("%sdefault:\n%sreturn parent::get(%s, %s);\n", $indent, str_repeat($indent, 2), '$name', '$params');
     $switch .= "}\n\n";
     // Build get() method
     $nameParam = new ParameterGenerator();
     $nameParam->setName('name');
     $paramsParam = new ParameterGenerator();
     $paramsParam->setName('params')->setType('array')->setDefaultValue(array());
     $get = new MethodGenerator();
     $get->setName('get');
     $get->setParameters(array($nameParam, $paramsParam));
     $get->setBody($switch);
     // Create getters for aliases
     $aliasMethods = array();
     foreach ($aliases as $class => $classAliases) {
         foreach ($classAliases as $alias) {
             $aliasMethods[] = $this->getCodeGenMethodFromAlias($alias, $class);
         }
     }
     // Create class code generation object
     $container = new ClassGenerator();
     $container->setName($this->containerClass)->setExtendedClass('ServiceLocator')->addMethodFromGenerator($get)->addMethods($getters)->addMethods($aliasMethods);
     // Create PHP file code generation object
     $classFile = new FileGenerator();
     $classFile->setUse('Zend\\Di\\ServiceLocator')->setClass($container);
     if (null !== $this->namespace) {
         $classFile->setNamespace($this->namespace);
     }
     if (null !== $filename) {
         $classFile->setFilename($filename);
     }
     return $classFile;
 }
Beispiel #8
0
    protected function viewStub($part)
    {
        /**
         * @var $part \Model\Generator\Part\Model
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $table = $part->getTable();
        $tableNameAsCamelCase = $table->getNameAsCamelCase();
        $entity = $tableNameAsCamelCase . 'Entity';
        $collection = $tableNameAsCamelCase . 'Collection';
        $p = new \Zend\Code\Generator\ParameterGenerator('cond');
        $p->setType('Cond');
        $p->setDefaultValue(null);
        $params[] = $p;
        $docblock = new DocBlockGenerator('Получить объект условий в виде представления \'Extended\'

$param Cond $cond
$return Cond
        ');
        $method = new MethodGenerator();
        $method->setName('getCondAsExtendedView');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setFinal(false);
        $method->setDocBlock($docblock);
        $method->setParameters($params);
        $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);
\$cond->where(array('status' => 'active'));
return \$cond;
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
        $p = new \Zend\Code\Generator\ParameterGenerator('cond');
        $p->setType('Cond');
        $p->setDefaultValue(null);
        $params[] = $p;
        $docblock = new DocBlockGenerator('Получить элемент в виде представления \'Extended\'

@param Cond $cond
@return ' . $entity);
        $method = new MethodGenerator();
        $method->setName('getAsExtendedView');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setFinal(false);
        $method->setDocBlock($docblock);
        $method->setParameters($params);
        $method->setBody(<<<EOS
\$cond = \$this->getCondAsExtendedView(\$cond);
return \$this->get(\$cond);
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
        $p = new \Zend\Code\Generator\ParameterGenerator('cond');
        $p->setType('Cond');
        $p->setDefaultValue(null);
        $params[] = $p;
        $docblock = new DocBlockGenerator('Получить коллекцию в виде представления \'Extended\'

@param Cond $cond
@return ' . $collection);
        $method = new MethodGenerator();
        $method->setName('getCollectionAsExtendedView');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setFinal(false);
        $method->setDocBlock($docblock);
        $method->setParameters($params);
        $method->setBody(<<<EOS
\$cond = \$this->getCondAsExtendedView(\$cond);
return \$this->getCollection(\$cond);
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $moduleName
  * @param string $tableName
  */
 protected function addCreateServiceMethod($className, $moduleName, $tableName)
 {
     $managerName = 'serviceLocator';
     $hydratorName = ucfirst($tableName) . 'Hydrator';
     $hydratorService = $moduleName . '\\Db\\' . ucfirst($tableName);
     $entityName = ucfirst($tableName) . 'Entity';
     // set action body
     $body = array('/** @var HydratorPluginManager $hydratorManager */', '$hydratorManager = $serviceLocator->get(\'HydratorManager\');', '', '/** @var AdapterInterface $dbAdapter */', '$dbAdapter = $serviceLocator->get(\'Zend\\Db\\Adapter\\Adapter\');', '', '/** @var ' . $hydratorName . ' $hydrator */', '$hydrator  = $hydratorManager->get(\'' . $hydratorService . '\');', '$entity    = new ' . $entityName . '();', '$resultSet = new HydratingResultSet($hydrator, $entity);', '', '$instance = new ' . $className . '(', '    \'' . $tableName . '\', $dbAdapter, null, $resultSet', ');', '', 'return $instance;');
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters(array(new ParameterGenerator($managerName, 'ServiceLocatorInterface')));
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, array(new ParamTag($managerName, array('ServiceLocatorInterface')), new ReturnTag(array($className)))));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param        $moduleName
  * @param string $entityModule
  * @param        $entityClass
  */
 protected function addCreateServiceMethod($className, $moduleName, $entityModule, $entityClass)
 {
     // prepare repository params
     $repositoryClass = str_replace('Entity', '', $entityClass) . 'Repository';
     $repositoryParam = lcfirst($repositoryClass);
     $repositoryService = $entityModule . '\\' . $this->config['namespaceRepository'] . '\\' . str_replace('Entity', '', $entityClass);
     // prepare form params
     if (in_array($className, ['CreateController', 'UpdateController'])) {
         $formClass = str_replace('Entity', '', $entityClass) . 'DataForm';
         $formParam = lcfirst($formClass);
         $formService = $moduleName . '\\Data\\Form';
     } elseif (in_array($className, ['DeleteController'])) {
         $formClass = str_replace('Entity', '', $entityClass) . 'DeleteForm';
         $formParam = lcfirst($formClass);
         $formService = $moduleName . '\\Delete\\Form';
     } else {
         $formClass = null;
         $formParam = null;
         $formService = null;
     }
     // set action body
     $body = [];
     $body[] = '$serviceLocator = $controllerManager->getServiceLocator();';
     $body[] = '';
     if ($formClass) {
         $body[] = '/** @var ServiceLocatorInterface $formElementManager */';
         $body[] = '$formElementManager = $serviceLocator->get(\'FormElementManager\');';
         $body[] = '';
     }
     $body[] = '/** @var ' . $repositoryClass . ' $' . $repositoryParam . ' */';
     $body[] = '$' . $repositoryParam . ' = $serviceLocator->get(\'' . $repositoryService . '\');';
     $body[] = '';
     if ($formClass) {
         $body[] = '/** @var ' . $formClass . ' $' . $formParam . ' */';
         $body[] = '$' . $formParam . ' = $formElementManager->get(\'' . $formService . '\');';
         $body[] = '';
     }
     $body[] = '$instance = new ' . $className . '();';
     $body[] = '$instance->set' . $repositoryClass . '($' . $repositoryParam . ');';
     if ($formClass) {
         $body[] = '$instance->set' . $formClass . '($' . $formParam . ');';
     }
     $body[] = '';
     $body[] = 'return $instance;';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('controllerManager', 'ServiceLocatorInterface')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag('controllerManager', ['ServiceLocatorInterface', 'ServiceLocatorAwareInterface']), new ReturnTag([$className])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Beispiel #11
0
    public function generateMethodsByLink($part)
    {
        /** @var $part \Model\Generator\Part\Model */
        /** @var $file \Model\Code\Generator\FileGenerator */
        $file = $part->getFile();
        $table = $part->getTable();
        $tableNameAsCamelCase = $part->getTable()->getNameAsCamelCase();
        $indexList = $table->getIndex();
        /*        $userStat = $part->getTable()->getSchema()->getTable('user');
                $indexList = $userStat->getIndex();
                foreach ($indexList as $index) {
                    print_r($index->toArray());
                    $column = reset($index);
                    if ($index->count() > 1 || !($link = $table->getLinkByColumn($column))) {
        
                    }
                }
                die;*/
        $methods = array();
        foreach ($indexList as $index) {
            if ($index->getName() == 'PRIMARY') {
                continue;
            }
            $column = reset($index);
            if ($index->count() > 1 || !($link = $table->getLinkByColumn($column, $table->getName()))) {
                continue;
            }
            if ($link->getLocalTable() == $table->getName()) {
                $direct = true;
            } else {
                $direct = false;
            }
            $columnAsCamelCase = $link->getForeignTable()->getnameAsCamelCase();
            $columnAsVar = $link->getForeignTable()->getnameAsVar();
            $columnName = $link->getForeignTable()->getName();
            $localColumnName = $link->getLocalColumn()->getName();
            $localTableName = $link->getLocalTable()->getName();
            $type = "{$columnAsCamelCase}Entity|{$columnAsCamelCase}Collection|array|string|integer";
            $file->addUse('\\Model\\Entity\\' . $columnAsCamelCase . 'Entity');
            $file->addUse('\\Model\\Collection\\' . $columnAsCamelCase . 'Collection');
            $tags[] = array('name' => 'param', 'description' => "{$type} \$" . $columnAsVar);
            $params[] = new \Zend\Code\Generator\ParameterGenerator($columnAsVar);
            $docblock = new DocBlockGenerator('Получить один элемен по ');
            $docblock->setTags($tags);
            $method = new \Zend\Code\Generator\MethodGenerator();
            $method->setName('getBy' . $columnAsCamelCase);
            $method->setParameters($params);
            $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
            $method->setStatic(true);
            $method->setDocBlock($docblock);
            //            print_r($link->toArray());z
            if (($link->getLinkType() == AbstractLink::LINK_TYPE_ONE_TO_ONE || $link->getLinkType() == AbstractLink::LINK_TYPE_MANY_TO_ONE) && $direct) {
                $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);

\${$columnAsVar}Ids = {$columnAsCamelCase}Model::getInstance()->getIdsFromMixed(\${$columnAsVar});

if (!\${$columnAsVar}Ids) {
    return \$cond->getEmptySelectResult();
}

\$cond->where(array('`{$localTableName}`.`{$localColumnName}`' => \${$columnAsVar}Ids));

return \$this->get(\$cond);
EOS
);
            } elseif (($link->getLinkType() == AbstractLink::LINK_TYPE_ONE_TO_ONE || $link->getLinkType() == AbstractLink::LINK_TYPE_MANY_TO_ONE) && !$direct) {
                $localTableName = $link->getLocalTable()->getName();
                $localColumnName = $link->getLocalColumn()->getName();
                $localTableNameAsVar = $link->getLocalTable()->getNameAsVar();
                $localTableNameAsCamelCase = $link->getLocalTable()->getNameAsCamelCase();
                $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);

\${$columnAsVar}Collection = {$columnAsCamelCase}Model::getInstance()->getCollectionBy{$columnAsCamelCase}(\${$columnAsVar});

\${$localTableNameAsVar}Ids = array();
foreach (\${$columnAsVar}Collection as \${$columnAsVar}) {
    \${$localTableNameAsVar}Ids[] = \${$columnAsVar}->get{$localTableNameAsCamelCase}Id();
}
\${$localTableNameAsVar}Ids = \$this->getIdsFromMixed(\${$localTableNameAsVar}Ids);

if (!\${$localTableNameAsVar}Ids) {
    return \$cond->getEmptySelectResult();
}

\$cond->where(array('`{$localTableName}`.`{$localColumnName}`' => \${$localTableNameAsVar}Ids));

return \$this->get(\$cond);
EOS
);
            } elseif ($link->getLinkType() == AbstractLink::LINK_TYPE_MANY_TO_MANY) {
                die('ok');
            }
            $methods[] = $method;
        }
        return $methods;
    }
 /**
  * Generate an hydrate method
  */
 protected function addHydrateMethod()
 {
     /** @var TableObject $refTableObject */
     $refTableObject = $this->tableObjects[$this->refTableName];
     // set action body
     $body = array();
     $body[] = '$' . $this->refTableName . ' = new ' . $this->entityClass . '();';
     $body[] = '$' . $this->refTableName . '->exchangeArray(';
     $body[] = '    array(';
     /** @var ColumnObject $column */
     foreach ($refTableObject->getColumns() as $column) {
         $body[] = '        \'' . $column->getName() . '\' => $data[\'' . $this->refTableName . '.' . $column->getName() . '\'],';
     }
     $body[] = '    )';
     $body[] = ');';
     $body[] = '';
     $body[] = 'return $' . $this->refTableName . ';';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('hydrate');
     $method->setBody($body);
     $method->setParameters(array(new ParameterGenerator('value'), new ParameterGenerator('data', 'array', array())));
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Hydrate an entity by populating data', null, array(new ParamTag('value'), new ParamTag('data', array('array')), new ReturnTag(array($this->entityClass)))));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $moduleName
  */
 protected function addCreateServiceMethod($className, $moduleName)
 {
     $managerName = 'inputFilterManager';
     // set action body
     $body = [];
     $body[] = '$serviceLocator = $' . $managerName . '->getServiceLocator();';
     $body[] = '';
     /** @var ConstraintObject $foreignKey */
     foreach ($this->foreignKeys as $foreignKey) {
         $storageName = StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase') . 'Storage';
         $storageService = $moduleName . '\\' . $this->config['namespaceStorage'] . '\\' . StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase');
         $storageParam = lcfirst(StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase')) . 'Storage';
         $body[] = '/** @var ' . $storageName . ' $' . $storageParam . ' */';
         $body[] = '$' . $storageParam . ' = $serviceLocator->get(\'' . $storageService . '\');';
         $body[] = '';
     }
     $body[] = '$instance = new ' . $className . '();';
     /** @var ConstraintObject $foreignKey */
     foreach ($this->foreignKeys as $foreignKey) {
         $storageParam = lcfirst(StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase')) . 'Storage';
         $setterOption = 'set' . StaticFilter::execute($foreignKey->getReferencedTableName(), 'Word\\UnderscoreToCamelCase') . 'Options';
         $body[] = '$instance->' . $setterOption . '(array_keys($' . $storageParam . '->getOptions()));';
     }
     $body[] = '';
     $body[] = 'return $instance;';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator($managerName, 'ServiceLocatorInterface')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag($managerName, ['ServiceLocatorInterface', 'ServiceLocatorAwareInterface']), new ReturnTag([$className])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
    private function buildProxyClass(string $entityInterfaceName, string $proxyNamespace, string $proxyClassName) : string
    {
        $reflectionClass = new ReflectionClass($entityInterfaceName);
        if (!$reflectionClass->isInterface()) {
            throw InvalidInterfaceException::fromInvalidInterface($entityInterfaceName);
        }
        $classGenerator = new ClassGenerator();
        $classGenerator->setNamespaceName($proxyNamespace);
        $classGenerator->setName($proxyClassName);
        $classGenerator->setImplementedInterfaces([$entityInterfaceName, ProxyInterface::class]);
        $classGenerator->addProperty('initializer', null, PropertyGenerator::FLAG_PRIVATE);
        $classGenerator->addProperty('relationId', null, PropertyGenerator::FLAG_PRIVATE);
        $classGenerator->addProperty('realEntity', null, PropertyGenerator::FLAG_PRIVATE);
        $constructorGenerator = new MethodGenerator('__construct', [['name' => 'initializer', 'type' => 'callable'], ['name' => 'relationId']]);
        $constructorGenerator->setBody('
            $this->initializer = $initializer;
            $this->relationId = $relationId;
        ');
        $classGenerator->addMethodFromGenerator($constructorGenerator);
        $getRelationIdGenerator = new MethodGenerator('__getRelationId');
        $getRelationIdGenerator->setBody('
            return $this->relationId;
        ');
        $classGenerator->addMethodFromGenerator($getRelationIdGenerator);
        $getRealEntityGenerator = new MethodGenerator('__getRealEntity');
        $getRealEntityGenerator->setBody('
            if (null === $this->realEntity) {
                $this->realEntity = ($this->initializer)();
                \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class);
            };

            return $this->realEntity;
        ');
        $classGenerator->addMethodFromGenerator($getRealEntityGenerator);
        foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
            $parameters = [];
            $parameterGenerators = [];
            $returnType = $reflectionMethod->getReturnType();
            foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
                $parameterGenerator = new ParameterGenerator($reflectionParameter->getName(), $reflectionParameter->getType(), $reflectionParameter->isDefaultValueAvailable() ? $reflectionParameter->getDefaultValue() : null);
                $parameterGenerator->setVariadic($reflectionParameter->isVariadic());
                $parameterGenerators[] = $parameterGenerator;
                if ($reflectionParameter->isVariadic()) {
                    $parameters[] = '...$' . $reflectionParameter->getName();
                } else {
                    $parameters[] = '$' . $reflectionParameter->getName();
                }
            }
            $methodGenerator = new MethodGenerator();
            $methodGenerator->setName($reflectionMethod->getName());
            $methodGenerator->setVisibility(MethodGenerator::VISIBILITY_PUBLIC);
            $methodGenerator->setParameters($parameterGenerators);
            $methodGenerator->setReturnType($returnType);
            $body = '
                if (null === $this->realEntity) {
                    $this->realEntity = ($this->initializer)();
                    \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class);
                };
            ';
            if ('void' !== $returnType) {
                $body .= 'return ';
            }
            $body .= '$this->realEntity->' . $reflectionMethod->getName() . '(' . implode(', ', $parameters) . ');';
            $methodGenerator->setBody($body);
            $classGenerator->addMethodFromGenerator($methodGenerator);
        }
        $fileGenerator = new FileGenerator();
        $fileGenerator->setClass($classGenerator);
        $filename = null === $this->proxyFolder ? tempnam(sys_get_temp_dir(), $proxyClassName) : sprintf('%s/%s.php', $this->proxyFolder, $proxyClassName);
        $fileGenerator->setFilename($filename);
        $fileGenerator->write();
        return $filename;
    }
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $moduleName
  * @param string $entityModule
  * @param string $entityClass
  */
 protected function addCreateServiceMethod($className, $moduleName, $entityModule, $entityClass)
 {
     $managerName = 'formElementManager';
     $entityPrefix = str_replace('Entity', '', $entityClass);
     $hydratorName = ucfirst($entityPrefix) . 'Hydrator';
     $hydratorService = $entityModule . '\\' . ucfirst($entityPrefix);
     $inputFilterName = ucfirst($entityPrefix) . 'InputFilter';
     $inputFilterService = $entityModule . '\\' . ucfirst($entityPrefix);
     // set action body
     $body = [];
     $body[] = '$serviceLocator = $' . $managerName . '->getServiceLocator();';
     $body[] = '';
     $body[] = '/** @var HydratorPluginManager $hydratorManager */';
     $body[] = '$hydratorManager = $serviceLocator->get(\'HydratorManager\');';
     $body[] = '';
     $body[] = '/** @var InputFilterPluginManager $inputFilterManager */';
     $body[] = '$inputFilterManager = $serviceLocator->get(\'InputFilterManager\');';
     $body[] = '';
     /** @var ConstraintObject $foreignKey */
     foreach ($this->foreignKeys as $foreignKey) {
         $storageName = $this->filterUnderscoreToCamelCase($foreignKey->getReferencedTableName()) . 'Storage';
         $storageService = $entityModule . '\\' . $this->config['namespaceStorage'] . '\\' . $this->filterUnderscoreToCamelCase($foreignKey->getReferencedTableName());
         $storageParam = lcfirst($this->filterUnderscoreToCamelCase($foreignKey->getReferencedTableName())) . 'Storage';
         $body[] = '/** @var ' . $storageName . ' $' . $storageParam . ' */';
         $body[] = '$' . $storageParam . ' = $serviceLocator->get(\'' . $storageService . '\');';
         $body[] = '';
     }
     $body[] = '/** @var ' . $hydratorName . ' $hydrator */';
     $body[] = '$hydrator  = $hydratorManager->get(\'' . $hydratorService . '\');';
     $body[] = '';
     $body[] = '/** @var ' . $inputFilterName . ' $inputFilter */';
     $body[] = '$inputFilter  = $inputFilterManager->get(\'' . $inputFilterService . '\');';
     $body[] = '';
     $body[] = '$instance = new ' . $className . '();';
     /** @var ConstraintObject $foreignKey */
     foreach ($this->foreignKeys as $foreignKey) {
         $storageParam = lcfirst($this->filterUnderscoreToCamelCase($foreignKey->getReferencedTableName())) . 'Storage';
         $foreignKeyColumns = $foreignKey->getColumns();
         $setterOption = 'set' . $this->filterUnderscoreToCamelCase(array_pop($foreignKeyColumns)) . 'Options';
         $body[] = '$instance->' . $setterOption . '($' . $storageParam . '->getOptions());';
     }
     $body[] = '$instance->setHydrator($hydrator);';
     $body[] = '$instance->setInputFilter($inputFilter);';
     $body[] = '';
     $body[] = 'return $instance;';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator($managerName, 'ServiceLocatorInterface')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag($managerName, ['ServiceLocatorInterface', 'ServiceLocatorAwareInterface']), new ReturnTag([$className])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $moduleName
  * @param string $tableName
  * @param array  $loadedTable
  */
 protected function addCreateServiceMethod($className, $moduleName, $tableName, array $loadedTable = [])
 {
     /** @var ConstraintObject $primaryKey */
     $primaryKey = $loadedTable['primaryKey'];
     $primaryColumns = $primaryKey->getColumns();
     $managerName = 'serviceLocator';
     $hydratorName = StaticFilter::execute($tableName, 'Word\\UnderscoreToCamelCase') . 'Hydrator';
     $hydratorService = $moduleName . '\\' . StaticFilter::execute($tableName, 'Word\\UnderscoreToCamelCase');
     $entityName = StaticFilter::execute($tableName, 'Word\\UnderscoreToCamelCase') . 'Entity';
     // set action body
     $body = [];
     $body[] = '/** @var HydratorPluginManager $hydratorManager */';
     $body[] = '$hydratorManager = $serviceLocator->get(\'HydratorManager\');';
     $body[] = '';
     $body[] = '/** @var AdapterInterface $dbAdapter */';
     $body[] = '$dbAdapter = $serviceLocator->get(\'Zend\\Db\\Adapter\\Adapter\');';
     $body[] = '';
     $body[] = '/** @var ' . $hydratorName . ' $hydrator */';
     $body[] = '$hydrator  = $hydratorManager->get(\'' . $hydratorService . '\');';
     $body[] = '$entity    = new ' . $entityName . '();';
     $body[] = '$resultSet = new HydratingResultSet($hydrator, $entity);';
     $body[] = '';
     $body[] = '$instance = new ' . $className . '(';
     $body[] = '    \'' . $tableName . '.' . $primaryColumns[0] . '\', \'' . $tableName . '\', $dbAdapter, $resultSet';
     $body[] = ');';
     $body[] = '';
     $body[] = 'return $instance;';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator($managerName, 'ServiceLocatorInterface')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag($managerName, ['ServiceLocatorInterface']), new ReturnTag([$className])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Beispiel #17
0
    /**
     * @group ZF-6444
     */
    public function testMethodWithFinalModifierIsNotEmittedWhenMethodIsAbstract()
    {
        $methodGenerator = new MethodGenerator();
        $methodGenerator->setName('foo');
        $methodGenerator->setParameters(array('one'));
        $methodGenerator->setFinal(true);
        $methodGenerator->setAbstract(true);

        $expected = <<<EOS
    abstract public function foo(\$one)
    {
    }

EOS;
        $this->assertEquals($expected, $methodGenerator->generate());
    }
 /**
  * Generate a isValid method
  */
 protected function addIsValidMethod()
 {
     // set action body
     $body = ['$this->setValue((string) $value);', '', '// add validation code here', '$isValid = true;', '', 'if (!$isValid) {', '    $this->error(self::INVALID);', '    return false;', '}', '', 'return true;'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('isValid');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('value', 'mixed')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Called when validator is executed', null, [new ParamTag('value', ['mixed']), new ReturnTag(['mixed'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 /**
  * Generate an hydrate method
  */
 protected function addHydrateMethod()
 {
     $refTableData = $this->loadedTables[$this->refTableName];
     /** @var ColumnObject $firstColumn */
     $firstColumn = reset($refTableData['columns']);
     // set action body
     $body = [];
     $body[] = 'if (isset($data[\'' . $this->refTableName . '.' . $firstColumn->getName() . '\'])) {';
     /** @var ColumnObject $column */
     foreach ($refTableData['columns'] as $column) {
         $body[] = '    $' . $column->getName() . ' = $data[\'' . $this->refTableName . '.' . $column->getName() . '\'];';
     }
     $body[] = '} else {';
     /** @var ColumnObject $column */
     foreach ($refTableData['columns'] as $column) {
         $body[] = '    $' . $column->getName() . ' = $value;';
     }
     $body[] = '}';
     $body[] = '';
     $body[] = '$' . $this->refTableName . ' = new ' . $this->entityClass . '();';
     $body[] = '$' . $this->refTableName . '->exchangeArray(';
     $body[] = '    [';
     /** @var ColumnObject $column */
     foreach ($refTableData['columns'] as $column) {
         $body[] = '        \'' . $column->getName() . '\' => $' . $column->getName() . ',';
     }
     $body[] = '    ]';
     $body[] = ');';
     $body[] = '';
     $body[] = 'return $' . $this->refTableName . ';';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('hydrate');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('value'), new ParameterGenerator('data', 'array', [])]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Hydrate an entity by populating data', null, [new ParamTag('value'), new ParamTag('data', ['array']), new ReturnTag([$this->entityClass])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Beispiel #20
0
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $moduleName
  * @param string $managerName
  */
 protected function addCreateServiceMethod($className, $moduleName, $managerName)
 {
     // set action body
     $body = [];
     $body[] = '$serviceLocator = $' . $managerName . '->getServiceLocator();';
     $body[] = '';
     $body[] = '$instance = new ' . $className . '();';
     foreach ($this->hydratorStrategies as $table => $strategy) {
         $body[] = '$instance->addStrategy(\'' . $strategy['column'] . '\', new ' . $strategy['class'] . '());';
     }
     $body[] = '';
     $body[] = 'return $instance;';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     foreach ($this->hydratorStrategies as $table => $strategy) {
         $this->addUse($moduleName . '\\' . $this->config['namespaceHydrator'] . '\\Strategy\\' . $strategy['class']);
     }
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator($managerName, 'ServiceLocatorInterface')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag($managerName, ['ServiceLocatorInterface', 'ServiceLocatorAwareInterface']), new ReturnTag([$className])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }