Build a Code Generation Php Object from a Class Reflection
public static fromReflection ( Zend\Code\Reflection\ClassReflection $classReflection ) : self | ||
$classReflection | Zend\Code\Reflection\ClassReflection | |
Результат | self |
/** * @param FileReflection $fileReflection * @return FileGenerator */ public static function fromReflection(FileReflection $fileReflection) { $file = new static(); $file->setSourceContent($fileReflection->getContents()); $file->setSourceDirty(false); $uses = $fileReflection->getUses(); foreach ($fileReflection->getClasses() as $class) { $phpClass = ClassGenerator::fromReflection($class); $phpClass->setContainingFileGenerator($file); foreach ($uses as $fileUse) { $phpClass->addUse($fileUse['use'], $fileUse['as']); } $file->setClass($phpClass); } $namespace = $fileReflection->getNamespace(); if ($namespace != '') { $file->setNamespace($namespace); } if ($uses) { $file->setUses($uses); } if ($fileReflection->getDocComment() != '') { $docBlock = $fileReflection->getDocBlock(); $file->setDocBlock(DocBlockGenerator::fromReflection($docBlock)); } return $file; }
/** * {@inheritDoc} */ public function __invoke(Identifier $identifier) { if (!($name = $this->getInternalReflectionClassName($identifier))) { return null; } return new EvaledLocatedSource("<?php\n\n" . ClassGenerator::fromReflection(new ClassReflection($name))->generate()); }
private function writeParamFile() { $file = $this->path . DIRECTORY_SEPARATOR . 'Params.php'; if (file_exists($file) && class_exists($this->namespace . '\\Params')) { $class = new ClassReflection($this->namespace . '\\Params'); $paramsClass = ClassGenerator::fromReflection($class); } else { $paramsClass = new ClassGenerator('Params', $this->namespace, null, 'OpenStack\\Common\\Api\\AbstractParams'); } foreach ($this->operations as $operation) { $params = $operation['params']; if (empty($params)) { continue; } foreach ($params as $paramName => $paramVal) { $name = $paramName . ucfirst($paramVal['location']); if ($paramsClass->hasMethod($name)) { continue; } $body = sprintf("return %s;", $this->arrayEncoder->encode($paramVal, ['array.align' => true])); $body = str_replace("'\$", '$', $body); $body = str_replace("()'", '()', $body); $docblock = new DocBlockGenerator(sprintf("Returns information about %s parameter", $paramName), null, [new ReturnTag(['array'])]); $paramsClass->addMethod($name, [], MethodGenerator::FLAG_PUBLIC, $body, $docblock); } } $output = sprintf("<?php\n\n%s", $paramsClass->generate()); file_put_contents($file, $output); }
/** * Process the command * * @return integer */ public function processCommandTask() { // output message $this->console->writeTaskLine('task_delete_action_method_deleting'); // set controller file and action method $controllerFile = $this->params->controllerDir . '/' . $this->params->paramController . 'Controller.php'; // get file and class reflection $fileReflection = new FileReflection($controllerFile, true); $classReflection = $fileReflection->getClass($this->params->paramModule . '\\' . $this->params->config['namespaceController'] . '\\' . $this->params->paramController . 'Controller'); // setup class generator with reflected class $class = ClassGenerator::fromReflection($classReflection); // set method to check $actionMethod = strtolower($this->params->paramAction) . 'action'; // check for action method if (!$class->hasMethod($actionMethod)) { $this->console->writeFailLine('task_delete_action_method_not_exists', [$this->console->colorize($this->params->paramAction, Color::GREEN), $this->console->colorize($this->params->paramController, Color::GREEN), $this->console->colorize($this->params->paramModule, Color::GREEN)]); return 1; } // fix namespace usage $class->addUse('Zend\\Mvc\\Controller\\AbstractActionController'); $class->addUse('Zend\\View\\Model\\ViewModel'); $class->setExtendedClass('AbstractActionController'); $class->removeMethod($actionMethod); // create file $file = new ClassFileGenerator($class->generate(), $this->params->config); // write file file_put_contents($controllerFile, $file->generate()); return 0; }
/** * @param FileReflection $fileReflection * @return FileGenerator */ public static function fromReflection(FileReflection $fileReflection) { $file = new static(); $file->setSourceContent($fileReflection->getContents()); $file->setSourceDirty(false); $body = $fileReflection->getContents(); $uses = $fileReflection->getUses(); foreach ($fileReflection->getClasses() as $class) { $phpClass = ClassGenerator::fromReflection($class); $phpClass->setContainingFileGenerator($file); foreach ($uses as $fileUse) { $phpClass->addUse($fileUse['use'], $fileUse['as']); } $file->setClass($phpClass); $classStartLine = $class->getStartLine(true); $classEndLine = $class->getEndLine(); $bodyLines = explode("\n", $body); $bodyReturn = array(); for ($lineNum = 1, $count = count($bodyLines); $lineNum <= $count; $lineNum++) { if ($lineNum == $classStartLine) { $bodyReturn[] = str_replace('?', $class->getName(), '/* Zend_Code_Generator_Php_File-ClassMarker: {?} */'); $lineNum = $classEndLine; } else { $bodyReturn[] = $bodyLines[$lineNum - 1]; // adjust for index -> line conversion } } $body = implode("\n", $bodyReturn); unset($bodyLines, $bodyReturn, $classStartLine, $classEndLine); } $namespace = $fileReflection->getNamespace(); if ($namespace != '') { $file->setNamespace($namespace); } if ($uses) { $file->setUses($uses); } if ($fileReflection->getDocComment() != '') { $docBlock = $fileReflection->getDocBlock(); $file->setDocBlock(DocBlockGenerator::fromReflection($docBlock)); $bodyLines = explode("\n", $body); $bodyReturn = array(); for ($lineNum = 1, $count = count($bodyLines); $lineNum <= $count; $lineNum++) { if ($lineNum == $docBlock->getStartLine()) { $bodyReturn[] = str_replace('?', $class->getName(), '/* Zend_Code_Generator_FileGenerator-DocBlockMarker */'); $lineNum = $docBlock->getEndLine(); } else { $bodyReturn[] = $bodyLines[$lineNum - 1]; // adjust for index -> line conversion } } $body = implode("\n", $bodyReturn); unset($bodyLines, $bodyReturn, $classStartLine, $classEndLine); } $file->setBody($body); return $file; }
/** * @param ClassReflection $reflection * * @return string */ public function __invoke(ClassReflection $reflection) { $stubCode = ClassGenerator::fromReflection($reflection)->generate(); $isInterface = $reflection->isInterface(); if (!($isInterface || $reflection->isTrait())) { return $stubCode; } return $this->prettyPrinter->prettyPrint($this->replaceNodesRecursively($this->parser->parse('<?php ' . $stubCode), $isInterface)); }
protected function convert(AbstractConverter $converter, array $schemas, array $targets, OutputInterface $output) { $generator = new ClassGenerator(); $pathGenerator = new Psr4PathGenerator($targets); $progress = $this->getHelperSet()->get('progress'); $converter->addAliasMap('http://schemas.microsoft.com/exchange/services/2006/types', 'Or', function ($type) use($schemas) { return "OrElement"; }); $converter->addAliasMap('http://schemas.microsoft.com/exchange/services/2006/types', 'And', function ($type) use($schemas) { return "AndElement"; }); $converter->addAliasMap('http://schemas.microsoft.com/exchange/services/2006/types', 'EmailAddress', function ($type) use($schemas) { return "jamesiarmes\\PEWS\\API\\Type\\EmailAddressType"; }); $items = $converter->convert($schemas); $progress->start($output, count($items)); $classMap = []; foreach ($items as $item) { /** @var PHPClass $item */ $progress->advance(1, true); $output->write(" Creating <info>" . $output->getFormatter()->escape($item->getFullName()) . "</info>... "); $path = $pathGenerator->getPath($item); $fileGen = new FileGenerator(); $fileGen->setFilename($path); $classGen = new \Zend\Code\Generator\ClassGenerator(); $itemClass = $item->getNamespace() . '\\' . $item->getName(); if (class_exists($itemClass)) { $existingClass = Generator\ClassGenerator::fromReflection(new ClassReflection($itemClass)); $classGen = $existingClass; } if ($generator->generate($classGen, $item)) { $fileGen->setClass($classGen); $fileGen->write(); $output->writeln("done."); if (isset($item->type) && $item->type->getName() != "") { $classMap[$item->type->getName()] = '\\' . $classGen->getNamespaceName() . '\\' . $classGen->getName(); } } else { $output->write("skip."); } } $mappingClassReflection = new ClassReflection(ClassMap::class); $mappingClass = Generator\ClassGenerator::fromReflection($mappingClassReflection); $mappingClass->getProperty('classMap')->setDefaultValue($classMap); $fileGen = new FileGenerator(); $fileGen->setFilename($mappingClassReflection->getFileName()); $fileGen->setClass($mappingClass); $fileGen->write(); $progress->finish(); }
public function testExtendedClassProperies() { $reflClass = new ClassReflection('ZendTest\Code\Generator\TestAsset\ExtendedClassWithProperties'); $classGenerator = ClassGenerator::fromReflection($reflClass); $code = $classGenerator->generate(); $this->assertContains('publicExtendedClassProperty', $code); $this->assertContains('protectedExtendedClassProperty', $code); $this->assertContains('privateExtendedClassProperty', $code); $this->assertNotContains('publicClassProperty', $code); $this->assertNotContains('protectedClassProperty', $code); $this->assertNotContains('privateClassProperty', $code); }
/** * @group namespace */ public function testCodeGenerationShouldTakeIntoAccountNamespacesFromReflection() { $reflClass = new ClassReflection('ZendTest\Code\Generator\TestAsset\ClassWithNamespace'); $classGenerator = ClassGenerator::fromReflection($reflClass); $this->assertEquals('ZendTest\Code\Generator\TestAsset', $classGenerator->getNamespaceName()); $this->assertEquals('ClassWithNamespace', $classGenerator->getName()); $expected = <<<CODE namespace ZendTest\Code\Generator\\TestAsset; class ClassWithNamespace { } CODE; $received = $classGenerator->generate(); $this->assertEquals($expected, $received, $received); }
/** * Update module class with class map autoloading * * @return bool * @throws \Zend\Code\Generator\Exception */ public function updateModuleWithClassmapAutoloader() { // get needed options to shorten code $path = realpath($this->requestOptions->getPath()); $directory = $this->requestOptions->getDirectory(); $destination = $this->requestOptions->getDestination(); $moduleFile = $directory . '/Module.php'; $moduleClass = str_replace($path . '/module/', '', $directory) . '\\Module'; $moduleName = str_replace($path . '/module/', '', $directory); // check for module file if (!file_exists($moduleFile)) { return false; } // get file and class reflection $fileReflection = new FileReflection($moduleFile, true); $classReflection = $fileReflection->getClass($moduleClass); // setup class generator with reflected class $code = ClassGenerator::fromReflection($classReflection); // check for action method if ($code->hasMethod('getAutoloaderConfig')) { $code->removeMethod('getAutoloaderConfig'); } // add getAutoloaderConfig method with class map $code->addMethodFromGenerator($this->generateGetAutoloaderConfigMethod($destination, $moduleName)); // create file with file generator $file = new FileGenerator(); $file->setClass($code); // add optional doc block if ($this->flagCreateApiDocs) { $file->setDocBlock(new DocBlockGenerator('This file was generated by FrilleZFTool.', null, array($this->generatePackageTag($moduleName), $this->generateSeeTag()))); } // create file with file generator $file = new FileGenerator(); $file->setClass($code); // add optional doc block if ($this->flagCreateApiDocs) { $file->setDocBlock(new DocBlockGenerator('This file was generated by FrilleZFTool.', null, array($this->generatePackageTag($moduleName), $this->generateSeeTag()))); } // write module class if (!file_put_contents($moduleFile, $file->generate())) { return false; } return true; }
/** * Get actions for a controller * * @return array */ protected function getActionsForController($controllerPath, $controllerKey) { // get file and class reflection $fileReflection = new FileReflection($controllerPath, true); $classReflection = $fileReflection->getClass($controllerKey . 'Controller'); // setup class generator with reflected class $code = ClassGenerator::fromReflection($classReflection); // initialize controllers $actions = array(); // lop through methods foreach (array_keys($code->getMethods()) as $methodName) { if (substr($methodName, -6) == 'Action') { $actions[] = $methodName; } } // sort actions sort($actions); return $actions; }
/** * Create a new subclass and factory to override a factory-generated * service. * * @param mixed $factory Factory configuration for class to extend * @param string $module Module in which to create the new factory * * @return string * @throws \Exception */ protected function cloneFactory($factory, $module) { // Make sure we can figure out how to handle the factory; it should // either be a [controller, method] array or a "controller::method" // string; anything else will cause a problem. $parts = is_string($factory) ? explode('::', $factory) : $factory; if (!is_array($parts) || count($parts) != 2 || !class_exists($parts[0]) || !method_exists($parts[0], $parts[1])) { throw new \Exception('Unexpected factory configuration format.'); } list($factoryClass, $factoryMethod) = $parts; $newFactoryClass = $this->generateLocalClassName($factoryClass, $module); if (!class_exists($newFactoryClass)) { $this->createClassInModule($newFactoryClass, $module); $skipBackup = true; } else { $skipBackup = false; } if (method_exists($newFactoryClass, $factoryMethod)) { throw new \Exception("{$newFactoryClass}::{$factoryMethod} already exists."); } $oldReflection = new ClassReflection($factoryClass); $newReflection = new ClassReflection($newFactoryClass); $generator = ClassGenerator::fromReflection($newReflection); $method = MethodGenerator::fromReflection($oldReflection->getMethod($factoryMethod)); $this->createServiceClassAndUpdateFactory($method, $oldReflection->getNamespaceName(), $module); $generator->addMethodFromGenerator($method); $this->writeClass($generator, $module, true, $skipBackup); return $newFactoryClass . '::' . $factoryMethod; }
/** * @return array */ protected function setClientMethodDocblocks() { $client = new \SoapClient(__DIR__ . '/../../Resources/wsdl/services.wsdl'); $functions = $client->__getFunctions(); sort($functions); $functions = array_map(function ($function) { return preg_replace("~^[a-z]+\\s([a-z]+) ?\\(.+\\)\$~i", "\$1", $function); }, $functions); $exchangeWebServicesReflection = new ClassReflection(ExchangeWebServices::class); $fileGen = Generator\FileGenerator::fromReflectedFileName($exchangeWebServicesReflection->getFileName()); $fileGen->setFilename($exchangeWebServicesReflection->getFileName()); $exchangeWebServicesClass = Generator\ClassGenerator::fromReflection($exchangeWebServicesReflection); $docblock = $exchangeWebServicesClass->getDocBlock(); $reflection = new \ReflectionClass($docblock); $property = $reflection->getProperty('tags'); $property->setAccessible(true); $property->setValue($docblock, []); $docblock->setWordWrap(false); $tags = []; $tags[] = new Generator\DocBlock\Tag\GenericTag('@package php-ews\\Client'); $tags[] = new EmptyDocblockTag(); foreach ($functions as $function) { $tag = new MethodWIthRequestTag($function, ['Type']); $tags[] = $tag; } $docblock->setTags($tags); $exchangeWebServicesClass->getDocBlock()->setSourceDirty(true); $fileGen->setClass($exchangeWebServicesClass); $fileGen->write(); }
} continue; } $requiredParameters[] = new ParameterGenerator($fieldName, Collection::class); } foreach ($metadataClass->getFieldNames() as $fieldName) { if (in_array($fieldName, $metadataClass->getIdentifierFieldNames(), true) && $metadataClass->isIdGeneratorIdentity()) { // auto-incremental identifier, skip it. continue; } $fieldMapping = $metadataClass->getFieldMapping($fieldName); $type = null; if ('datetime' === $fieldMapping['type']) { $type = 'DateTime'; } $parameter = new ParameterGenerator($fieldName, $type); if (isset($fieldMapping['nullable']) && $fieldMapping['nullable']) { $parameter->setDefaultValue(null); $optionalParameters[] = $parameter; } else { $requiredParameters[] = $parameter; } } $classGenerator = ClassGenerator::fromReflection(new ClassReflection($metadataClass->getName())); $classGenerator->removeMethod('__construct'); $classGenerator->addMethodFromGenerator(new MethodGenerator('__construct', array_merge($requiredParameters, $optionalParameters), MethodGenerator::FLAG_PUBLIC, implode("\n", array_map(function (ParameterGenerator $parameterGenerator) { $name = $parameterGenerator->getName(); return '$this->' . $name . ' = $' . $name . ';'; }, array_merge($requiredParameters, $optionalParameters))))); file_put_contents($metadataClass->getReflectionClass()->getFileName(), preg_replace('/private \\$([A-Za-z0-9]+) = null;/i', 'private \\$${1};', "<?php\n\n\n" . $classGenerator->generate())); }
/** * {@inheritdoc} */ public function createClassmap() { /* * INI FILE GENERATION */ $outputPath = array($this->config->getOutputPath()); // if the psr0 autoloader has been selected, transform the class namespace into a filesystem path if ($this->config->getAutoloader() === Config::AUTOLOADER_PSR0) { $outputPath[] = str_ireplace('\\', DIRECTORY_SEPARATOR, $this->config->getNamespace()); } // append the file name $outputPath[] = 'classmap.ini'; // finalize the output path $outputPath = implode(DIRECTORY_SEPARATOR, $outputPath); // remove the file if exists $fs = new Filesystem(); $fs->remove($outputPath); foreach ($this->classmap as $wsdlType => $phpType) { file_put_contents($outputPath, "{$wsdlType} = {$phpType}" . AbstractGenerator::LINE_FEED, FILE_APPEND); } /* * CLASS GENERATION */ // create the class $class = ClassGenerator::fromReflection(new ClassReflection('\\Sapone\\Template\\ClassmapTemplate')); $class->setName('Classmap'); $class->setExtendedClass('\\ArrayObject'); $class->setNamespaceName($this->config->getNamespace()); $doc = new DocBlockGenerator(); $doc->setTag(new GenericTag('@service', $this->config->getWsdlDocumentPath())); $class->setDocBlock($doc); $this->serializeClass($class); return $class->getName(); }
public function methodAction() { $console = $this->getServiceLocator()->get('console'); $request = $this->getRequest(); $action = $request->getParam('name'); $controller = $request->getParam('controllerName'); $module = $request->getParam('module'); $path = $request->getParam('path', '.'); $ucController = ucfirst($controller); $controllerPath = sprintf('%s/module/%s/src/%s/Controller/%sController.php', $path, $module, $module, $ucController); $class = sprintf('%s\\Controller\\%sController', $module, $ucController); $console->writeLine("Creating action '{$action}' in controller '{$module}\\Controller\\{$controller}'.", Color::YELLOW); if (!file_exists("{$path}/module") || !file_exists("{$path}/config/application.config.php")) { return $this->sendError("The path {$path} doesn't contain a ZF2 application. I cannot create a controller action."); } if (!file_exists($controllerPath)) { return $this->sendError("The controller {$controller} does not exists in module {$module}. I cannot create a controller action."); } $fileReflection = new Reflection\FileReflection($controllerPath, true); $classReflection = $fileReflection->getClass($class); $classGenerator = Generator\ClassGenerator::fromReflection($classReflection); $classGenerator->addUse('Zend\\Mvc\\Controller\\AbstractActionController')->addUse('Zend\\View\\Model\\ViewModel')->setExtendedClass('AbstractActionController'); if ($classGenerator->hasMethod($action . 'Action')) { return $this->sendError("The action {$action} already exists in controller {$controller} of module {$module}."); } $classGenerator->addMethods(array(new Generator\MethodGenerator($action . 'Action', array(), Generator\MethodGenerator::FLAG_PUBLIC, 'return new ViewModel();'))); $fileGenerator = new Generator\FileGenerator(array('classes' => array($classGenerator))); $filter = new CamelCaseToDashFilter(); $phtmlPath = sprintf('%s/module/%s/view/%s/%s/%s.phtml', $path, $module, strtolower($filter->filter($module)), strtolower($filter->filter($controller)), strtolower($filter->filter($action))); if (!file_exists($phtmlPath)) { $contents = sprintf("Module: %s\nController: %s\nAction: %s", $module, $controller, $action); if (file_put_contents($phtmlPath, $contents)) { $console->writeLine(sprintf("Created view script at %s", $phtmlPath), Color::GREEN); } else { $console->writeLine(sprintf("An error occurred when attempting to create view script at location %s", $phtmlPath), Color::RED); } } if (file_put_contents($controllerPath, $fileGenerator->generate())) { $console->writeLine(sprintf('The action %s has been created in controller %s\\Controller\\%s.', $action, $module, $controller), Color::GREEN); } else { $console->writeLine("There was an error during action creation.", Color::RED); } }