/**
  * 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);
 }
 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);
     }
 }
Example #3
0
 public function testSetGetDefaultValue()
 {
     $prop = new PhpProperty();
     $this->assertNull($prop->getDefaultValue());
     $this->assertFalse($prop->hasDefaultValue());
     $this->assertSame($prop, $prop->setDefaultValue('foo'));
     $this->assertEquals('foo', $prop->getDefaultValue());
     $this->assertTrue($prop->hasDefaultValue());
     $this->assertSame($prop, $prop->unsetDefaultValue());
     $this->assertNull($prop->getDefaultValue());
     $this->assertFalse($prop->hasDefaultValue());
 }
Example #4
0
 public function refinePropertyType(PhpClass $class, PhpProperty $property)
 {
     $name = $class->getName() . '::' . $property->getName();
     if (!isset(self::$refinedElements[$name]['type'])) {
         if ($this->shouldBeRefined($propertyType = $property->getAttributeOrElse('type', null))) {
             $this->nonRefinedElements[$name]['type'] = $propertyType;
             $this->logger->info(sprintf('The property "%s" is not refined, and has type "%s".', $name, $propertyType));
         }
     } else {
         $property->setAttribute('type', self::$refinedElements[$name]['type']);
     }
 }
Example #5
0
 /**
  * @param PhpClass $class
  *
  * @return string
  */
 public function generate(PhpClass $class)
 {
     $dispatcherContainer = new PhpProperty('dispatcher');
     $dispatcherContainer->setVisibility('protected');
     $class->setProperty($dispatcherContainer);
     try {
         $method = $class->getMethod('setDispatcher');
         $method->setBody('$this->dispatcher=$dispatcher;');
     } catch (\Exception $e) {
     }
     $this->generateAopMethodProxy($class, PhpClass::fromReflection(new \ReflectionClass($class->getParentClassName())));
     $this->visitor->reset();
     $this->navigator->accept($this->visitor, $class);
     return $this->visitor->getContent();
 }
Example #6
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 <*****@*****.**>
 */')->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 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()));
 }
Example #8
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();
 }
Example #11
0
    public function testFromReflection()
    {
        $class = new PhpClass();
        $class->setName('CG\\Tests\\Generator\\Fixture\\Entity')->setAbstract(true)->setDocblock('/**
 * Doc Comment.
 *
 * @author Johannes M. Schmitt <*****@*****.**>
 */')->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')));
    }
 /**
  * @param string   $propertyType
  * @param array    $schema
  * @param PhpClass $class
  */
 protected function generateProperties($propertyType, array $schema, PhpClass $class)
 {
     foreach ($schema[$propertyType] as $fieldName => $config) {
         $class->setProperty(PhpProperty::create($fieldName)->setVisibility('protected'));
         $isPrivate = is_array($config) && isset($config['private']) && $config['private'];
         if (!$isPrivate) {
             $class->setMethod($this->generateClassMethod($this->generateGetMethodName($fieldName), 'return $this->' . $fieldName . ';'))->setMethod($this->generateClassMethod($this->generateSetMethodName($fieldName), $this->getSetterBody($fieldName, $schema), ['value']));
         }
     }
 }
 /**
  * @param string   $propertyType
  * @param array    $schema
  * @param PhpClass $class
  */
 protected function generateProperties($propertyType, array $schema, PhpClass $class)
 {
     foreach ($schema[$propertyType] as $fieldName => $config) {
         $class->setProperty(PhpProperty::create($fieldName)->setVisibility('protected'))->setMethod($this->generateClassMethod('get' . ucfirst(Inflector::camelize($fieldName)), 'return $this->' . $fieldName . ';'))->setMethod($this->generateClassMethod('set' . ucfirst(Inflector::camelize($fieldName)), '$this->' . $fieldName . ' = $value; return $this;', ['value']));
     }
 }
Example #14
0
 /**
  * Create a property for the received aspect name
  *
  * @param string $aspect
  * @return \CG\Generator\PhpProperty
  */
 protected function generateAspectProperty($aspect, AspectCodeGenerator $generator)
 {
     $interceptorLoader = new PhpProperty();
     $interceptorLoader->setName($generator->getAspectPropertyName($aspect))->setVisibility(PhpProperty::VISIBILITY_PRIVATE);
     return $interceptorLoader;
 }
 private function getClass()
 {
     $class = PhpClass::create()->setName('GenerationTestClass')->setMethod(PhpMethod::create('a'))->setMethod(PhpMethod::create('b'))->setProperty(PhpProperty::create('a'))->setProperty(PhpProperty::create('b'))->setConstant('a', 'foo')->setConstant('b', 'bar');
     return $class;
 }
Example #16
0
 public function setProperty(PhpProperty $property)
 {
     $this->properties[$property->getName()] = $property;
     return $this;
 }
 /**
  * @param $config
  * @param $class
  *
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 protected function generateClassMethods($config, &$class)
 {
     foreach ($config['property'] as $property => $method) {
         $class->setProperty(PhpProperty::create($property)->setVisibility('protected'))->setMethod($this->generateClassMethod('get' . ucfirst(Inflector::camelize($method)), 'return $this->' . $property . ';'))->setMethod($this->generateClassMethod('set' . ucfirst(Inflector::camelize($method)), '$this->' . $property . ' = $value; return $this;', array('value')));
     }
     foreach ($config['relation'] as $relation => $method) {
         $class->setProperty(PhpProperty::create($relation)->setVisibility('protected'))->setMethod($this->generateClassMethod('get' . ucfirst(Inflector::camelize($method)), 'return $this->' . $relation . ';'))->setMethod($this->generateClassMethod('set' . ucfirst(Inflector::camelize($method)), '$this->' . $relation . ' = $value; return $this;', array('value')));
     }
     foreach ($config['default'] as $default => $method) {
         $class->setProperty(PhpProperty::create($default)->setVisibility('protected'))->setMethod($this->generateClassMethod('get' . ucfirst(Inflector::camelize($method)), 'return $this->' . $default . ';'))->setMethod($this->generateClassMethod('set' . ucfirst(Inflector::camelize($method)), '$this->' . $default . ' = $value; return $this;', array('value')));
     }
     foreach ($config['addremove'] as $addremove => $method) {
         $class->setMethod($this->generateClassMethod('add' . ucfirst(Inflector::camelize($method['self'])), 'if (!$this->' . $addremove . ') {
                         $this->' . $addremove . ' = new \\Doctrine\\Common\\Collections\\ArrayCollection();
                     }
                     if (!$this->' . $addremove . '->contains($value)) {
                         $this->' . $addremove . '->add($value);
                         $value->' . ($method['is_target_addremove'] ? 'add' : 'set') . ucfirst(Inflector::camelize($method['target'])) . '($this);
                     }', array('value')))->setMethod($this->generateClassMethod('remove' . ucfirst(Inflector::camelize($method['self'])), 'if ($this->' . $addremove . ' && $this->' . $addremove . '->contains($value)) {
                         $this->' . $addremove . '->removeElement($value);
                         $value->' . ($method['is_target_addremove'] ? 'remove' : 'set') . ucfirst(Inflector::camelize($method['target'])) . '(' . ($method['is_target_addremove'] ? '$this' : 'null') . ');
                     }', array('value')));
     }
 }