addMethodFromGenerator() public method

Add Method from MethodGenerator
public addMethodFromGenerator ( MethodGenerator $method ) : self
$method MethodGenerator
return self
 /**
  * {@inheritdoc}
  */
 public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
 {
     CanProxyAssertion::assertClassCanBeProxied($originalClass);
     $classGenerator->setExtendedClass($originalClass->getName());
     $additionalInterfaces = ['OpenClassrooms\\ServiceProxy\\ServiceProxyInterface'];
     $additionalProperties['proxy_realSubject'] = new PropertyGenerator('proxy_realSubject', null, PropertyGenerator::FLAG_PRIVATE);
     $additionalMethods['setProxy_realSubject'] = new MethodGenerator('setProxy_realSubject', [['name' => 'realSubject']], MethodGenerator::FLAG_PUBLIC, '$this->proxy_realSubject = $realSubject;');
     $methods = $originalClass->getMethods(\ReflectionMethod::IS_PUBLIC);
     foreach ($methods as $method) {
         $preSource = '';
         $postSource = '';
         $exceptionSource = '';
         $methodAnnotations = $this->annotationReader->getMethodAnnotations($method);
         foreach ($methodAnnotations as $methodAnnotation) {
             if ($methodAnnotation instanceof Cache) {
                 $additionalInterfaces['cache'] = 'OpenClassrooms\\ServiceProxy\\ServiceProxyCacheInterface';
                 $response = $this->cacheStrategy->execute($this->serviceProxyStrategyRequestBuilder->create()->withAnnotation($methodAnnotation)->withClass($originalClass)->withMethod($method)->build());
                 foreach ($response->getMethods() as $methodToAdd) {
                     $additionalMethods[$methodToAdd->getName()] = $methodToAdd;
                 }
                 foreach ($response->getProperties() as $propertyToAdd) {
                     $additionalProperties[$propertyToAdd->getName()] = $propertyToAdd;
                 }
                 $preSource .= $response->getPreSource();
                 $postSource .= $response->getPostSource();
                 $exceptionSource .= $response->getExceptionSource();
             }
         }
         $classGenerator->addMethodFromGenerator($this->generateProxyMethod($method, $preSource, $postSource, $exceptionSource));
     }
     $classGenerator->setImplementedInterfaces($additionalInterfaces);
     $classGenerator->addProperties($additionalProperties);
     $classGenerator->addMethods($additionalMethods);
 }
Example #2
0
 /**
  * {@inheritDoc}
  */
 public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
 {
     $interfaces = array('ProxyManager\\Proxy\\NullObjectInterface');
     if ($originalClass->isInterface()) {
         $interfaces[] = $originalClass->getName();
     } else {
         foreach ($originalClass->getInterfaceNames() as $name) {
             $interfaces[] = $name;
         }
     }
     $classGenerator->setImplementedInterfaces($interfaces);
     foreach (ProxiedMethodsFilter::getProxiedMethods($originalClass) as $method) {
         $classGenerator->addMethodFromGenerator(NullObjectMethodInterceptor::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName())));
     }
     $classGenerator->addMethodFromGenerator(new Constructor($originalClass));
 }
 /**
  * @param ReflectionClass  $originalClass
  * @param ClassGenerator   $classGenerator
  * @param MethodGenerator  $generatedMethod
  *
  * @return void|false
  */
 public static function addMethodIfNotFinal(ReflectionClass $originalClass, ClassGenerator $classGenerator, MethodGenerator $generatedMethod)
 {
     $methodName = $generatedMethod->getName();
     if ($originalClass->hasMethod($methodName) && $originalClass->getMethod($methodName)->isFinal()) {
         return false;
     }
     $classGenerator->addMethodFromGenerator($generatedMethod);
 }
 /**
  * Build method factory
  *
  * @param ClassGenerator $generator
  */
 public function buildFactory(ClassGenerator $generator)
 {
     $docBlock = new DocBlockGenerator('@return ' . $this->config->getName());
     $factory = new MethodGenerator();
     $factory->setDocBlock($docBlock);
     $factory->setName('factory');
     $factory->setBody('return new ' . $this->config->getName() . '();');
     $generator->addMethodFromGenerator($factory);
 }
 /**
  * @param ContextInterface $context
  * @param ClassGenerator   $class
  * @param Property         $property
  *
  * @throws \Zend\Code\Generator\Exception\InvalidArgumentException
  */
 private function implementGetResult(ContextInterface $context, ClassGenerator $class, Property $property)
 {
     $useAssembler = new UseAssembler($this->wrapperClass ?: ResultInterface::class);
     if ($useAssembler->canAssemble($context)) {
         $useAssembler->assemble($context);
     }
     $methodName = 'getResult';
     $class->removeMethod($methodName);
     $class->addMethodFromGenerator(MethodGenerator::fromArray(['name' => $methodName, 'parameters' => [], 'visibility' => MethodGenerator::VISIBILITY_PUBLIC, 'body' => $this->generateGetResultBody($property), 'docblock' => DocBlockGenerator::fromArray(['tags' => [['name' => 'return', 'description' => $this->generateGetResultReturnTag($property)]]])]));
 }
 /**
  * {@inheritDoc}
  */
 public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
 {
     CanProxyAssertion::assertClassCanBeProxied($originalClass);
     $interfaces = array('ProxyManager\\Proxy\\NullObjectInterface');
     if ($originalClass->isInterface()) {
         $interfaces[] = $originalClass->getName();
     }
     $classGenerator->setImplementedInterfaces($interfaces);
     foreach (ProxiedMethodsFilter::getProxiedMethods($originalClass) as $method) {
         $classGenerator->addMethodFromGenerator(NullObjectMethodInterceptor::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName())));
     }
     ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, new Constructor($originalClass));
 }
 /**
  * {@inheritDoc}
  */
 public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
 {
     if ($originalClass->isInterface()) {
         throw InvalidProxiedClassException::interfaceNotSupported($originalClass);
     }
     $classGenerator->setExtendedClass($originalClass->getName());
     $classGenerator->setImplementedInterfaces(array('ProxyManager\\Proxy\\AccessInterceptorInterface'));
     $classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors());
     $classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodPrefixInterceptors());
     $methods = ProxiedMethodsFilter::getProxiedMethods($originalClass, array('__get', '__set', '__isset', '__unset', '__clone', '__sleep'));
     foreach ($methods as $method) {
         $classGenerator->addMethodFromGenerator(InterceptedMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $prefixInterceptors, $suffixInterceptors));
     }
     $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $prefixInterceptors, $suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new SetMethodPrefixInterceptor($prefixInterceptors));
     $classGenerator->addMethodFromGenerator(new SetMethodSuffixInterceptor($suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new MagicGet($originalClass, $prefixInterceptors, $suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new MagicSet($originalClass, $prefixInterceptors, $suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new MagicIsset($originalClass, $prefixInterceptors, $suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new MagicUnset($originalClass, $prefixInterceptors, $suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $prefixInterceptors, $suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new MagicClone($originalClass, $prefixInterceptors, $suffixInterceptors));
 }
 /**
  * Build generators
  *
  * @param  State|\Scaffold\State $state
  * @return \Scaffold\State|void
  */
 public function build(State $state)
 {
     $model = $this->model;
     $generator = new ClassGenerator($model->getName());
     $generator->addUse('Zend\\ServiceManager\\FactoryInterface');
     $generator->addUse('Zend\\ServiceManager\\ServiceLocatorInterface');
     $generator->addUse('Zend\\ServiceManager\\ServiceManager');
     $generator->addUse($state->getServiceModel()->getName());
     $generator->setImplementedInterfaces(['FactoryInterface']);
     $method = new MethodGenerator('createService');
     $method->setParameter(new ParameterGenerator('serviceLocator', 'ServiceLocatorInterface'));
     $method->setBody('return new ' . $state->getServiceModel()->getClassName() . '($serviceLocator);');
     $doc = new DocBlockGenerator('Create service');
     $doc->setTag(new Tag\GenericTag('param', 'ServiceLocatorInterface|ServiceManager $serviceLocator'));
     $doc->setTag(new Tag\GenericTag('return', $state->getServiceModel()->getClassName()));
     $method->setDocBlock($doc);
     $generator->addMethodFromGenerator($method);
     $model->setGenerator($generator);
 }
Example #9
0
    /**
     *
     */
    protected function buildParseMethod()
    {
        $method = new MethodGenerator('parse', ['data']);
        $body = <<<'EOF'
$tokens = $this->tokenizer($data);
$this->stack = new \SplStack();
$this->stack->push(0);

while (true) {
    $token = $tokens[0];
    $state = $this->stack->top();
    $terminal = $token[0];

    if (!isset($this->action[$state][$terminal])) {
        throw new \Exception('Token not allowed here (' . $token[1] . ')');
    }

    $action = $this->action[$state][$terminal];
    if ($action[0] === 0) {
        $this->stack->push($token[1]);
        $this->stack->push($action[1]);
        array_shift($tokens);
    } elseif ($action[0] === 1) {
        $value = $this->reduce($action[2], $action[1]);
        array_unshift($tokens, array($action[3], $value));
    } elseif ($action[0] === 2) {
        $this->stack->pop();
        return $this->stack->pop();
    } else {
        throw new \RuntimeException('Cannot compile');
    }
}

throw new \RuntimeException('Cannot compile. EOF');
EOF;
        $method->setBody($body);
        $this->class->addMethodFromGenerator($method);
    }
Example #10
0
 /**
  * {@inheritDoc}
  */
 public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
 {
     $interfaces = array('ProxyManager\\Proxy\\RemoteObjectInterface');
     if ($originalClass->isInterface()) {
         $interfaces[] = $originalClass->getName();
     } else {
         $classGenerator->setExtendedClass($originalClass->getName());
     }
     $classGenerator->setImplementedInterfaces($interfaces);
     $classGenerator->addPropertyFromGenerator($adapter = new AdapterProperty());
     $methods = ProxiedMethodsFilter::getProxiedMethods($originalClass, array('__get', '__set', '__isset', '__unset'));
     foreach ($methods as $method) {
         $classGenerator->addMethodFromGenerator(RemoteObjectMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $adapter, $originalClass));
     }
     $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $adapter));
     $classGenerator->addMethodFromGenerator(new MagicGet($originalClass, $adapter));
     $classGenerator->addMethodFromGenerator(new MagicSet($originalClass, $adapter));
     $classGenerator->addMethodFromGenerator(new MagicIsset($originalClass, $adapter));
     $classGenerator->addMethodFromGenerator(new MagicUnset($originalClass, $adapter));
 }
    private function buildProxyClass(string $entityInterfaceName, string $proxyNamespace, string $proxyClassName) : string
    {
        $reflectionClass = new ReflectionClass($entityInterfaceName);
        if (!$reflectionClass->isInterface()) {
            throw InvalidInterfaceException::fromInvalidInterface($entityInterfaceName);
        }
        $classGenerator = new ClassGenerator();
        $classGenerator->setNamespaceName($proxyNamespace);
        $classGenerator->setName($proxyClassName);
        $classGenerator->setImplementedInterfaces([$entityInterfaceName, ProxyInterface::class]);
        $classGenerator->addProperty('initializer', null, PropertyGenerator::FLAG_PRIVATE);
        $classGenerator->addProperty('relationId', null, PropertyGenerator::FLAG_PRIVATE);
        $classGenerator->addProperty('realEntity', null, PropertyGenerator::FLAG_PRIVATE);
        $constructorGenerator = new MethodGenerator('__construct', [['name' => 'initializer', 'type' => 'callable'], ['name' => 'relationId']]);
        $constructorGenerator->setBody('
            $this->initializer = $initializer;
            $this->relationId = $relationId;
        ');
        $classGenerator->addMethodFromGenerator($constructorGenerator);
        $getRelationIdGenerator = new MethodGenerator('__getRelationId');
        $getRelationIdGenerator->setBody('
            return $this->relationId;
        ');
        $classGenerator->addMethodFromGenerator($getRelationIdGenerator);
        $getRealEntityGenerator = new MethodGenerator('__getRealEntity');
        $getRealEntityGenerator->setBody('
            if (null === $this->realEntity) {
                $this->realEntity = ($this->initializer)();
                \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class);
            };

            return $this->realEntity;
        ');
        $classGenerator->addMethodFromGenerator($getRealEntityGenerator);
        foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
            $parameters = [];
            $parameterGenerators = [];
            $returnType = $reflectionMethod->getReturnType();
            foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
                $parameterGenerator = new ParameterGenerator($reflectionParameter->getName(), $reflectionParameter->getType(), $reflectionParameter->isDefaultValueAvailable() ? $reflectionParameter->getDefaultValue() : null);
                $parameterGenerator->setVariadic($reflectionParameter->isVariadic());
                $parameterGenerators[] = $parameterGenerator;
                if ($reflectionParameter->isVariadic()) {
                    $parameters[] = '...$' . $reflectionParameter->getName();
                } else {
                    $parameters[] = '$' . $reflectionParameter->getName();
                }
            }
            $methodGenerator = new MethodGenerator();
            $methodGenerator->setName($reflectionMethod->getName());
            $methodGenerator->setVisibility(MethodGenerator::VISIBILITY_PUBLIC);
            $methodGenerator->setParameters($parameterGenerators);
            $methodGenerator->setReturnType($returnType);
            $body = '
                if (null === $this->realEntity) {
                    $this->realEntity = ($this->initializer)();
                    \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class);
                };
            ';
            if ('void' !== $returnType) {
                $body .= 'return ';
            }
            $body .= '$this->realEntity->' . $reflectionMethod->getName() . '(' . implode(', ', $parameters) . ');';
            $methodGenerator->setBody($body);
            $classGenerator->addMethodFromGenerator($methodGenerator);
        }
        $fileGenerator = new FileGenerator();
        $fileGenerator->setClass($classGenerator);
        $filename = null === $this->proxyFolder ? tempnam(sys_get_temp_dir(), $proxyClassName) : sprintf('%s/%s.php', $this->proxyFolder, $proxyClassName);
        $fileGenerator->setFilename($filename);
        $fileGenerator->write();
        return $filename;
    }
 /**
  * {@inheritDoc}
  * @throws InvalidProxiedClassException
  * @throws InvalidArgumentException
  */
 public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
 {
     CanProxyAssertion::assertClassCanBeProxied($originalClass, false);
     $annotation = null;
     $forceLazyInitProperty = new ForceLazyInitProperty();
     $sessionBeansProperty = new SessionBeansProperty();
     $postProcessorsProperty = new BeanPostProcessorsProperty();
     $parameterValuesProperty = new ParameterValuesProperty();
     $beanFactoryConfigurationProperty = new BeanFactoryConfigurationProperty();
     $aliasesProperty = new AliasesProperty();
     $getParameterMethod = new GetParameter($originalClass, $parameterValuesProperty);
     $wrapBeanAsLazyMethod = new WrapBeanAsLazy($originalClass, $beanFactoryConfigurationProperty);
     try {
         $reader = new AnnotationReader();
         $annotation = $reader->getClassAnnotation($originalClass, Configuration::class);
     } catch (Exception $e) {
         throw new InvalidProxiedClassException($e->getMessage(), $e->getCode(), $e);
     }
     if (null === $annotation) {
         throw new InvalidProxiedClassException(sprintf('"%s" seems not to be a valid configuration class. @Configuration annotation missing!', $originalClass->getName()));
     }
     $classGenerator->setExtendedClass($originalClass->getName());
     $classGenerator->setImplementedInterfaces([AliasContainerInterface::class]);
     $classGenerator->addPropertyFromGenerator($forceLazyInitProperty);
     $classGenerator->addPropertyFromGenerator($sessionBeansProperty);
     $classGenerator->addPropertyFromGenerator($postProcessorsProperty);
     $classGenerator->addPropertyFromGenerator($parameterValuesProperty);
     $classGenerator->addPropertyFromGenerator($beanFactoryConfigurationProperty);
     $classGenerator->addPropertyFromGenerator($aliasesProperty);
     $postProcessorMethods = [];
     $aliases = [];
     $methods = $originalClass->getMethods(ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED);
     foreach ($methods as $method) {
         if (null !== $reader->getMethodAnnotation($method, BeanPostProcessor::class)) {
             $postProcessorMethods[] = $method->getName();
             continue;
         }
         /* @var \bitExpert\Disco\Annotations\Bean $beanAnnotation */
         $beanAnnotation = $reader->getMethodAnnotation($method, Bean::class);
         if (null === $beanAnnotation) {
             throw new InvalidProxiedClassException(sprintf('Method "%s" on "%s" is missing the @Bean annotation!', $method->getName(), $originalClass->getName()));
         }
         // if alias is defined append it to the aliases list
         if ($beanAnnotation->getAlias() !== '' && !isset($aliases[$beanAnnotation->getAlias()])) {
             $aliases[$beanAnnotation->getAlias()] = $method->getName();
         }
         /* @var \bitExpert\Disco\Annotations\Parameters $parametersAnnotation */
         $parametersAnnotation = $reader->getMethodAnnotation($method, Parameters::class);
         if (null === $parametersAnnotation) {
             $parametersAnnotation = new Parameters();
         }
         $beanType = $method->getReturnType();
         if (null === $beanType) {
             throw new InvalidProxiedClassException(sprintf('Method "%s" on "%s" is missing the return typehint!', $method->getName(), $originalClass->getName()));
         }
         $beanType = (string) $beanType;
         if (!in_array($beanType, ['array', 'callable', 'bool', 'float', 'int', 'string']) && !class_exists($beanType) && !interface_exists($beanType)) {
             throw new InvalidProxiedClassException(sprintf('Return type of method "%s" on "%s" cannot be found! Did you use the full qualified name?', $method->getName(), $originalClass->getName()));
         }
         $methodReflection = new MethodReflection($method->class, $method->getName());
         $proxyMethod = BeanMethod::generateMethod($methodReflection, $beanAnnotation, $parametersAnnotation, $beanType, $forceLazyInitProperty, $sessionBeansProperty, $postProcessorsProperty, $beanFactoryConfigurationProperty, $getParameterMethod, $wrapBeanAsLazyMethod);
         $classGenerator->addMethodFromGenerator($proxyMethod);
     }
     $aliasesProperty->setDefaultValue($aliases);
     $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $parameterValuesProperty, $sessionBeansProperty, $beanFactoryConfigurationProperty, $postProcessorsProperty, $postProcessorMethods));
     $classGenerator->addMethodFromGenerator($wrapBeanAsLazyMethod);
     $classGenerator->addMethodFromGenerator($getParameterMethod);
     $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $sessionBeansProperty));
     $classGenerator->addMethodFromGenerator(new GetAlias($originalClass, $aliasesProperty));
     $classGenerator->addMethodFromGenerator(new HasAlias($originalClass, $aliasesProperty));
 }
 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;
 }
 /**
  * {@inheritdoc}
  */
 public function addMethodFromGenerator(MethodGenerator $method)
 {
     $method->setInterface(true);
     return parent::addMethodFromGenerator($method);
 }
 /**
  * creates Module class
  */
 protected function createModuleClass()
 {
     $moduleClassFilePath = $this->moduleRoot() . '/Module.php';
     if (!file_exists($moduleClassFilePath)) {
         $this->console('creating Module Class');
         $moduleClassFile = new FileGenerator();
         $moduleClassFile->setNamespace($this->params->getParam('moduleName'));
         $moduleClass = new ClassGenerator();
         $moduleClass->setDocBlock($this->getFileDocBlock())->getDocBlock()->setShortDescription($this->codeLibrary()->get('module.moduleClassDescription'));
         $moduleClass->setName('Module');
         // onbootstrap
         $onBootstrapMethod = new MethodGenerator();
         $onBootstrapMethod->setName('onBootstrap')->setBody($this->codeLibrary()->get('module.onBootstrap.body'));
         $onBootstrapMethod->setDocBlock(new DocBlockGenerator($this->codeLibrary()->get('module.onBootstrap.shortdescription'), $this->codeLibrary()->get('module.onBootstrap.longdescription'), array(new ParamTag('e', '\\Zend\\Mvc\\MvcEvent'))));
         $eventParam = new ParameterGenerator('e', '\\Zend\\Mvc\\MvcEvent');
         $onBootstrapMethod->setParameter($eventParam);
         $moduleClass->addMethodFromGenerator($onBootstrapMethod);
         // config
         $configMethod = new MethodGenerator('getConfig', array(), MethodGenerator::FLAG_PUBLIC, $this->codeLibrary()->get('module.config.body'), new DocBlockGenerator($this->codeLibrary()->get('module.config.shortdescription'), $this->codeLibrary()->get('module.config.longdescription'), array()));
         $moduleClass->addMethodFromGenerator($configMethod);
         // getAutoloaderConfig
         $getAutoloaderConfigMethod = new MethodGenerator('getAutoloaderConfig', array(), MethodGenerator::FLAG_PUBLIC, $this->codeLibrary()->get('module.getAutoloaderConfig.body'), new DocBlockGenerator($this->codeLibrary()->get('module.getAutoloaderConfig.shortdescription'), $this->codeLibrary()->get('module.getAutoloaderConfig.longdescription'), array()));
         $moduleClass->addMethodFromGenerator($getAutoloaderConfigMethod);
         // adding class method and generating file
         $moduleClassFile->setClass($moduleClass);
         file_put_contents($moduleClassFilePath, $moduleClassFile->generate());
     }
 }
 /**
  * generates empty methods for events to be overwriten in model
  *
  * @param \Zend\Code\Generator\ClassGenerator $class
  */
 protected function addEventsMethods(ClassGenerator $class)
 {
     foreach ($this->baseModelEventsMethods as $methodName) {
         $method = new MethodGenerator();
         $method->setName($methodName);
         $parameter = new \Zend\Code\Generator\ParameterGenerator();
         $parameter->setName("eventManager");
         $parameter->setType("EventManagerInterface");
         $method->setParameter($parameter);
         $docblock = new \Zend\Code\Generator\DocblockGenerator($this->codeLibrary()->get('model.' . $methodName . '.description'));
         $docblock->setTag(array("name" => "param", "description" => "EventManagerInterface"));
         $method->setDocBlock($docblock);
         $class->addMethodFromGenerator($method);
     }
 }
Example #17
0
 /**
  * Create view helper factory
  *
  * @return bool
  */
 public function createViewHelperFactory()
 {
     // get needed options to shorten code
     $moduleName = $this->requestOptions->getModuleName();
     $viewHelperClass = $this->requestOptions->getViewHelperClass();
     $viewHelperPath = $this->requestOptions->getViewHelperPath();
     $factoryClass = $viewHelperClass . 'Factory';
     $factoryFile = $factoryClass . '.php';
     $factoryFilePath = $viewHelperPath . $factoryFile;
     // check for factory class
     if (file_exists($factoryFilePath)) {
         throw new GeneratorException('The factory for this view helper exists already.');
     }
     // create controller class with class generator
     $code = new ClassGenerator();
     $code->setNamespaceName($moduleName . '\\View\\Helper');
     $code->addUse('Zend\\ServiceManager\\FactoryInterface');
     $code->addUse('Zend\\ServiceManager\\ServiceLocatorInterface');
     $code->setName($factoryClass);
     $code->setImplementedInterfaces(array('FactoryInterface'));
     $code->addMethodFromGenerator($this->generateCreateServiceMethod($viewHelperClass, 'viewHelperManager', 'viewHelper'));
     // add optional doc block
     if ($this->flagCreateApiDocs) {
         $code->setDocBlock(new DocBlockGenerator('Factory for ' . $viewHelperClass, 'Please add a proper description for the ' . $viewHelperClass . ' factory', array($this->generatePackageTag($moduleName))));
     }
     // create file with file generator
     $file = new FileGenerator();
     $file->setClass($code);
     // add optional doc block
     if ($this->flagCreateApiDocs) {
         $file->setDocBlock(new DocBlockGenerator('This file was generated by FrilleZFTool.', null, array($this->generatePackageTag($moduleName), $this->generateSeeTag())));
     }
     // write controller class
     if (!file_put_contents($factoryFilePath, $file->generate())) {
         return false;
     }
     return true;
 }
Example #18
0
 /**
  * Add method from MethodGenerator
  *
  * @param  MethodGenerator $method
  * @return $this
  * @throws \InvalidArgumentException
  */
 public function addMethodFromGenerator(MethodGenerator $method)
 {
     if (!is_string($method->getName())) {
         throw new \InvalidArgumentException('addMethodFromGenerator() expects string for name');
     }
     return parent::addMethodFromGenerator($method);
 }
    public function testSetMethodNameAlreadyExistsThrowsException()
    {
        $methodA = new MethodGenerator();
        $methodA->setName("foo");
        $methodB = new MethodGenerator();
        $methodB->setName("foo");

        $classGenerator = new ClassGenerator();
        $classGenerator->addMethodFromGenerator($methodA);

        $this->setExpectedException(
            'Zend\Code\Generator\Exception\InvalidArgumentException',
            'A method by name foo already exists in this class.'
        );

        $classGenerator->addMethodFromGenerator($methodB);
    }
 /**
  * generates method initFilters for grid
  *
  * @param \Zend\Code\Generator\ClassGenerator $class
  * @param DataSetDescriptorInterface $dataSet
  */
 protected function generateInitFiltersMehod(ClassGenerator $class, DataSetDescriptorInterface $dataSet)
 {
     $body = "";
     foreach ($dataSet->listGenerator() as $column) {
         $name = $column->getName();
         $type = $this->getFieldType($column);
         $body .= sprintf($this->codeLibrary()->get('grid.initFilters.' . $type), $name, $name);
     }
     $method = new MethodGenerator("initFilters");
     $method->setBody($body);
     $method->setFlags(\Zend\Code\Generator\MethodGenerator::FLAG_PROTECTED);
     $parameter = new \Zend\Code\Generator\ParameterGenerator("query");
     $parameter->setType("\\Zend\\Db\\Sql\\Select");
     $method->setParameter($parameter);
     $class->addMethodFromGenerator($method);
 }
 /**
  * generates propertiy, getter, setter and other methods...
  *
  * @param \Zend\Code\Generator\ClassGenerator $class
  * @param \VisioCrudModeler\Descriptor\Db\DbDataSetDescriptor $dataSet
  */
 protected function generateConstructor(ClassGenerator $class, \VisioCrudModeler\Descriptor\AbstractDataSetDescriptor $dataSet)
 {
     $constructor = new MethodGenerator("__construct");
     $constructor->addFlag(MethodGenerator::FLAG_PUBLIC);
     $methodBody = $this->codeLibrary()->get("filter.constructor.body.begin");
     foreach ($dataSet->listGenerator() as $column) {
         $methodBody .= $this->generateFilterForColumn($column);
     }
     $constructor->setBody($methodBody);
     $class->addMethodFromGenerator($constructor);
 }
Example #22
0
 private function handleAdder(Generator\ClassGenerator $generator, PHPProperty $prop, PHPClass $class)
 {
     $type = $prop->getType();
     $propName = $type->getArg()->getName();
     $docblock = new DocBlockGenerator();
     $docblock->setShortDescription("Adds as {$propName}");
     if ($prop->getDoc()) {
         $docblock->setLongDescription($prop->getDoc());
     }
     $return = new ReturnTag();
     $return->setTypes("self");
     $docblock->setTag($return);
     $patramTag = new ParamTag($propName, $this->getPhpType($type->getArg()->getType()));
     $docblock->setTag($patramTag);
     $method = new MethodGenerator("addTo" . Inflector::classify($prop->getName()));
     $parameter = new ParameterGenerator($propName);
     $tt = $type->getArg()->getType();
     if (!$this->isNativeType($tt)) {
         if ($p = $this->isOneType($tt)) {
             if ($t = $p->getType()) {
                 $patramTag->setTypes($this->getPhpType($t));
                 if (!$this->isNativeType($t)) {
                     $parameter->setType($this->getPhpType($t));
                 }
             }
         } elseif (!$this->isNativeType($tt)) {
             $parameter->setType($this->getPhpType($tt));
         }
     }
     $methodBody = "\$this->" . $prop->getName() . "[] = \$" . $propName . ";" . PHP_EOL;
     $methodBody .= "return \$this;";
     $method->setBody($methodBody);
     $method->setDocBlock($docblock);
     $method->setParameter($parameter);
     $generator->addMethodFromGenerator($method);
 }
Example #23
0
 /**
  * @param string $proxyName
  * @return \Zend\Code\Generator\ClassGenerator
  */
 private function createProxyClass($proxyName)
 {
     $proxyClass = new Generator\ClassGenerator($proxyName);
     $proxyClass->setExtendedClass($this->fullClassName);
     foreach ($this->injectableArguments as $injectableArgument) {
         $injectorMethod = new \Zend\Code\Generator\MethodGenerator('propertyInjection' . $injectableArgument->getName());
         $injectorMethod->setBody($injectableArgument->getProcessingBody());
         $proxyClass->addMethodFromGenerator($injectorMethod);
     }
     return $proxyClass;
 }
 public function controllerAction()
 {
     $config = $this->getServiceLocator()->get('config');
     $moduleName = $config['VisioCrudModeler']['params']['moduleName'];
     $modulePath = $config['VisioCrudModeler']['params']['modulesDirectory'];
     $db = $this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter');
     $dataSourceDescriptor = new DbDataSourceDescriptor($db, 'K08_www_biedronka_pl');
     $listDataSets = $dataSourceDescriptor->listDataSets();
     $filter = new \Zend\Filter\Word\UnderscoreToCamelCase();
     foreach ($listDataSets as $d) {
         $className = $filter->filter($d) . 'Controller';
         $file = new FileGenerator();
         $file->setFilename($className);
         $file->setNamespace($moduleName)->setUse('Zend\\Mvc\\Controller\\AbstractActionController');
         $foo = new ClassGenerator();
         $docblock = DocBlockGenerator::fromArray(array('shortDescription' => 'Sample generated class', 'longDescription' => 'This is a class generated with Zend\\Code\\Generator.', 'tags' => array(array('name' => 'version', 'description' => '$Rev:$'), array('name' => 'license', 'description' => 'New BSD'))));
         $foo->setName($className);
         $foo->setExtendedClass('Base' . $className);
         $foo->setDocblock($docblock);
         $file->setClass($foo);
         echo '<pre>';
         echo htmlentities($file->generate());
         echo '</pre>';
         $fileView = new FileGenerator();
         $body = "echo '{$className}';";
         $fileView->setBody($body);
         echo '<pre>';
         echo htmlentities($fileView->generate());
         echo '</pre>';
     }
     echo '<hr />';
     foreach ($listDataSets as $d) {
         $className = 'Base' . $filter->filter($d) . 'Controller';
         $fileBase = new FileGenerator();
         $fileBase->setFilename($className);
         $fileBase->setNamespace($moduleName)->setUse('Zend\\Mvc\\Controller\\AbstractActionController');
         $fooBase = new ClassGenerator();
         $docblockBase = DocBlockGenerator::fromArray(array('shortDescription' => 'Sample generated class', 'longDescription' => 'This is a class generated with Zend\\Code\\Generator.', 'tags' => array(array('name' => 'version', 'description' => '$Rev:$'), array('name' => 'license', 'description' => 'New BSD'))));
         $fooBase->setName($className);
         $index = new MethodGenerator();
         $index->setName('indexAction');
         $create = new MethodGenerator();
         $create->setName('createAction');
         $read = new MethodGenerator();
         $read->setName('readAction');
         $update = new MethodGenerator();
         $update->setName('updateAction');
         $delete = new MethodGenerator();
         $delete->setName('deleteAction');
         $fooBase->setExtendedClass('AbstractActionController');
         //$fooBase->set
         $fooBase->setDocblock($docblock);
         $fooBase->addMethodFromGenerator($index);
         $fooBase->addMethodFromGenerator($create);
         $fooBase->addMethodFromGenerator($read);
         $fooBase->addMethodFromGenerator($update);
         $fooBase->addMethodFromGenerator($delete);
         $fileBase->setClass($fooBase);
         echo '<pre>';
         echo htmlentities($fileBase->generate());
         echo '</pre>';
     }
     exit;
 }
 /**
  * {@inheritDoc}
  */
 public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
 {
     $interfaces = array('ProxyManager\\Proxy\\GhostObjectInterface');
     $publicProperties = new PublicPropertiesMap($originalClass);
     $publicPropsDefaults = new PublicPropertiesDefaults($originalClass);
     if ($originalClass->isInterface()) {
         $interfaces[] = $originalClass->getName();
     } else {
         $classGenerator->setExtendedClass($originalClass->getName());
     }
     $classGenerator->setImplementedInterfaces($interfaces);
     $classGenerator->addPropertyFromGenerator($initializer = new InitializerProperty());
     $classGenerator->addPropertyFromGenerator($initializationTracker = new InitializationTracker());
     $classGenerator->addPropertyFromGenerator($publicProperties);
     $classGenerator->addPropertyFromGenerator($publicPropsDefaults);
     $init = new CallInitializer($initializer, $publicPropsDefaults, $initializationTracker);
     $classGenerator->addMethodFromGenerator($init);
     foreach (ProxiedMethodsFilter::getProxiedMethods($originalClass) as $method) {
         $classGenerator->addMethodFromGenerator(LazyLoadingMethodInterceptor::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $initializer, $init));
     }
     $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $initializer));
     $classGenerator->addMethodFromGenerator(new MagicGet($originalClass, $initializer, $init, $publicProperties));
     $classGenerator->addMethodFromGenerator(new MagicSet($originalClass, $initializer, $init, $publicProperties));
     $classGenerator->addMethodFromGenerator(new MagicIsset($originalClass, $initializer, $init, $publicProperties));
     $classGenerator->addMethodFromGenerator(new MagicUnset($originalClass, $initializer, $init, $publicProperties));
     $classGenerator->addMethodFromGenerator(new MagicClone($originalClass, $initializer, $init));
     $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $initializer, $init));
     $classGenerator->addMethodFromGenerator(new SetProxyInitializer($initializer));
     $classGenerator->addMethodFromGenerator(new GetProxyInitializer($initializer));
     $classGenerator->addMethodFromGenerator(new InitializeProxy($initializer, $init));
     $classGenerator->addMethodFromGenerator(new IsProxyInitialized($initializer));
 }
 /**
  * adds standard CRUD methods to given class
  *
  * @param ClassGenerator $class
  * @param DataSetDescriptorInterface $dataSet
  */
 protected function addControllerMethods(ClassGenerator $class, DataSetDescriptorInterface $dataSet)
 {
     $class->addMethodFromGenerator($this->generateMethod($dataSet, 'createAction'));
     $class->addMethodFromGenerator($this->generateMethod($dataSet, 'listAction'));
     $class->addMethodFromGenerator($this->generateMethod($dataSet, 'ajaxListAction'));
     $class->addMethodFromGenerator($this->generateMethod($dataSet, 'updateAction'));
     $class->addMethodFromGenerator($this->generateMethod($dataSet, 'deleteAction'));
     $class->addMethodFromGenerator($this->generateMethod($dataSet, 'getAdapter'));
     $class->addMethodFromGenerator($this->generateMethod($dataSet, 'getTable'));
     $htmlResponse = $this->generateMethod($dataSet, 'htmlResponse');
     $htmlResponse->setParameter('html');
     $class->addMethodFromGenerator($htmlResponse);
 }
Example #27
0
 /**
  * @param ClassGenerator $class
  * @param Attribute $tagAttribute
  */
 protected function addAttribute(ClassGenerator $class, Attribute $tagAttribute)
 {
     $methodName = str_replace(':', '-', $tagAttribute->getName());
     $methodName = ucfirst($this->stringToCamelCaseConverter->convert($methodName, '-'));
     $method = new MethodGenerator();
     if ($tagAttribute->isFlag()) {
         $method->setName('is' . $methodName);
         $method->setParameter(new ParameterGenerator('v', 'bool', true));
     } else {
         $method->setName('set' . $methodName);
         $method->setParameter(new ParameterGenerator('v', 'string'));
     }
     $body = [];
     $body[] = '$this->attributes[\'' . $tagAttribute->getName() . '\'] = $v;';
     $body[] = 'return $this;';
     $method->setBody(implode(PHP_EOL, $body));
     $docBlock = new DocBlockGenerator();
     $docBlock->setTag(new GenericTag('var', 'string'));
     $docBlock->setTag(new GenericTag('return', '$this'));
     if (!is_null($tagAttribute->getDescription())) {
         $docBlock->setLongDescription($tagAttribute->getDescription());
     }
     $method->setDocBlock($docBlock);
     $class->addMethodFromGenerator($method);
 }
    public function buildGetInputFilter(ClassGenerator $generator, State $state)
    {
        $method = new MethodGenerator('getInputFilter');
        $method->setDocBlock(new DocBlockGenerator());
        $method->getDocBlock()->setTag(['name' => 'return', 'description' => 'InputFilterInterface']);
        $method->setBody(<<<EOF
return (new Factory())->createInputFilter(
    array(

    )
);
EOF
);
        $generator->addMethodFromGenerator($method);
    }
 /**
  * {@inheritDoc}
  */
 public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
 {
     $publicProperties = new PublicPropertiesMap($originalClass);
     $interfaces = array('ProxyManager\\Proxy\\AccessInterceptorInterface', 'ProxyManager\\Proxy\\ValueHolderInterface');
     if ($originalClass->isInterface()) {
         $interfaces[] = $originalClass->getName();
     } else {
         $classGenerator->setExtendedClass($originalClass->getName());
     }
     $classGenerator->setImplementedInterfaces($interfaces);
     $classGenerator->addPropertyFromGenerator($valueHolder = new ValueHolderProperty());
     $classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors());
     $classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodSuffixInterceptors());
     $classGenerator->addPropertyFromGenerator($publicProperties);
     foreach (ProxiedMethodsFilter::getProxiedMethods($originalClass) as $method) {
         $classGenerator->addMethodFromGenerator(InterceptedMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $valueHolder, $prefixInterceptors, $suffixInterceptors));
     }
     $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new GetWrappedValueHolderValue($valueHolder));
     $classGenerator->addMethodFromGenerator(new SetMethodPrefixInterceptor($prefixInterceptors));
     $classGenerator->addMethodFromGenerator(new SetMethodSuffixInterceptor($suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new MagicGet($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties));
     $classGenerator->addMethodFromGenerator(new MagicSet($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties));
     $classGenerator->addMethodFromGenerator(new MagicIsset($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties));
     $classGenerator->addMethodFromGenerator(new MagicUnset($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties));
     $classGenerator->addMethodFromGenerator(new MagicClone($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors));
     $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $valueHolder));
     $classGenerator->addMethodFromGenerator(new MagicWakeup($originalClass, $valueHolder));
 }
Example #30
0
 /**
  * @param ClassGenerator $class
  * @param Property       $firstProperty
  *
  * @throws \Zend\Code\Generator\Exception\InvalidArgumentException
  */
 private function implementGetIterator($class, $firstProperty)
 {
     $methodName = 'getIterator';
     $class->removeMethod($methodName);
     $class->addMethodFromGenerator(MethodGenerator::fromArray(['name' => $methodName, 'parameters' => [], 'visibility' => MethodGenerator::VISIBILITY_PUBLIC, 'body' => sprintf('return new \\ArrayIterator(is_array($this->%1$s) ? $this->%1$s : []);', $firstProperty->getName()), 'docblock' => DocBlockGenerator::fromArray(['tags' => [['name' => 'return', 'description' => '\\ArrayIterator']]])]));
 }