public function testCreateFromArray() { $docBlock = DocBlockGenerator::fromArray(array('shortdescription' => 'foo', 'longdescription' => 'bar', 'tags' => array(array('name' => 'foo', 'description' => 'bar')))); $this->assertEquals('foo', $docBlock->getShortDescription()); $this->assertEquals('bar', $docBlock->getLongDescription()); $this->assertCount(1, $docBlock->getTags()); }
/** * Generate from array * * @configkey name string [required] Class Name * @configkey filegenerator FileGenerator File generator that holds this class * @configkey namespacename string The namespace for this class * @configkey docblock string The docblock information * @configkey properties * @configkey methods * * @throws Exception\InvalidArgumentException * @param array $array * @return TraitGenerator */ public static function fromArray(array $array) { if (!isset($array['name'])) { throw new Exception\InvalidArgumentException('Class generator requires that a name is provided for this object'); } $cg = new static($array['name']); foreach ($array as $name => $value) { // normalize key switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) { case 'containingfile': $cg->setContainingFileGenerator($value); break; case 'namespacename': $cg->setNamespaceName($value); break; case 'docblock': $docBlock = $value instanceof DocBlockGenerator ? $value : DocBlockGenerator::fromArray($value); $cg->setDocBlock($docBlock); break; case 'properties': $cg->addProperties($value); break; case 'methods': $cg->addMethods($value); break; } } return $cg; }
private function addCustomFiltersMethod() { $body = 'return $inputFilter;'; $inputFilterParm = new ParameterGenerator('inputFilter', null, null, null, true); $docBlock = DocBlockGenerator::fromArray(array('shortDescription' => 'You may customize the filters behaviours using this method')); $result = new MethodGenerator('addCustomFilters', array($inputFilterParm, 'factory'), MethodGenerator::FLAG_PUBLIC, $body, $docBlock); return $result; }
private function generate($version) { $generator = new ClassGenerator(); $docblock = DocBlockGenerator::fromArray(array('shortDescription' => 'PDO Simple Migration Class', 'longDescription' => 'Add your queries below')); $generator->setName('PDOSimpleMigration\\Migrations\\Migration' . $version)->setExtendedClass('AbstractMigration')->addUse('PDOSimpleMigration\\Library\\AbstractMigration')->setDocblock($docblock)->addProperties(array(array('description', 'Migration description', PropertyGenerator::FLAG_STATIC)))->addMethods(array(MethodGenerator::fromArray(array('name' => 'up', 'parameters' => array(), 'body' => '//$this->addSql(/*Sql instruction*/);', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Migrate up', 'longDescription' => null)))), MethodGenerator::fromArray(array('name' => 'down', 'parameters' => array(), 'body' => '//$this->addSql(/*Sql instruction*/);', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Migrate down', 'longDescription' => null)))))); $file = FileGenerator::fromArray(array('classes' => array($generator))); return $file->generate(); }
/** * @param ContextInterface $context * @param ClassGenerator $class * @param Property $property * * @throws \Zend\Code\Generator\Exception\InvalidArgumentException */ private function implementGetResult(ContextInterface $context, ClassGenerator $class, Property $property) { $useAssembler = new UseAssembler($this->wrapperClass ?: ResultInterface::class); if ($useAssembler->canAssemble($context)) { $useAssembler->assemble($context); } $methodName = 'getResult'; $class->removeMethod($methodName); $class->addMethodFromGenerator(MethodGenerator::fromArray(['name' => $methodName, 'parameters' => [], 'visibility' => MethodGenerator::VISIBILITY_PUBLIC, 'body' => $this->generateGetResultBody($property), 'docblock' => DocBlockGenerator::fromArray(['tags' => [['name' => 'return', 'description' => $this->generateGetResultReturnTag($property)]]])])); }
/** * @param ContextInterface|PropertyContext $context * * @throws AssemblerException */ public function assemble(ContextInterface $context) { $class = $context->getClass(); $property = $context->getProperty(); try { $methodName = Normalizer::generatePropertyMethod('get', $property->getName()); $class->removeMethod($methodName); $class->addMethodFromGenerator(MethodGenerator::fromArray(['name' => $methodName, 'parameters' => [], 'visibility' => MethodGenerator::VISIBILITY_PUBLIC, 'body' => sprintf('return $this->%s;', $property->getName()), 'docblock' => DocBlockGenerator::fromArray(['tags' => [['name' => 'return', 'description' => $property->getType()]]])])); } catch (\Exception $e) { throw AssemblerException::fromException($e); } }
/** * @param ContextInterface|PropertyContext $context * * @throws AssemblerException */ public function assemble(ContextInterface $context) { $class = $context->getClass(); $property = $context->getProperty(); try { // It's not possible to overwrite a property in zend-code yet! if ($class->hasProperty($property->getName())) { return; } $class->addPropertyFromGenerator(PropertyGenerator::fromArray(['name' => $property->getName(), 'visibility' => PropertyGenerator::VISIBILITY_PROTECTED, 'docblock' => DocBlockGenerator::fromArray(['tags' => [['name' => 'var', 'description' => $property->getType()]]])])); } catch (\Exception $e) { throw AssemblerException::fromException($e); } }
/** * @param Type $type * * @return MethodGenerator * @throws \Zend\Code\Generator\Exception\InvalidArgumentException */ private function assembleConstructor(Type $type) { $body = []; $constructor = MethodGenerator::fromArray(['name' => '__construct', 'visibility' => MethodGenerator::VISIBILITY_PUBLIC]); $docblock = DocBlockGenerator::fromArray(['shortdescription' => 'Constructor']); foreach ($type->getProperties() as $property) { $body[] = sprintf('$this->%1$s = $%1$s;', $property->getName()); $constructor->setParameter(['name' => $property->getName()]); $docblock->setTag(['name' => 'var', 'description' => sprintf('%s $%s', $property->getType(), $property->getName())]); } $constructor->setDocBlock($docblock); $constructor->setBody(implode($constructor::LINE_FEED, $body)); return $constructor; }
/** * Generate from array * * @configkey name string [required] Class Name * @configkey const bool * @configkey defaultvalue null|bool|string|int|float|array|ValueGenerator * @configkey flags int * @configkey abstract bool * @configkey final bool * @configkey static bool * @configkey visibility string * * @throws Exception\InvalidArgumentException * @param array $array * @return PropertyGenerator */ public static function fromArray(array $array) { if (!isset($array['name'])) { throw new Exception\InvalidArgumentException('Property generator requires that a name is provided for this object'); } $property = new static($array['name']); foreach ($array as $name => $value) { // normalize key switch (strtolower(str_replace(array('.', '-', '_'), '', $name))) { case 'const': $property->setConst($value); break; case 'defaultvalue': $property->setDefaultValue($value); break; case 'docblock': $docBlock = $value instanceof DocBlockGenerator ? $value : DocBlockGenerator::fromArray($value); $property->setDocBlock($docBlock); break; case 'flags': $property->setFlags($value); break; case 'abstract': $property->setAbstract($value); break; case 'final': $property->setFinal($value); break; case 'static': $property->setStatic($value); break; case 'visibility': $property->setVisibility($value); break; } } return $property; }
public function getClassArrayRepresentation() { $this->data = $this->getData(); return array('name' => 'Manager', 'namespacename' => $this->data['_namespace'] . '\\Table', 'extendedclass' => $this->tableGatewayClass, 'flags' => ClassGenerator::FLAG_ABSTRACT, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Application Model DbTables', 'longDescription' => null, 'tags' => array(array('name' => 'package', 'description' => $this->data['_namespace']), array('name' => 'author', 'description' => $this->data['_author']), array('name' => 'copyright', 'description' => $this->data['_copyright']), array('name' => 'license', 'description' => $this->data['_license'])))), 'properties' => array(array('entity', null, PropertyGenerator::FLAG_PROTECTED), array('container', null, PropertyGenerator::FLAG_PROTECTED), PropertyGenerator::fromArray(array('name' => 'wasInTransaction', 'defaultvalue' => false, 'flags' => PropertyGenerator::FLAG_PROTECTED, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'True if we were already in a transaction when try to start a new one', 'longDescription' => '', 'tags' => array(new GenericTag('var', 'bool'))))))), 'methods' => array(array('name' => '__construct', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'adapter')), ParameterGenerator::fromArray(array('name' => 'entity', 'type' => 'Entity'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$this->adapter = $adapter;' . "\n" . '$this->entity = $entity;' . "\n" . '$this->featureSet = new Feature\\FeatureSet();' . "\n" . '$this->initialize();', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Constructor', 'longDescription' => null, 'tags' => array(new ParamTag('adapter', array('Adapter')), new ParamTag('entity', array('Entity')))))), array('name' => 'setContainer', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'c', 'type' => 'Container'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$this->container = $c;' . "\n" . 'return $this;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Inject container', 'longDescription' => null, 'tags' => array(new ParamTag('c', array('Container')), new ReturnTag(array('datatype' => 'self')))))), array('name' => 'getContainer', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'return $this->container;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => '', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'Container')))))), array('name' => 'all', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$select = $this->select();' . '$result = array();' . PHP_EOL . 'foreach ($select as $v) {' . PHP_EOL . ' $result[] = $v->getArrayCopy();' . PHP_EOL . '}' . PHP_EOL . 'return $result;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => '', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'self')))))), array('name' => 'getPrimaryKeyName', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'return $this->id;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => '', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'array|string')))))), array('name' => 'getTableName', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'return $this->table;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => '', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'array|string')))))), array('name' => 'findBy', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'criteria', 'defaultvalue' => array(), 'type' => 'array')), ParameterGenerator::fromArray(array('name' => 'order', 'defaultvalue' => null)), ParameterGenerator::fromArray(array('name' => 'limit', 'defaultvalue' => null)), ParameterGenerator::fromArray(array('name' => 'offset', 'defaultvalue' => null)), ParameterGenerator::fromArray(array('name' => 'toEntity', 'defaultvalue' => false))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$r = $this->sql->select()->where($criteria);' . PHP_EOL . 'if ($order) {' . PHP_EOL . ' $r->order($order);' . PHP_EOL . '}' . PHP_EOL . 'if ($limit) {' . PHP_EOL . ' $r->limit($limit);' . PHP_EOL . '}' . PHP_EOL . 'if ($offset) {' . PHP_EOL . ' $r->offset($offset);' . PHP_EOL . '}' . PHP_EOL . '$result = $this->selectWith($r)->toArray();' . PHP_EOL . 'if ($toEntity) {' . PHP_EOL . ' foreach($result as &$v){' . PHP_EOL . ' $entity = clone $this->entity;' . PHP_EOL . ' $v = $entity->exchangeArray($v);' . PHP_EOL . ' }' . PHP_EOL . '}' . PHP_EOL . 'return $result;' . PHP_EOL, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Find by criteria', 'longDescription' => null, 'tags' => array(new ParamTag('criteria', array('array'), 'Search criteria'), new ParamTag('order', array('string'), 'sorting option'), new ParamTag('limit', array('int'), 'limit option'), new ParamTag('offset', array('int'), 'offset option'), new ParamTag('toEntity', array('boolean'), 'return entity result'), new ReturnTag(array('array'), ''))))), array('name' => 'countBy', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'criteria', 'defaultvalue' => array(), 'type' => 'array'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$r = $this->sql->select()->columns(array("count" => new Expression("count(*)")))->where($criteria);' . PHP_EOL . 'return (int)current($this->selectWith($r)->toArray())["count"];' . PHP_EOL, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Count by criteria', 'longDescription' => null, 'tags' => array(new ParamTag('criteria', array('array'), 'Criteria'), new ReturnTag(array('int'), ''))))), array('name' => 'deleteEntity', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'entity', 'type' => 'Entity')), 'useTransaction = true'), 'flags' => array(MethodGenerator::FLAG_PUBLIC, MethodGenerator::FLAG_ABSTRACT), 'body' => null, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Converts database column name to php setter/getter function name', 'longDescription' => null, 'tags' => array(new ParamTag('entity', array('Entity')), new ParamTag('useTransaction', array('boolean')), new ReturnTag(array('datatype' => 'int')))))), array('name' => 'beginTransaction', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PROTECTED, 'body' => <<<'BODY' if ($this->adapter->getDriver()->getConnection()->inTransaction()) { $this->wasInTransaction = true; return; } $this->adapter->getDriver()->getConnection()->beginTransaction(); BODY , 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Begin a transaction', 'longDescription' => null, 'tags' => array()))), array('name' => 'rollback', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PROTECTED, 'body' => <<<'BODY' if ($this->wasInTransaction) { throw new \Exception('Inside transaction rollback call'); } $this->adapter->getDriver()->getConnection()->rollback(); BODY , 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Rollback a transaction', 'longDescription' => null, 'tags' => array()))), array('name' => 'commit', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PROTECTED, 'body' => <<<'BODY' if (!$this->wasInTransaction) { $this->adapter->getDriver()->getConnection()->commit(); } BODY , 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => ' Commit a transaction', 'longDescription' => null, 'tags' => array()))))); }
private function getUtils() { $constructBody = 'return $this->adapter->platform->quoteIdentifier($name); '; $methods[] = array('name' => 'qi', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'name', 'type' => 'string'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => $constructBody, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Apply quoteIdentifier', 'longDescription' => null, 'tags' => array(new ParamTag('name', array('string'), 'String to quote'), new ReturnTag(array('datatype' => 'string'), 'Quoted string'))))); $constructBody = 'return $this->adapter->driver->formatParameterName($name); '; $methods[] = array('name' => 'fp', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'name', 'type' => 'string'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => $constructBody, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Apply formatParameterName', 'longDescription' => null, 'tags' => array(new ParamTag('name', array('string'), 'Parameter name to format'), new ReturnTag(array('datatype' => 'string'), 'Formated parameter name'))))); return $methods; }
public function getClassArrayRepresentation() { $data = $this->getData(); return array('name' => 'Entity', 'namespacename' => $data['_namespace'] . '\\Entity', 'flags' => ClassGenerator::FLAG_ABSTRACT, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Generic Entity Class', 'longDescription' => null, 'tags' => array(array('name' => 'package', 'description' => $data['_namespace']), array('name' => 'author', 'description' => $data['_author']), array('name' => 'copyright', 'description' => $data['_copyright']), array('name' => 'license', 'description' => $data['_license'])))), 'methods' => array(array('name' => 'setColumnsList', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'data', 'type' => 'array'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$this->_columnsList = $data;' . "\n" . 'return $this;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Set the list of columns associated with this model', 'longDescription' => null, 'tags' => array(new ParamTag('data', array('array'), 'array of field names'), new ReturnTag(array('datatype' => 'self')))))), array('name' => 'getColumnsList', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'return $this->_columnsList;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Returns columns list array', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'array')))))), array('name' => 'setParentList', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'data', 'type' => 'array'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$this->_parentList = $data;' . "\n" . 'return $this;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Set the list of relationships associated with this model', 'longDescription' => null, 'tags' => array(new ParamTag('data', array('array'), 'Array of relationship'), new ReturnTag(array('datatype' => 'self')))))), array('name' => 'getParentList', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'return $this->_parentList;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Returns relationship list array', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'array')))))), array('name' => 'setDependentList', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'data', 'type' => 'array'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$this->_dependentList = $data;' . "\n" . 'return $this;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Set the list of relationships associated with this model', 'longDescription' => null, 'tags' => array(new ParamTag('data', array('array'), 'array of relationships'), new ReturnTag(array('datatype' => 'self')))))), array('name' => 'getDependentList', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'return $this->_dependentList;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Returns relationship list array', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'array')))))), array('name' => 'columnNameToVar', 'parameters' => array('column'), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'if (! isset($this->_columnsList[$column])) {' . "\n" . ' throw new \\Exception("column \'$column\' not found!");' . "\n" . '}' . "\n" . 'return $this->_columnsList[$column];', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Converts database column name to php setter/getter function name', 'longDescription' => null, 'tags' => array(new ParamTag('column', array('string'), 'Column name'), new ReturnTag(array('datatype' => 'self')))))), array('name' => 'varNameToColumn', 'parameters' => array('thevar'), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'foreach ($this->_columnsList as $column => $var) {' . "\n" . ' if ($var == $thevar) {' . "\n" . ' return $column;' . "\n" . ' }' . "\n" . '}' . "\n" . 'return null;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Converts database column name to PHP setter/getter function name', 'longDescription' => null, 'tags' => array(new ParamTag('thevar', array('string'), 'Column name'), new ReturnTag(array('datatype' => 'self')))))), array('name' => 'setOptions', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'options', 'type' => 'array'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => '$this->exchangeArray($options);' . "\n" . 'return $this;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Array of options/values to be set for this model.', 'longDescription' => 'Options without a matching method are ignored.', 'tags' => array(new ParamTag('options', array('array'), 'array of Options'), new ReturnTag(array('datatype' => 'self')))))), array('name' => 'exchangeArray', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'options', 'type' => 'array'))), 'flags' => MethodGenerator::FLAG_ABSTRACT, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Array of options/values to be set for this model.', 'longDescription' => 'Options without a matching method are ignored.', 'tags' => array(new ParamTag('options', array('array'), 'array of Options'), new ReturnTag(array('datatype' => 'self')))))), array('name' => 'getPrimaryKey', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => 'return $this->primary_key;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Returns primary key.', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'array|string')))))))); }
/** * Metodo para criar docBlock para o metodo __construct * * @return DocBlockGenerator */ public function getDocBlockMethodConstruct() { return DocBlockGenerator::fromArray(array('shortDescription' => $this->getStrFilterNameWithPrefix() . ' constructor.')); }
public function controllerAction() { $config = $this->getServiceLocator()->get('config'); $moduleName = $config['VisioCrudModeler']['params']['moduleName']; $modulePath = $config['VisioCrudModeler']['params']['modulesDirectory']; $db = $this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter'); $dataSourceDescriptor = new DbDataSourceDescriptor($db, 'K08_www_biedronka_pl'); $listDataSets = $dataSourceDescriptor->listDataSets(); $filter = new \Zend\Filter\Word\UnderscoreToCamelCase(); foreach ($listDataSets as $d) { $className = $filter->filter($d) . 'Controller'; $file = new FileGenerator(); $file->setFilename($className); $file->setNamespace($moduleName)->setUse('Zend\\Mvc\\Controller\\AbstractActionController'); $foo = new ClassGenerator(); $docblock = DocBlockGenerator::fromArray(array('shortDescription' => 'Sample generated class', 'longDescription' => 'This is a class generated with Zend\\Code\\Generator.', 'tags' => array(array('name' => 'version', 'description' => '$Rev:$'), array('name' => 'license', 'description' => 'New BSD')))); $foo->setName($className); $foo->setExtendedClass('Base' . $className); $foo->setDocblock($docblock); $file->setClass($foo); echo '<pre>'; echo htmlentities($file->generate()); echo '</pre>'; $fileView = new FileGenerator(); $body = "echo '{$className}';"; $fileView->setBody($body); echo '<pre>'; echo htmlentities($fileView->generate()); echo '</pre>'; } echo '<hr />'; foreach ($listDataSets as $d) { $className = 'Base' . $filter->filter($d) . 'Controller'; $fileBase = new FileGenerator(); $fileBase->setFilename($className); $fileBase->setNamespace($moduleName)->setUse('Zend\\Mvc\\Controller\\AbstractActionController'); $fooBase = new ClassGenerator(); $docblockBase = DocBlockGenerator::fromArray(array('shortDescription' => 'Sample generated class', 'longDescription' => 'This is a class generated with Zend\\Code\\Generator.', 'tags' => array(array('name' => 'version', 'description' => '$Rev:$'), array('name' => 'license', 'description' => 'New BSD')))); $fooBase->setName($className); $index = new MethodGenerator(); $index->setName('indexAction'); $create = new MethodGenerator(); $create->setName('createAction'); $read = new MethodGenerator(); $read->setName('readAction'); $update = new MethodGenerator(); $update->setName('updateAction'); $delete = new MethodGenerator(); $delete->setName('deleteAction'); $fooBase->setExtendedClass('AbstractActionController'); //$fooBase->set $fooBase->setDocblock($docblock); $fooBase->addMethodFromGenerator($index); $fooBase->addMethodFromGenerator($create); $fooBase->addMethodFromGenerator($read); $fooBase->addMethodFromGenerator($update); $fooBase->addMethodFromGenerator($delete); $fileBase->setClass($fooBase); echo '<pre>'; echo htmlentities($fileBase->generate()); echo '</pre>'; } exit; }
/** * @param ClassGenerator $class * @param Property $firstProperty * * @throws \Zend\Code\Generator\Exception\InvalidArgumentException */ private function implementGetIterator($class, $firstProperty) { $methodName = 'getIterator'; $class->removeMethod($methodName); $class->addMethodFromGenerator(MethodGenerator::fromArray(['name' => $methodName, 'parameters' => [], 'visibility' => MethodGenerator::VISIBILITY_PUBLIC, 'body' => sprintf('return new \\ArrayIterator(is_array($this->%1$s) ? $this->%1$s : []);', $firstProperty->getName()), 'docblock' => DocBlockGenerator::fromArray(['tags' => [['name' => 'return', 'description' => '\\ArrayIterator']]])])); }
/** * @param string $modelName * @return array */ protected function getMethodsForCollection($modelName) { return array(MethodGenerator::fromArray(array('name' => 'add', 'parameters' => array(lcfirst($modelName)), 'body' => ' if (is_array($' . lcfirst($modelName) . ')) { $this->collection[] = new ' . ucfirst($modelName) . '($' . lcfirst($modelName) . '); } elseif (is_object($' . lcfirst($modelName) . ') && $' . lcfirst($modelName) . ' instanceof ' . ucfirst($modelName) . ') { $this->collection[] = $' . lcfirst($modelName) . '; } return $this; ', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Add item', 'longDescription' => null, new Tag\ParamTag($modelName, ucfirst($modelName)), new Tag\ReturnTag(array('datatype' => '$this')))))), MethodGenerator::fromArray(array('name' => 'getAll', 'body' => 'return $this->collection;', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Get items', 'longDescription' => null, new Tag\ParamTag($modelName, ucfirst($modelName)), new Tag\ReturnTag(array('datatype' => '$this'))))))); }
public function getDocBlock() { return DocBlockGenerator::fromArray(array('shortDescription' => $this->entity . ' ' . $this->subDir . ' class', 'longDescription' => 'This is an auto-generated class. Always remember to keep your custom code inside of the PROTECTED_ZONE to avoid losses.')); }
/** * Metodo para criar docBlock para o metodo __construct * * @return DocBlockGenerator */ public function getDocBlockMethodConstruct() { return DocBlockGenerator::fromArray(array('shortDescription' => 'CategoriaForm constructor.')); }
/** * @param $className * @param $nameSpace * @return ClassGenerator */ private function initClass($className, $nameSpace) { $user = $this->getCurrentStaff()->getStaffName(); $date = date('Y-m-d H:i:s', time()); $class = new ClassGenerator($className); $class->setDocBlock(DocBlockGenerator::fromArray(array('shortDescription' => 'System Generated Code', 'longDescription' => "User : {$user}\nDate : {$date}", 'tags' => array(array('name' => 'package', 'description' => $nameSpace))))); $class->setNamespaceName($nameSpace); return $class; }
private function getUtils() { $constructBody = ''; foreach ($this->data['_columns'] as $column) { $constructBody .= '$this->' . $column['capital'] . ' = (isset($data[\'' . $column['field'] . '\'] )) ? $data[\'' . $column['field'] . '\'] : null;' . PHP_EOL; } $constructBody .= 'return $this;'; $methods[] = array('name' => 'exchangeArray', 'parameters' => array(ParameterGenerator::fromArray(array('name' => 'data', 'type' => 'array'))), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => $constructBody, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Array of options/values to be set for this model.', 'longDescription' => 'Options without a matching method are ignored.', 'tags' => array(new ParamTag('data', array('array'), 'array of values to set'), new ReturnTag(array('datatype' => 'self')))))); $constructBody = ''; $constructBody .= '$result = array(' . PHP_EOL; foreach ($this->data['_columns'] as $column) { $constructBody .= ' \'' . $column['field'] . '\' => $this->get' . $column['capital'] . '(),' . PHP_EOL; } $constructBody .= ');' . PHP_EOL; $constructBody .= 'return $result;' . PHP_EOL; $methods[] = array('name' => 'toArray', 'parameters' => array(), 'flags' => MethodGenerator::FLAG_PUBLIC, 'body' => $constructBody, 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Returns an array, keys are the field names.', 'longDescription' => null, 'tags' => array(new ReturnTag(array('datatype' => 'array')))))); return $methods; }
/** * Metodo para criar docBlock para o metodo prepareElements * * @return DocBlockGenerator */ public function getDocBlockMethodPrepareElements() { return DocBlockGenerator::fromArray(array('shortDescription' => 'Adicionando html, campos e botoes no formulario.', 'tags' => array(array('name' => 'name', 'description' => 'prepareElements'), new ReturnTag('$this')))); }
/** * Fill file level phpdoc * * @param ClassGenerator $class contained class */ protected function defineFileInfo(ClassGenerator $class) { $doc = DocBlockGenerator::fromArray(array('shortDescription' => 'Contains ' . $class->getName() . ' class file', 'longDescription' => 'Generated Automatically.' . PHP_EOL . 'Please do not modify', 'tags' => array(array('name' => 'author', 'description' => $this->data['_author']), array('name' => 'license', 'description' => $this->data['_license']), array('name' => 'package', 'description' => $class->getNamespaceName())))); $this->fileGenerator->setDocBlock($doc); }
/** * Generate from array * * @configkey name string [required] Class Name * @configkey docblock string The docblock information * @configkey flags int Flags, one of MethodGenerator::FLAG_ABSTRACT MethodGenerator::FLAG_FINAL * @configkey parameters string Class which this class is extending * @configkey body string * @configkey abstract bool * @configkey final bool * @configkey static bool * @configkey visibility string * * @throws Exception\InvalidArgumentException * @param array $array * @return MethodGenerator */ public static function fromArray(array $array) { if (!isset($array['name'])) { throw new Exception\InvalidArgumentException('Method generator requires that a name is provided for this object'); } $method = new static($array['name']); foreach ($array as $name => $value) { // normalize key switch (strtolower(str_replace(['.', '-', '_'], '', $name))) { case 'docblock': $docBlock = $value instanceof DocBlockGenerator ? $value : DocBlockGenerator::fromArray($value); $method->setDocBlock($docBlock); break; case 'flags': $method->setFlags($value); break; case 'parameters': $method->setParameters($value); break; case 'body': $method->setBody($value); break; case 'abstract': $method->setAbstract($value); break; case 'final': $method->setFinal($value); break; case 'static': $method->setStatic($value); break; case 'visibility': $method->setVisibility($value); break; } } return $method; }
/** * Função geradora das entidades dos schemas e tabelas do banco de dados * * @return \Cityware\Generator\Adapter\ModelAdapter */ private function generatorClassEntity() { /* Lista os schemas do banco de dados */ foreach ($this->oMetadata->getSchemas() as $valueSchema) { $tableNames = $this->oMetadata->getTableNames($valueSchema); $namespaceSchema = 'Orm\\' . $this->toCamelCase($valueSchema) . '\\Entities'; /* Lista as tabelas do banco de dados */ foreach ($tableNames as $tableName) { $multiPk = $primaryKey = $bodyExchangeArray = null; $class = new ClassGenerator(); $class->setNamespaceName($namespaceSchema); $docBlockClass = DocBlockGenerator::fromArray(array('shortDescription' => 'Classe tipo model da tabela ' . $tableName . ' dentro do schema ' . $valueSchema, 'longDescription' => null)); $class->setDocBlock($docBlockClass); $class->setName($this->toCamelCase($tableName)); $class->addProperty('DBSCHEMA', $valueSchema, PropertyGenerator::FLAG_STATIC); $class->addProperty('DBTABLE', $tableName, PropertyGenerator::FLAG_STATIC); foreach ($this->oMetadata->getConstraints($tableName, $valueSchema) as $constraint) { if (!$constraint->hasColumns()) { continue; } if ($constraint->isPrimaryKey()) { $columns = $constraint->getColumns(); if (count($columns) > 1) { $multiPk = true; $primaryKey = implode(', ', $columns); } else { $multiPk = false; $primaryKey = $columns[0]; } $class->addProperty('MULTIPK', $multiPk, PropertyGenerator::FLAG_STATIC); $class->addProperty('PKCOLUMN', $primaryKey, PropertyGenerator::FLAG_STATIC); } } /* Cria os metodos setter/getter e as variáveis das colunas da tabela */ $table = $this->oMetadata->getTable($tableName, $valueSchema); /* Lista as colunas da tabela do banco de dados */ foreach ($table->getColumns() as $column) { $varName = $this->camelCase($column->getName()); $class->addProperty($varName, null, PropertyGenerator::FLAG_PRIVATE); $methodGet = 'get' . $this->toCamelCase($column->getName()); $methodSet = 'set' . $this->toCamelCase($column->getName()); $docBlockSet = DocBlockGenerator::fromArray(array('shortDescription' => 'Setter da coluna ' . $column->getName(), 'longDescription' => null, 'tags' => array(new Tag\ParamTag($varName, $this->prepareSqlTypeDocBlock($column->getDataType()))))); $docBlockGet = DocBlockGenerator::fromArray(array('shortDescription' => 'Getter da coluna ' . $column->getName(), 'longDescription' => null, 'tags' => array(new Tag\ReturnTag(array('datatype' => $this->prepareSqlTypeDocBlock($column->getDataType())))))); $bodyGet = 'return $this->' . $varName . ';'; $bodySet = '$this->' . $varName . ' = $' . $this->camelCase($column->getName()) . ';'; $class->addMethod($methodSet, array($this->camelCase($column->getName())), MethodGenerator::FLAG_PUBLIC, $bodySet, $docBlockSet); $class->addMethod($methodGet, array(), MethodGenerator::FLAG_PUBLIC, $bodyGet, $docBlockGet); $bodyExchangeArray .= '$this->' . $varName . ' = (isset($data["' . $column->getName() . '"])) ? $data["' . $column->getName() . '"] : null;' . "\n\n"; } $docBlockExchangeArray = DocBlockGenerator::fromArray(array('shortDescription' => 'Função para settar todos os objetos por meio de array', 'longDescription' => null, 'tags' => array(new Tag\ParamTag('data', 'array')))); $class->addMethod('exchangeArray', array('data'), MethodGenerator::FLAG_PUBLIC, $bodyExchangeArray, $docBlockExchangeArray); $docBlockGetArrayCopy = DocBlockGenerator::fromArray(array('shortDescription' => 'Função para retornar os valores por meio de array dos objetos da classe', 'longDescription' => null, 'tags' => array(new Tag\ReturnTag(array('datatype' => 'mixed'))))); $class->addMethod('getArrayCopy', array(), MethodGenerator::FLAG_PUBLIC, 'return get_object_vars($this);', $docBlockGetArrayCopy); $classCode = "<?php" . PHP_EOL; $classCode .= $class->generate(); /* $idxConstraint = 0; foreach ($this->oMetadata->getConstraints($tableName, $valueSchema) as $constraint) { $typeConstraint = ($constraint->isPrimaryKey()) ? 'pk' : (($constraint->isForeignKey()) ? 'fk' : null); if (!empty($typeConstraint)) { $consName = $constraint->getName(); $contraintObj = $this->oMetadata->getConstraint($consName, $tableName, $valueSchema); $constraintColumns = $contraintObj->getColumns(); if (count($constraintColumns) > 1) { foreach ($constraintColumns as $valueConsColumns) { $this->aDatabase[$valueSchema][$tableName][$valueConsColumns]['constraints']['type'] = $typeConstraint; if ($typeConstraint === 'fk') { $this->aDatabase[$valueSchema][$tableName][$valueConsColumns]['constraints']['schemaRef'] = $contraintObj->getReferencedTableSchema(); $this->aDatabase[$valueSchema][$tableName][$valueConsColumns]['constraints']['tableRef'] = $contraintObj->getReferencedTableName(); $this->aDatabase[$valueSchema][$tableName][$valueConsColumns]['constraints']['columnsRef'] = $contraintObj->getReferencedColumns(); } } } else { $this->aDatabase[$valueSchema][$tableName][$constraintColumns[0]]['constraints']['type'] = $typeConstraint; if ($typeConstraint === 'fk') { $this->aDatabase[$valueSchema][$tableName][$constraintColumns[0]]['constraints']['schemaRef'] = $contraintObj->getReferencedTableSchema(); $this->aDatabase[$valueSchema][$tableName][$constraintColumns[0]]['constraints']['tableRef'] = $contraintObj->getReferencedTableName(); $this->aDatabase[$valueSchema][$tableName][$constraintColumns[0]]['constraints']['columnsRef'] = $contraintObj->getReferencedColumns(); } } } $idxConstraint++; } * */ file_put_contents($this->ormFolder . $this->toCamelCase($valueSchema) . DS . 'Entities' . DS . $this->toCamelCase($tableName) . '.php', $classCode); chmod($this->ormFolder . $this->toCamelCase($valueSchema) . DS . 'Entities' . DS . $this->toCamelCase($tableName) . '.php', 0644); $this->generatorClassEntityTable($valueSchema, $tableName); } //gera arquivo por tabela } return $this; }
/** * @param null|string $module * @param null|string $migrationBody * @return string */ public function create($module = null, $migrationBody = null) { $path = $this->getMigrationsDirectoryPath($module); list(, $mSec) = explode(".", microtime(true)); $migrationName = date('Ymd_His_') . substr($mSec, 0, 2); $methodUp = array('name' => 'up', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Upgrade', 'longDescription' => null))); $methodDown = array('name' => 'down', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Degrade', 'longDescription' => null))); if ($migrationBody) { if (isset($migrationBody['up'])) { $upBody = ''; foreach ($migrationBody['up'] as $query) { $upBody .= '$this->query("' . $query . '");' . PHP_EOL; } $methodUp['body'] = $upBody; } if (isset($migrationBody['down'])) { $downBody = ''; foreach ($migrationBody['down'] as $query) { $downBody .= '$this->query("' . $query . '");' . PHP_EOL; } $methodDown['body'] = $downBody; } } $class = new ClassGenerator(); $class->setName('Migration_' . $migrationName)->setExtendedClass('AbstractMigration')->addUse('ZFCTool\\Service\\Migration\\AbstractMigration')->addMethods(array(MethodGenerator::fromArray($methodUp), MethodGenerator::fromArray($methodDown))); $file = new FileGenerator(array('classes' => array($class))); $code = $file->generate(); $migrationPath = $path . '/' . $migrationName . '.php'; file_put_contents($migrationPath, $code); return $migrationPath; }
/** * Generate the code for the given className and primaryKey and write it in a file. * @param string $className The class name. * @param string $primaryKey The primary key. */ private function generateCode($className, $primaryKey) { $tags = $this->config->getTags(); $class = new ClassGenerator(); $docblock = DocBlockGenerator::fromArray(array('shortDescription' => ucfirst($className) . ' model class', 'longDescription' => 'This is a model class generated with DavidePastore\\ParisModelGenerator.', 'tags' => $tags)); $idColumn = new PropertyGenerator('_id_column'); $idColumn->setStatic(true)->setDefaultValue($primaryKey); $table = new PropertyGenerator('_table'); $table->setStatic(true)->setDefaultValue($className); $tableUseShortName = new PropertyGenerator('_table_use_short_name'); $tableUseShortName->setStatic(true)->setDefaultValue(true); $namespace = $this->config->getNamespace(); $extendedClass = '\\Model'; if (isset($namespace) && !empty($namespace)) { $class->setNamespaceName($this->config->getNamespace()); } $class->setName(ucfirst($className))->setDocblock($docblock)->setExtendedClass($extendedClass)->addProperties(array($idColumn, $table, $tableUseShortName)); $file = FileGenerator::fromArray(array('classes' => array($class), 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => ucfirst($className) . ' class file', 'longDescription' => null, 'tags' => $tags)))); $generatedCode = $file->generate(); $directory = $this->config->getDestinationFolder() . $namespace; if (!file_exists($directory)) { mkdir($directory, 0777, true); } $filePath = $directory . "/" . $class->getName() . ".php"; if (file_exists($filePath) && !$this->force) { $helper = $this->getHelper('question'); $realPath = realpath($filePath); $this->output->writeln("\n"); $question = new ConfirmationQuestion('Do you want to overwrite the file "' . $realPath . '"?', false); if ($helper->ask($this->input, $this->output, $question)) { $this->writeInFile($filePath, $generatedCode); } } else { $this->writeInFile($filePath, $generatedCode); } }
/** * @param string $class * @param Entity $entity * * @return string */ protected function generateFileContent($class, $entity) { $generator = new FileGenerator(); $descriptor = $entity->getFileDescriptor(); $generator->setClass($class); $generator->setDocblock(DocBlockGenerator::fromArray(array('shortDescription' => 'Generated by Protobuf protoc plugin.', 'longDescription' => 'File descriptor : ' . $descriptor->getName()))); return $generator->generate(); }
/** * Metodo para criar docBlock para o metodo __construct * * @return DocBlockGenerator */ public function getDocBlockMethodConstruct() { $arrParameters = array_keys($this->arrForeignKeys); $arrTags = []; foreach ($arrParameters as $arrParameter) { $arrTags[] = new Tag\ParamTag($arrParameter, 'array', 'Valores da tabela ' . $this->arrForeignKeys[$arrParameter]['strColumns']); } return DocBlockGenerator::fromArray(array('shortDescription' => 'CategoriaFilter constructor.', 'tags' => $arrTags)); }