public function generate() { if ($this->controller) { $modelBuilder = $this->controller->getModelBuilder(); $className = $modelBuilder->getName(); } else { $className = $this->class; } $modelClass = $this->modelClass ? $this->modelClass : $this->class; $class = new ClassGenerator(); $class->setName($className); $class->setExtendedClass('CrudController'); $class->addUse('Boyhagemann\\Crud\\CrudController'); $class->addUse('Boyhagemann\\Form\\FormBuilder'); $class->addUse('Boyhagemann\\Model\\ModelBuilder'); $class->addUse('Boyhagemann\\Overview\\OverviewBuilder'); $param = new ParameterGenerator(); $param->setName('fb')->setType('FormBuilder'); $body = $this->generateFormBuilderBody(); $docblock = '@param FormBuilder $fb'; $class->addMethod('buildForm', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $param = new ParameterGenerator(); $param->setName('mb')->setType('ModelBuilder'); $body = sprintf('$mb->name(\'%s\')->table(\'%s\');' . PHP_EOL, $modelClass, strtolower(str_replace('\\', '_', $modelClass))); $docblock = '@param ModelBuilder $mb'; $class->addMethod('buildModel', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $param = new ParameterGenerator(); $param->setName('ob')->setType('OverviewBuilder'); $body = ''; $docblock = '@param OverviewBuilder $ob'; $class->addMethod('buildOverview', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $this->generator->setClass($class); return $this->generator->generate(); }
public function generate() { $modelBuilder = $this->controller->getModelBuilder(); $className = $modelBuilder->getName() . 'Controller'; $class = new ClassGenerator(); $class->setName($className); $class->setExtendedClass('CrudController'); $param = new ParameterGenerator(); $param->setName('fb')->setType('FormBuilder'); $body = $this->generateFormBuilderBody(); $docblock = '@param FormBuilder $fb'; $class->addMethod('buildForm', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $param = new ParameterGenerator(); $param->setName('mb')->setType('ModelBuilder'); $body = ''; $docblock = '@param ModelBuilder $mb'; $class->addMethod('buildModel', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $param = new ParameterGenerator(); $param->setName('ob')->setType('OverviewBuilder'); $body = ''; $docblock = '@param OverviewBuilder $ob'; $class->addMethod('buildOverview', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $this->generator->setClass($class); $this->generator->setUses(array('Boyhagemann\\Crud\\CrudController', 'Boyhagemann\\Form\\FormBuilder', 'Boyhagemann\\Model\\ModelBuilder', 'Boyhagemann\\Overview\\OverviewBuilder')); return $this->generator->generate(); }
private function writeParamFile() { $file = $this->path . DIRECTORY_SEPARATOR . 'Params.php'; if (file_exists($file) && class_exists($this->namespace . '\\Params')) { $class = new ClassReflection($this->namespace . '\\Params'); $paramsClass = ClassGenerator::fromReflection($class); } else { $paramsClass = new ClassGenerator('Params', $this->namespace, null, 'OpenStack\\Common\\Api\\AbstractParams'); } foreach ($this->operations as $operation) { $params = $operation['params']; if (empty($params)) { continue; } foreach ($params as $paramName => $paramVal) { $name = $paramName . ucfirst($paramVal['location']); if ($paramsClass->hasMethod($name)) { continue; } $body = sprintf("return %s;", $this->arrayEncoder->encode($paramVal, ['array.align' => true])); $body = str_replace("'\$", '$', $body); $body = str_replace("()'", '()', $body); $docblock = new DocBlockGenerator(sprintf("Returns information about %s parameter", $paramName), null, [new ReturnTag(['array'])]); $paramsClass->addMethod($name, [], MethodGenerator::FLAG_PUBLIC, $body, $docblock); } } $output = sprintf("<?php\n\n%s", $paramsClass->generate()); file_put_contents($file, $output); }
public function generate() { $gen = new ClassGenerator($this->name); $fnGetter = $this->fnGetter; foreach ($this->options["properties"] as $prop => $type) { $c = ucfirst($prop); $gen->addProperty($prop, null, PropertyGenerator::FLAG_PRIVATE); $gen->addMethod("get" . $c, [], MethodGenerator::FLAG_PUBLIC, $fnGetter($prop, $type), "???"); } return $gen->generate(); }
/** * @param \ReflectionClass $originalClass * @param ClassGenerator $classGenerator */ public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator) { $classGenerator->setExtendedClass('\\' . $originalClass->getName()); if ($originalClass->isSubclassOf(Collection::class)) { $reflectionMethod = new \ReflectionMethod($originalClass->getName(), 'getMetadata'); $className = $originalClass->getName(); $metadata = $reflectionMethod->invoke(new $className()); foreach ($metadata as $fieldName => $mappingClass) { $classGenerator->addMethod('get' . ucfirst($fieldName), [], MethodGenerator::FLAG_PUBLIC, '$this->mapProperty(\'' . $fieldName . '\');' . "\n" . 'return parent::get' . ucfirst($fieldName) . '();', '@return ' . $mappingClass); } } }
/** * Dynamically scope an audit class */ public function loadClass($auditClassName, $type) { $foundClassName = false; foreach ($this->getAuditEntities() as $className => $classOptions) { if ($this->getAuditObjectManager()->getRepository('ZF\\Doctrine\\Audit\\Entity\\AuditEntity')->generateClassName($className) == $auditClassName) { $foundClassName = true; break; } } if (!$foundClassName) { return false; } // Get fields from target entity $metadataFactory = $this->getObjectManager()->getMetadataFactory(); $auditedClassMetadata = $metadataFactory->getMetadataFor($className); $fields = $auditedClassMetadata->getFieldNames(); $identifiers = $auditedClassMetadata->getFieldNames(); $auditClass = new ClassGenerator(); $auditClass->setNamespaceName("ZF\\Doctrine\\Audit\\RevisionEntity"); $auditClass->setName(str_replace('\\', '_', $className)); $auditClass->setExtendedClass('AbstractAudit'); // Add revision reference getter and setter $auditClass->addProperty('revisionEntity', null, PropertyGenerator::FLAG_PROTECTED); $auditClass->addMethod('getRevisionEntity', array(), MethodGenerator::FLAG_PUBLIC, " return \$this->revisionEntity;"); $auditClass->addMethod('setRevisionEntity', array('value'), MethodGenerator::FLAG_PUBLIC, " \$this->revisionEntity = \$value;\n\nreturn \$this;\n "); // Generate audit entity foreach ($fields as $field) { $auditClass->addProperty($field, null, PropertyGenerator::FLAG_PROTECTED); } foreach ($auditedClassMetadata->getAssociationNames() as $associationName) { $auditClass->addProperty($associationName, null, PropertyGenerator::FLAG_PROTECTED); $fields[] = $associationName; } $auditClass->addMethod('getAssociationMappings', array(), MethodGenerator::FLAG_PUBLIC, "return unserialize('" . serialize($auditedClassMetadata->getAssociationMappings()) . "');"); // Add exchange array method $setters = array(); foreach ($fields as $fieldName) { $setters[] = '$this->' . $fieldName . ' = (isset($data["' . $fieldName . '"])) ? $data["' . $fieldName . '"]: null;'; $arrayCopy[] = " \"{$fieldName}\"" . ' => $this->' . $fieldName; } $auditClass->addMethod('getArrayCopy', array(), MethodGenerator::FLAG_PUBLIC, "return array(\n" . implode(",\n", $arrayCopy) . "\n);"); $auditClass->addMethod('exchangeArray', array('data'), MethodGenerator::FLAG_PUBLIC, implode("\n", $setters)); // Add function to return the entity class this entity audits $auditClass->addMethod('getAuditedEntityClass', array(), MethodGenerator::FLAG_PUBLIC, " return '" . addslashes($className) . "';"); eval($auditClass->generate()); return true; }
protected function addMethodsFromAbstractClass($classToExtends, ClassGenerator $classGenerator) { //Add methods from interface $reflection = new \ReflectionClass($classToExtends); foreach ($reflection->getMethods() as $method) { if (FALSE === $method->isAbstract()) { continue; } $staticFlag = $method->isStatic() ? MethodGenerator::FLAG_STATIC : NULL; $publicFlag = $method->isPublic() ? MethodGenerator::FLAG_PUBLIC : NULL; $privateFlag = $method->isPrivate() ? MethodGenerator::FLAG_PRIVATE : NULL; $protectedFlag = $method->isProtected() ? MethodGenerator::FLAG_PROTECTED : NULL; //Get parameters for each method to add from interface $reflectionParameters = $method->getParameters(); $parameters = []; /** @var \ReflectionParameter $tmpParameter */ foreach ($reflectionParameters as $tmpParameter) { $par = $this->getParametersForFunction($tmpParameter); $parameters[] = $par; } //Add the method to given class $classGenerator->addMethod($method->getName(), $parameters, [$staticFlag, $publicFlag, $privateFlag, $protectedFlag]); } }
/** * @group ZF-7361 */ public function testHasMethod() { $classGenerator = new ClassGenerator(); $classGenerator->addMethod('methodOne'); $this->assertTrue($classGenerator->hasMethod('methodOne')); }
/** * Dynamically scope an audit class * * @param string $className * @return false|string */ public function loadClass($className, $type) { $moduleOptions = \ZF\Doctrine\Audit\Module::getModuleOptions(); if (!$moduleOptions) { return; } $entityManager = $moduleOptions->getEntityManager(); $auditClass = new ClassGenerator(); // Build a discovered many to many join class $joinClasses = $moduleOptions->getJoinClasses(); if (in_array($className, array_keys($joinClasses))) { $auditClass->setNamespaceName("ZF\\Doctrine\\Audit\\Entity"); $auditClass->setName($className); $auditClass->setExtendedClass('AbstractAudit'); $auditClass->addProperty('id', null, PropertyGenerator::FLAG_PROTECTED); $auditClass->addProperty('targetRevisionEntity', null, PropertyGenerator::FLAG_PROTECTED); $auditClass->addProperty('sourceRevisionEntity', null, PropertyGenerator::FLAG_PROTECTED); $auditClass->addMethod('getTargetRevisionEntity', array(), MethodGenerator::FLAG_PUBLIC, 'return $this->targetRevisionEntity;'); $auditClass->addMethod('getSourceRevisionEntity', array(), MethodGenerator::FLAG_PUBLIC, 'return $this->sourceRevisionEntity;'); $auditClass->addMethod('getId', array(), MethodGenerator::FLAG_PUBLIC, 'return $this->id;'); $auditClass->addMethod('setTargetRevisionEntity', array(ParameterGenerator::fromArray(array('name' => 'value', 'type' => '\\ZF\\Doctrine\\Audit\\Entity\\RevisionEntity'))), MethodGenerator::FLAG_PUBLIC, '$this->targetRevisionEntity = $value;' . "\n" . 'return $this;'); $auditClass->addMethod('setSourceRevisionEntity', array(ParameterGenerator::fromArray(array('name' => 'value', 'type' => '\\ZF\\Doctrine\\Audit\\Entity\\RevisionEntity'))), MethodGenerator::FLAG_PUBLIC, '$this->sourceRevisionEntity = $value;' . "\n" . 'return $this;'); # print_r($auditClass->generate()); # die(); eval($auditClass->generate()); return; } // Add revision reference getter and setter $auditClass->addProperty($moduleOptions->getRevisionEntityFieldName(), null, PropertyGenerator::FLAG_PROTECTED); $auditClass->addMethod('get' . $moduleOptions->getRevisionEntityFieldName(), array(), MethodGenerator::FLAG_PUBLIC, " return \$this->" . $moduleOptions->getRevisionEntityFieldName() . ";"); $auditClass->addMethod('set' . $moduleOptions->getRevisionEntityFieldName(), array('value'), MethodGenerator::FLAG_PUBLIC, " \$this->" . $moduleOptions->getRevisionEntityFieldName() . " = \$value;\nreturn \$this;\r\n "); // Verify this autoloader is used for target class #FIXME: why is this sent work outside the set namespace? foreach ($moduleOptions->getAuditedClassNames() as $targetClass => $targetClassOptions) { $auditClassName = 'ZF\\Doctrine\\Audit\\Entity\\' . str_replace('\\', '_', $targetClass); if ($auditClassName == $className) { $currentClass = $targetClass; } $autoloadClasses[] = $auditClassName; } if (!in_array($className, $autoloadClasses)) { return; } // Get fields from target entity $metadataFactory = $entityManager->getMetadataFactory(); $auditedClassMetadata = $metadataFactory->getMetadataFor($currentClass); $fields = $auditedClassMetadata->getFieldNames(); $identifiers = $auditedClassMetadata->getFieldNames(); $service = \ZF\Doctrine\Audit\Module::getModuleOptions()->getAuditService(); // Generate audit entity foreach ($fields as $field) { $auditClass->addProperty($field, null, PropertyGenerator::FLAG_PROTECTED); } foreach ($auditedClassMetadata->getAssociationNames() as $associationName) { $auditClass->addProperty($associationName, null, PropertyGenerator::FLAG_PROTECTED); $fields[] = $associationName; } $auditClass->addMethod('getAssociationMappings', array(), MethodGenerator::FLAG_PUBLIC, "return unserialize('" . serialize($auditedClassMetadata->getAssociationMappings()) . "');"); // Add exchange array method $setters = array(); foreach ($fields as $fieldName) { $setters[] = '$this->' . $fieldName . ' = (isset($data["' . $fieldName . '"])) ? $data["' . $fieldName . '"]: null;'; $arrayCopy[] = " \"{$fieldName}\"" . ' => $this->' . $fieldName; } $auditClass->addMethod('getArrayCopy', array(), MethodGenerator::FLAG_PUBLIC, "return array(\n" . implode(",\n", $arrayCopy) . "\n);"); $auditClass->addMethod('exchangeArray', array('data'), MethodGenerator::FLAG_PUBLIC, implode("\n", $setters)); // Add function to return the entity class this entity audits $auditClass->addMethod('getAuditedEntityClass', array(), MethodGenerator::FLAG_PUBLIC, " return '" . addslashes($currentClass) . "';"); $auditClass->setNamespaceName("ZF\\Doctrine\\Audit\\Entity"); $auditClass->setName(str_replace('\\', '_', $currentClass)); $auditClass->setExtendedClass('AbstractAudit'); # $auditedClassMetadata = $metadataFactory->getMetadataFor($currentClass); $auditedClassMetadata = $metadataFactory->getMetadataFor($currentClass); foreach ($auditedClassMetadata->getAssociationMappings() as $mapping) { if (isset($mapping['joinTable']['name'])) { $auditJoinTableClassName = "ZF\\Doctrine\\Audit\\Entity\\" . str_replace('\\', '_', $mapping['joinTable']['name']); $auditEntities[] = $auditJoinTableClassName; $moduleOptions->addJoinClass($auditJoinTableClassName, $mapping); } } # if ($auditClass->getName() == 'AppleConnect_Entity_UserAuthenticationLog') { # echo '<pre>'; # echo($auditClass->generate()); # die(); # } eval($auditClass->generate()); # die(); return true; }
/** * @param ClassGenerator $class */ private function generateGenericMethods(ClassGenerator $class) { $class->addMethod('__construct', [new ParameterGenerator('manager', 'ManagerInterface'), new ParameterGenerator('host', 'HostInterface'), new ParameterGenerator('ref')], MethodGenerator::FLAG_PUBLIC, '$this->manager = $manager;' . PHP_EOL . '$this->host = $host;' . PHP_EOL . '$this->ref = $ref;' . PHP_EOL); $class->addMethod('__proxy_run', ['cmd', 'name', 'args=[]'], MethodGenerator::FLAG_PRIVATE, '$args = $this->manager->insertProxyMarker($args);' . PHP_EOL . '$this->host->getTransport()->send([' . PHP_EOL . ' C::REF => $this->ref,' . PHP_EOL . ' C::CMD => $cmd,' . PHP_EOL . ' C::NAME => $name,' . PHP_EOL . ' C::ARGS => $args,' . PHP_EOL . ']);' . PHP_EOL . '// restore possible ProxyMarker in object properties of a TransferObject' . PHP_EOL . '$this->manager->restoreWithoutProxyMarker($args);' . PHP_EOL . 'return $this->host->run();' . PHP_EOL); $class->addMethod('__call', ['name', 'args'], MethodGenerator::FLAG_PUBLIC, 'return $this->__proxy_run(C::CALL, $name, $args);'); $class->addMethod('__set', ['name', 'value'], MethodGenerator::FLAG_PUBLIC, 'return $this->__proxy_run(C::SET, $name, $value);'); $class->addMethod('__get', ['name'], MethodGenerator::FLAG_PUBLIC, 'return $this->__proxy_run(C::GET, $name);'); $class->addMethod('__isset', ['name'], MethodGenerator::FLAG_PUBLIC, 'return $this->__proxy_run(C::CISSET, $name);'); $class->addMethod('__unset', ['name'], MethodGenerator::FLAG_PUBLIC, 'return $this->__proxy_run(C::CUNSET, $name);'); }
/** * 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; }
/** * Append Properties, Getter and Setter to Model class * * @param Generator\ClassGenerator $class * @param array $properties * @param array $hydratorStrategy */ protected function addProperties(Generator\ClassGenerator &$class, array $properties) { foreach ($properties as $metadata) { $propertyInfos = $this->getNormalizedFilterOrProperty($metadata); $name = $propertyInfos['name']; $required = $propertyInfos['required']; $lazyLoading = $propertyInfos['lazyLoading']; $dataType = $propertyInfos['dataType']; $defaultValue = $propertyInfos['defaultValue']; $description = $propertyInfos['description']; $flags = Generator\PropertyGenerator::FLAG_PROTECTED; foreach ($propertyInfos['uses'] as $use) { $class->addUse($use); } $property = new Generator\PropertyGenerator($name); $property->setFlags($flags); if (!empty($defaultValue) or 'bool' === $dataType) { $property->setDefaultValue($defaultValue, $dataType); } $property->setDocBlock(new Generator\DocBlockGenerator($description)); $class->addPropertyFromGenerator($property); // Add Setter method $setterParam = new Generator\ParameterGenerator($name, true === $lazyLoading ? null : $dataType); if (!$required) { $setterParam->setDefaultValue(null); } $setterBody = ''; if (true === $lazyLoading) { if ($dataType == "ResultSet") { $class->addUse('Mailjet\\Api\\ResultSet\\Exception'); $setterBody .= sprintf('if (! ($%s instanceof \\Closure || $%s instanceof %s)) {' . PHP_EOL . ' throw new Exception\\InvalidArgumentException("%s must be an instance of \'%s\' or \\Closure");' . PHP_EOL . '}' . PHP_EOL . PHP_EOL, $name, $name, $dataType, $name, $dataType); } else { $setterBody .= sprintf('if (! ($%s instanceof \\Closure || $%s instanceof %s)) {' . PHP_EOL . ' throw new Exception\\InvalidArgumentException("$%s must be an instance of \'%s\' or \\Closure");' . PHP_EOL . '}' . PHP_EOL . PHP_EOL, $name, $name, $dataType, $name, $dataType); } } $setterBody .= sprintf('$this->%s = $%s;' . PHP_EOL . 'return $this;' . PHP_EOL, $name, $name); $class->addMethod('set' . ucfirst($name), array($setterParam), Generator\MethodGenerator::FLAG_PUBLIC, $setterBody, new Generator\DocBlockGenerator("Sets the " . $property->getDocBlock()->getShortDescription(), '', array(new ParamTag(array('name' => $name, 'datatype' => $dataType)), new ReturnTag(array('datatype' => $class->getName()))))); // Add Getter method $getterBody = ''; if (true === $lazyLoading) { $getterBody .= sprintf('if ($this->%s instanceof \\Closure) {' . PHP_EOL . ' $this->%s = call_user_func($this->%s);' . PHP_EOL . '}' . PHP_EOL . 'if (! $this->%s instanceof %s) {' . PHP_EOL . ' $this->%s = new %s();' . PHP_EOL . '}' . PHP_EOL . PHP_EOL, $name, $name, $name, $name, $dataType, $name, $dataType); } $getterBody .= sprintf('return $this->%s;', $name); $class->addMethod('get' . ucfirst($name), array(), Generator\MethodGenerator::FLAG_PUBLIC, $getterBody, new Generator\DocBlockGenerator('Gets the ' . $property->getDocBlock()->getShortDescription(), '', array(new ReturnTag(array('datatype' => $dataType))))); // If DataType Resulset => add/remove methods if ('ResultSet' === $dataType) { $class->addMethod('add' . ucfirst($name) . 'Item', array(new Generator\ParameterGenerator('item', $propertyInfos['model'])), Generator\MethodGenerator::FLAG_PUBLIC, sprintf('return $this->get%s()->add($item);' . PHP_EOL, ucfirst($name)), new Generator\DocBlockGenerator('Add new item to ' . ucfirst($name), '', array(new ReturnTag(array('datatype' => 'bool'))))); $class->addMethod('remove' . ucfirst($name) . 'Item', array(new Generator\ParameterGenerator('item', $propertyInfos['model'])), Generator\MethodGenerator::FLAG_PUBLIC, sprintf('return $this->get%s()->remove($item);' . PHP_EOL, ucfirst($name)), new Generator\DocBlockGenerator('Remove $item from ' . ucfirst($name), '', array(new ReturnTag(array('datatype' => 'bool'))))); } } }
public function testGenerateClassAndAddMethod() { $classGenerator = new ClassGenerator(); $classGenerator->setName('MyClass'); $classGenerator->addMethod('methodOne'); $expected = <<<CODE class MyClass { public function methodOne() { } } CODE; $output = $classGenerator->generate(); $this->assertEquals($expected, $output); }