protected function getMethods() { $methods = [$this->getConstructor()]; foreach ($this->properties as $propertyName) { $setterParam = new ParameterGenerator($propertyName); $methodGenerator = new MethodGenerator('set' . ucfirst($propertyName), [$setterParam]); $methodGenerator->setBody('$this->' . $propertyName . ' = ' . $setterParam->generate() . ';' . PHP_EOL . PHP_EOL . 'return $this;'); $methods[] = $methodGenerator; $methodGenerator = new MethodGenerator('get' . ucfirst($propertyName)); $methodGenerator->setBody('return $this->' . $propertyName . ';'); $methods[] = $methodGenerator; } foreach ($this->edgeProperties as $edgeCollection => $targetCollection) { $setterParam = new ParameterGenerator(lcfirst($edgeCollection)); $methodGenerator = new MethodGenerator('add' . $edgeCollection, [$setterParam]); $methodGenerator->setBody('$this->lazyAddNeighbor($this, \'' . $edgeCollection . '\', ' . $setterParam->generate() . ');'); $methods[] = $methodGenerator; $setterParam = new ParameterGenerator(lcfirst($edgeCollection)); $methodGenerator = new MethodGenerator('remove' . $edgeCollection, [$setterParam]); $methodGenerator->setBody('$this->lazyRemoveNeighbor($this, \'' . $edgeCollection . '\', ' . $setterParam->generate() . ');'); $methods[] = $methodGenerator; $setterParam = new ParameterGenerator(lcfirst($edgeCollection)); $methodGenerator = new MethodGenerator('set' . $edgeCollection, [$setterParam]); $methodGenerator->setBody('$this->lazySetNeighbor($this, \'' . $edgeCollection . '\', ' . $setterParam->generate() . ');'); $methods[] = $methodGenerator; $defaultValue = new ValueGenerator([], ValueGenerator::TYPE_ARRAY); $setterParam = new ParameterGenerator('filter', null, $defaultValue); $methodGenerator = new MethodGenerator('get' . $edgeCollection, [$setterParam]); $methodGenerator->setBody('return $this->lazyGetNeighbor(\'' . $edgeCollection . '\', \'' . $targetCollection . '\', $filter);'); $methods[] = $methodGenerator; } return $methods; }
/** * 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); }
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(); }
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(); }
/** * 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;'); }
/** * Creates a new {@link \bitExpert\Disco\Proxy\Configuration\MethodGenerator\HasAlias}. * * @param ReflectionClass $originalClass * @param AliasesProperty $aliasesProperty * @throws InvalidArgumentException */ public function __construct(ReflectionClass $originalClass, AliasesProperty $aliasesProperty) { parent::__construct('hasAlias'); $aliasParameter = new ParameterGenerator('alias'); $aliasParameter->setType('string'); $this->setParameter($aliasParameter); $this->setVisibility(self::VISIBILITY_PUBLIC); $this->setReturnType('bool'); $this->setBody('return !empty($' . $aliasParameter->getName() . ') && ' . 'isset($this->' . $aliasesProperty->getName() . '[$' . $aliasParameter->getName() . ']);'); }
/** * @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; }
/** * @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 $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;'); }
public function generatePropertyAdder($propertyName) { $parameterName = rtrim($propertyName, 's'); $methodName = 'add' . ucfirst($parameterName); $setterGenerator = clone $this->getPropertySetterGenerator(); $setterGenerator->setName($methodName); $parameter = new CodeGenerator\ParameterGenerator(); $parameter->setName($parameterName); $setterGenerator->setParameter($parameter); $valueParameter = new CodeGenerator\ParameterGenerator(); $valueParameter->setName('value'); $setterGenerator->setParameter($valueParameter); $setterGenerator->setBody("\$this->{$propertyName}[\${$parameterName}] = \$value;\nreturn \$this;"); return $setterGenerator; }
/** * 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;'); }
/** * 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; }
/** * 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;'); }
/** * 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"); }
public function generatePropertyAdder($propertyName, $withIndex = true, $proxyPropertyName = null) { $proxyPropertyName = $proxyPropertyName ?: $propertyName; list($parameterName, $methodName) = $this->generatePropertyAdderName($proxyPropertyName); $setterGenerator = clone $this->getPropertySetterGenerator(); $setterGenerator->setName($methodName); if ($withIndex) { $parameter = new CodeGenerator\ParameterGenerator(); $parameter->setName($parameterName); $setterGenerator->setParameter($parameter); } $valueParameter = new CodeGenerator\ParameterGenerator(); $valueParameter->setName('value'); $setterGenerator->setParameter($valueParameter); if ($withIndex) { $setterGenerator->setBody("\$this->{$propertyName}[\${$parameterName}] = \$value;\nreturn \$this;"); } else { $setterGenerator->setBody("\$this->{$propertyName}[] = \$value;\nreturn \$this;"); } return $setterGenerator; }
public function transform() { $classGenerator = $this->getService()->getClassGenerator(); if ($createContactBatch = $classGenerator->getMethod('CreateContactBatch')) { $newMethod = new CodeGenerator\MethodGenerator(); $newMethod->setName($createContactBatch->getName()); $docblock = $createContactBatch->getDocBlock(); $docblock->setTag((new CodeGenerator\DocBlock\Tag\ParamTag())->setParamName('id')->setDataType('int')); $newMethod->setDocBlock($docblock); $parameters = $createContactBatch->getParameters(); $idParameter = new CodeGenerator\ParameterGenerator(); $idParameter->setName('id'); $createContactBatch->setParameter($idParameter); $newMethod->setParameters(array("id" => $idParameter, "CreateContactBatch" => $parameters['CreateContactBatch'])); $body = $createContactBatch->getBody(); $body = str_replace('array()', 'array($id)', $body); $newMethod->setBody($body); $classGenerator->removeMethod('CreateContactBatch'); $classGenerator->addMethodFromGenerator($newMethod); } }
/** * @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; }
/** * Creates a new {@link \bitExpert\Disco\Proxy\Configuration\MethodGenerator\GetAlias}. * * @param ReflectionClass $originalClass * @param AliasesProperty $aliasesProperty * @throws InvalidArgumentException */ public function __construct(ReflectionClass $originalClass, AliasesProperty $aliasesProperty) { parent::__construct('getAlias'); $aliasParameter = new ParameterGenerator('alias'); $aliasParameter->setType('string'); $body = 'if ($this->hasAlias($' . $aliasParameter->getName() . ')) {' . PHP_EOL; $body .= ' $methodname = $this->' . $aliasesProperty->getName() . '[$' . $aliasParameter->getName() . '];' . PHP_EOL; $body .= ' return $this->$methodname();' . PHP_EOL; $body .= '}' . PHP_EOL . PHP_EOL; $body .= 'throw new ' . BeanNotFoundException::class . '(sprintf(\'Alias "%s" is not defined!\', $' . $aliasParameter->getName() . '));' . PHP_EOL; $this->setParameter($aliasParameter); $this->setVisibility(self::VISIBILITY_PUBLIC); $this->setBody($body); }
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()))))); }
/** * @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 generatePropertySetter($property) { $property = lcfirst($property); $methodName = 'set' . ucfirst($property); $setterGenerator = clone $this->getPropertySetterGenerator(); $setterGenerator->setName($methodName); $parameter = new CodeGenerator\ParameterGenerator(); $parameter->setName($property); $setterGenerator->setParameter($parameter); $setterGenerator->setBody("\$this->{$property} = \${$property};\nreturn \$this;"); return $setterGenerator; }
/** * setParameter() * * @param ParameterGenerator|string $parameter * @return MethodGenerator */ public function setParameter($parameter) { if (is_string($parameter)) { $parameter = new ParameterGenerator($parameter); } elseif (!$parameter instanceof ParameterGenerator) { throw new Exception\InvalidArgumentException('setParameter() is expecting either a string, array or an instance of Zend\\Code\\Generator\\ParameterGenerator'); } $parameterName = $parameter->getName(); $this->parameters[$parameterName] = $parameter; return $this; }
/** * Construct, configure, and return a PHP class file code generation object * * Creates a Zend\Code\Generator\FileGenerator object that has * created the specified class and service locator methods. * * @param null|string $filename * @throws \Zend\Di\Exception\RuntimeException * @return FileGenerator */ public function getCodeGenerator($filename = null) { $injector = $this->injector; $im = $injector->instanceManager(); $indent = ' '; $aliases = $this->reduceAliases($im->getAliases()); $caseStatements = array(); $getters = array(); $definitions = $injector->definitions(); $fetched = array_unique(array_merge($definitions->getClasses(), $im->getAliases())); foreach ($fetched as $name) { $getter = $this->normalizeAlias($name); $meta = $injector->get($name); $params = $meta->getParams(); // Build parameter list for instantiation foreach ($params as $key => $param) { if (null === $param || is_scalar($param) || is_array($param)) { $string = var_export($param, 1); if (strstr($string, '::__set_state(')) { throw new Exception\RuntimeException('Arguments in definitions may not contain objects'); } $params[$key] = $string; } elseif ($param instanceof GeneratorInstance) { /* @var $param GeneratorInstance */ $params[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName())); } else { $message = sprintf('Unable to use object arguments when building containers. Encountered with "%s", parameter of type "%s"', $name, get_class($param)); throw new Exception\RuntimeException($message); } } // Strip null arguments from the end of the params list $reverseParams = array_reverse($params, true); foreach ($reverseParams as $key => $param) { if ('NULL' === $param) { unset($params[$key]); continue; } break; } // Create instantiation code $constructor = $meta->getConstructor(); if ('__construct' != $constructor) { // Constructor callback $callback = var_export($constructor, 1); if (strstr($callback, '::__set_state(')) { throw new Exception\RuntimeException('Unable to build containers that use callbacks requiring object instances'); } if (count($params)) { $creation = sprintf('$object = call_user_func(%s, %s);', $callback, implode(', ', $params)); } else { $creation = sprintf('$object = call_user_func(%s);', $callback); } } else { // Normal instantiation $className = '\\' . ltrim($name, '\\'); $creation = sprintf('$object = new %s(%s);', $className, implode(', ', $params)); } // Create method call code $methods = ''; foreach ($meta->getMethods() as $methodData) { if (!isset($methodData['name']) && !isset($methodData['method'])) { continue; } $methodName = isset($methodData['name']) ? $methodData['name'] : $methodData['method']; $methodParams = $methodData['params']; // Create method parameter representation foreach ($methodParams as $key => $param) { if (null === $param || is_scalar($param) || is_array($param)) { $string = var_export($param, 1); if (strstr($string, '::__set_state(')) { throw new Exception\RuntimeException('Arguments in definitions may not contain objects'); } $methodParams[$key] = $string; } elseif ($param instanceof GeneratorInstance) { $methodParams[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName())); } else { $message = sprintf('Unable to use object arguments when generating method calls. Encountered with class "%s", method "%s", parameter of type "%s"', $name, $methodName, get_class($param)); throw new Exception\RuntimeException($message); } } // Strip null arguments from the end of the params list $reverseParams = array_reverse($methodParams, true); foreach ($reverseParams as $key => $param) { if ('NULL' === $param) { unset($methodParams[$key]); continue; } break; } $methods .= sprintf("\$object->%s(%s);\n", $methodName, implode(', ', $methodParams)); } // Generate caching statement $storage = ''; if ($im->hasSharedInstance($name, $params)) { $storage = sprintf("\$this->services['%s'] = \$object;\n", $name); } // Start creating getter $getterBody = ''; // Create fetch of stored service if ($im->hasSharedInstance($name, $params)) { $getterBody .= sprintf("if (isset(\$this->services['%s'])) {\n", $name); $getterBody .= sprintf("%sreturn \$this->services['%s'];\n}\n\n", $indent, $name); } // Creation and method calls $getterBody .= sprintf("%s\n", $creation); $getterBody .= $methods; // Stored service $getterBody .= $storage; // End getter body $getterBody .= "return \$object;\n"; $getterDef = new MethodGenerator(); $getterDef->setName($getter); $getterDef->setBody($getterBody); $getters[] = $getterDef; // Get cases for case statements $cases = array($name); if (isset($aliases[$name])) { $cases = array_merge($aliases[$name], $cases); } // Build case statement and store $statement = ''; foreach ($cases as $value) { $statement .= sprintf("%scase '%s':\n", $indent, $value); } $statement .= sprintf("%sreturn \$this->%s();\n", str_repeat($indent, 2), $getter); $caseStatements[] = $statement; } // Build switch statement $switch = sprintf("switch (%s) {\n%s\n", '$name', implode("\n", $caseStatements)); $switch .= sprintf("%sdefault:\n%sreturn parent::get(%s, %s);\n", $indent, str_repeat($indent, 2), '$name', '$params'); $switch .= "}\n\n"; // Build get() method $nameParam = new ParameterGenerator(); $nameParam->setName('name'); $paramsParam = new ParameterGenerator(); $paramsParam->setName('params')->setType('array')->setDefaultValue(array()); $get = new MethodGenerator(); $get->setName('get'); $get->setParameters(array($nameParam, $paramsParam)); $get->setBody($switch); // Create getters for aliases $aliasMethods = array(); foreach ($aliases as $class => $classAliases) { foreach ($classAliases as $alias) { $aliasMethods[] = $this->getCodeGenMethodFromAlias($alias, $class); } } // Create class code generation object $container = new ClassGenerator(); $container->setName($this->containerClass)->setExtendedClass('ServiceLocator')->addMethodFromGenerator($get)->addMethods($getters)->addMethods($aliasMethods); // Create PHP file code generation object $classFile = new FileGenerator(); $classFile->setUse('Zend\\Di\\ServiceLocator')->setClass($container); if (null !== $this->namespace) { $classFile->setNamespace($this->namespace); } if (null !== $filename) { $classFile->setFilename($filename); } return $classFile; }
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); }
/** * 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; }
private function buildClass($replacement) { $type = $this->splitNsandClass($replacement['originalFullyQualifiedType']); $class = new ClassGenerator(); $class->setName($type['class']); $class->setNamespaceName($type['ns']); $class->setExtendedClass('\\Brads\\Ppm\\Proxy'); $properties = []; $methods = []; $implementedInterfaces = []; foreach ($versions as $version => $info) { foreach ($info['files'] as $file) { echo "Parsing: " . $this->vendorDir . '/' . $package . '/' . $version . '/' . $file . "\n"; $parsedFile = new ReflectionFile($this->vendorDir . '/' . $package . '/' . $version . '/' . $file); $parsedClass = $parsedFile->getFileNamespace($info['toNs'])->getClass($info['toNs'] . '\\' . $type['class']); if ($parsedClass->getInterfaceNames() != null) { $implementedInterfaces = array_merge($implementedInterfaces, $parsedClass->getInterfaceNames()); } foreach ($parsedClass->getMethods() as $method) { if ($method->isPublic()) { $generatedMethod = new MethodGenerator(); $generatedMethod->setName($method->name); $generatedMethod->setBody('echo "Hello world!";'); $generatedMethod->setAbstract($method->isAbstract()); $generatedMethod->setFinal($method->isFinal()); $generatedMethod->setStatic($method->isStatic()); $generatedMethod->setVisibility(MethodGenerator::VISIBILITY_PUBLIC); foreach ($method->getParameters() as $param) { $generatedParam = new ParameterGenerator(); $generatedParam->setName($param->name); if ($param->hasType()) { $generatedParam->setType($param->getType()); } //$generatedParam->setDefaultValue($param->getDefaultValue()); $generatedParam->setPosition($param->getPosition()); $generatedParam->setVariadic($param->isVariadic()); $generatedParam->setPassedByReference($param->isPassedByReference()); $generatedMethod->setParameter($generatedParam); } $existingMethod = Linq::from($methods)->firstOrDefault(null, function (MethodGenerator $v) use($method) { return $v->getName() == $method->name; }); if ($existingMethod != null) { $existingParams = $existingMethod->getParameters(); foreach ($generatedMethod->getParameters() as $newParam) { $existingParam = Linq::from($existingParams)->firstOrDefault(function (ParameterGenerator $v) { return $v->getName() == $newParam->getName(); }); if ($existingParam == null) { $existingMethod->setParameter($newParam); } } } else { $methods[] = $generatedMethod; } } } foreach ($parsedClass->getProperties() as $prop) { //$properties[] = PropertyGenerator::fromReflection($prop); } } } $class->setImplementedInterfaces($implementedInterfaces); $class->addMethods($methods); $class->addProperties($properties); return (new FileGenerator(['classes' => [$class]]))->generate(); }
/** * @dataProvider dataFromReflectionGenerate * @param string $methodName * @param string $expectedCode */ public function testFromReflectionGenerate($methodName, $expectedCode) { //$this->markTestSkipped('Test may not be necessary any longer'); $reflectionParameter = $this->getFirstReflectionParameter($methodName); $codeGenParam = ParameterGenerator::fromReflection($reflectionParameter); $this->assertEquals($expectedCode, $codeGenParam->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; }
/** * @param ParameterGenerator|string $parameter * @throws Exception\InvalidArgumentException * @return MethodGenerator */ public function setParameter($parameter) { if (is_string($parameter)) { $parameter = new ParameterGenerator($parameter); } elseif (!$parameter instanceof ParameterGenerator) { throw new Exception\InvalidArgumentException(sprintf('%s is expecting either a string, array or an instance of %s\\ParameterGenerator', __METHOD__, __NAMESPACE__)); } $parameterName = $parameter->getName(); $this->parameters[$parameterName] = $parameter; return $this; }
private function getServiceCode() { $code = new ClassGenerator($this->service->getName(), $this->namespace, null, '\\SoapClient'); $doc = $this->service->getDoc(); if ($doc) { $docBlock = new DocBlockGenerator($doc); $code->setDocBlock($docBlock); } foreach ($this->service->getFunctions() as $function) { $method = new MethodGenerator($function->getMethod()); $docBlock = new DocBlockGenerator($function->getDoc()); foreach ($function->getParams() as $param) { $methodParam = new ParameterGenerator($param->getName()); if (false === $param->isPrimitive()) { $methodParam->setType('\\' . $this->getFullNamespace($param->getType())); } $method->setParameter($methodParam); $tag = new Tag(); $tag->setName('property'); $type = $param->getType(); if (false === $param->isPrimitive()) { $type = '\\' . $this->getFullNamespace($param->getType()); } $tag->setDescription(sprintf('%s $%s', $type, $param->getName())); $docBlock->setTag($tag); } $tag = new Tag(); $tag->setName('returns'); $tag->setDescription("\\" . $this->getFullNamespace($function->getReturns())); $docBlock->setTag($tag); $method->setBody(sprintf('return $this->__soapCall("%s", func_get_args());', $function->getName())); $method->setDocBlock($docBlock); $code->addMethodFromGenerator($method); } return $code; }