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); } }
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); } }
/** * {@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 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'))); }
/** * TODO remove this fix backport CG lib version > 1.0.0 * * {@inheritdoc} * @SuppressWarnings(PHPMD.NPathComplexity) */ public function startVisitingClass(PhpClass $class) { if ($namespace = $class->getNamespace()) { $this->getWriter()->write('namespace ' . $namespace . ';' . "\n\n"); } if ($files = $class->getRequiredFiles()) { foreach ($files as $file) { $this->getWriter()->writeln('require_once ' . var_export($file, true) . ';'); } $this->getWriter()->write("\n"); } if ($useStatements = $class->getUseStatements()) { foreach ($useStatements as $alias => $namespace) { $this->getWriter()->write('use ' . $namespace); if (substr($namespace, strrpos($namespace, '\\') + 1) !== $alias) { $this->getWriter()->write(' as ' . $alias); } $this->getWriter()->write(";\n"); } $this->getWriter()->write("\n"); } if ($docblock = $class->getDocblock()) { $this->getWriter()->write($docblock); } if ($class->isAbstract()) { $this->getWriter()->write('abstract '); } if ($class->isFinal()) { $this->getWriter()->write('final '); } $this->getWriter()->write('class ' . $class->getShortName()); if ($parentClassName = $class->getParentClassName()) { $this->getWriter()->write(' extends ' . ('\\' . ltrim($parentClassName, '\\'))); } $interfaceNames = $class->getInterfaceNames(); if (!empty($interfaceNames)) { $interfaceNames = array_unique($interfaceNames); $interfaceNames = array_map(function ($name) { if ('\\' === $name[0]) { return $name; } return '\\' . $name; }, $interfaceNames); $this->getWriter()->write(' implements ' . implode(', ', $interfaceNames)); } $this->getWriter()->write("\n{\n")->indent(); }
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())); }
public function testGenerate() { $schema = ['relationData' => [['field_id' => new FieldConfigId('extend', 'Test\\Entity', ExtendHelper::buildAssociationName('Test\\TargetEntity1', ActivityScope::ASSOCIATION_KIND), 'manyToMany'), 'target_entity' => 'Test\\TargetEntity1'], ['field_id' => new FieldConfigId('extend', 'Test\\Entity', ExtendHelper::buildAssociationName('Test\\TargetEntity2', ActivityScope::ASSOCIATION_KIND), 'manyToMany'), 'target_entity' => 'Test\\TargetEntity2'], ['field_id' => new FieldConfigId('extend', 'Test\\Entity', ExtendHelper::buildAssociationName('Test\\TargetEntity3', ActivityScope::ASSOCIATION_KIND), 'manyToOne'), 'target_entity' => 'Test\\TargetEntity3'], ['field_id' => new FieldConfigId('extend', 'Test\\Entity', 'testField', 'manyToMany'), 'target_entity' => 'Test\\TargetEntity4']]]; $class = PhpClass::create('Test\\Entity'); $this->extension->generate($schema, $class); $strategy = new DefaultGeneratorStrategy(); $classBody = $strategy->generate($class); $expectedBody = file_get_contents(__DIR__ . '/Fixtures/generationResult.txt'); $this->assertEquals(trim($expectedBody), $classBody); }
public function testOverridingOfTwoArgumentsBehavior() { $gen = new BackgroundGenerator(); $proxy = PhpClass::create('BlahBlan' . sha1(microtime(true))); $refl = new \ReflectionClass('Nfx\\AsyncBundle\\Generator\\BackgroundGenerator'); $method = $refl->getMethod('override'); $origCodeIn = $gen->override($method, new Background(array('value' => 'foobar'))); $gen->generate($refl, $proxy); $this->assertTrue($proxy->hasMethod('override')); $this->assertTrue($proxy->hasMethod($origCodeIn)); }
public function testVisitClassWithPhp7Features() { if (PHP_VERSION_ID < 70000) { $this->markTestSkipped('Test only valid for PHP >=7.0'); } $ref = new \ReflectionClass('CG\\Tests\\Generator\\Fixture\\EntityPhp7'); $class = PhpClass::fromReflection($ref); $generator = new DefaultGeneratorStrategy(); $content = $generator->generate($class); $this->assertEquals($this->getContent('php7_class.php'), $content); }
/** * @param string $expectedFile * @param array $schema * @param bool $dump */ protected function assertGeneration($expectedFile, $schema, $dump = false) { $class = PhpClass::create('Test\\Entity'); $this->extension->generate($schema, $class); $strategy = new DefaultGeneratorStrategy(); $classBody = $strategy->generate($class); if ($dump) { print_r("\n" . $classBody . "\n"); } $expectedBody = file_get_contents(__DIR__ . '/../Fixtures/' . $expectedFile); $this->assertEquals(trim($expectedBody), $classBody); }
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)); } }
/** * @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()); }
/** * Generate php and yml files for schema * * @param array $schema */ public function generateSchemaFiles(array $schema) { // generate PHP code $class = PhpClass::create($schema['entity']); foreach ($this->getExtensions() as $extension) { if ($extension->supports($schema)) { $extension->generate($schema, $class); } } $className = ExtendHelper::getShortClassName($schema['entity']); // write PHP class to the file $strategy = new DefaultGeneratorStrategy(); file_put_contents($this->entityCacheDir . DIRECTORY_SEPARATOR . $className . '.php', "<?php\n\n" . $strategy->generate($class)); // write doctrine metadata in separate yaml file file_put_contents($this->entityCacheDir . DIRECTORY_SEPARATOR . $className . '.orm.yml', Yaml::dump($schema['doctrine'], 5)); }
/** * Creates a new enhanced class * * @throws \RuntimeException * @return string */ public final function generateClass() { static $docBlock; if (empty($docBlock)) { $writer = new Writer(); $writer->writeln('/**')->writeln(' * CG library enhanced proxy class.')->writeln(' *')->writeln(' * This code was generated automatically by the CG library, manual changes to it')->writeln(' * will be lost upon next generation.')->writeln(' */')->writeln(''); $docBlock = $writer->getContent() . $this->class->getDocComment() . "\n"; } $this->generatedClass = PhpClass::create()->setDocblock($docBlock)->setParentClassName($this->class->name); $proxyClassName = $this->getClassName($this->class); if (false === strpos($proxyClassName, NamingStrategyInterface::SEPARATOR)) { throw new \RuntimeException(sprintf('The proxy class name must be suffixed with "%s" and an optional string, but got "%s".', NamingStrategyInterface::SEPARATOR, $proxyClassName)); } $this->generatedClass->setName($proxyClassName); foreach ($this->aspectGenerators as $generator) { $generator->generate($this->class, $this->generatedClass); } return $this->generateCode($this->generatedClass); }
public function testVisit() { $conditionObject = new ElementDependentVisitor('header'); $phpClass = PhpClass::create('LayoutUpdateClass'); $visitContext = new VisitContext($phpClass); $conditionObject->startVisit($visitContext); $conditionObject->endVisit($visitContext); $strategy = new DefaultGeneratorStrategy(); $this->assertSame(<<<CONTENT class LayoutUpdateClass implements \\Oro\\Component\\Layout\\Loader\\Generator\\ElementDependentLayoutUpdateInterface { public function getElement() { return 'header'; } } CONTENT , $strategy->generate($visitContext->getClass())); }
/** * @param string $expectedFile * @param array $schema * @param bool $dump */ protected function assertGeneration($expectedFile, $schema, $dump = false) { $class = PhpClass::create('Test\\Entity'); $this->extension->generate($schema, $class); $strategy = new DefaultGeneratorStrategy(); $classBody = $strategy->generate($class); if ($dump) { print_r("\n" . $classBody . "\n"); } $expectedBody = file_get_contents(__DIR__ . '/../Fixtures/' . $expectedFile); /** * Support different line endings. */ $expectedBody = str_replace(PHP_EOL, "\n", $expectedBody); $classBody = str_replace(PHP_EOL, "\n", $classBody); $expectedBody = trim($expectedBody); $classBody = trim($classBody); $this->assertEquals($expectedBody, $classBody); }
public function introspect(\ReflectionExtension $extension) { $classes = $functions = $constants = array(); foreach ($extension->getClasses() as $class) { assert($class instanceof \ReflectionClass); $phpClass = PhpClass::fromReflection($class); $classes[] = $phpClass; } foreach ($extension->getFunctions() as $function) { assert($function instanceof \ReflectionFunction); $phpFunction = PhpFunction::fromReflection($function); $functions[] = $phpFunction; } foreach ($extension->getConstants() as $name => $value) { $phpConstant = new PhpConstant($name); $phpConstant->setValue($value); $constants[] = $phpConstant; } return array('classes' => $classes, 'functions' => $functions, 'constants' => $constants); }
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())); }
protected function generateClass($item) { $this->writer = new Writer(); $class = PhpClass::create($item['entity']); if ($item['type'] == 'Extend') { if (isset($item['inherit'])) { $class->setParentClassName($item['inherit']); } } else { $class->setProperty(PhpProperty::create('id')->setVisibility('protected')); $class->setMethod($this->generateClassMethod('getId', 'return $this->id;')); /** * TODO * custom entity instance as manyToOne relation * find the way to show it on view * we should mark some field as title */ $toString = array(); foreach ($item['property'] as $propKey => $propValue) { if ($item['doctrine'][$item['entity']]['fields'][$propKey]['type'] == 'string') { $toString[] = '$this->get' . ucfirst(Inflector::camelize($propValue)) . '()'; } } $toStringBody = 'return (string) $this->getId();'; if (count($toString) > 0) { $toStringBody = 'return (string)' . implode(' . ', $toString) . ';'; } $class->setMethod($this->generateClassMethod('__toString', $toStringBody)); } $class->setInterfaceNames(array('Oro\\Bundle\\EntityExtendBundle\\Entity\\ExtendEntityInterface')); $this->generateClassMethods($item, $class); $classArray = explode('\\', $item['entity']); $className = array_pop($classArray); $filePath = $this->entityCacheDir . '/' . $className . '.php'; $strategy = new DefaultGeneratorStrategy(); file_put_contents($filePath, "<?php\n\n" . $strategy->generate($class)); }
/** * {@inheritdoc} */ public function generate(array $schema, PhpClass $class) { $class->addInterfaceName('Oro\\Bundle\\ActivityBundle\\Model\\ActivityInterface'); parent::generate($schema, $class); }
/** * @param array $schema * @param PhpClass $class * * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function generateManyToManyAssociationMethods(array $schema, PhpClass $class) { $prefix = $this->getAssociationKind(); $prefix = Inflector::classify(null === $prefix ? '' : $prefix); $supportMethodName = sprintf('support%sTarget', $prefix); $getMethodName = sprintf('get%sTargets', $prefix); $hasMethodName = sprintf('has%sTarget', $prefix); $addMethodName = sprintf('add%sTarget', $prefix); $removeMethodName = sprintf('remove%sTarget', $prefix); $supportMethodBody = ['$className = \\Doctrine\\Common\\Util\\ClassUtils::getRealClass($targetClass);']; $getMethodBody = ['$className = \\Doctrine\\Common\\Util\\ClassUtils::getRealClass($targetClass);']; $hasMethodBody = ['$className = \\Doctrine\\Common\\Util\\ClassUtils::getClass($target);']; $addMethodBody = ['$className = \\Doctrine\\Common\\Util\\ClassUtils::getClass($target);']; $removeMethodBody = ['$className = \\Doctrine\\Common\\Util\\ClassUtils::getClass($target);']; foreach ($schema['relationData'] as $relationData) { if (!$this->isSupportedRelation($relationData)) { continue; } /** @var FieldConfigId $fieldConfigId */ $fieldConfigId = $relationData['field_id']; $fieldName = $fieldConfigId->getFieldName(); $targetClassName = $relationData['target_entity']; $supportMethodBody[] = sprintf('if ($className === \'%s\') { return true; }', $targetClassName); $getMethodBody[] = sprintf('if ($className === \'%s\') { return $this->%s; }', $targetClassName, $fieldName); $hasMethodBody[] = str_replace(['{class}', '{field}'], [$targetClassName, $fieldName], "if (\$className === '{class}') { return \$this->{field}->contains(\$target); }"); $addMethodBody[] = str_replace(['{class}', '{field}'], [$targetClassName, $fieldName], "if (\$className === '{class}') {\n" . " if (!\$this->{field}->contains(\$target)) { \$this->{field}->add(\$target); }\n" . " return \$this;\n}"); $removeMethodBody[] = str_replace(['{class}', '{field}'], [$targetClassName, $fieldName], "if (\$className === '{class}') {\n" . " if (\$this->{field}->contains(\$target)) { \$this->{field}->removeElement(\$target); }\n" . " return \$this;\n}"); } $throwStmt = 'throw new \\RuntimeException(' . 'sprintf(\'The association with "%s" entity was not configured.\', $className));'; $supportMethodBody[] = 'return false;'; $getMethodBody[] = $throwStmt; $hasMethodBody[] = 'return false;'; $addMethodBody[] = $throwStmt; $removeMethodBody[] = $throwStmt; $supportMethodDocblock = "/**\n" . " * Checks if an entity of the given type can be associated with this entity\n" . " *\n" . " * @param string \$targetClass The class name of the target entity\n" . " * @return bool\n" . " */"; $getMethodDocblock = "/**\n" . " * Gets entities of the given type associated with this entity\n" . " *\n" . " * @param string \$targetClass The class name of the target entity\n" . " * @return object[]\n" . " */"; $hasMethodDocblock = "/**\n" . " * Checks is the given entity is associated with this entity\n" . " *\n" . " * @param object \$target Any configurable entity that can be associated with this type of entity\n" . " * @return bool\n" . " */"; $addMethodDocblock = "/**\n" . " * Associates the given entity with this entity\n" . " *\n" . " * @param object \$target Any configurable entity that can be associated with this type of entity\n" . " * @return object This object\n" . " */"; $removeMethodDocblock = "/**\n" . " * Removes the association of the given entity and this entity\n" . " *\n" . " * @param object \$target Any configurable entity that can be associated with this type of entity\n" . " * @return object This object\n" . " */"; $class->setMethod($this->generateClassMethod($supportMethodName, implode("\n", $supportMethodBody), ['targetClass'])->setDocblock($supportMethodDocblock))->setMethod($this->generateClassMethod($getMethodName, implode("\n", $getMethodBody), ['targetClass'])->setDocblock($getMethodDocblock))->setMethod($this->generateClassMethod($hasMethodName, implode("\n", $hasMethodBody), ['target'])->setDocblock($hasMethodDocblock))->setMethod($this->generateClassMethod($addMethodName, implode("\n", $addMethodBody), ['target'])->setDocblock($addMethodDocblock))->setMethod($this->generateClassMethod($removeMethodName, implode("\n", $removeMethodBody), ['target'])->setDocblock($removeMethodDocblock)); }
/** * Creates a new enhanced class * * @return string */ public final function generateClass() { static $docBlock; if (empty($docBlock)) { $writer = new Writer(); $writer->writeln('/**')->writeln(' * CG library enhanced proxy class.')->writeln(' *')->writeln(' * This code was generated automatically by the CG library, manual changes to it')->writeln(' * will be lost upon next generation.')->writeln(' */'); $docBlock = $writer->getContent(); } $this->generatedClass = PhpClass::create()->setDocblock($docBlock)->setParentClassName($this->class->name); $proxyClassName = $this->getClassName($this->class); if (false === strpos($proxyClassName, NamingStrategyInterface::SEPARATOR)) { throw new \RuntimeException(sprintf('The proxy class name must be suffixed with "%s" and an optional string, but got "%s".', NamingStrategyInterface::SEPARATOR, $proxyClassName)); } $this->generatedClass->setName($proxyClassName); if (!empty($this->interfaces)) { $this->generatedClass->setInterfaceNames(array_map(function ($v) { return '\\' . $v; }, $this->interfaces)); foreach ($this->getInterfaceMethods() as $method) { $method = PhpMethod::fromReflection($method); $method->setAbstract(false); $this->generatedClass->setMethod($method); } } if (!empty($this->generators)) { foreach ($this->generators as $generator) { $generator->generate($this->class, $this->generatedClass); } } return $this->generateCode($this->generatedClass); }
/** * @param array $schema * @param PhpClass $class */ protected function generateCollectionMethods(array $schema, PhpClass $class) { foreach ($schema['addremove'] as $fieldName => $config) { $addMethodBody = ['if (!$this->' . $fieldName . '->contains($value)) {', ' $this->' . $fieldName . '->add($value);']; $removeMethodBody = ['if ($this->' . $fieldName . ' && $this->' . $fieldName . '->contains($value)) {', ' $this->' . $fieldName . '->removeElement($value);']; if (isset($config['target'])) { $addMethodBody[] = ' $value->' . ($config['is_target_addremove'] ? 'add' : 'set') . ucfirst(Inflector::camelize($config['target'])) . '($this);'; $removeMethodBody[] = ' $value->' . ($config['is_target_addremove'] ? 'remove' : 'set') . ucfirst(Inflector::camelize($config['target'])) . '(' . ($config['is_target_addremove'] ? '$this' : 'null') . ');'; } $addMethodBody[] = '}'; $removeMethodBody[] = '}'; $class->setMethod($this->generateClassMethod('add' . ucfirst(Inflector::camelize($config['self'])), implode("\n", $addMethodBody), ['value']))->setMethod($this->generateClassMethod('remove' . ucfirst(Inflector::camelize($config['self'])), implode("\n", $removeMethodBody), ['value'])); } }
protected function addDependentFixtureInterface(PhpClass $class, ClassMetadata $metadata, array $options) { $class->addInterfaceName('Doctrine\\Common\\DataFixtures\\DependentFixtureInterface'); $writer = new Writer(); $method = PhpMethod::create('getDependencies'); $writer->writeln("return array("); $associations = array(); foreach ($metadata->getAssociationNames() as $assocName) { $targetClass = $metadata->getAssociationTargetClass($assocName); $associations[] = sprintf("'%s\\%s'", $options['namespace'], $this->namingStrategy->fixtureName($this->getManager()->getClassMetadata($targetClass))); } $writer->indent(); $writer->writeln(implode(",\n", $associations)); $writer->outdent(); $writer->writeln(");"); $method->setBody($writer->getContent()); $class->setMethod($method); }
private function addMethods(PhpClass $class, array $methods) { foreach ($methods as $method) { $initializingCode = 'if (false === $this->' . $this->prefix . 'initialized) {' . "\n" . ' $this->' . $this->prefix . 'initialize();' . "\n" . '}'; if ($class->hasMethod($method->name)) { $genMethod = $class->getMethod($method->name); $genMethod->setBody($initializingCode . "\n" . $genMethod->getBody()); continue; } $genMethod = PhpMethod::fromReflection($method); $genMethod->setBody($initializingCode . "\n\n" . 'return ' . GeneratorUtils::callMethod($method) . ';'); $class->setMethod($genMethod); } }
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; }
/** * Add the required properties and setters for the aspects used by the generated class * * @param \ReflectionClass $originalClass * @param \CG\Generator\PhpClass $generatedClass * @return \CG\Generator\PhpClass */ protected function prepareAspectInjection(\ReflectionClass $originalClass, PhpClass $generatedClass) { $aspects = $this->getRequiredAspects(); $generatedClass->setMethod($this->generateMethod($originalClass->getConstructor(), $aspects)); $generator = new AspectCodeGenerator($originalClass->name); foreach ($aspects as $aspect) { $generatedClass->setProperty($this->generateAspectProperty($aspect, $generator)); $generatedClass->setMethod($this->generateAspectSetter($aspect, $generator)); } return $generatedClass; }
public function testSetGetRequiredFiles() { $class = new PhpClass(); $this->assertEquals(array(), $class->getRequiredFiles()); $this->assertSame($class, $class->setRequiredFiles(array('foo'))); $this->assertEquals(array('foo'), $class->getRequiredFiles()); $this->assertSame($class, $class->addRequiredFile('bar')); $this->assertEquals(array('foo', 'bar'), $class->getRequiredFiles()); }
/** * @param array $schema * @param PhpClass $class */ protected function generateCollectionMethods(array $schema, PhpClass $class) { foreach ($schema['addremove'] as $fieldName => $config) { $addMethodBody = ['if (!$this->' . $fieldName . '->contains($value)) {', ' $this->' . $fieldName . '->add($value);']; $removeMethodBody = ['if ($this->' . $fieldName . ' && $this->' . $fieldName . '->contains($value)) {', ' $this->' . $fieldName . '->removeElement($value);']; if (isset($config['target'])) { if ($config['is_target_addremove']) { $addMethodBody[] = " \$value->{$this->generateAddMethodName($config['target'])}(\$this);"; $removeMethodBody[] = " \$value->{$this->generateRemoveMethodName($config['target'])}(\$this);"; } else { $addMethodBody[] = " \$value->{$this->generateSetMethodName($config['target'])}(\$this);"; $removeMethodBody[] = " \$value->{$this->generateSetMethodName($config['target'])}(null);"; } } $addMethodBody[] = '}'; $removeMethodBody[] = '}'; $class->setMethod($this->generateClassMethod($this->generateAddMethodName($config['self']), implode("\n", $addMethodBody), ['value']))->setMethod($this->generateClassMethod($this->generateRemoveMethodName($config['self']), implode("\n", $removeMethodBody), ['value'])); } }
/** * @return PhpClass */ protected function getClass() { return PhpClass::create(uniqid('testClassName', true)); }