Пример #1
0
 public function testSetGetType()
 {
     $param = new PhpParameter();
     $this->assertNull($param->getType());
     $this->assertSame($param, $param->setType('array'));
     $this->assertEquals('array', $param->getType());
 }
 public function generate(\ReflectionClass $originalClass, PhpClass $genClass)
 {
     $methods = ReflectionUtils::getOverrideableMethods($originalClass);
     if (null !== $this->filter) {
         $methods = array_filter($methods, $this->filter);
     }
     if (empty($methods)) {
         return;
     }
     if (!empty($this->requiredFile)) {
         $genClass->addRequiredFile($this->requiredFile);
     }
     $interceptorLoader = new PhpProperty();
     $interceptorLoader->setName($this->prefix . 'loader')->setVisibility(PhpProperty::VISIBILITY_PRIVATE);
     $genClass->setProperty($interceptorLoader);
     $loaderSetter = new PhpMethod();
     $loaderSetter->setName($this->prefix . 'setLoader')->setVisibility(PhpMethod::VISIBILITY_PUBLIC)->setBody('$this->' . $this->prefix . 'loader = $loader;');
     $genClass->setMethod($loaderSetter);
     $loaderParam = new PhpParameter();
     $loaderParam->setName('loader')->setType('CG\\Proxy\\InterceptorLoaderInterface');
     $loaderSetter->addParameter($loaderParam);
     $interceptorCode = '$ref = new \\ReflectionMethod(%s, %s);' . "\n" . '$interceptors = $this->' . $this->prefix . 'loader->loadInterceptors($ref, $this, array(%s));' . "\n" . '$invocation = new \\CG\\Proxy\\MethodInvocation($ref, $this, array(%s), $interceptors);' . "\n\n" . 'return $invocation->proceed();';
     foreach ($methods as $method) {
         $params = array();
         foreach ($method->getParameters() as $param) {
             $params[] = '$' . $param->name;
         }
         $params = implode(', ', $params);
         $genMethod = PhpMethod::fromReflection($method)->setBody(sprintf($interceptorCode, var_export(ClassUtils::getUserClass($method->class), true), var_export($method->name, true), $params, $params))->setDocblock(null);
         $genClass->setMethod($genMethod);
     }
 }
Пример #3
0
 public function testVisitMethodWithCallable()
 {
     if (PHP_VERSION_ID < 50400) {
         $this->markTestSkipped('`callable` is only supported in PHP >=5.4.0');
     }
     $method = new PhpMethod();
     $parameter = new PhpParameter('bar');
     $parameter->setType('callable');
     $method->setName('foo')->addParameter($parameter);
     $visitor = new DefaultVisitor();
     $visitor->visitMethod($method);
     $this->assertEquals($this->getContent('callable_parameter.php'), $visitor->getContent());
 }
 /**
  * {@inheritdoc}
  */
 public function generate($className, GeneratorData $data, VisitorCollection $visitorCollection = null)
 {
     $this->visitorCollection = $visitorCollection ?: new VisitorCollection();
     $this->prepare($data, $this->visitorCollection);
     $this->validate($data);
     $class = PhpClass::create($className);
     $visitContext = new VisitContext($class);
     if ($data->getFilename()) {
         $writer = $visitContext->createWriter();
         $writer->writeln('/**')->writeln(' * Filename: ' . $data->getFilename())->writeln(' */');
         $class->setDocblock($writer->getContent());
     }
     $class->addInterfaceName('Oro\\Component\\Layout\\LayoutUpdateInterface');
     $method = PhpMethod::create(LayoutUpdateGeneratorInterface::UPDATE_METHOD_NAME);
     $manipulatorParameter = PhpParameter::create(LayoutUpdateGeneratorInterface::PARAM_LAYOUT_MANIPULATOR);
     $manipulatorParameter->setType('Oro\\Component\\Layout\\LayoutManipulatorInterface');
     $method->addParameter($manipulatorParameter);
     $layoutItemParameter = PhpParameter::create(LayoutUpdateGeneratorInterface::PARAM_LAYOUT_ITEM);
     $layoutItemParameter->setType('Oro\\Component\\Layout\\LayoutItemInterface');
     $method->addParameter($layoutItemParameter);
     /** @var VisitorInterface $condition */
     foreach ($this->visitorCollection as $condition) {
         $condition->startVisit($visitContext);
     }
     $writer = $visitContext->getUpdateMethodWriter();
     $writer->writeLn(trim($this->doGenerateBody($data)));
     /** @var VisitorInterface $condition */
     foreach ($this->visitorCollection as $condition) {
         $condition->endVisit($visitContext);
     }
     $method->setBody($writer->getContent());
     $class->setMethod($method);
     $strategy = new DefaultGeneratorStrategy();
     return "<?php\n\n" . $strategy->generate($class);
 }
 public function generate(\ReflectionClass $original, PhpClass $proxy)
 {
     $writer = new Writer();
     // copy over all public methods
     foreach ($original->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
         if ($method->isStatic()) {
             continue;
         }
         $writer->reset()->write('return $this->delegate->')->write($method->name)->write('(');
         $first = true;
         foreach ($method->getParameters() as $param) {
             if (!$first) {
                 $writer->write(', ');
             }
             $first = false;
             $writer->write('$')->write($param->name);
         }
         $writer->write(');');
         $proxyMethod = PhpMethod::fromReflection($method)->setBody($writer->getContent());
         $proxy->setMethod($proxyMethod);
     }
     $proxy->setProperty(PhpProperty::create('delegate')->setVisibility('private'));
     $proxy->setProperty(PhpProperty::create('container')->setVisibility('private'));
     $proxy->setMethod(PhpMethod::create('__construct')->setVisibility('public')->addParameter(PhpParameter::create('objectManager')->setType('Doctrine\\Common\\Persistence\\ObjectManager'))->addParameter(PhpParameter::create('container')->setType('Symfony\\Component\\DependencyInjection\\ContainerInterface'))->setBody($writer->reset()->writeln('$this->delegate = $objectManager;')->writeln('$this->container = $container;')->getContent()));
     $proxy->setMethod(PhpMethod::fromReflection($original->getMethod('getRepository'))->setParameters(array(PhpParameter::create('className')))->setBody($writer->reset()->writeln('$repository = $this->delegate->getRepository($className);' . "\n")->writeln('if (null !== $metadata = $this->container->get("jms_di_extra.metadata.metadata_factory")->getMetadataForClass(get_class($repository))) {')->indent()->writeln('foreach ($metadata->classMetadata as $classMetadata) {')->indent()->writeln('foreach ($classMetadata->methodCalls as $call) {')->indent()->writeln('list($method, $arguments) = $call;')->writeln('call_user_func_array(array($repository, $method), $this->prepareArguments($arguments));')->outdent()->writeln('}')->outdent()->writeln('}')->outdent()->writeln('}' . "\n")->writeln('return $repository;')->getContent()));
     $proxy->setMethod(PhpMethod::create('prepareArguments')->setVisibility('private')->addParameter(PhpParameter::create('arguments')->setType('array'))->setBody($writer->reset()->writeln('$processed = array();')->writeln('foreach ($arguments as $arg) {')->indent()->writeln('if ($arg instanceof \\Symfony\\Component\\DependencyInjection\\Reference) {')->indent()->writeln('$processed[] = $this->container->get((string) $arg, $arg->getInvalidBehavior());')->outdent()->writeln('} else if ($arg instanceof \\Symfony\\Component\\DependencyInjection\\Parameter) {')->indent()->writeln('$processed[] = $this->container->getParameter((string) $arg);')->outdent()->writeln('} else {')->indent()->writeln('$processed[] = $arg;')->outdent()->writeln('}')->outdent()->writeln('}' . "\n")->writeln('return $processed;')->getContent()));
 }
 /**
  * @param array    $schema
  * @param PhpClass $class
  */
 protected function generateConstructor(array $schema, PhpClass $class)
 {
     $constructorParams = [];
     $constructorBody = [];
     if (!empty($schema['inherit'])) {
         $parent = new \ReflectionClass($schema['inherit']);
         $parentConstructor = $parent->getConstructor();
         if ($parentConstructor) {
             $params = $parentConstructor->getParameters();
             $callParamsDef = [];
             foreach ($params as $param) {
                 $constructorParams[] = PhpParameter::fromReflection($param);
                 $callParamsDef[] = '$' . $param->getName();
             }
             $constructorBody[] = sprintf('parent::__construct(%s);', implode(', ', $callParamsDef));
         }
     }
     foreach ($schema['addremove'] as $fieldName => $config) {
         $constructorBody[] = '$this->' . $fieldName . ' = new \\Doctrine\\Common\\Collections\\ArrayCollection();';
     }
     $constructor = $this->generateClassMethod('__construct', implode("\n", $constructorBody));
     foreach ($constructorParams as $constructorParam) {
         $constructor->addParameter($constructorParam);
     }
     $class->setMethod($constructor);
 }
Пример #7
0
    public function testFromReflection()
    {
        if (PHP_VERSION_ID < 70000) {
            $this->markTestSkipped("Test is only valid for PHP >=7");
        }
        $class = new PhpClass();
        $class->setName('CG\\Tests\\Generator\\Fixture\\EntityPhp7')->setDocblock('/**
 * Doc Comment.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */')->setProperty(PhpProperty::create('id')->setVisibility('private')->setDefaultValue(0)->setDocblock('/**
 * @var integer
 */'));
        $class->setMethod(PhpMethod::create()->setName('getId')->setDocblock('/**
 * @return int
 */')->setVisibility('public')->setReturnType('int'));
        $class->setMethod(PhpMethod::create()->setName('setId')->setVisibility('public')->setDocBlock('/**
 * @param int $id
 * @return EntityPhp7
 */')->addParameter(PhpParameter::create()->setName('id')->setType('int')->setDefaultValue(null))->setReturnType('self'));
        $class->setMethod(PhpMethod::create()->setName('getTime')->setVisibility('public')->setReturnType('DateTime'));
        $class->setMethod(PhpMethod::create()->setName('getTimeZone')->setVisibility('public')->setReturnType('DateTimeZone'));
        $class->setMethod(PhpMethod::create()->setName('setTime')->setVisibility('public')->addParameter(PhpParameter::create()->setName('time')->setType('DateTime')));
        $class->setMethod(PhpMethod::create()->setName('setTimeZone')->setVisibility('public')->addParameter(PhpParameter::create()->setName('timezone')->setType('DateTimeZone')));
        $class->setMethod(PhpMethod::create()->setName('setArray')->setVisibility('public')->setReturnType('array')->addParameter(PhpParameter::create()->setName('array')->setDefaultValue(null)->setPassedByReference(true)->setType('array')));
        $class->setMethod(PhpMethod::create()->setName('getFoo')->setReturnType('CG\\Tests\\Generator\\Fixture\\SubFixture\\Foo'));
        $class->setMethod(PhpMethod::create()->setName('getBar')->setReturnType('CG\\Tests\\Generator\\Fixture\\SubFixture\\Bar'));
        $class->setMethod(PhpMethod::create()->setName('getBaz')->setReturnType('CG\\Tests\\Generator\\Fixture\\SubFixture\\Baz'));
        $this->assertEquals($class, PhpClass::fromReflection(new \ReflectionClass('CG\\Tests\\Generator\\Fixture\\EntityPhp7')));
    }
 public function testVisitFunction()
 {
     $writer = new Writer();
     $function = new PhpFunction();
     $function->setName('foo')->addParameter(PhpParameter::create('a'))->addParameter(PhpParameter::create('b'))->setBody($writer->writeln('if ($a === $b) {')->indent()->writeln('throw new \\InvalidArgumentException(\'$a is not allowed to be the same as $b.\');')->outdent()->write("}\n\n")->write('return $b;')->getContent());
     $visitor = new DefaultVisitor();
     $visitor->visitFunction($function);
     $this->assertEquals($this->getContent('a_b_function.php'), $visitor->getContent());
 }
 /**
  * @param string $methodName
  * @param string $methodBody
  * @param array  $methodArgs
  *
  * @return PhpMethod
  */
 protected function generateClassMethod($methodName, $methodBody, $methodArgs = [])
 {
     $writer = new Writer();
     $method = PhpMethod::create($methodName)->setBody($writer->write($methodBody)->getContent());
     if (count($methodArgs)) {
         foreach ($methodArgs as $arg) {
             $method->addParameter(PhpParameter::create($arg));
         }
     }
     return $method;
 }
Пример #10
0
 public function generate(\ReflectionClass $original, PhpClass $proxy)
 {
     if (empty($this->overrides)) {
         throw new \RuntimeException('No overriding methods defined');
     }
     $writer = new Writer();
     $proxy->setProperty(PhpProperty::create('__MessagingAdapter')->setVisibility(PhpProperty::VISIBILITY_PRIVATE))->setMethod(PhpMethod::create('__setMessagingAdapter')->addParameter(PhpParameter::create('adapter')->setType('Nfx\\AsyncBundle\\Adapter\\AdapterInterface'))->setBody($writer->reset()->writeln('$this->__MessagingAdapter = $adapter;')->getContent()))->setProperty(PhpProperty::create('__defaultTransform')->setVisibility(PhpProperty::VISIBILITY_PRIVATE))->setMethod(PhpMethod::create('__setDefaultTransform')->addParameter(PhpParameter::create('transform')->setType('Nfx\\AsyncBundle\\Message\\Transform\\TransformInterface'))->setBody($writer->reset()->writeln('$this->__defaultTransform = $transform;')->getContent()));
     foreach ($this->overrides as $closure) {
         $closure($proxy);
     }
 }
 public function generate(\ReflectionClass $class, PhpClass $genClass)
 {
     if (!empty($this->requiredFile)) {
         $genClass->addRequiredFile($this->requiredFile);
     }
     $genClass->setProperty(PhpProperty::create()->setName(self::PREFIX . 'container')->setVisibility('private'));
     $genClass->setMethod(PhpMethod::create()->setName(self::PREFIX . 'setContainer')->addParameter(PhpParameter::create()->setName('container')->setType('Symfony\\Component\\DependencyInjection\\ContainerInterface'))->setBody('$this->' . self::PREFIX . 'container = $container;'));
     $genClass->addInterfaceName('JMS\\DiExtraBundle\\DependencyInjection\\LookupMethodClassInterface');
     $genClass->setMethod(PhpMethod::create()->setName(self::PREFIX . 'getOriginalClassName')->setFinal(true)->setBody('return ' . var_export($class->name, true) . ';'));
     foreach ($this->getLookupMethods() as $name => $value) {
         $genClass->setMethod(PhpMethod::fromReflection($class->getMethod($name))->setAbstract(false)->setBody('return ' . $this->dumpValue($value) . ';')->setDocblock(null));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function startVisit(VisitContext $visitContext)
 {
     $writer = $visitContext->createWriter();
     $class = $visitContext->getClass();
     $class->addInterfaceName('Oro\\Component\\ConfigExpression\\ExpressionFactoryAwareInterface');
     $setFactoryMethod = PhpMethod::create('setExpressionFactory');
     $setFactoryMethod->addParameter(PhpParameter::create('expressionFactory')->setType('Oro\\Component\\ConfigExpression\\ExpressionFactoryInterface'));
     $setFactoryMethod->setBody($writer->write('$this->expressionFactory = $expressionFactory;')->getContent());
     $class->setMethod($setFactoryMethod);
     $factoryProperty = PhpProperty::create('expressionFactory');
     $factoryProperty->setVisibility(PhpProperty::VISIBILITY_PRIVATE);
     $class->setProperty($factoryProperty);
     $visitContext->getUpdateMethodWriter()->writeln('if (null === $this->expressionFactory) {')->writeln('    throw new \\RuntimeException(\'Missing expression factory for layout update\');')->writeln('}')->writeln('')->writeln(sprintf('$expr = %s;', $this->expression->compile('$this->expressionFactory')))->writeln(sprintf('$context = [\'context\' => $%s->getContext()];', LayoutUpdateGeneratorInterface::PARAM_LAYOUT_ITEM))->writeln('if ($expr->evaluate($context)) {')->indent();
 }
 /**
  * @dataProvider conditionDataProvider
  *
  * @param string $oldMethodBody
  * @param mixed  $value
  * @param string $condition
  * @param string $expectedMethodBody
  */
 public function testVisit($oldMethodBody, $value, $condition, $expectedMethodBody)
 {
     $conditionObject = new SimpleContextValueComparisonConditionVisitor('valueToCompare', $condition, $value);
     $phpClass = PhpClass::create('LayoutUpdateClass');
     $visitContext = new VisitContext($phpClass);
     $method = PhpMethod::create(LayoutUpdateGeneratorInterface::UPDATE_METHOD_NAME);
     $method->addParameter(PhpParameter::create(LayoutUpdateGeneratorInterface::PARAM_LAYOUT_MANIPULATOR));
     $method->addParameter(PhpParameter::create(LayoutUpdateGeneratorInterface::PARAM_LAYOUT_ITEM));
     $conditionObject->startVisit($visitContext);
     $visitContext->getUpdateMethodWriter()->writeln($oldMethodBody);
     $conditionObject->endVisit($visitContext);
     $method->setBody($visitContext->getUpdateMethodWriter()->getContent());
     $phpClass->setMethod($method);
     $this->assertSame($expectedMethodBody, $method->getBody());
 }
 protected function generateLoadMethod(PhpClass $class, ClassMetadata $metadata, array $data)
 {
     $writer = new Writer();
     $method = PhpMethod::create('load');
     $managerParameter = PhpParameter::create('manager');
     $managerParameter->setType('Doctrine\\Common\\Persistence\\ObjectManager');
     $method->addParameter($managerParameter);
     $class->setMethod($method);
     foreach ($data as $modelName => $modelData) {
         $search = array(' ', '-', 'á', 'é', 'í', 'ó', 'ú', 'ñ');
         $replace = array('_', '_', 'a', 'e', 'i', 'o', 'u', 'n');
         $withoutSpace = str_replace($search, $replace, $modelName);
         $this->generateModel($withoutSpace, $modelData, $metadata, $writer);
         $writer->writeln("");
     }
     $writer->writeln('$manager->flush();');
     $method->setBody($writer->getContent());
 }
Пример #15
0
 public static function fromReflection(\ReflectionFunction $ref)
 {
     $function = new static();
     if (false === ($pos = strrpos($ref->name, '\\'))) {
         $function->setName(substr($ref->name, $pos + 1));
         $function->setNamespace(substr($ref->name, $pos));
     } else {
         $function->setName($ref->name);
     }
     $function->referenceReturned = $ref->returnsReference();
     $function->docblock = ReflectionUtils::getUnindentedDocComment($ref->getDocComment());
     foreach ($ref->getParameters() as $refParam) {
         assert($refParam instanceof \ReflectionParameter);
         $param = PhpParameter::fromReflection($refParam);
         $function->addParameter($param);
     }
     return $function;
 }
    public function testVisit()
    {
        $condition = new ConfigExpressionConditionVisitor(new Condition\True());
        $phpClass = PhpClass::create('LayoutUpdateClass');
        $visitContext = new VisitContext($phpClass);
        $method = PhpMethod::create(LayoutUpdateGeneratorInterface::UPDATE_METHOD_NAME);
        $method->addParameter(PhpParameter::create(LayoutUpdateGeneratorInterface::PARAM_LAYOUT_MANIPULATOR));
        $method->addParameter(PhpParameter::create(LayoutUpdateGeneratorInterface::PARAM_LAYOUT_ITEM));
        $condition->startVisit($visitContext);
        $visitContext->getUpdateMethodWriter()->writeln('echo 123;');
        $condition->endVisit($visitContext);
        $method->setBody($visitContext->getUpdateMethodWriter()->getContent());
        $phpClass->setMethod($method);
        $strategy = new DefaultGeneratorStrategy();
        $this->assertSame(<<<CLASS
class LayoutUpdateClass implements \\Oro\\Component\\ConfigExpression\\ExpressionFactoryAwareInterface
{
    private \$expressionFactory;

    public function updateLayout(\$layoutManipulator, \$item)
    {
        if (null === \$this->expressionFactory) {
            throw new \\RuntimeException('Missing expression factory for layout update');
        }

        \$expr = \$this->expressionFactory->create('true', []);
        \$context = ['context' => \$item->getContext()];
        if (\$expr->evaluate(\$context)) {
            echo 123;
        }
    }

    public function setExpressionFactory(\\Oro\\Component\\ConfigExpression\\ExpressionFactoryInterface \$expressionFactory)
    {
        \$this->expressionFactory = \$expressionFactory;
    }
}
CLASS
, $strategy->generate($visitContext->getClass()));
    }
Пример #17
0
    public function testFromReflection()
    {
        $class = new PhpClass();
        $class->setName('CG\\Tests\\Generator\\Fixture\\Entity')->setAbstract(true)->setDocblock('/**
 * Doc Comment.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */')->setProperty(PhpProperty::create('id')->setVisibility('private')->setDocblock('/**
 * @var integer
 */'))->setProperty(PhpProperty::create('enabled')->setVisibility('private')->setDefaultValue(false));
        $method = PhpMethod::create()->setName('__construct')->setFinal(true)->addParameter(new PhpParameter('a'))->addParameter(PhpParameter::create()->setName('b')->setType('array')->setPassedByReference(true))->addParameter(PhpParameter::create()->setName('c')->setType('stdClass'))->addParameter(PhpParameter::create()->setName('d')->setDefaultValue('foo'))->setDocblock('/**
 * Another doc comment.
 *
 * @param unknown_type $a
 * @param array        $b
 * @param \\stdClass    $c
 * @param string       $d
 */');
        $class->setMethod($method);
        $class->setMethod(PhpMethod::create()->setName('foo')->setAbstract(true)->setVisibility('protected'));
        $class->setMethod(PhpMethod::create()->setName('bar')->setStatic(true)->setVisibility('private'));
        $this->assertEquals($class, PhpClass::fromReflection(new \ReflectionClass('CG\\Tests\\Generator\\Fixture\\Entity')));
    }
Пример #18
0
 /**
  * @return \Symforce\AdminBundle\Compiler\Generator\PhpWriter
  */
 public function getCompileValidatorWriter()
 {
     if (null === $this->_compile_validator_writer) {
         $class = $this->getCompileClass();
         $loadValidatorMetadata = $class->addMethod('loadValidatorMetadata')->setVisibility('public')->addParameter(\CG\Generator\PhpParameter::create('metadata')->setType('\\Symfony\\Component\\Validator\\Mapping\\ClassMetadata'));
         $this->_compile_validator_writer = $loadValidatorMetadata->getWriter();
     }
     return $this->_compile_validator_writer;
 }
Пример #19
0
 /**
  * @return PhpParameter
  */
 protected static function createParameter(\ReflectionParameter $parameter)
 {
     return PhpParameter::fromReflection($parameter);
 }
 /**
  * Generates the necessary methods in the class.
  *
  * @param  \ReflectionClass $originalClass
  * @param  PhpClass         $class
  * @return void
  */
 public function generate(\ReflectionClass $originalClass, PhpClass $class)
 {
     $methods = ReflectionUtils::getOverrideableMethods($originalClass, true);
     // no public, non final methods
     if (empty($methods)) {
         return;
     }
     if (null !== $this->markerInterface) {
         $class->setImplementedInterfaces(array_merge($class->getImplementedInterfaces(), array($this->markerInterface)));
     }
     $initializer = new PhpProperty();
     $initializer->setName($this->prefix . 'lazyInitializer');
     $initializer->setVisibility(PhpProperty::VISIBILITY_PRIVATE);
     $class->setProperty($initializer);
     $initialized = new PhpProperty();
     $initialized->setName($this->prefix . 'initialized');
     $initialized->setDefaultValue(false);
     $initialized->setVisibility(PhpProperty::VISIBILITY_PRIVATE);
     $class->setProperty($initialized);
     $initializerSetter = new PhpMethod();
     $initializerSetter->setName($this->prefix . 'setLazyInitializer');
     $initializerSetter->setBody('$this->' . $this->prefix . 'lazyInitializer = $initializer;');
     $parameter = new PhpParameter();
     $parameter->setName('initializer');
     $parameter->setType('\\CG\\Proxy\\LazyInitializerInterface');
     $initializerSetter->addParameter($parameter);
     $class->setMethod($initializerSetter);
     $this->addMethods($class, $methods);
     $initializingMethod = new PhpMethod();
     $initializingMethod->setName($this->prefix . 'initialize');
     $initializingMethod->setVisibility(PhpMethod::VISIBILITY_PRIVATE);
     $initializingMethod->setBody($this->writer->reset()->writeln('if (null === $this->' . $this->prefix . 'lazyInitializer) {')->indent()->writeln('throw new \\RuntimeException("' . $this->prefix . 'setLazyInitializer() must be called prior to any other public method on this object.");')->outdent()->write("}\n\n")->writeln('$this->' . $this->prefix . 'lazyInitializer->initializeObject($this);')->writeln('$this->' . $this->prefix . 'initialized = true;')->getContent());
     $class->setMethod($initializingMethod);
 }
Пример #21
0
 /**
  * @return \Symforce\AdminBundle\Compiler\Generator\PhpWriter
  */
 public function getCompileActionFormWriter()
 {
     if (null !== $this->_compile_action_form_writer) {
         return $this->_compile_action_form_writer;
     }
     $class = $this->admin_object->getCompileClass();
     $fn = 'buildActionFormElement';
     $method = $class->addMethod($fn)->setVisibility('public')->addParameter(\CG\Generator\PhpParameter::create('controller')->setType('\\Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller'))->addParameter(\CG\Generator\PhpParameter::create('builder')->setType('\\Symfony\\Component\\Form\\FormBuilder'))->addParameter(\CG\Generator\PhpParameter::create('admin')->setType('\\Symforce\\AdminBundle\\Compiler\\Cache\\AdminCache'))->addParameter(\CG\Generator\PhpParameter::create('action')->setType('\\Symforce\\AdminBundle\\Compiler\\Cache\\ActionCache'))->addParameter(\CG\Generator\PhpParameter::create('object'))->addParameter(\CG\Generator\PhpParameter::create('property_name'))->addParameter(\CG\Generator\PhpParameter::create('parent_property'))->addParameter(\CG\Generator\PhpParameter::create('options')->setType('array')->setPassedByReference(true));
     $this->_compile_action_form_writer = $method->getWriter();
     return $this->_compile_action_form_writer;
 }
Пример #22
0
 /**
  * @return \Symforce\AdminBundle\Compiler\Generator\PhpWriter
  */
 public function getCompileFormWriter()
 {
     if (null !== $this->_compile_form_writer) {
         return $this->_compile_form_writer;
     }
     $class = $this->admin_object->getCompileClass();
     $fn = 'build' . ucfirst($this->name) . 'Form';
     $method = $class->addMethod($fn)->setVisibility('public')->addParameter(\CG\Generator\PhpParameter::create('controller')->setType('\\Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller'))->addParameter(\CG\Generator\PhpParameter::create('object'))->addParameter(\CG\Generator\PhpParameter::create('builder')->setType('\\Symfony\\Component\\Form\\FormBuilder'))->addParameter(\CG\Generator\PhpParameter::create('action')->setType('\\' . $this->_compile_class_name));
     $method->addLazyCode('$this->buildForm($controller, $builder, $action, $object);');
     $this->_compile_form_writer = $method->getWriter();
     return $this->_compile_form_writer;
 }
 public function compileAnnotations()
 {
     $cache_class = new \Symforce\CoreBundle\PhpHelper\PhpClass();
     $cache_class->setName('Symforce\\Builder\\SymforceAnnotationCache')->setFinal(true)->setParentClassName('Symforce\\CoreBundle\\Annotation\\SymforceAnnotationCache');
     $base_parent_class = sprintf('%s\\SymforceAbstractAnnotation', __NAMESPACE__);
     /**
      * @var $class_builder SymforceAnnotationClassBuilder
      */
     foreach ($this->class_builders as $annotation_name => $class_builder) {
         $_parents = array();
         if ($this->hasParentsLoop($class_builder, $_parents)) {
             throw new \Exception(sprintf("services(tag:{name:%s}) parent circular dependencies: %s ! ", self::CLASS_TAG_NAME, join(',', array_map(function (SymforceAnnotationBuilder $builder) {
                 return sprintf("\n\t,service(%s, tag{alias:%s%s})", $class_builder->getId(), $class_builder->getName(), $class_builder->getParentName() ? ', parent:' . $class_builder->getParentName() : '');
             }, $_parents))));
         }
         $_properties = $class_builder->getProperties();
         $_public_properties = $class_builder->getPublicProperties();
         if ($_public_properties) {
             foreach ($_public_properties as $_public_property_name) {
                 if (!isset($this->public_properties[$_public_property_name])) {
                     throw new \Exception(sprintf("service(%s, tags:{name: %s, alias: %s, properties: %s}) property(%s) must be one of (%s)", $class_builder->getId(), self::CLASS_TAG_NAME, $class_builder->getName(), var_export($_public_properties, 1), var_export($_public_property_name, 1), join(',', array_keys($this->public_properties))));
                 }
             }
         }
         $value_property_name = $class_builder->getValuePropertyName();
         if ($value_property_name) {
             if ($_public_properties) {
                 $_all_properties = array_unique(array_merge(array_keys($_properties), $_public_properties));
             } else {
                 $_all_properties = $_properties;
             }
             if (!$class_builder->hasPropertyBuilder($value_property_name) && !isset($this->public_properties[$value_property_name])) {
                 throw new \Exception(sprintf("service(%s, tags:{name: %s, alias: %s, value: %s}) value must be one of(%s)", $class_builder->getId(), self::CLASS_TAG_NAME, $class_builder->getName(), $value_property_name, join(',', $_all_properties)));
             }
         } else {
             if ($class_builder->getValueNotNull() || $class_builder->getValueAsKey()) {
                 throw new \Exception(sprintf("service(%s, tags:{name:%s, alias:%s}) tag.value is required", $class_builder->getId(), self::CLASS_TAG_NAME, $class_builder->getName()));
             }
         }
         $annotation_camelize_name = $class_builder->getCamelizeName();
         $class = new \Symforce\CoreBundle\PhpHelper\PhpClass($this->getAnnotationClassName($annotation_camelize_name));
         $parent_name = $class_builder->getParentName();
         if ($parent_name) {
             $class->setParentClassName($this->getAnnotationClassName($parent_name));
         } else {
             $class->setParentClassName($base_parent_class);
         }
         $class->setConstant('SYMFORCE_ANNOTATION_NAME', $annotation_name);
         $group_id = $class_builder->getGroupId();
         if (null !== $group_id) {
             $class->setConstant('SYMFORCE_ANNOTATION_GROUP_ID', $group_id);
         }
         $value_property_name = $class_builder->getValuePropertyName();
         if ($value_property_name) {
             $class->setConstant('SYMFORCE_ANNOTATION_VALUE_AS_PROPERTY', $value_property_name);
         }
         if ($class_builder->getValueAsKey()) {
             $class->setConstant('SYMFORCE_ANNOTATION_VALUE_AS_KEY', 1);
         }
         if ($class_builder->getValueNotNull()) {
             $class->setConstant('SYMFORCE_ANNOTATION_VALUE_NOT_NULL', 1);
         }
         $doc = sprintf(" * @Annotation");
         $annotation_target = $class_builder->getTarget();
         if (!$annotation_target) {
             $annotation_target = array('CLASS', 'PROPERTY');
         }
         $doc .= sprintf("\n * @Target({\"") . join('","', $annotation_target) . sprintf("\"})");
         $class->setDocblock($doc);
         if (in_array('CLASS', $annotation_target)) {
             $cache_class->addMethod('get' . $annotation_camelize_name . 'ClassAnnotation', true)->setDocblock('/* @return \\' . $class->getName() . ' */')->getWriter()->writeln(sprintf('return $this->getClassValue("%s");', $class_builder->getName()));
             if ($class_builder->getValueAsKey()) {
                 $cache_class->addMethod('get' . $annotation_camelize_name . 'ClassValues', true)->setDocblock('/* @return array(\\' . $class->getName() . ') */')->getWriter()->writeln(sprintf('return $this->getClassValue("%s", true);', $class_builder->getName()));
             }
         }
         if (in_array('PROPERTY', $annotation_target)) {
             $cache_class->addMethod('get' . $annotation_camelize_name . 'PropertyAnnotation', true)->addParameter(\CG\Generator\PhpParameter::create('property_name'))->setDocblock('/* @return \\' . $class->getName() . ' */')->getWriter()->writeln(sprintf('return $this->getPropertyValue($property_name, "%s");', $class_builder->getName()));
             if ($class_builder->getValueAsKey()) {
                 $cache_class->addMethod('get' . $annotation_camelize_name . 'PropertyValues', true)->addParameter(\CG\Generator\PhpParameter::create('property_name'))->setDocblock('/* @return array(\\' . $class->getName() . ') */')->getWriter()->writeln(sprintf('return $this->getPropertyValue($property_name, "%s", true);', $class_builder->getName()));
             }
         }
         $value_property_name = null;
         /**
          * @var $property_builder SymforceAnnotationPropertyBuilder
          */
         if ($_public_properties) {
             foreach ($_public_properties as $property_name) {
                 if (!isset($_properties[$property_name])) {
                     $property_builder = $this->public_properties[$property_name];
                     $type = $property_builder->getType();
                     if (!$type) {
                         $type = 'string';
                     }
                     $class->addProperty($property_name, null, $type, false, true);
                 }
             }
         }
         foreach ($_properties as $property_name => $property_builder) {
             $type = $property_builder->getType();
             if (!$type) {
                 $type = 'string';
             }
             $class->addProperty($property_name, null, $type, false, true);
         }
         $class->writeCache();
     }
     $cache_class->writeCache();
 }
Пример #24
0
 /**
  * Generate a parameter for a method expecting an aspect
  *
  * @param string $aspect
  * @return \CG\Generator\PhpParameter
  */
 protected function generateAspectParameter($aspect)
 {
     $loaderParam = new PhpParameter();
     $loaderParam->setName('aspect' . ucfirst($aspect))->setType('PUGX\\AOP\\Aspect\\AspectInterface');
     return $loaderParam;
 }
Пример #25
0
 private function createParamForElem(\SimpleXMLElement $paramElem)
 {
     $name = trim((string) $paramElem->parameter);
     if ($name === '...') {
         $name = '_';
     }
     $param = PhpParameter::create($name);
     $param->setAttribute('type', $type = (string) $paramElem->type);
     $role = (string) $paramElem->parameter->attributes()->role;
     if ($role === 'reference') {
         $param->setPassedByReference(true);
     }
     if (isset($paramElem->initializer)) {
         $value = (string) $paramElem->initializer;
         if (strlen($value) > 0 && '"' === $value[0] && '"' === substr($value, -1)) {
             $value = substr($value, 1, -1);
         } else {
             if ('integer' === $type || 'int' === $type) {
                 $value = (int) $value;
             } else {
                 if ('double' === $type || 'float' === $type) {
                     $value = (double) $value;
                 }
             }
         }
         switch ($value) {
             case 'false':
                 $value = false;
                 break;
             case 'true':
                 $value = true;
                 break;
             case 'NULL':
             case 'null':
                 $value = null;
                 break;
             case 'array()':
                 $value = array();
                 break;
         }
         $param->setDefaultValue($value);
     } else {
         if ('opt' === (string) @$paramElem->attributes()->choice) {
             if ('array' === $type) {
                 $param->setDefaultValue(array());
             } else {
                 $param->setDefaultValue(null);
             }
         }
     }
     return $param;
 }