public function testSetIsReferenceReturned() { $method = new PhpMethod(); $this->assertFalse($method->isReferenceReturned()); $this->assertSame($method, $method->setReferenceReturned(true)); $this->assertTrue($method->isReferenceReturned()); $this->assertSame($method, $method->setReferenceReturned(false)); $this->assertFalse($method->isReferenceReturned()); }
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()); }
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'))); }
/** * {@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 $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) { $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())); }
/** * {@inheritdoc} */ public function endVisit(VisitContext $visitContext) { $writer = $visitContext->createWriter(); $writer->writeln(sprintf('return \'%s\';', $this->elementId)); $method = PhpMethod::create('getElement'); $method->setBody($writer->getContent()); $visitContext->getClass()->setMethod($method); }
public function genGetter() { if ($this->_get) { $get_name = 'get' . ucfirst($this->getFixedName()); $this->_class->setMethod(\CG\Generator\PhpMethod::create($get_name)->setFinal(true)->setDocblock('/** @return ' . $this->type . ' */')->setBody('return $this->' . $this->getName() . ';')); } return $this; }
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); } }
/** * @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; }
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()); }
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())); }
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'))); }
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); }
/** * Create a setter for the aspect property with the received aspect name * * @param string $aspect * @return \CG\Generator\PhpMethod */ protected function generateAspectSetter($aspect, AspectCodeGenerator $generator) { $loaderSetter = new PhpMethod(); $loaderSetter->setName($generator->getSetterName($aspect))->setVisibility(PhpMethod::VISIBILITY_PUBLIC)->setBody($generator->getSetterCode($aspect)); $loaderSetter->addParameter($this->generateAspectParameter($aspect)); return $loaderSetter; }
public function writeCache() { static $_psr4_map = null; if (null === $_psr4_map) { $_psr4_file = dirname((new \ReflectionClass('Composer\\Autoload\\ClassLoader'))->getFileName()) . '/autoload_psr4.php'; if (!file_exists($_psr4_file)) { throw new \Exception(sprintf("psr4 file(%s) not exits!", $_psr4_file)); } $_psr4_map = (include $_psr4_file); } $_class_file = null; foreach ($_psr4_map as $_namespace => $_namespace_dir) { if (!empty($_namespace_dir)) { $_pos = strpos($this->getName(), $_namespace); if (0 === $_pos) { $_class_file = $_namespace_dir[0] . '/' . str_replace('\\', '/', substr($this->getName(), strlen($_namespace))) . '.php'; } } } if (!$_class_file) { throw new \Exception(sprintf("can not resolve file for class(%s) by psr4 rule!", $this->getName())); } $shortName = pathinfo($_class_file, \PATHINFO_FILENAME); $namespace = $this->getNamespace(); $writer = new \Symforce\AdminBundle\Compiler\Generator\PhpWriter(); $writer->writeln("<?php\n"); if (!empty($namespace)) { $writer->writeln("namespace " . $namespace . ";\n"); } $imports = $this->getUseStatements(); foreach ($imports as $alias => $use) { $_alias = substr($use, -1 - strlen($alias)); if ($_alias == '\\' . $alias) { $writer->writeln(sprintf("use %s ;", $use)); } else { $writer->writeln(sprintf("use %s as %s ;", $use, $alias)); } } $writer->writeln('')->writeln('/**')->writeln(' * This code has been auto-generated by the SymforceAdminBundule')->writeln(' * Manual changes to it will be lost.')->writeln(' */'); if ($this->isAbstract()) { $writer->write('abstract '); } else { if ($this->isFinal()) { $writer->write('final '); } } $writer->write('class ' . $shortName); if ($this->getParentClassName()) { $writer->write(' extends ' . $this->getParentClassName()); } $writer->writeln(' {')->indent(); $lazy_writer = $this->getLazyWriter(); foreach ($this->getProperties() as $property) { $property->writeCache($lazy_writer, $writer); } foreach ($this->lazy_properties as $name => $value) { $writer->writeln("\npublic \${$name} = " . $this->propertyEncode($value) . " ;"); // $lazy_writer->writeln( '$this->' . $name . ' = ' . . ' ; ' ); } if ($this->hasMethod('__wakeup')) { $lazy_writer->writeln($this->getMethod('__wakeup')->getBody()); $this->getMethod('__wakeup')->setBody($lazy_writer->getContent()); } else { $this->setMethod(\CG\Generator\PhpMethod::create('__wakeup')->setFinal(true)->setVisibility('protected')->setBody($lazy_writer->getContent())); } foreach ($this->getMethods() as $method) { if ($method instanceof PhpMethod) { $method->flushLazyCode(); $_body = $method->getWriter()->getContent(); } else { $_body = $method->getBody(); } $writer->write("\n"); if ($method->getDocblock()) { $writer->writeln($method->getDocblock()); } if ($method->isFinal()) { $writer->write('final '); } $writer->write($method->getVisibility())->write(' function ')->write($method->getName()); $ps = $method->getParameters(); if (empty($ps)) { $writer->write('()'); } else { $writer->writeln('(')->indent(); foreach ($method->getParameters() as $i => $p) { if ($p->getType()) { if (in_array($p->getType(), array('mixed'))) { $writer->write('/** @var ' . $p->getType() . ' */'); } else { $writer->write($p->getType() . ' '); } } if ($p->isPassedByReference()) { $writer->write(' & '); } $writer->write(' $')->write($p->getName()); if ($p->hasDefaultValue()) { $writer->write(' = ' . json_encode($p->getDefaultValue())); } if ($i < count($ps) - 1) { $writer->writeln(","); } else { $writer->write("\n"); } } $writer->writeln(')')->outdent(); } $writer->writeln('{')->indent()->writeln($_body)->outdent()->writeln("}"); } $writer->outdent()->writeln('}'); $content = $writer->getContent(); /** * convert the fake php code * '#php{% $this->admin->trans("test.form.enabled.choices.no") %}' */ $content = preg_replace_callback(self::PHP_CODE, function ($m) { return stripslashes($m[1]); }, $content); $_class_dir = dirname($_class_file); if (!file_exists($_class_dir)) { if (!@mkdir($_class_dir, 0755)) { throw new \Exception(sprintf("mkdir(%s) error!", $_class_dir)); } } \Dev::write_file($_class_file, $content); return $_class_file; }
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; }
private function parseMethod(\SimpleXMLElement $doc) { list($className, $methodName) = explode("::", (string) $doc->refnamediv->refname); $class = $this->getOrCreateClass($className); $class->setMethod($method = new PhpMethod($methodName)); $method->setAttribute('purpose', (string) $doc->refnamediv->refpurpose); foreach ($doc->refsect1 as $refsect) { if (isset($refsect->methodsynopsis)) { foreach ($doc->refsect1->methodsynopsis as $methodElem) { $method->setAttribute('return_type', (string) $methodElem->type); foreach ($methodElem->methodparam as $paramElem) { $method->addParameter($this->createParamForElem($paramElem)); if ('...' === (string) $paramElem->parameter) { $method->setAttribute('variable_parameters', true); } } } continue; } $this->parseRefsect($refsect, $method); } $this->typeRefiner->refineMethodTypes($class, $method); }
public function setMethod(PhpMethod $method) { $this->methods[$method->getName()] = $method; return $this; }
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); } }
/** * 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); }
/** * Constructor * * @param PhpMethod $method */ public function __construct(PhpMethod $method) { parent::__construct($method->getName()); $this->method = $method; $this->createAsProxy(); }