public function generate() { if ($this->controller) { $modelBuilder = $this->controller->getModelBuilder(); $className = $modelBuilder->getName(); } else { $className = $this->class; } $modelClass = $this->modelClass ? $this->modelClass : $this->class; $class = new ClassGenerator(); $class->setName($className); $class->setExtendedClass('CrudController'); $class->addUse('Boyhagemann\\Crud\\CrudController'); $class->addUse('Boyhagemann\\Form\\FormBuilder'); $class->addUse('Boyhagemann\\Model\\ModelBuilder'); $class->addUse('Boyhagemann\\Overview\\OverviewBuilder'); $param = new ParameterGenerator(); $param->setName('fb')->setType('FormBuilder'); $body = $this->generateFormBuilderBody(); $docblock = '@param FormBuilder $fb'; $class->addMethod('buildForm', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $param = new ParameterGenerator(); $param->setName('mb')->setType('ModelBuilder'); $body = sprintf('$mb->name(\'%s\')->table(\'%s\');' . PHP_EOL, $modelClass, strtolower(str_replace('\\', '_', $modelClass))); $docblock = '@param ModelBuilder $mb'; $class->addMethod('buildModel', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $param = new ParameterGenerator(); $param->setName('ob')->setType('OverviewBuilder'); $body = ''; $docblock = '@param OverviewBuilder $ob'; $class->addMethod('buildOverview', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $this->generator->setClass($class); return $this->generator->generate(); }
public function generate() { $modelBuilder = $this->controller->getModelBuilder(); $className = $modelBuilder->getName() . 'Controller'; $class = new ClassGenerator(); $class->setName($className); $class->setExtendedClass('CrudController'); $param = new ParameterGenerator(); $param->setName('fb')->setType('FormBuilder'); $body = $this->generateFormBuilderBody(); $docblock = '@param FormBuilder $fb'; $class->addMethod('buildForm', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $param = new ParameterGenerator(); $param->setName('mb')->setType('ModelBuilder'); $body = ''; $docblock = '@param ModelBuilder $mb'; $class->addMethod('buildModel', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $param = new ParameterGenerator(); $param->setName('ob')->setType('OverviewBuilder'); $body = ''; $docblock = '@param OverviewBuilder $ob'; $class->addMethod('buildOverview', array($param), MethodGenerator::FLAG_PUBLIC, $body, $docblock); $this->generator->setClass($class); $this->generator->setUses(array('Boyhagemann\\Crud\\CrudController', 'Boyhagemann\\Form\\FormBuilder', 'Boyhagemann\\Model\\ModelBuilder', 'Boyhagemann\\Overview\\OverviewBuilder')); return $this->generator->generate(); }
public function getContents() { $className = $this->getFullClassName($this->_dbTableName, 'Model\\DbTable'); $codeGenFile = new FileGenerator($this->getPath()); $codeGenFile->setClass(new ClassGenerator($className, null, null, '\\Zend\\Db\\Table\\AbstractTable', null, array(new PropertyGenerator('_name', $this->_actualTableName, PropertyGenerator::FLAG_PROTECTED)))); return $codeGenFile->generate(); }
protected function convert(AbstractConverter $converter, array $schemas, array $targets, OutputInterface $output) { $generator = new ClassGenerator(); $generator->setTargetPhpVersion($converter->getTargetPhpVersion()); $generator->setBaseClass($converter->getBaseClass()); $pathGenerator = new Psr4PathGenerator($targets); $progress = $this->getHelperSet()->get('progress'); $items = $converter->convert($schemas); $progress->start($output, count($items)); foreach ($items as $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(); if ($generator->generate($classGen, $item)) { $fileGen->setClass($classGen); $fileGen->write(); $output->writeln("done."); } else { $output->write("skip."); } } $progress->finish(); }
/** * (non-PHPdoc) * * @see \Symfony\Component\Console\Command\Command::execute() */ public function execute(InputInterface $input, OutputInterface $output) { $document = $this->getDocument($input->getArgument('document')); $items = $document->getElement(); $directory = sprintf($input->getArgument('elementOutput'), $document->getFileInfo()->getBasename('.dtd')); $namespace = sprintf($input->getArgument('elementNamespace'), $document->getFileInfo()->getBasename('.dtd')); $parentClass = $input->getArgument('elementParentClass'); $description = str_replace("\\", " ", $namespace); if (!file_exists($directory)) { mkdir($directory, 0777, true); } $progressBar = new ProgressBar($output, $items->count()); $progressBar->setFormat('verbose'); foreach ($items as $item) { $name = sprintf("%sElement", Source::camelCase($item->getName())); $filename = sprintf("%s/%s.php", $directory, $name); $classDescription = sprintf("%s %s", $description, $name); $datetime = new \DateTime(); $properties = array((new PropertyGenerator("name", $item->getName()))->setDocBlock(new DocBlockGenerator(sprintf("%s Name", $classDescription), "", array(new Tag("var", "string")))), (new PropertyGenerator("value", $item->getValue()))->setDocBlock(new DocBlockGenerator(sprintf("%s Value", $classDescription), "", array(new Tag("var", "string"))))); $docblock = new DocBlockGenerator($classDescription, "", array(new Tag("author", "ITC Generator " . $datetime->format("d.m.Y h:m:s")), new Tag("copyright", "LGPL"))); $fileGenerator = new FileGenerator(); $fileGenerator->setClass(new ClassGenerator($name, $namespace, null, $parentClass, array(), $properties, array(), $docblock)); file_put_contents($filename, $fileGenerator->generate()); $progressBar->advance(); } $progressBar->finish(); }
/** * getContents() * * @return string */ public function getContents() { $filter = new \Zend\Filter\Word\DashToCamelCase(); $className = $filter->filter($this->_forControllerName) . 'ControllerTest'; $codeGenFile = new FileGenerator(); $codeGenFile->setRequiredFiles(array('PHPUnit/Framework/TestCase.php')); $codeGenFile->setClass(new ClassGenerator($className, null, null, 'PHPUnit_Framework_TestCase', array(), array(), array('methods' => array(new MethodGenerator('setUp', array(), MethodGenerator::FLAG_PUBLIC, ' /* Setup Routine */'), new MethodGenerator('tearDown', array(), MethodGenerator::FLAG_PUBLIC, ' /* Tear Down Routine */'))))); return $codeGenFile->generate(); }
public function write(array $items) { foreach ($items as $item) { $path = $this->pathGenerator->getPath($item); $fileGen = new FileGenerator(); $fileGen->setFilename($path); $fileGen->setClass($item); $fileGen->write(); $this->logger->debug(sprintf("Written PHP class file %s", $path)); } $this->logger->info(sprintf("Written %s STUB classes", count($items))); }
/** * @param FileGenerator $file * @param Type $type * * @return string */ public function generate(FileGenerator $file, $type) { $class = $file->getClass() ?: new ClassGenerator(); $class->setNamespaceName($type->getNamespace()); $class->setName($type->getName()); $this->ruleSet->applyRules(new TypeContext($class, $type)); foreach ($type->getProperties() as $property) { $this->ruleSet->applyRules(new PropertyContext($class, $type, $property)); } $file->setClass($class); return $file->generate(); }
protected function convert(AbstractConverter $converter, array $schemas, array $targets, OutputInterface $output) { $this->setClientMethodDocblocks(); $generator = new ClassGenerator(); $pathGenerator = new Psr4PathGenerator($targets); $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 "garethp\\ews\\API\\Type\\EmailAddressType"; }); $items = $converter->convert($schemas); $progress = new ProgressBar($output, count($items)); $progress->start(count($items)); $classMap = []; foreach ($items as $item) { /** @var PHPClass $item */ $progress->advance(1, true); $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)) { $fileGen = FileGenerator::fromReflectedFileName($path); $fileGen->setFilename($path); $classGen = Generator\ClassGenerator::fromReflection(new ClassReflection($itemClass)); } if ($generator->generate($classGen, $item)) { $namespace = $classGen->getNamespaceName(); $fileGen->setClass($classGen); $fileGen->write(); if (isset($item->type) && $item->type->getName() != "" && $item->getNamespace() !== Enumeration::class) { $classMap[$item->type->getName()] = '\\' . $namespace . '\\' . $classGen->getName(); } } else { } } $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(); }
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(); }
/** * * @param DTDDocument $document * @param string $outputDirectory * @param string $namespace * @param string $parentClass */ public function generate(DTDDocument $document, $outputDirectory, $namespace, $parentClass) { if (!file_exists($outputDirectory)) { mkdir($outputDirectory, 0777, true); } $name = ucfirst($document->getFileInfo()->getBasename('.dtd')); $filename = sprintf("%s/%s.php", $outputDirectory, $name); $classGenerator = new ClassGenerator($name, $namespace, null, $parentClass); $fileGenerator = new FileGenerator(); $fileGenerator->setClass($classGenerator); $fileDocblock = new DocBlockGenerator(sprintf("%s %s", str_replace("\\", " ", $namespace), $name)); $fileDocblock->setTag(new Tag("author", "Generator")); $fileDocblock->setTag(new Tag("licence", "LGPL")); $fileGenerator->setDocBlock($fileDocblock); file_put_contents($filename, $fileGenerator->generate()); }
function it_generates_types(RuleSetInterface $ruleSet, FileGenerator $file, ClassGenerator $class) { $type = new Type('MyNamespace', 'MyType', ['prop1' => 'string']); $property = $type->getProperties()[0]; $file->generate()->willReturn('code'); $file->getClass()->willReturn($class); $class->setNamespaceName('MyNamespace')->shouldBeCalled(); $class->setName('MyType')->shouldBeCalled(); $file->setClass($class)->shouldBeCalled(); $ruleSet->applyRules(Argument::that(function (ContextInterface $context) use($type) { return $context instanceof TypeContext && $context->getType() === $type; }))->shouldBeCalled(); $ruleSet->applyRules(Argument::that(function (ContextInterface $context) use($type, $property) { return $context instanceof PropertyContext && $context->getType() === $type && $context->getProperty() === $property; }))->shouldBeCalled(); $this->generate($file, $type)->shouldReturn('code'); }
/** * (non-PHPdoc) * * @see \Symfony\Component\Console\Command\Command::execute() */ public function execute(InputInterface $input, OutputInterface $output) { $document = $this->getDocument($input->getArgument('document')); $directory = $input->getArgument('output'); $namespace = $input->getArgument('namespace'); $parentClass = $input->getArgument('parentClass'); if (!file_exists($directory)) { mkdir($directory, 0777, true); } $name = ucfirst($document->getFileInfo()->getBasename('.dtd')); $output->writeln("Generating Document " . $name); $filename = sprintf("%s/%s.php", $directory, $name); $classGenerator = new ClassGenerator($name, $namespace, null, $parentClass); $fileGenerator = new FileGenerator(); $fileGenerator->setClass($classGenerator); $fileDocblock = new DocBlockGenerator(sprintf("%s %s", str_replace("\\", " ", $namespace), $name)); $fileDocblock->setTag(new Tag("author", "Generator")); $fileDocblock->setTag(new Tag("licence", "LGPL")); $fileGenerator->setDocBlock($fileDocblock); file_put_contents($filename, $fileGenerator->generate()); }
public function generate(DTDDocument $document, $outputDirectory, $namespace, $parentClass) { $items = $document->getElement(); $directory = sprintf($outputDirectory, $document->getFileInfo()->getBasename('.dtd')); $namespace = sprintf($namespace, $document->getFileInfo()->getBasename('.dtd')); $description = str_replace("\\", " ", $namespace); if (!file_exists($directory)) { mkdir($directory, 0777, true); } foreach ($items as $item) { $name = sprintf("%sElement", Source::camelCase($item->getName())); $filename = sprintf("%s/%s.php", $directory, $name); $classDescription = sprintf("%s %s", $description, $name); $datetime = new \DateTime(); $properties = array((new PropertyGenerator("name", $item->getName()))->setDocBlock(new DocBlockGenerator(sprintf("%s Name", $classDescription), "", array(new Tag("var", "string")))), (new PropertyGenerator("value", $item->getValue()))->setDocBlock(new DocBlockGenerator(sprintf("%s Value", $classDescription), "", array(new Tag("var", "string"))))); $docblock = new DocBlockGenerator($classDescription, "", array(new Tag("author", "ITC Generator " . $datetime->format("d.m.Y h:m:s")), new Tag("copyright", "LGPL"))); $fileGenerator = new FileGenerator(); $fileGenerator->setClass(new ClassGenerator($name, $namespace, null, $parentClass, array(), $properties, array(), $docblock)); file_put_contents($filename, $fileGenerator->generate()); } }
/** * @param ClassGenerator $class */ protected function writeClass(ClassGenerator $class) { $generator = new FileGenerator(); $generator->setClass($class); $generator->setFilename('src/Flex/Code/Html/Tag/' . $class->getName() . '.php'); $generator->write(); }
/** * 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; }
private function buildProxyClass(string $entityInterfaceName, string $proxyNamespace, string $proxyClassName) : string { $reflectionClass = new ReflectionClass($entityInterfaceName); if (!$reflectionClass->isInterface()) { throw InvalidInterfaceException::fromInvalidInterface($entityInterfaceName); } $classGenerator = new ClassGenerator(); $classGenerator->setNamespaceName($proxyNamespace); $classGenerator->setName($proxyClassName); $classGenerator->setImplementedInterfaces([$entityInterfaceName, ProxyInterface::class]); $classGenerator->addProperty('initializer', null, PropertyGenerator::FLAG_PRIVATE); $classGenerator->addProperty('relationId', null, PropertyGenerator::FLAG_PRIVATE); $classGenerator->addProperty('realEntity', null, PropertyGenerator::FLAG_PRIVATE); $constructorGenerator = new MethodGenerator('__construct', [['name' => 'initializer', 'type' => 'callable'], ['name' => 'relationId']]); $constructorGenerator->setBody(' $this->initializer = $initializer; $this->relationId = $relationId; '); $classGenerator->addMethodFromGenerator($constructorGenerator); $getRelationIdGenerator = new MethodGenerator('__getRelationId'); $getRelationIdGenerator->setBody(' return $this->relationId; '); $classGenerator->addMethodFromGenerator($getRelationIdGenerator); $getRealEntityGenerator = new MethodGenerator('__getRealEntity'); $getRealEntityGenerator->setBody(' if (null === $this->realEntity) { $this->realEntity = ($this->initializer)(); \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class); }; return $this->realEntity; '); $classGenerator->addMethodFromGenerator($getRealEntityGenerator); foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) { $parameters = []; $parameterGenerators = []; $returnType = $reflectionMethod->getReturnType(); foreach ($reflectionMethod->getParameters() as $reflectionParameter) { $parameterGenerator = new ParameterGenerator($reflectionParameter->getName(), $reflectionParameter->getType(), $reflectionParameter->isDefaultValueAvailable() ? $reflectionParameter->getDefaultValue() : null); $parameterGenerator->setVariadic($reflectionParameter->isVariadic()); $parameterGenerators[] = $parameterGenerator; if ($reflectionParameter->isVariadic()) { $parameters[] = '...$' . $reflectionParameter->getName(); } else { $parameters[] = '$' . $reflectionParameter->getName(); } } $methodGenerator = new MethodGenerator(); $methodGenerator->setName($reflectionMethod->getName()); $methodGenerator->setVisibility(MethodGenerator::VISIBILITY_PUBLIC); $methodGenerator->setParameters($parameterGenerators); $methodGenerator->setReturnType($returnType); $body = ' if (null === $this->realEntity) { $this->realEntity = ($this->initializer)(); \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class); }; '; if ('void' !== $returnType) { $body .= 'return '; } $body .= '$this->realEntity->' . $reflectionMethod->getName() . '(' . implode(', ', $parameters) . ');'; $methodGenerator->setBody($body); $classGenerator->addMethodFromGenerator($methodGenerator); } $fileGenerator = new FileGenerator(); $fileGenerator->setClass($classGenerator); $filename = null === $this->proxyFolder ? tempnam(sys_get_temp_dir(), $proxyClassName) : sprintf('%s/%s.php', $this->proxyFolder, $proxyClassName); $fileGenerator->setFilename($filename); $fileGenerator->write(); return $filename; }
/** * getContents() * * @return string */ public function getContents() { $className = $this->_moduleName ? ucfirst($this->_moduleName) . '\\' : ''; $className .= ucfirst($this->_controllerName) . 'Controller'; $codeGenFile = new FileGenerator(); $codeGenFile->setFilename($this->getPath()); $cg = new ClassGenerator($className); $cg->setMethod(new MethodGenerator('init', array(), null, '/* Initialize action controller here */')); $codeGenFile->setClass($cg); if ($className == 'ErrorController') { $codeGenFile = new FileGenerator(); $codeGenFile->setFilename($this->getPath()); $cg = new ClassGenerator($className); $cg->setMethods(array(new MethodGenerator('errorAction', array(), null, <<<'EOS' $errors = $this->_getParam('error_handler'); if (!$errors || !$errors instanceof \ArrayObject) { $this->view->vars()->message = 'You have reached the error page'; return; } switch ($errors->type) { case \Zend\Controller\Plugin\ErrorHandler::EXCEPTION_NO_ROUTE: case \Zend\Controller\Plugin\ErrorHandler::EXCEPTION_NO_CONTROLLER: case \Zend\Controller\Plugin\ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $priority = \Zend\Log\Logger::NOTICE; $this->view->vars()->message = 'Page not found'; break; default: // application error $this->getResponse()->setHttpResponseCode(500); $priority = \Zend\Log\Logger::CRIT; $this->view->vars()->message = 'Application error'; break; } // Log exception, if logger available if (($log = $this->getLog())) { $log->log($this->view->vars()->message, $priority, $errors->exception); $log->log('Request Parameters', $priority, $errors->request->getParams()); } // conditionally display exceptions if ($this->getInvokeArg('displayExceptions') == true) { $this->view->vars()->exception = $errors->exception; } $this->view->vars()->request = $errors->request; EOS ), new MethodGenerator('getLog', array(), null, <<<'EOS' /* @var $bootstrap Zend\Application\Bootstrap */ $bootstrap = $this->getInvokeArg('bootstrap'); if (!$bootstrap->getBroker()->hasPlugin('Log')) { return false; } $log = $bootstrap->getResource('Log'); return $log; EOS ))); } // store the generator into the registry so that the addAction command can use the same object later FileGeneratorRegistry::registerFileCodeGenerator($codeGenFile); // REQUIRES filename to be set return $codeGenFile->generate(); }
/** * generates base controller for given dataSet * * @param DataSetDescriptorInterface $dataSet * @return string generated controller full class name */ protected function generateBaseController(DataSetDescriptorInterface $dataSet) { $name = $dataSet->getName(); $className = 'Base' . $this->underscoreToCamelCase->filter($name) . 'Controller'; $namespace = $this->params->getParam("moduleName") . '\\Controller\\Base'; $fullClassName = '\\' . $namespace . '\\' . $className; $moduleName = $this->params->getParam("moduleName"); $fileBase = new FileGenerator(); $fileBase->setFilename($className); $fileBase->setNamespace($namespace); $class = new ClassGenerator(); $class->setName($className)->setExtendedClass('\\' . $this->extendedController); $docBlock = new \Zend\Code\Generator\DocblockGenerator(sprintf($this->codeLibrary()->get('controller.standardBaseControllerDescription'), $name)); $docBlock->setTag(new GenericTag('author', $this->params->getParam('author')))->setTag(new GenericTag('project', $this->params->getParam('project')))->setTag(new GenericTag('license', $this->params->getParam('license')))->setTag(new GenericTag('copyright', $this->params->getParam('copyright'))); $class->setDocBlock($docBlock); $this->addControllerMethods($class, $dataSet); $fileBase->setClass($class); $modelClassFilePath = $this->moduleRoot() . "/src/" . $this->params->getParam("moduleName") . "/Controller/Base/" . $className . ".php"; file_put_contents($modelClassFilePath, $fileBase->generate()); return $fullClassName; }
/** * @param string $class * @param Entity $entity * * @return string */ protected function generateFileContent($class, $entity) { $generator = new FileGenerator(); $descriptor = $entity->getFileDescriptor(); $generator->setClass($class); $generator->setDocblock(DocBlockGenerator::fromArray(array('shortDescription' => 'Generated by Protobuf protoc plugin.', 'longDescription' => 'File descriptor : ' . $descriptor->getName()))); return $generator->generate(); }
/** * creates Module class */ protected function createModuleClass() { $moduleClassFilePath = $this->moduleRoot() . '/Module.php'; if (!file_exists($moduleClassFilePath)) { $this->console('creating Module Class'); $moduleClassFile = new FileGenerator(); $moduleClassFile->setNamespace($this->params->getParam('moduleName')); $moduleClass = new ClassGenerator(); $moduleClass->setDocBlock($this->getFileDocBlock())->getDocBlock()->setShortDescription($this->codeLibrary()->get('module.moduleClassDescription')); $moduleClass->setName('Module'); // onbootstrap $onBootstrapMethod = new MethodGenerator(); $onBootstrapMethod->setName('onBootstrap')->setBody($this->codeLibrary()->get('module.onBootstrap.body')); $onBootstrapMethod->setDocBlock(new DocBlockGenerator($this->codeLibrary()->get('module.onBootstrap.shortdescription'), $this->codeLibrary()->get('module.onBootstrap.longdescription'), array(new ParamTag('e', '\\Zend\\Mvc\\MvcEvent')))); $eventParam = new ParameterGenerator('e', '\\Zend\\Mvc\\MvcEvent'); $onBootstrapMethod->setParameter($eventParam); $moduleClass->addMethodFromGenerator($onBootstrapMethod); // config $configMethod = new MethodGenerator('getConfig', array(), MethodGenerator::FLAG_PUBLIC, $this->codeLibrary()->get('module.config.body'), new DocBlockGenerator($this->codeLibrary()->get('module.config.shortdescription'), $this->codeLibrary()->get('module.config.longdescription'), array())); $moduleClass->addMethodFromGenerator($configMethod); // getAutoloaderConfig $getAutoloaderConfigMethod = new MethodGenerator('getAutoloaderConfig', array(), MethodGenerator::FLAG_PUBLIC, $this->codeLibrary()->get('module.getAutoloaderConfig.body'), new DocBlockGenerator($this->codeLibrary()->get('module.getAutoloaderConfig.shortdescription'), $this->codeLibrary()->get('module.getAutoloaderConfig.longdescription'), array())); $moduleClass->addMethodFromGenerator($getAutoloaderConfigMethod); // adding class method and generating file $moduleClassFile->setClass($moduleClass); file_put_contents($moduleClassFilePath, $moduleClassFile->generate()); } }
public function controllerAction() { $config = $this->getServiceLocator()->get('config'); $moduleName = $config['VisioCrudModeler']['params']['moduleName']; $modulePath = $config['VisioCrudModeler']['params']['modulesDirectory']; $db = $this->getServiceLocator()->get('Zend\\Db\\Adapter\\Adapter'); $dataSourceDescriptor = new DbDataSourceDescriptor($db, 'K08_www_biedronka_pl'); $listDataSets = $dataSourceDescriptor->listDataSets(); $filter = new \Zend\Filter\Word\UnderscoreToCamelCase(); foreach ($listDataSets as $d) { $className = $filter->filter($d) . 'Controller'; $file = new FileGenerator(); $file->setFilename($className); $file->setNamespace($moduleName)->setUse('Zend\\Mvc\\Controller\\AbstractActionController'); $foo = new ClassGenerator(); $docblock = DocBlockGenerator::fromArray(array('shortDescription' => 'Sample generated class', 'longDescription' => 'This is a class generated with Zend\\Code\\Generator.', 'tags' => array(array('name' => 'version', 'description' => '$Rev:$'), array('name' => 'license', 'description' => 'New BSD')))); $foo->setName($className); $foo->setExtendedClass('Base' . $className); $foo->setDocblock($docblock); $file->setClass($foo); echo '<pre>'; echo htmlentities($file->generate()); echo '</pre>'; $fileView = new FileGenerator(); $body = "echo '{$className}';"; $fileView->setBody($body); echo '<pre>'; echo htmlentities($fileView->generate()); echo '</pre>'; } echo '<hr />'; foreach ($listDataSets as $d) { $className = 'Base' . $filter->filter($d) . 'Controller'; $fileBase = new FileGenerator(); $fileBase->setFilename($className); $fileBase->setNamespace($moduleName)->setUse('Zend\\Mvc\\Controller\\AbstractActionController'); $fooBase = new ClassGenerator(); $docblockBase = DocBlockGenerator::fromArray(array('shortDescription' => 'Sample generated class', 'longDescription' => 'This is a class generated with Zend\\Code\\Generator.', 'tags' => array(array('name' => 'version', 'description' => '$Rev:$'), array('name' => 'license', 'description' => 'New BSD')))); $fooBase->setName($className); $index = new MethodGenerator(); $index->setName('indexAction'); $create = new MethodGenerator(); $create->setName('createAction'); $read = new MethodGenerator(); $read->setName('readAction'); $update = new MethodGenerator(); $update->setName('updateAction'); $delete = new MethodGenerator(); $delete->setName('deleteAction'); $fooBase->setExtendedClass('AbstractActionController'); //$fooBase->set $fooBase->setDocblock($docblock); $fooBase->addMethodFromGenerator($index); $fooBase->addMethodFromGenerator($create); $fooBase->addMethodFromGenerator($read); $fooBase->addMethodFromGenerator($update); $fooBase->addMethodFromGenerator($delete); $fileBase->setClass($fooBase); echo '<pre>'; echo htmlentities($fileBase->generate()); echo '</pre>'; } exit; }
protected static function generatePHPFiles(array $schemas) { $phpcreator = new PhpConverter(new ShortNamingStrategy()); $phpcreator->addNamespace('http://www.opentravel.org/OTA/2003/05', self::$namespace); $phpcreator->addAliasMapType('http://www.opentravel.org/OTA/2003/05', 'DateOrTimeOrDateTimeType', 'Goetas\\Xsd\\XsdToPhp\\Tests\\JmsSerializer\\OTA\\OTADateTime'); $phpcreator->addAliasMapType('http://www.opentravel.org/OTA/2003/05', 'DateOrDateTimeType', 'Goetas\\Xsd\\XsdToPhp\\Tests\\JmsSerializer\\OTA\\OTADateTime'); $phpcreator->addAliasMapType('http://www.opentravel.org/OTA/2003/05', 'TimeOrDateTimeType', 'Goetas\\Xsd\\XsdToPhp\\Tests\\JmsSerializer\\OTA\\OTADateTime'); $items = $phpcreator->convert($schemas); $generator = new ClassGenerator(); $pathGenerator = new Psr4PathGenerator(array(self::$namespace . "\\" => self::$phpDir)); foreach ($items as $item) { $path = $pathGenerator->getPath($item); $fileGen = new FileGenerator(); $fileGen->setFilename($path); $classGen = new \Zend\Code\Generator\ClassGenerator(); if ($generator->generate($classGen, $item)) { $fileGen->setClass($classGen); $fileGen->write(); } } }
/** * generates file with target grid (if not exists yet) * * @param DataSetDescriptorInterface $dataSet * @param string $extends * base class for grid * @return string full name of generated class */ protected function generateGrid(DataSetDescriptorInterface $dataSet, $extends) { $name = $dataSet->getName(); $className = $this->underscoreToCamelCase->filter($name) . "Grid"; $namespace = $this->params->getParam("moduleName") . "\\Grid"; $fullClassName = '\\' . $namespace . '\\' . $className; $gridClassFilePath = $this->moduleRoot() . "/src/" . $this->params->getParam("moduleName") . "/Grid/" . $className . ".php"; if (file_exists($gridClassFilePath)) { return $fullClassName; } $class = new ClassGenerator(); $class->setName($className); $class->setNamespaceName($namespace); $class->setExtendedClass($extends); $file = new FileGenerator(); $docBlock = new \Zend\Code\Generator\DocblockGenerator(sprintf($this->codeLibrary()->get('grid.standardConfigDescription'), $name)); $docBlock->setTag(new GenericTag('author', $this->params->getParam('author')))->setTag(new GenericTag('project', $this->params->getParam('project')))->setTag(new GenericTag('license', $this->params->getParam('license')))->setTag(new GenericTag('copyright', $this->params->getParam('copyright'))); $file->setClass($class)->setDocBlock($docBlock); file_put_contents($gridClassFilePath, $file->generate()); return $fullClassName; }
/** * @param PhpConverter $converter * @param array $schemas * @param array $targets * @param XsdGeneratePhpArgs $input * @param XsdGeneratePhpCommand $command * @throws \Goetas\Xsd\XsdToPhp\PathGenerator\PathGeneratorException */ protected function convert(PhpConverter $converter, array $schemas, array $targets, XsdGeneratePhpArgs $input, XsdGeneratePhpCommand $command) { $generator = new ClassGenerator(); $pathGenerator = new Psr4PathGenerator($targets); $items = $converter->convert($schemas); /** @var ProgressBar $progressBar */ $progressBar = new ProgressBar($this->output, count($items)); $progressBar->start(); $extendClass = null; if ($input->hasExtendedClass()) { $extendClass = new PHPClass($input->getExtendedClassName(), $input->getExtendedClassNamespaceName()); } $this->outputWriteLine("Generating PHP files"); $skippedFiles = array(); /** @var PHPClass $item */ foreach ($items as $item) { $progressBar->advance(); $path = $pathGenerator->getPath($item); $fileGen = new FileGenerator(); $fileGen->setFilename($path); $classGen = new \Zend\Code\Generator\ClassGenerator(); if (!$item->getExtends() instanceof PHPClass && $extendClass instanceof PHPClass) { $item->setExtends($extendClass); } if (!$generator->generate($classGen, $item)) { $skippedFiles[] = $item->getFullName(); } $fileGen->setClass($classGen); $fileGen->write(); } $progressBar->finish(); if (!empty($skippedFiles)) { foreach ($skippedFiles as $skippedFile) { $this->outputWriteLine(" + <info>" . $this->outputFormatterEscape($skippedFile) . "</info>... "); } } }
/** * @return \Zend\Code\Generator\FileGenerator|null */ public function getGeneratedFile() { $classConfig = $this->config->getClassConfig($this->fullClassName); $factoryName = $this->dic->getFactoryClassName($this->fullClassName); $classReflection = $this->dic->getClassReflection($this->fullClassName); if (strpos($classReflection->getDocComment(), '@generator ignore') !== false) { return null; } $file = new Generator\FileGenerator(); $factoryClass = new \rg\injektor\generators\FactoryClass($factoryName); $instanceMethod = new \rg\injektor\generators\InstanceMethod($this->factoryGenerator); $arguments = array(); $constructorMethodReflection = null; if ($this->dic->isSingleton($classReflection)) { $constructorMethodReflection = $classReflection->getMethod('getInstance'); $arguments = $constructorMethodReflection->getParameters(); } else { if ($classReflection->hasMethod('__construct')) { $constructorMethodReflection = $classReflection->getMethod('__construct'); $arguments = $constructorMethodReflection->getParameters(); } } $isSingleton = $this->dic->isConfiguredAsSingleton($classConfig, $classReflection); $isService = $this->dic->isConfiguredAsService($classConfig, $classReflection); $body = '$i = 0;' . PHP_EOL; if ($isSingleton || $isService) { $defaultValue = new Generator\PropertyValueGenerator(array(), Generator\ValueGenerator::TYPE_ARRAY, Generator\ValueGenerator::OUTPUT_SINGLE_LINE); $property = new Generator\PropertyGenerator('instance', $defaultValue, Generator\PropertyGenerator::FLAG_PRIVATE); $property->setStatic(true); $factoryClass->addPropertyFromGenerator($property); } if ($isSingleton) { $body .= '$singletonKey = serialize($parameters) . "#" . getmypid();' . PHP_EOL; $body .= 'if (isset(self::$instance[$singletonKey])) {' . PHP_EOL; $body .= ' return self::$instance[$singletonKey];' . PHP_EOL; $body .= '}' . PHP_EOL . PHP_EOL; } if ($isService) { $body .= 'if (self::$instance) {' . PHP_EOL; $body .= ' return self::$instance;' . PHP_EOL; $body .= '}' . PHP_EOL . PHP_EOL; } $providerClassName = $this->dic->getProviderClassName($classConfig, new \ReflectionClass($this->fullClassName), null); if ($providerClassName && $providerClassName->getClassName()) { $argumentFactory = $this->dic->getFullFactoryClassName($providerClassName->getClassName()); $this->factoryGenerator->processFileForClass($providerClassName->getClassName()); $body .= '$instance = \\' . $argumentFactory . '::getInstance(array())->get();' . PHP_EOL; $this->usedFactories[] = $argumentFactory; } else { // constructor method arguments if (count($arguments) > 0) { foreach ($arguments as $argument) { /** @var \ReflectionParameter $argument */ $argumentName = $argument->name; $this->constructorArguments[] = $argumentName; $this->constructorArgumentStringParts[] = '$' . $argumentName; $this->realConstructorArgumentStringParts[] = '$' . $argumentName; } $body .= 'if (!$parameters) {' . PHP_EOL; foreach ($arguments as $argument) { /** @var \ReflectionParameter $argument */ $injectionParameter = new \rg\injektor\generators\InjectionParameter($argument, $classConfig, $this->config, $this->dic, InjectionParameter::MODE_NO_ARGUMENTS); try { if ($injectionParameter->getClassName()) { $this->factoryGenerator->processFileForClass($injectionParameter->getClassName()); } if ($injectionParameter->getFactoryName()) { $this->usedFactories[] = $injectionParameter->getFactoryName(); } $body .= ' ' . $injectionParameter->getProcessingBody(); } catch (\Exception $e) { $body .= ' ' . $injectionParameter->getDefaultProcessingBody(); } } $body .= '}' . PHP_EOL; $body .= 'else if (array_key_exists(0, $parameters)) {' . PHP_EOL; foreach ($arguments as $argument) { /** @var \ReflectionParameter $argument */ $injectionParameter = new \rg\injektor\generators\InjectionParameter($argument, $classConfig, $this->config, $this->dic, InjectionParameter::MODE_NUMERIC); try { if ($injectionParameter->getClassName()) { $this->factoryGenerator->processFileForClass($injectionParameter->getClassName()); } if ($injectionParameter->getFactoryName()) { $this->usedFactories[] = $injectionParameter->getFactoryName(); } $body .= ' ' . $injectionParameter->getProcessingBody(); } catch (\Exception $e) { $body .= ' ' . $injectionParameter->getDefaultProcessingBody(); } } $body .= '}' . PHP_EOL; $body .= 'else {' . PHP_EOL; foreach ($arguments as $argument) { /** @var \ReflectionParameter $argument */ $injectionParameter = new \rg\injektor\generators\InjectionParameter($argument, $classConfig, $this->config, $this->dic, InjectionParameter::MODE_STRING); try { if ($injectionParameter->getClassName()) { $this->factoryGenerator->processFileForClass($injectionParameter->getClassName()); } if ($injectionParameter->getFactoryName()) { $this->usedFactories[] = $injectionParameter->getFactoryName(); } $body .= ' ' . $injectionParameter->getProcessingBody(); } catch (\Exception $e) { $body .= ' ' . $injectionParameter->getDefaultProcessingBody(); } } $body .= '}' . PHP_EOL; } // Property injection $this->injectProperties($classConfig, $classReflection); if (count($this->injectableProperties) > 0) { $proxyName = $this->dic->getProxyClassName($this->fullClassName); if ($this->dic->isSingleton($classReflection)) { $file->setClass($this->createProxyClass($proxyName)); $body .= PHP_EOL . '$instance = ' . $proxyName . '::getInstance(' . implode(', ', $this->constructorArgumentStringParts) . ');' . PHP_EOL; } else { $file->setClass($this->createProxyClass($proxyName)); $body .= PHP_EOL . '$instance = new ' . $proxyName . '(' . implode(', ', $this->constructorArgumentStringParts) . ');' . PHP_EOL; } } else { if ($this->dic->isSingleton($classReflection)) { $body .= PHP_EOL . '$instance = \\' . $this->fullClassName . '::getInstance(' . implode(', ', $this->constructorArgumentStringParts) . ');' . PHP_EOL; } else { $body .= PHP_EOL . '$instance = new \\' . $this->fullClassName . '(' . implode(', ', $this->constructorArgumentStringParts) . ');' . PHP_EOL; } } } if ($isSingleton) { $body .= 'self::$instance[$singletonKey] = $instance;' . PHP_EOL; } if ($isService) { $body .= 'self::$instance = $instance;' . PHP_EOL; } foreach ($this->injectableArguments as $injectableArgument) { $body .= '$instance->propertyInjection' . $injectableArgument->getName() . '();' . PHP_EOL; } $body .= 'return $instance;' . PHP_EOL; $instanceMethod->setBody($body); $instanceMethod->setStatic(true); $factoryClass->addMethodFromGenerator($instanceMethod); // Add Factory Method $methods = $classReflection->getMethods(); foreach ($methods as $method) { /** @var \ReflectionMethod $method */ if ($method->isPublic() && substr($method->name, 0, 2) !== '__') { $factoryMethod = $this->getFactoryMethod($method, $classConfig); $factoryClass->addMethodFromGenerator($factoryMethod); } } // Generate File $file->setNamespace('rg\\injektor\\generated'); $this->usedFactories = array_unique($this->usedFactories); foreach ($this->usedFactories as &$usedFactory) { $usedFactory = str_replace('rg\\injektor\\generated\\', '', $usedFactory); $usedFactory = $usedFactory . '.php'; } $file->setRequiredFiles($this->usedFactories); $file->setClass($factoryClass); $file->setFilename($this->factoryPath . DIRECTORY_SEPARATOR . $factoryName . '.php'); return $file; }
/** * Generate Madel class from metadata * * @param stdClass $metadata * @return Generator\ClassGenerator|null */ protected function generateModelFromMetadata($metadata) { $console = $this->getServiceLocator()->get('console'); $name = $metadata->Name; $ucName = ucfirst($name); // Create Api Class $class = new Generator\ClassGenerator($ucName, 'Mailjet\\Model'); $class->setImplementedInterfaces(array('ModelInterface'))->setDocBlock(new Generator\DocBlockGenerator($class->getName() . ' Model', $metadata->Description, array())); $this->addProperties($class, $metadata->Properties); // Create and Write Api Class File $file = new Generator\FileGenerator(); $file->setClass($class); $file->setDocBlock(new Generator\DocBlockGenerator('MailJet Model', self::LICENSE)); $file->setFilename(dirname(__DIR__) . '/Model/' . $class->getName() . '.php'); if (file_put_contents($file->getFilename(), $file->generate())) { $console->writeLine(sprintf("The Model '%s' has been created.", $class->getName()), Color::GREEN); return $class; } else { $console->writeLine(sprintf("There was an error during '%s' Model creation.", $class->getName()), Color::RED); } return $class; }
public function fileCreate($filename, $classGenerator) { if (file_exists($this->getFilePath())) { $content = file_get_contents($this->getFilePath()); //Get protected code $protectedPos = strpos($content, PROTECTED_ZONE); $protectedCode = ''; if ($protectedPos !== false) { $protectedCode = explode(PROTECTED_ZONE, $content); $this->setProtectedCode($protectedCode[1]); } $generator = FileGenerator::fromReflectedFileName($this->getFilePath()); $generator->setClass($classGenerator); $content = $generator->generate(); // Insert the protected code into the new string $this->insertString($content, '}', $this->buildProtectedZone()); // print_r($content);exit; } else { $generator = new FileGenerator(); $generator->setClass($classGenerator); $content = $generator->generate(); $this->insertString($content, '}', $this->buildProtectedZone()); } $this->filePutContents($filename, $content); }
/** * generates code for base model and saves in file (overrides file if exists) * * @param DataSetDescriptorInterface $dataSet * @return string name of generated class */ protected function generateBaseModel(DataSetDescriptorInterface $dataSet) { $name = $dataSet->getName(); $className = "Base" . $this->underscoreToCamelCase->filter($name); $namespace = $this->params->getParam("moduleName") . "\\Model\\BaseModel"; $fullClassName = '\\' . $namespace . '\\' . $className; $class = new ClassGenerator(); $class->setName($className); $class->setNamespaceName($namespace); $class->setExtendedClass($this->baseModelParent); foreach ($this->baseModelUses as $use) { $class->addUse($use); } $this->addEventsMethods($class); foreach ($dataSet->listFields() as $name) { $column = $dataSet->getFieldDescriptor($name); $this->generateColumnRelatedElements($class, $column); } $file = new FileGenerator(); $docBlock = new \Zend\Code\Generator\DocblockGenerator(sprintf($this->codeLibrary()->get('model.generatedConfigDescription'), $name)); $docBlock->setTag(new GenericTag('author', $this->params->getParam('author')))->setTag(new GenericTag('project', $this->params->getParam('project')))->setTag(new GenericTag('license', $this->params->getParam('license')))->setTag(new GenericTag('copyright', $this->params->getParam('copyright'))); $class->setDocBlock($docBlock); $file->setClass($class); $modelClassFilePath = $this->moduleRoot() . "/src/" . $this->params->getParam("moduleName") . "/Model/BaseModel/" . $className . ".php"; file_put_contents($modelClassFilePath, $file->generate()); return $fullClassName; }