public function testGenerateIsCorrect() { $parameterGenerator = new ParameterGenerator(); $parameterGenerator->setType('Foo'); $parameterGenerator->setName('bar'); $parameterGenerator->setDefaultValue(15); $this->assertEquals('Foo $bar = 15', $parameterGenerator->generate()); $parameterGenerator->setDefaultValue('foo'); $this->assertEquals('Foo $bar = \'foo\'', $parameterGenerator->generate()); }
/** * @param ParameterReflection $reflectionParameter * @return ParameterGenerator */ public static function fromReflection(ParameterReflection $reflectionParameter) { $param = new ParameterGenerator(); $param->setName($reflectionParameter->getName()); if ($reflectionParameter->isArray()) { $param->setType('array'); } elseif (method_exists($reflectionParameter, 'isCallable') && $reflectionParameter->isCallable()) { $param->setType('callable'); } else { $typeClass = $reflectionParameter->getClass(); if ($typeClass) { $parameterType = $typeClass->getName(); $currentNamespace = $reflectionParameter->getDeclaringClass()->getNamespaceName(); if (!empty($currentNamespace) && substr($parameterType, 0, strlen($currentNamespace)) == $currentNamespace) { $parameterType = substr($parameterType, strlen($currentNamespace) + 1); } else { $parameterType = '\\' . trim($parameterType, '\\'); } $param->setType($parameterType); } } $param->setPosition($reflectionParameter->getPosition()); if ($reflectionParameter->isOptional()) { $param->setDefaultValue($reflectionParameter->getDefaultValue()); } $param->setPassedByReference($reflectionParameter->isPassedByReference()); return $param; }
/** * Creates a new {@link \bitExpert\Disco\Proxy\Configuration\MethodGenerator\GetParameter}. * * @param ReflectionClass $originalClass * @param ParameterValuesProperty $parameterValueProperty * @throws InvalidArgumentException */ public function __construct(ReflectionClass $originalClass, ParameterValuesProperty $parameterValueProperty) { parent::__construct('getParameter'); $propertyNameParameter = new ParameterGenerator('propertyName'); $requiredParameter = new ParameterGenerator('required'); $requiredParameter->setDefaultValue(true); $defaultValueParameter = new ParameterGenerator('defaultValue'); $defaultValueParameter->setDefaultValue(null); $body = '$steps = explode(\'.\', $' . $propertyNameParameter->getName() . ');' . PHP_EOL; $body .= '$value = $this->' . $parameterValueProperty->getName() . ';' . PHP_EOL; $body .= '$currentPath = [];' . PHP_EOL; $body .= 'foreach ($steps as $step) {' . PHP_EOL; $body .= ' $currentPath[] = $step;' . PHP_EOL; $body .= ' if (isset($value[$step])) {' . PHP_EOL; $body .= ' $value = $value[$step];' . PHP_EOL; $body .= ' } else {' . PHP_EOL; $body .= ' $value = $' . $defaultValueParameter->getName() . ';' . PHP_EOL; $body .= ' break;' . PHP_EOL; $body .= ' }' . PHP_EOL; $body .= '}' . PHP_EOL . PHP_EOL; $body .= 'if ($' . $requiredParameter->getName() . ' && (null === $value)) {' . PHP_EOL; $body .= ' if (null === $' . $defaultValueParameter->getName() . ') {' . PHP_EOL; $body .= ' throw new \\RuntimeException(\'Parameter "\' .$' . $propertyNameParameter->getName() . '. \'" is required but not defined and no default value provided!\');' . PHP_EOL; $body .= ' }' . PHP_EOL; $body .= ' throw new \\RuntimeException(\'Parameter "\' .$' . $propertyNameParameter->getName() . '. \'" not defined!\');' . PHP_EOL; $body .= '}' . PHP_EOL . PHP_EOL; $body .= 'return $value;' . PHP_EOL; $this->setParameter($propertyNameParameter); $this->setParameter($requiredParameter); $this->setParameter($defaultValueParameter); $this->setVisibility(self::VISIBILITY_PROTECTED); $this->setBody($body); }
/** * @param ParameterReflection $reflectionParameter * @return ParameterGenerator */ public static function fromReflection(ParameterReflection $reflectionParameter) { $param = new ParameterGenerator(); $param->setName($reflectionParameter->getName()); if ($reflectionParameter->isArray()) { $param->setType('array'); } elseif (method_exists($reflectionParameter, 'isCallable') && $reflectionParameter->isCallable()) { $param->setType('callable'); } else { $typeClass = $reflectionParameter->getClass(); if ($typeClass) { $param->setType($typeClass->getName()); } } $param->setPosition($reflectionParameter->getPosition()); if ($reflectionParameter->isOptional()) { $param->setDefaultValue($reflectionParameter->getDefaultValue()); } $param->setPassedByReference($reflectionParameter->isPassedByReference()); return $param; }
/** * Constructor * * @param PropertyGenerator $initializerProperty */ public function __construct(PropertyGenerator $initializerProperty) { parent::__construct('setProxyInitializer'); $initializerParameter = new ParameterGenerator('initializer'); $initializerParameter->setType(Closure::class); $initializerParameter->setDefaultValue(null); $this->setParameter($initializerParameter); $this->setDocblock('{@inheritDoc}'); $this->setBody('$this->' . $initializerProperty->getName() . ' = $initializer;'); }
/** * @param ParameterReflection $reflectionParameter * @return ParameterGenerator */ public static function fromReflection(ParameterReflection $reflectionParameter) { $param = new ParameterGenerator(); $param->setName($reflectionParameter->getName()); if ($type = self::extractFQCNTypeFromReflectionType($reflectionParameter)) { $param->setType($type); } $param->setPosition($reflectionParameter->getPosition()); $variadic = method_exists($reflectionParameter, 'isVariadic') && $reflectionParameter->isVariadic(); $param->setVariadic($variadic); if (!$variadic && $reflectionParameter->isOptional()) { try { $param->setDefaultValue($reflectionParameter->getDefaultValue()); } catch (\ReflectionException $e) { $param->setDefaultValue(null); } } $param->setPassedByReference($reflectionParameter->isPassedByReference()); return $param; }
/** * Constructor * * @param PropertyGenerator $suffixInterceptor */ public function __construct(PropertyGenerator $suffixInterceptor) { parent::__construct('setMethodSuffixInterceptor'); $interceptor = new ParameterGenerator('suffixInterceptor'); $interceptor->setType(Closure::class); $interceptor->setDefaultValue(null); $this->setParameter(new ParameterGenerator('methodName', 'string')); $this->setParameter($interceptor); $this->setDocblock('{@inheritDoc}'); $this->setBody('$this->' . $suffixInterceptor->getName() . '[$methodName] = $suffixInterceptor;'); }
private function handleValueMethod(Generator\ClassGenerator $generator, PHPProperty $prop, PHPClass $class, $all = true) { $type = $prop->getType(); $docblock = new DocBlockGenerator('Construct'); $paramTag = new ParamTag("value", "mixed"); $paramTag->setTypes($type ? $this->getPhpType($type) : "mixed"); $docblock->setTag($paramTag); $param = new ParameterGenerator("value"); if ($type && !$this->isNativeType($type)) { $param->setType($this->getPhpType($type)); } $method = new MethodGenerator("__construct", [$param]); $method->setDocBlock($docblock); $method->setBody("\$this->value(\$value);"); $generator->addMethodFromGenerator($method); $docblock = new DocBlockGenerator('Gets or sets the inner value'); $paramTag = new ParamTag("value", "mixed"); if ($type && $type instanceof PHPClassOf) { $paramTag->setTypes($this->getPhpType($type->getArg()->getType()) . "[]"); } elseif ($type) { $paramTag->setTypes($this->getPhpType($prop->getType())); } $docblock->setTag($paramTag); $returnTag = new ReturnTag("mixed"); if ($type && $type instanceof PHPClassOf) { $returnTag->setTypes($this->getPhpType($type->getArg()->getType()) . "[]"); } elseif ($type) { $returnTag->setTypes($this->getPhpType($type)); } $docblock->setTag($returnTag); $param = new ParameterGenerator("value"); $param->setDefaultValue(null); if ($type && !$this->isNativeType($type)) { $param->setType($this->getPhpType($type)); } $method = new MethodGenerator("value", []); $method->setDocBlock($docblock); $methodBody = "if (\$args = func_get_args()) {" . PHP_EOL; $methodBody .= " \$this->" . $prop->getName() . " = \$args[0];" . PHP_EOL; $methodBody .= "}" . PHP_EOL; $methodBody .= "return \$this->" . $prop->getName() . ";" . PHP_EOL; $method->setBody($methodBody); $generator->addMethodFromGenerator($method); $docblock = new DocBlockGenerator('Gets a string value'); $docblock->setTag(new ReturnTag("string")); $method = new MethodGenerator("__toString"); $method->setDocBlock($docblock); $method->setBody("return strval(\$this->" . $prop->getName() . ");"); $generator->addMethodFromGenerator($method); }
/** * Constructor * * @param ReflectionClass $originalClass * @param PropertyGenerator $valueHolder * @param PropertyGenerator $prefixInterceptors * @param PropertyGenerator $suffixInterceptors */ public function __construct(ReflectionClass $originalClass, PropertyGenerator $valueHolder, PropertyGenerator $prefixInterceptors, PropertyGenerator $suffixInterceptors) { parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC); $prefix = new ParameterGenerator('prefixInterceptors'); $suffix = new ParameterGenerator('suffixInterceptors'); $prefix->setDefaultValue([]); $suffix->setDefaultValue([]); $prefix->setType('array'); $suffix->setType('array'); $this->setParameter(new ParameterGenerator('wrappedObject')); $this->setParameter($prefix); $this->setParameter($suffix); $this->setReturnType($originalClass->getName()); $this->setDocblock("Constructor to setup interceptors\n\n" . "@param \\" . $originalClass->getName() . " \$wrappedObject\n" . "@param \\Closure[] \$prefixInterceptors method interceptors to be used before method logic\n" . "@param \\Closure[] \$suffixInterceptors method interceptors to be used before method logic\n\n" . "@return self"); $this->setBody('static $reflection;' . "\n\n" . '$reflection = $reflection ?: $reflection = new \\ReflectionClass(__CLASS__);' . "\n" . '$instance = (new \\ReflectionClass(get_class()))->newInstanceWithoutConstructor();' . "\n\n" . UnsetPropertiesGenerator::generateSnippet(Properties::fromReflectionClass($originalClass), 'instance') . '$instance->' . $valueHolder->getName() . " = \$wrappedObject;\n" . '$instance->' . $prefixInterceptors->getName() . " = \$prefixInterceptors;\n" . '$instance->' . $suffixInterceptors->getName() . " = \$suffixInterceptors;\n\n" . 'return $instance;'); }
/** * Constructor * * @param ReflectionClass $originalClass */ public function __construct(ReflectionClass $originalClass) { parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC); $localizedObject = new ParameterGenerator('localizedObject'); $prefix = new ParameterGenerator('prefixInterceptors'); $suffix = new ParameterGenerator('suffixInterceptors'); $localizedObject->setType($originalClass->getName()); $prefix->setDefaultValue([]); $suffix->setDefaultValue([]); $prefix->setType('array'); $suffix->setType('array'); $this->setParameter($localizedObject); $this->setParameter($prefix); $this->setParameter($suffix); $this->setDocblock("Constructor to setup interceptors\n\n" . "@param \\" . $originalClass->getName() . " \$localizedObject\n" . "@param \\Closure[] \$prefixInterceptors method interceptors to be used before method logic\n" . "@param \\Closure[] \$suffixInterceptors method interceptors to be used before method logic\n\n" . "@return self"); $this->setBody('static $reflection;' . "\n\n" . '$reflection = $reflection ?: $reflection = new \\ReflectionClass(__CLASS__);' . "\n" . '$instance = $reflection->newInstanceWithoutConstructor();' . "\n\n" . '$instance->bindProxyProperties($localizedObject, $prefixInterceptors, $suffixInterceptors);' . "\n\n" . 'return $instance;'); }
/** * Process and create code/files */ public function create() { $class = ClassGen::classGen($this->name, $this->namespace, ['Phrest\\SDK\\Request\\AbstractRequest', 'Phrest\\SDK\\Request\\RequestOptions', 'Phrest\\SDK\\PhrestSDK'], 'AbstractRequest'); // Path $path = '/' . $this->version . '/' . strtolower($this->entityName) . $this->getPlaceholderUriFromUrl($this->action->url); $property = ClassGen::property('path', 'private', $path, 'string'); $class->addPropertyFromGenerator($property); // Properties and constructor parameters /** @var ParameterGenerator[] $parameters */ $parameters = []; // Get properties $getParams = $this->generateGetParamsFromUrl($this->action->url); if (!empty($getParams)) { foreach ($getParams as $getParam) { $class->addPropertyFromGenerator(ClassGen::property($getParam, 'public', null)); $parameter = new ParameterGenerator($getParam); $parameter->setDefaultValue(null); $parameters[$getParam] = $parameter; } } // Post properties if (!empty($this->action->postParams)) { foreach ($this->action->postParams as $name => $type) { if ($class->hasProperty($name)) { continue; } $class->addPropertyFromGenerator(ClassGen::property($name, 'public', null, $type)); $parameter = new ParameterGenerator($name, $type); $parameter->setDefaultValue(null); $parameters[$name] = $parameter; } } // Constructor if (!empty($parameters)) { $constructor = ClassGen::constructor($parameters); $class->addMethodFromGenerator($constructor); } // Create method $create = ClassGen::method('create', [], 'public', $this->getCreateBody()); $class->addMethodFromGenerator($create); // Setters foreach ($parameters as $parameter) { $class->addMethodFromGenerator(ClassGen::setter($parameter->getName(), $parameter->getType())); } return $class; }
/** * Creates a new {@link \bitExpert\Disco\Proxy\Configuration\MethodGenerator\Constructor}. * * @param ReflectionClass $originalClass * @param ParameterValuesProperty $parameterValuesProperty * @param SessionBeansProperty $sessionBeansProperty * @param BeanFactoryConfigurationProperty $beanFactoryConfigurationProperty * @param BeanPostProcessorsProperty $beanPostProcessorsProperty * @param string[] $beanPostProcessorMethodNames */ public function __construct(ReflectionClass $originalClass, ParameterValuesProperty $parameterValuesProperty, SessionBeansProperty $sessionBeansProperty, BeanFactoryConfigurationProperty $beanFactoryConfigurationProperty, BeanPostProcessorsProperty $beanPostProcessorsProperty, array $beanPostProcessorMethodNames) { parent::__construct('__construct'); $beanFactoryConfigurationParameter = new ParameterGenerator('config'); $beanFactoryConfigurationParameter->setType(BeanFactoryConfiguration::class); $parametersParameter = new ParameterGenerator('params'); $parametersParameter->setDefaultValue([]); $body = '$this->' . $parameterValuesProperty->getName() . ' = $' . $parametersParameter->getName() . ';' . PHP_EOL; $body .= '$this->' . $beanFactoryConfigurationProperty->getName() . ' = $' . $beanFactoryConfigurationParameter->getName() . ';' . PHP_EOL; $body .= '$this->' . $sessionBeansProperty->getName() . ' = $' . $beanFactoryConfigurationParameter->getName() . '->getSessionBeanStore();' . PHP_EOL; $body .= '// register {@link \\bitExpert\\Disco\\BeanPostProcessor} instances' . PHP_EOL; $body .= '$this->' . $beanPostProcessorsProperty->getName() . '[] = new \\bitExpert\\Disco\\BeanFactoryPostProcessor();' . PHP_EOL; foreach ($beanPostProcessorMethodNames as $methodName) { $body .= '$this->' . $beanPostProcessorsProperty->getName() . '[] = $this->' . $methodName . '(); '; $body .= PHP_EOL; } $this->setParameter($beanFactoryConfigurationParameter); $this->setParameter($parametersParameter); $this->setBody($body); $this->setDocBlock("@override constructor"); }
protected function viewStub($part) { /** * @var $part \Model\Generator\Part\Model */ /** * @var $file \Model\Code\Generator\FileGenerator */ $file = $part->getFile(); $table = $part->getTable(); $tableNameAsCamelCase = $table->getNameAsCamelCase(); $entity = $tableNameAsCamelCase . 'Entity'; $collection = $tableNameAsCamelCase . 'Collection'; $p = new \Zend\Code\Generator\ParameterGenerator('cond'); $p->setType('Cond'); $p->setDefaultValue(null); $params[] = $p; $docblock = new DocBlockGenerator('Получить объект условий в виде представления \'Extended\' $param Cond $cond $return Cond '); $method = new MethodGenerator(); $method->setName('getCondAsExtendedView'); $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC); $method->setFinal(false); $method->setDocBlock($docblock); $method->setParameters($params); $method->setBody(<<<EOS \$cond = \$this->prepareCond(\$cond); \$cond->where(array('status' => 'active')); return \$cond; EOS ); $file->getClass()->addMethodFromGenerator($method); $p = new \Zend\Code\Generator\ParameterGenerator('cond'); $p->setType('Cond'); $p->setDefaultValue(null); $params[] = $p; $docblock = new DocBlockGenerator('Получить элемент в виде представления \'Extended\' @param Cond $cond @return ' . $entity); $method = new MethodGenerator(); $method->setName('getAsExtendedView'); $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC); $method->setFinal(false); $method->setDocBlock($docblock); $method->setParameters($params); $method->setBody(<<<EOS \$cond = \$this->getCondAsExtendedView(\$cond); return \$this->get(\$cond); EOS ); $file->getClass()->addMethodFromGenerator($method); $p = new \Zend\Code\Generator\ParameterGenerator('cond'); $p->setType('Cond'); $p->setDefaultValue(null); $params[] = $p; $docblock = new DocBlockGenerator('Получить коллекцию в виде представления \'Extended\' @param Cond $cond @return ' . $collection); $method = new MethodGenerator(); $method->setName('getCollectionAsExtendedView'); $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC); $method->setFinal(false); $method->setDocBlock($docblock); $method->setParameters($params); $method->setBody(<<<EOS \$cond = \$this->getCondAsExtendedView(\$cond); return \$this->getCollection(\$cond); EOS ); $file->getClass()->addMethodFromGenerator($method); }
/** * {@inheritdoc} */ public function createDTO(Type $type) { $class = $this->createClassFromType($type); $parentType = $type->getParent(); // set the parent class if ($parentType) { $parentType = $parentType->getBase(); if ($parentType->getSchema()->getTargetNamespace() !== SchemaReader::XSD_NS) { $class->setExtendedClass($parentType->getName()); } } // check if the type is abstract $class->setAbstract($type->isAbstract()); // create the constructor $constructor = new MethodGenerator('__construct'); $constructorDoc = new DocBlockGenerator(); $constructorBody = ''; $constructor->setDocBlock($constructorDoc); $class->addMethodFromGenerator($constructor); /* @var \Goetas\XML\XSDReader\Schema\Type\ComplexType $type */ foreach ($type->getElements() as $element) { /* @var \Goetas\XML\XSDReader\Schema\Element\Element $element */ $docElementType = $this->namespaceInflector->inflectDocBlockQualifiedName($element->getType()); $elementName = $element->getName(); // create a param and a param tag used in constructor and setter docs $param = new ParameterGenerator($elementName, $this->namespaceInflector->inflectName($element->getType())); $paramTag = new ParamTag($elementName, $docElementType); // if the param type is not a PHP primitive type and its namespace is different that the class namespace if ($type->getSchema()->getTargetNamespace() === SchemaReader::XSD_NS and $class->getNamespaceName() !== $this->namespaceInflector->inflectNamespace($element->getType())) { $class->addUse($this->namespaceInflector->inflectQualifiedName($element->getType())); } // set the parameter nullability if ($element->isNil() or $this->config->isNullConstructorArguments()) { $param->setDefaultValue(new ValueGenerator(null, ValueGenerator::TYPE_NULL)); } /* * PROPERTY CREATION */ $docDescription = new Html2Text($type->getDoc()); $doc = new DocBlockGenerator(); $doc->setShortDescription($docDescription->getText()); $doc->setTag(new GenericTag('var', $docElementType)); $property = new PropertyGenerator(); $property->setDocBlock($doc); $property->setName(filter_var($elementName, FILTER_CALLBACK, array('options' => array($this, 'sanitizeVariableName')))); $property->setVisibility($this->config->isAccessors() ? AbstractMemberGenerator::VISIBILITY_PROTECTED : AbstractMemberGenerator::VISIBILITY_PUBLIC); $class->addPropertyFromGenerator($property); /* * IMPORTS */ if ($element->getType()->getSchema()->getTargetNamespace() !== SchemaReader::XSD_NS and $this->namespaceInflector->inflectNamespace($element->getType()) !== $class->getNamespaceName()) { $class->addUse($this->namespaceInflector->inflectQualifiedName($element->getType())); } /* * CONSTRUCTOR PARAM CREATION */ $constructorDoc->setTag($paramTag); $constructorBody .= "\$this->{$elementName} = \${$elementName};" . AbstractGenerator::LINE_FEED; $constructor->setParameter($param); /* * ACCESSORS CREATION */ if ($this->config->isAccessors()) { // create the setter $setterDoc = new DocBlockGenerator(); $setterDoc->setTag($paramTag); $setter = new MethodGenerator('set' . ucfirst($elementName)); $setter->setParameter($param); $setter->setDocBlock($setterDoc); $setter->setBody("\$this->{$elementName} = \${$elementName};"); $class->addMethodFromGenerator($setter); // create the getter $getterDoc = new DocBlockGenerator(); $getterDoc->setTag(new ReturnTag($docElementType)); $getter = new MethodGenerator('get' . ucfirst($elementName)); $getter->setDocBlock($getterDoc); $getter->setBody("return \$this->{$elementName};"); $class->addMethodFromGenerator($getter); } } // finalize the constructor body $constructor->setBody($constructorBody); $this->serializeClass($class); // register the class in the classmap $this->classmap[$class->getName()] = $class->getNamespaceName() . '\\' . $class->getName(); return $class->getName(); }
} continue; } $requiredParameters[] = new ParameterGenerator($fieldName, Collection::class); } foreach ($metadataClass->getFieldNames() as $fieldName) { if (in_array($fieldName, $metadataClass->getIdentifierFieldNames(), true) && $metadataClass->isIdGeneratorIdentity()) { // auto-incremental identifier, skip it. continue; } $fieldMapping = $metadataClass->getFieldMapping($fieldName); $type = null; if ('datetime' === $fieldMapping['type']) { $type = 'DateTime'; } $parameter = new ParameterGenerator($fieldName, $type); if (isset($fieldMapping['nullable']) && $fieldMapping['nullable']) { $parameter->setDefaultValue(null); $optionalParameters[] = $parameter; } else { $requiredParameters[] = $parameter; } } $classGenerator = ClassGenerator::fromReflection(new ClassReflection($metadataClass->getName())); $classGenerator->removeMethod('__construct'); $classGenerator->addMethodFromGenerator(new MethodGenerator('__construct', array_merge($requiredParameters, $optionalParameters), MethodGenerator::FLAG_PUBLIC, implode("\n", array_map(function (ParameterGenerator $parameterGenerator) { $name = $parameterGenerator->getName(); return '$this->' . $name . ' = $' . $name . ';'; }, array_merge($requiredParameters, $optionalParameters))))); file_put_contents($metadataClass->getReflectionClass()->getFileName(), preg_replace('/private \\$([A-Za-z0-9]+) = null;/i', 'private \\$${1};', "<?php\n\n\n" . $classGenerator->generate())); }
/** * @param \ReflectionMethod $method * @return MethodGenerator */ private function generateMethod(\ReflectionMethod $method) { $gen = new MethodGenerator($method->getName()); foreach ($method->getParameters() as $param) { $paramgen = new ParameterGenerator($param->getName(), $param->getClass() ? '\\' . $param->getClass()->name : null, null, $param->isPassedByReference()); // setting default value here because the construtor ignores "null" as default if ($param->isDefaultValueAvailable()) { $paramgen->setDefaultValue($param->getDefaultValue()); } $gen->setParameter($paramgen); } $gen->setBody('return $this->__proxy_run(C::CALL, __FUNCTION__, func_get_args());'); return $gen; }
/** * Set the default value for a parameter (if it is optional) * * @param ZendParameterGenerator $parameterGenerator * @param ParameterReflection $reflectionParameter */ private static function setOptionalParameter(ZendParameterGenerator $parameterGenerator, ParameterReflection $reflectionParameter) { if ($reflectionParameter->isOptional()) { try { $parameterGenerator->setDefaultValue($reflectionParameter->getDefaultValue()); } catch (ReflectionException $e) { $parameterGenerator->setDefaultValue(null); } } }
/** * Generate method * * @param string $methodName * @return void */ protected function generateMethod($methodName) { $methodReflection = $this->_method[$methodName]; $docBlock = new DocBlockGenerator(); $docBlock->setShortDescription("Delicate {$methodName}() to __call() method "); if ($methodReflection->getDocComment()) { $docBlockReflection = new DocBlockReflection($methodReflection); $docBlock->fromReflection($docBlockReflection); } $method = new MethodGenerator(); $method->setName($methodName); $method->setDocBlock($docBlock); $method->setBody(sprintf(self::METHOD_TEMPLATE, $methodName)); if ($methodReflection->isPublic()) { $method->setVisibility(MethodGenerator::VISIBILITY_PUBLIC); } else { if ($methodReflection->isProtected()) { $method->setVisibility(MethodGenerator::VISIBILITY_PROTECTED); } else { if ($methodReflection->isPrivate()) { $method->setVisibility(MethodGenerator::VISIBILITY_PRIVATE); } } } foreach ($methodReflection->getParameters() as $parameter) { $parameterGenerator = new ParameterGenerator(); $parameterGenerator->setPosition($parameter->getPosition()); $parameterGenerator->setName($parameter->getName()); $parameterGenerator->setPassedByReference($parameter->isPassedByReference()); if ($parameter->isDefaultValueAvailable()) { $parameterGenerator->setDefaultValue($parameter->getDefaultValue()); } if ($parameter->isArray()) { $parameterGenerator->setType('array'); } if ($typeClass = $parameter->getClass()) { $parameterGenerator->setType($typeClass->getName()); } $method->setParameter($parameterGenerator); } $this->addMethodFromGenerator($method); }
/** * @group 6023 * * @coversNothing */ public function testGeneratedParametersHaveEscapedDefaultValues() { $parameter = new ParameterGenerator(); $parameter->setName('foo'); $parameter->setDefaultValue("\\'"); $parameter->setType('stdClass'); $this->assertSame("stdClass \$foo = '\\\\\\''", $parameter->generate()); }
public function generateMethodsByIndex($part) { /** @var $part \Model\Generator\Part\Model */ /** @var $file \Model\Code\Generator\FileGenerator */ $file = $part->getFile(); $table = $part->getTable(); $tableName = $table->getName(); $indexList = $table->getIndex(); foreach ($indexList as $index) { $params = $getBy = array(); $prepare = ''; $paramNames = array(); $checkForEmpty = ''; $indexColumn = 'id'; $where = ''; foreach ($index as $column) { if ($index->getName() == 'PRIMARY') { $indexColumn = $column->getName(); } //echo $index->getName() . "\n"; if ($index->getName() == 'PRIMARY' || $index->count() == 1 && ($link = $table->getLinkByColumn($column, $table->getName()))) { continue 2; } $link = $table->getLinkByColumn($column, $table->getName()); if ($link) { $indexColumnName = $link->getForeignEntity(); $indexColumnNameAsVar = $link->getForeignEntityAsVar(); $indexColumnNameAsCamelCase = $link->getForeignEntityAsCamelCase(); } else { $indexColumnName = $column->getName(); $indexColumnNameAsVar = $column->getNameAsVar(); $indexColumnNameAsCamelCase = $column->getNameAsCamelCase(); } $indexColumnField = $column->getName(); $params[] = new \Zend\Code\Generator\ParameterGenerator($indexColumnNameAsVar); $getBy[] = $indexColumnNameAsCamelCase; $paramNames[] = '$' . $indexColumnNameAsVar; if ($link) { $foreignTableNameAsCamelCase = $link->getForeignTable()->getNameAsCamelCase(); $prepare .= <<<EOS \${$indexColumnNameAsVar}Ids = {$foreignTableNameAsCamelCase}Model::getInstance()->getIdsFromMixed(\${$indexColumnNameAsVar}); EOS; } else { $prepare .= <<<EOS \${$indexColumnNameAsVar}Ids = \$this->filterValue(\${$indexColumnNameAsVar}, '{$indexColumnName}'); EOS; } $checkForEmpty .= "empty(\${$indexColumnNameAsVar}Ids) || "; $where .= "'`{$tableName}`.`{$indexColumnField}`' => \${$indexColumnNameAsVar}Ids,\n"; } //@method int borp() borp(int $int1, int $int2) multiply two integers $p = new \Zend\Code\Generator\ParameterGenerator('cond'); $p->setDefaultValue(null); $p->setType('Cond'); $params[] = $p; $where = 'array(' . rtrim($where, " \n,") . ")"; $checkForEmpty = rtrim($checkForEmpty, "\r\n |"); $method = new \Zend\Code\Generator\MethodGenerator(); $method->setName('getBy' . implode('And', $getBy)); $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC); //$method->setDocBlock($docblock); $method->setParameters($params); $method->setBody(<<<EOS \$cond = \$this->prepareCond(\$cond); {$prepare} if ({$checkForEmpty}) { return \$cond->getEmptySelectResult(); } \$cond->where({$where}); return \$this->get(\$cond); EOS ); try { $part->getFile()->getClass()->addMethodFromGenerator($method); } catch (\Exception $e) { } } }
/** * @group ZF-7268 */ public function testDefaultValueGenerationDoesNotIncludeTrailingSemicolon() { $method = new MethodGenerator('setOptions'); $default = new ValueGenerator(); $default->setValue(array()); $param = new ParameterGenerator('options', 'array'); $param->setDefaultValue($default); $method->setParameter($param); $generated = $method->generate(); $this->assertRegexp('/array \$options = array\(\)\)/', $generated, $generated); }
public function getConstructorGenerator() { if (!$this->constructorGenerator && ($extendedClass = $this->getClassGenerator()->getExtendedClass())) { $constructorGenerator = new CodeGenerator\MethodGenerator(); $constructorGenerator->setName('__construct'); $wsdlParameter = new CodeGenerator\ParameterGenerator(); $wsdlParameter->setName('wsdl'); $wsdlParameter->setDefaultValue($this->getWsdl()); $constructorGenerator->setParameter($wsdlParameter); $optionsParameter = new CodeGenerator\ParameterGenerator(); $optionsParameter->setName('options'); $optionsParameter->setDefaultValue(array()); $constructorGenerator->setParameter($optionsParameter); $constructorGenerator->setBody("parent::__construct(\$wsdl, \$options);"); $this->constructorGenerator = $constructorGenerator; } return $this->constructorGenerator; }
/** * 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'))))); } } }