/** * @param string $requestMethod * @param Config $action * @param ParameterGenerator[] $params * * @return DocBlockGenerator */ private function createDocblockForMethod($requestMethod, $action, $params) { if (empty($action->doc)) { $action->doc = 'TODO'; } /* * $action->doc * METHOD: /{url:[a-z]+} */ $docblock = new DocBlockGenerator($action->doc, strtoupper($requestMethod) . ': ' . $action->url); foreach ($params as $param) { /* * @param $paramName */ $docblock->setTag(new GenericTag('param', "\${$param->getName()}")); } if (!empty($action->throws)) { /* * @throws \Name\Space\Version\Exceptions\EntityName\SomethingException */ $docblock->setTag(new GenericTag('throws', sprintf("\\%s\\%s\\Exceptions\\%s\\%s", Generator::$namespace, $this->version, $this->entityName, $action->throws->exception))); } if (!empty($action->returns)) { /* * @returns \Name\Space\Version\EntityName\EntityName(s)?Response */ $docblock->setTag(new GenericTag('returns', sprintf("\\%s\\%s\\Responses\\%s\\%s", Generator::$namespace, $this->version, $this->entityName, $action->returns))); } return $docblock; }
/** * @param State|\Scaffold\State $state * @return State|void */ public function build(State $state) { $model = $state->getModel('options-factory'); $generator = new ClassGenerator($model->getName()); $generator->setImplementedInterfaces(['FactoryInterface']); $model->setGenerator($generator); $generator->addUse('Zend\\ServiceManager\\FactoryInterface'); $generator->addUse('Zend\\ServiceManager\\ServiceLocatorInterface'); $options = $state->getModel('options'); $key = $options->getServiceName(); $key = substr($key, 0, -7); $body = <<<EOF \$config = \$serviceLocator->get('Config'); return new {$options->getClassName()}( isset(\$config['{$key}']) ? \$config['{$key}'] : [] ); EOF; $method = new MethodGenerator('createService'); $method->setParameter(new ParameterGenerator('serviceLocator', 'ServiceLocatorInterface')); $method->setBody($body); $doc = new DocBlockGenerator(''); $doc->setTag(new Tag(['name' => 'inhertidoc'])); $method->setDocBlock($doc); $generator->addMethodFromGenerator($method); }
protected function getClassDocBlock(State $state) { $repository = $state->getRepositoryModel()->getName(); $doc = new DocBlockGenerator(); $doc->setTag(new Tag\GenericTag('ORM\\Entity(repositoryClass="' . $repository . '")')); $doc->setTag(new Tag\GenericTag('ORM\\Table(name="' . strtolower($this->config->getName()) . '")')); return $doc; }
public function generate(Generator\ClassGenerator $class, PHPClass $type) { $class = $this->fixInterfaces($class); if (!($extends = $type->getExtends()) && class_exists($type->getNamespace())) { $extendNamespace = $type->getNamespace(); $extendNamespace = explode('\\', $extendNamespace); $extendClass = array_pop($extendNamespace); $extendNamespace = implode('\\', $extendNamespace); $extends = new PHPClass(); $extends->setName($extendClass); $extends->setNamespace($extendNamespace); $class->setExtendedClass($extends); } if ($type->getNamespace() == Enumeration::class) { $extendNamespace = $type->getNamespace(); $extendNamespace = explode('\\', $extendNamespace); $extendClass = array_pop($extendNamespace); $extendNamespace = implode('\\', $extendNamespace); $extends = new PHPClass(); $extends->setName($extendClass); $extends->setNamespace($extendNamespace); $class->setExtendedClass($extends); } if ($extends->getName() == "string" && $extends->getNamespace() == "" && class_exists($type->getNamespace() . '\\String')) { $extends->setName('String'); $extends->setNamespace($type->getNamespace()); } elseif ($extends->getName() == "string" && $extends->getNamespace() == "" && class_exists($type->getNamespace())) { $extendNamespace = $type->getNamespace(); $extendNamespace = explode('\\', $extendNamespace); $extendClass = array_pop($extendNamespace); $extendNamespace = implode('\\', $extendNamespace); $extends = new PHPClass(); $extends->setName($extendClass); $extends->setNamespace($extendNamespace); $class->setExtendedClass($extends); } $docblock = new DocBlockGenerator("Class representing " . $type->getName()); if ($type->getDoc()) { $docblock->setLongDescription($type->getDoc()); } $class->setNamespaceName($type->getNamespace()); $class->setName($type->getName()); $class->setDocblock($docblock); $class->setExtendedClass($extends->getName()); if ($extends->getNamespace() != $type->getNamespace()) { if ($extends->getName() == $type->getName()) { $class->addUse($type->getExtends()->getFullName(), $extends->getName() . "Base"); $class->setExtendedClass($extends->getName() . "Base"); } else { $class->addUse($extends->getFullName()); } } if ($this->handleBody($class, $type)) { return true; } }
/** * Build method factory * * @param ClassGenerator $generator * @param \Scaffold\State $state */ public function buildFactory(ClassGenerator $generator, State $state) { $repository = ucfirst($state->getRepositoryModel()->getClassName()); $docBlock = new DocBlockGenerator(); $docBlock->setTag(new Tag\GenericTag('return', $this->config->getName())); $factory = new MethodGenerator(); $factory->setDocBlock($docBlock); $factory->setName('factory'); $factory->setBody('return $this->get' . $repository . '()->factory();'); $generator->addMethodFromGenerator($factory); }
/** * FileGenerator constructor. */ public function __construct() { parent::__construct(); $mockTag = new GenericTag(); $mockTag->setName('mock'); $author = new AuthorTag('ClassMocker'); $docBlock = new DocBlockGenerator(); $docBlock->setShortDescription("Auto generated file by ClassMocker, do not change"); $docBlock->setTag($author); $docBlock->setTag($mockTag); $this->setDocBlock($docBlock); }
/** * @param type $name * @param type $type * @param type $docString * @return PhpProperty */ public function addProperty($name, $type, $docString) { $property = new PropertyGenerator(); $docblock = new DocBlockGenerator(); $property->setName($name); $property->setVisibility(PropertyGenerator::VISIBILITY_PROTECTED); $docblock->setShortDescription($docString); $docblock->setTag(new Tag(array('name' => 'var', 'description' => $type))); $property->setDocblock($docblock); $this->addPropertyFromGenerator($property); return $property; }
/** * @param $name * @param ParameterGenerator[] $params * @param string $visibility * @param string $body * @param string|DocBlockGenerator $docblock * * @return \Zend\Code\Generator\MethodGenerator */ public static function method($name, $params = [], $visibility = 'public', $body = '//todo', $docblock = '') { if (empty($docblock)) { if (!empty($params)) { $docblock = new DocBlockGenerator(); foreach ($params as $param) { $tag = new Tag('param', $param->getType() . ' $' . $param->getName()); $docblock->setTag($tag); } } } return (new MethodGenerator($name, $params))->setBody($body)->setVisibility($visibility)->setDocBlock($docblock)->setIndentation(Generator::$indentation); }
/** * * @param DTDDocument $document * @param string $outputDirectory * @param string $namespace * @param string $parentClass */ public function generate(DTDDocument $document, $outputDirectory, $namespace, $parentClass) { if (!file_exists($outputDirectory)) { mkdir($outputDirectory, 0777, true); } $name = ucfirst($document->getFileInfo()->getBasename('.dtd')); $filename = sprintf("%s/%s.php", $outputDirectory, $name); $classGenerator = new ClassGenerator($name, $namespace, null, $parentClass); $fileGenerator = new FileGenerator(); $fileGenerator->setClass($classGenerator); $fileDocblock = new DocBlockGenerator(sprintf("%s %s", str_replace("\\", " ", $namespace), $name)); $fileDocblock->setTag(new Tag("author", "Generator")); $fileDocblock->setTag(new Tag("licence", "LGPL")); $fileGenerator->setDocBlock($fileDocblock); file_put_contents($filename, $fileGenerator->generate()); }
/** * fromReflection() * * @param MethodReflection $reflectionMethod * @return MethodGenerator */ public static function fromReflection(MethodReflection $reflectionMethod) { $method = new self(); $method->setSourceContent($reflectionMethod->getContents(false)); $method->setSourceDirty(false); if ($reflectionMethod->getDocComment() != '') { $method->setDocBlock(DocBlockGenerator::fromReflection($reflectionMethod->getDocBlock())); } $method->setFinal($reflectionMethod->isFinal()); if ($reflectionMethod->isPrivate()) { $method->setVisibility(self::VISIBILITY_PRIVATE); } elseif ($reflectionMethod->isProtected()) { $method->setVisibility(self::VISIBILITY_PROTECTED); } else { $method->setVisibility(self::VISIBILITY_PUBLIC); } $method->setStatic($reflectionMethod->isStatic()); $method->setName($reflectionMethod->getName()); foreach ($reflectionMethod->getParameters() as $reflectionParameter) { $method->setParameter(ParameterGenerator::fromReflection($reflectionParameter)); } $method->setBody($reflectionMethod->getBody()); return $method; }
/** * 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; }
/** * fromReflection() * * @param PropertyReflection $reflectionProperty * @return PropertyGenerator */ public static function fromReflection(PropertyReflection $reflectionProperty) { $property = new self(); $property->setName($reflectionProperty->getName()); $allDefaultProperties = $reflectionProperty->getDeclaringClass()->getDefaultProperties(); $property->setDefaultValue($allDefaultProperties[$reflectionProperty->getName()]); if ($reflectionProperty->getDocComment() != '') { $property->setDocBlock(DocBlockGenerator::fromReflection($reflectionProperty->getDocComment())); } if ($reflectionProperty->isStatic()) { $property->setStatic(true); } if ($reflectionProperty->isPrivate()) { $property->setVisibility(self::VISIBILITY_PRIVATE); } elseif ($reflectionProperty->isProtected()) { $property->setVisibility(self::VISIBILITY_PROTECTED); } else { $property->setVisibility(self::VISIBILITY_PUBLIC); } $property->setSourceDirty(false); return $property; }
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(); }
/** * @group #3753 */ public function testGenerateWithWordWrapDisabled() { $largeStr = '@var This is a very large string that will not be wrapped if it contains more than 80 characters'; $this->docBlockGenerator->setLongDescription($largeStr); $this->docBlockGenerator->setWordWrap(false); $expected = '/**' . DocBlockGenerator::LINE_FEED . ' * @var This is a very large string that will not be wrapped if it contains more than' . ' 80 characters' . DocBlockGenerator::LINE_FEED . ' */' . DocBlockGenerator::LINE_FEED; $this->assertEquals($expected, $this->docBlockGenerator->generate()); }
public function testGenerationOfDocBlock() { $this->docBlockGenerator->setShortDescription('@var Foo this is foo bar'); $expected = '/**' . DocBlockGenerator::LINE_FEED . ' * @var Foo this is foo bar' . DocBlockGenerator::LINE_FEED . ' */' . DocBlockGenerator::LINE_FEED; $this->assertEquals($expected, $this->docBlockGenerator->generate()); }
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; }
/** * @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)]]])])); }
/** * Build generators * * @param State|\Scaffold\State $state * @return \Scaffold\State|void */ public function build(State $state) { $model = $this->model; $generator = new ClassGenerator($model->getName()); $generator->addUse('Zend\\ServiceManager\\FactoryInterface'); $generator->addUse('Zend\\ServiceManager\\ServiceLocatorInterface'); $generator->addUse('Zend\\ServiceManager\\ServiceManager'); $generator->addUse($state->getServiceModel()->getName()); $generator->setImplementedInterfaces(['FactoryInterface']); $method = new MethodGenerator('createService'); $method->setParameter(new ParameterGenerator('serviceLocator', 'ServiceLocatorInterface')); $method->setBody('return new ' . $state->getServiceModel()->getClassName() . '($serviceLocator);'); $doc = new DocBlockGenerator('Create service'); $doc->setTag(new Tag\GenericTag('param', 'ServiceLocatorInterface|ServiceManager $serviceLocator')); $doc->setTag(new Tag\GenericTag('return', $state->getServiceModel()->getClassName())); $method->setDocBlock($doc); $generator->addMethodFromGenerator($method); $model->setGenerator($generator); }
/** * @param string $className * @return ClassGenerator */ public function handle(string $className) { if (!preg_match(static::MATCH_PATTERN, $className, $matches)) { return null; } $baseName = $matches[1]; $namespace = $this->deriveNamespaceFromClassName($className); $typeName = "{$namespace}\\{$baseName}"; $reflectedClass = new ReflectionClass($typeName); if ($reflectedClass->isTrait() === true || $reflectedClass->isAbstract() === true) { return null; } $class = $this->getClassTemplate(); $class->setNamespaceName($namespace)->setName($baseName . $class->getName()); $propertyDocBlock = new DocBlockGenerator(null, null, array(array("name" => "var", "content" => "\\{$typeName}"))); $class->getProperty("_instance")->setDocBlock($propertyDocBlock); $methodDocBlock = new DocBlockGenerator(); $returnTag = new ReturnTag("\\{$typeName}"); $methodDocBlock->setTag($returnTag); $instanceMethod = $class->getMethod("_getInstance"); $instanceMethod->setDocBlock($methodDocBlock)->setReturnType($typeName); if ($reflectedClass->isInterface() === true) { $class->setImplementedInterfaces(array("\\{$typeName}")); } else { $class->setExtendedClass("\\{$typeName}"); } $publicMethods = $reflectedClass->getMethods(ReflectionMethod::IS_PUBLIC); $addMethods = array(); foreach ($publicMethods as $method) { if ($method->isConstructor() || $method->isDestructor() || $method->isFinal() || $method->isStatic()) { continue; } if ($method->getName() === "__clone") { continue; } $addMethods[] = $this->getMethodDetails($method); } $class->addMethods($addMethods); $this->makeExtraModifications($class, $typeName); return $class; }
/** * (non-PHPdoc) * * @see \Symfony\Component\Console\Command\Command::execute() */ public function execute(InputInterface $input, OutputInterface $output) { $document = $this->getDocument($input->getArgument('document')); $directory = $input->getArgument('output'); $namespace = $input->getArgument('namespace'); $parentClass = $input->getArgument('parentClass'); if (!file_exists($directory)) { mkdir($directory, 0777, true); } $name = ucfirst($document->getFileInfo()->getBasename('.dtd')); $output->writeln("Generating Document " . $name); $filename = sprintf("%s/%s.php", $directory, $name); $classGenerator = new ClassGenerator($name, $namespace, null, $parentClass); $fileGenerator = new FileGenerator(); $fileGenerator->setClass($classGenerator); $fileDocblock = new DocBlockGenerator(sprintf("%s %s", str_replace("\\", " ", $namespace), $name)); $fileDocblock->setTag(new Tag("author", "Generator")); $fileDocblock->setTag(new Tag("licence", "LGPL")); $fileGenerator->setDocBlock($fileDocblock); file_put_contents($filename, $fileGenerator->generate()); }
/** * @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; }
/** * @param \Model\Generator\Part\Model|\Model\Generator\Part\PartInterface $part */ public function preRun(PartInterface $part) { /** * @var $file \Model\Code\Generator\FileGenerator */ $file = $part->getFile(); /** @var Table $table */ $table = $part->getTable(); /** @var string $tableName */ //$tableName = $table->getName(); /** @var $linkList|Link[] \Model\Cluster\Schema\Table\Column */ //$linkList = $table->getLink(); if ($table->isTree()) { $names = array('WITH_CHILD', 'WITH_CHILD_COLLECTION', 'WITH_ALL_CHILD', 'WITH_ALL_CHILD_COLLECTION'); foreach ($names as $name) { $property = new PropertyGenerator($name, strtolower($name), PropertyGenerator::FLAG_CONSTANT); $tags = array(array('name' => 'const'), array('name' => 'var', 'description' => 'string')); $docblock = new DocBlockGenerator('WITH entity for child list'); $docblock->setTags($tags); $property->setDocBlock($docblock); $file->getClass()->addPropertyFromGenerator($property); } } }
/** * @override enforces generation of \ProxyManager\Generator\MethodGenerator * * {@inheritDoc} */ public static function fromReflection(MethodReflection $reflectionMethod) { /* @var $method self */ $method = new static(); $method->setSourceContent($reflectionMethod->getContents(false)); $method->setSourceDirty(false); if ($reflectionMethod->getDocComment() != '') { $method->setDocBlock(DocBlockGenerator::fromReflection($reflectionMethod->getDocBlock())); } $method->setFinal($reflectionMethod->isFinal()); $method->setVisibility(self::extractVisibility($reflectionMethod)); foreach ($reflectionMethod->getParameters() as $reflectionParameter) { $method->setParameter(ParameterGenerator::fromReflection($reflectionParameter)); } $method->setStatic($reflectionMethod->isStatic()); $method->setName($reflectionMethod->getName()); $method->setBody($reflectionMethod->getBody()); $method->setReturnsReference($reflectionMethod->returnsReference()); return $method; }
/** * 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()))))); }
/** * @param FileReflection $fileReflection * @return FileGenerator */ public static function fromReflection(FileReflection $fileReflection) { $file = new static(); $file->setSourceContent($fileReflection->getContents()); $file->setSourceDirty(false); $uses = $fileReflection->getUses(); foreach ($fileReflection->getClasses() as $class) { $phpClass = ClassGenerator::fromReflection($class); $phpClass->setContainingFileGenerator($file); foreach ($uses as $fileUse) { $phpClass->addUse($fileUse['use'], $fileUse['as']); } $file->setClass($phpClass); } $namespace = $fileReflection->getNamespace(); if ($namespace != '') { $file->setNamespace($namespace); } if ($uses) { $file->setUses($uses); } if ($fileReflection->getDocComment() != '') { $docBlock = $fileReflection->getDocBlock(); $file->setDocBlock(DocBlockGenerator::fromReflection($docBlock)); } return $file; }
/** * @param FileReflection $fileReflection * @return FileGenerator */ public static function fromReflection(FileReflection $fileReflection) { $file = new static(); $file->setSourceContent($fileReflection->getContents()); $file->setSourceDirty(false); $body = $fileReflection->getContents(); foreach ($fileReflection->getClasses() as $class) { $phpClass = ClassGenerator::fromReflection($class); $phpClass->setContainingFileGenerator($file); $file->setClass($phpClass); $classStartLine = $class->getStartLine(true); $classEndLine = $class->getEndLine(); $bodyLines = explode("\n", $body); $bodyReturn = array(); for ($lineNum = 1, $count = count($bodyLines); $lineNum <= $count; $lineNum++) { if ($lineNum == $classStartLine) { $bodyReturn[] = str_replace('?', $class->getName(), '/* Zend_Code_Generator_Php_File-ClassMarker: {?} */'); $lineNum = $classEndLine; } else { $bodyReturn[] = $bodyLines[$lineNum - 1]; // adjust for index -> line conversion } } $body = implode("\n", $bodyReturn); unset($bodyLines, $bodyReturn, $classStartLine, $classEndLine); } $namespace = $fileReflection->getNamespace(); if ($namespace != '') { $file->setNamespace($namespace); } $uses = $fileReflection->getUses(); if ($uses) { $file->setUses($uses); } if ($fileReflection->getDocComment() != '') { $docBlock = $fileReflection->getDocBlock(); $file->setDocBlock(DocBlockGenerator::fromReflection($docBlock)); $bodyLines = explode("\n", $body); $bodyReturn = array(); for ($lineNum = 1, $count = count($bodyLines); $lineNum <= $count; $lineNum++) { if ($lineNum == $docBlock->getStartLine()) { $bodyReturn[] = str_replace('?', $class->getName(), '/* Zend_Code_Generator_FileGenerator-DocBlockMarker */'); $lineNum = $docBlock->getEndLine(); } else { $bodyReturn[] = $bodyLines[$lineNum - 1]; // adjust for index -> line conversion } } $body = implode("\n", $bodyReturn); unset($bodyLines, $bodyReturn, $classStartLine, $classEndLine); } $file->setBody($body); return $file; }
/** * @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; }