/** * ClassDiff constructor. * * @param string $currentFilePath * @param string $currentClassName * @param ClassGenerator $newClassGenerator */ public function __construct($currentFilePath, $currentClassName, ClassGenerator $newClassGenerator) { $this->currentFilePath = $currentFilePath; $this->currentClassName = $currentClassName; $this->currentClassCode = file_get_contents($currentFilePath); $this->currentClassGenerator = $this->getGeneratorFromReflection(new ClassReflection($currentClassName)); $this->newClassGenerator = $newClassGenerator; /* * PHP Reflections don't take into account use statements, so an entire * plugin is needed just for that. //shakes head */ $parser = new Parser(new Lexer()); $nodes = $parser->parse($this->currentClassCode); foreach ($nodes as $node) { /** @var $node Namespace_ */ if (get_class($node) == 'PhpParser\\Node\\Stmt\\Namespace_') { /** @var Use_ $stmt */ foreach ($node->stmts as $stmt) { if (get_class($stmt) == 'PhpParser\\Node\\Stmt\\Use_') { /** @var UseUse $use */ foreach ($stmt->uses as $use) { $this->currentClassGenerator->addUse($use->name->toString()); } } } } } if (in_array($this->currentClassGenerator->getExtendedClass(), $this->currentClassGenerator->getUses())) { $extended = new \ReflectionClass($this->currentClassGenerator->getExtendedClass()); $this->currentClassGenerator->setExtendedClass($extended->getShortName()); } }
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(); }
/** * Build generators * * @param State|\Scaffold\State $state * @return \Scaffold\State|void */ public function build(State $state) { $model = $state->getRepositoryModel(); $generator = new ClassGenerator($model->getName()); $generator->addUse('Doctrine\\ORM\\EntityRepository'); $generator->addUse($state->getEntityModel()->getName()); $generator->setExtendedClass('EntityRepository'); $this->buildFactory($generator); $model->setGenerator($generator); }
/** * generate * * @param string $className * @param null $namespace * * @return ClassGenerator */ protected function generate($className, $namespace = null) { $exceptionClass = MigrationException::class; $class = new ClassGenerator($className, $namespace, null, 'AbstractMigration', [], [], [new MethodGenerator('up', [], 'public', "throw new \\{$exceptionClass}(\"Not implemented.\");", new DocBlockGenerator('Executed when migrating upwards.', 'TODO: replace body.')), new MethodGenerator('down', [], 'public', "throw new \\{$exceptionClass}(\"Not implemented.\");", new DocBlockGenerator('Executed when migrating downwards.', 'TODO: replace body.'))], new DocBlockGenerator("Migration {$className}")); $class->addUse(AbstractMigration::class); return $class; }
public function getClass() { $classGenerator = new ClassGenerator($this->collection, $this->namespace); $classGenerator->addUse('ArangoOdm\\Document', 'ArangoDoc'); $classGenerator->setExtendedClass('ArangoDoc'); $classGenerator->addMethods($this->getMethods()); return '<?php' . "\n\n" . $classGenerator->generate(); }
public function generate(Generator\ClassGenerator $class, PHPClass $type) { if (!($extends = $type->getExtends()) && class_exists($type->getNamespace())) { $extendNamespace = $type->getNamespace(); $extendNamespace = explode('\\', $extendNamespace); $extendClass = array_pop($extendNamespace); $extendNamespace = implode('\\', $extendNamespace); $extends = new PHPClass(); $extends->setName($extendClass); $extends->setNamespace($extendNamespace); $class->setExtendedClass($extends); } if ($extends->getName() == "string" && $extends->getNamespace() == "" && class_exists($type->getNamespace() . '\\String')) { $extends->setName('String'); $extends->setNamespace($type->getNamespace()); } elseif ($extends->getName() == "string" && $extends->getNamespace() == "" && class_exists($type->getNamespace())) { $extendNamespace = $type->getNamespace(); $extendNamespace = explode('\\', $extendNamespace); $extendClass = array_pop($extendNamespace); $extendNamespace = implode('\\', $extendNamespace); $extends = new PHPClass(); $extends->setName($extendClass); $extends->setNamespace($extendNamespace); $class->setExtendedClass($extends); } $docblock = new DocBlockGenerator("Class representing " . $type->getName()); if ($type->getDoc()) { $docblock->setLongDescription($type->getDoc()); } $class->setNamespaceName($type->getNamespace()); $class->setName($type->getName()); $class->setDocblock($docblock); $class->setExtendedClass($extends->getName()); if ($extends->getNamespace() != $type->getNamespace()) { if ($extends->getName() == $type->getName()) { $class->addUse($type->getExtends()->getFullName(), $extends->getName() . "Base"); $class->setExtendedClass($extends->getName() . "Base"); } else { $class->addUse($extends->getFullName()); } } if ($this->handleBody($class, $type)) { return true; } }
/** * @param $name * @param $namespace * @param $uses * @param string $extends * @param array $implements * * @return ClassGenerator */ public static function classGen($name, $namespace, $uses = [], $extends = '', $implements = []) { $class = new ClassGenerator(); $class->setName($name)->setNamespaceName($namespace)->setExtendedClass($extends)->setImplementedInterfaces($implements)->setIndentation(Generator::$indentation); foreach ($uses as $use) { $class->addUse($use); } return $class; }
/** * Build generators * * @param State|\Scaffold\State $state * @return \Scaffold\State|void */ public function build(State $state) { $model = $this->model; $generator = new ClassGenerator($model->getName()); $generator->addUse('Zend\\ServiceManager\\FactoryInterface'); $generator->addUse('Zend\\ServiceManager\\ServiceLocatorInterface'); $generator->addUse('Zend\\ServiceManager\\ServiceManager'); $generator->addUse($state->getServiceModel()->getName()); $generator->setImplementedInterfaces(['FactoryInterface']); $method = new MethodGenerator('createService'); $method->setParameter(new ParameterGenerator('serviceLocator', 'ServiceLocatorInterface')); $method->setBody('return new ' . $state->getServiceModel()->getClassName() . '($serviceLocator);'); $doc = new DocBlockGenerator('Create service'); $doc->setTag(new Tag\GenericTag('param', 'ServiceLocatorInterface|ServiceManager $serviceLocator')); $doc->setTag(new Tag\GenericTag('return', $state->getServiceModel()->getClassName())); $method->setDocBlock($doc); $generator->addMethodFromGenerator($method); $model->setGenerator($generator); }
/** * Build generators * * @param State $state * @return void */ public function build(State $state) { $model = $state->getFormFactoryModel(); $generator = new ClassGenerator($model->getName()); $generator->setImplementedInterfaces(['FactoryInterface']); $generator->addUse('Doctrine\\ORM\\EntityManager'); $generator->addUse('DoctrineModule\\Stdlib\\Hydrator\\DoctrineObject'); $generator->addUse('Zend\\ServiceManager\\FactoryInterface'); $generator->addUse('Zend\\ServiceManager\\ServiceLocatorInterface'); $generator->addUse('Zend\\Form\\Form'); $generator->addUse('Zend\\Form\\Element'); $generator->addUse('Zend\\InputFilter\\Factory'); $generator->addUse('Zend\\InputFilter\\InputFilterInterface'); $this->buildCreateService($generator, $state); $this->buildGetInputFilter($generator, $state); $model->setGenerator($generator); }
/** * @group 4990 */ public function testAddOneUseWithAliasTwiceOnlyAddsOne() { $classGenerator = new ClassGenerator(); $classGenerator->setName('My\\Class'); $classGenerator->addUse('My\\First\\Use\\Class', 'MyAlias'); $classGenerator->addUse('My\\First\\Use\\Class', 'MyAlias'); $generated = $classGenerator->generate(); $this->assertCount(1, $classGenerator->getUses()); $this->assertContains('use My\\First\\Use\\Class as MyAlias;', $generated); }
/** * Create view helper factory * * @return bool */ public function createViewHelperFactory() { // get needed options to shorten code $moduleName = $this->requestOptions->getModuleName(); $viewHelperClass = $this->requestOptions->getViewHelperClass(); $viewHelperPath = $this->requestOptions->getViewHelperPath(); $factoryClass = $viewHelperClass . 'Factory'; $factoryFile = $factoryClass . '.php'; $factoryFilePath = $viewHelperPath . $factoryFile; // check for factory class if (file_exists($factoryFilePath)) { throw new GeneratorException('The factory for this view helper exists already.'); } // create controller class with class generator $code = new ClassGenerator(); $code->setNamespaceName($moduleName . '\\View\\Helper'); $code->addUse('Zend\\ServiceManager\\FactoryInterface'); $code->addUse('Zend\\ServiceManager\\ServiceLocatorInterface'); $code->setName($factoryClass); $code->setImplementedInterfaces(array('FactoryInterface')); $code->addMethodFromGenerator($this->generateCreateServiceMethod($viewHelperClass, 'viewHelperManager', 'viewHelper')); // add optional doc block if ($this->flagCreateApiDocs) { $code->setDocBlock(new DocBlockGenerator('Factory for ' . $viewHelperClass, 'Please add a proper description for the ' . $viewHelperClass . ' factory', array($this->generatePackageTag($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()))); } // write controller class if (!file_put_contents($factoryFilePath, $file->generate())) { return false; } return true; }
/** * Method for add USE for new form * For add more USE - add more ->addUse('namespace') */ private function addUseForNewFilter() { $this->newFilter->addUse('InepZend\\Filter\\Filter')->addUse($this->getStrModuleName() . '\\Message\\Message'); }
protected function createRealCommandQuery($commandPath, $name, $moduleName) { $this->directoryService->makeSureDirExist($commandPath); $this->directoryService->createAllNamespacedDir($name, $commandPath); $nameParts = explode('/', trim($name, '/')); $className = sprintf('%s%s', $nameParts[count($nameParts) - 1], $this->getSuffixClass()); $handlerName = sprintf('%s%s', $className, 'Handler'); $handlerFactoryName = sprintf('%s%s', $handlerName, 'Factory'); unset($nameParts[count($nameParts) - 1]); //Set namespace for generated files $namespace = sprintf('%s\\%s\\%s', $moduleName, $this->getDirectory(), implode('\\', $nameParts)); $classGenerator = new ClassGenerator(); $classGenerator->setNamespaceName(trim($namespace, '\\')); $handlerGenerator = new ClassGenerator(); $handlerGenerator->setNamespaceName(trim($namespace, '\\')); $handlerFactoryGenerator = new ClassGenerator(); $handlerFactoryGenerator->setNamespaceName(trim($namespace, '\\')); //Set basic properties for command $commandQueryInterfaceToImplement = $this->getCommandQueryInterfaceToImplement(); $classGenerator->setName($className); // $classGenerator->addUse($commandQueryInterfaceToImplement); $tmpRef = new \ReflectionClass($commandQueryInterfaceToImplement); $classGenerator->setImplementedInterfaces([$tmpRef->getName()]); $this->addMethodsFromInterface($commandQueryInterfaceToImplement, $classGenerator); //Set basic properties for command handler $commandHandlerClassToImplement = $this->getAbstractHandlerClassName(); $tmpRef = new \ReflectionClass($commandHandlerClassToImplement); $handlerGenerator->setName($handlerName); $handlerGenerator->setExtendedClass($tmpRef->getName()); $this->addMethodsFromAbstractClass($commandHandlerClassToImplement, $handlerGenerator); //Set basic properties for command handler factory $commandHandlerFactoryClassToImplement = FactoryInterface::class; $handlerFactoryGenerator->setName($handlerFactoryName); $handlerFactoryGenerator->addUse($commandHandlerFactoryClassToImplement); $handlerFactoryGenerator->setImplementedInterfaces([FactoryInterface::class]); $this->addMethodsFromInterface($commandHandlerFactoryClassToImplement, $handlerFactoryGenerator); // $method = $handlerFactoryGenerator->getMethod('__invoke'); //// $method->setParameters() // $method->setBody(sprintf('return new %s();', $handlerGenerator->getName())); //GENERATE IT !!! $fileGenerator = FileGenerator::fromArray(['classes' => [$classGenerator]]); file_put_contents(sprintf('%s%s%s%s%s%s', $commandPath, DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, $nameParts), DIRECTORY_SEPARATOR, $className, '.php'), $fileGenerator->generate()); $fileGenerator = FileGenerator::fromArray(['classes' => [$handlerGenerator]]); file_put_contents(sprintf('%s%s%s%s%s%s', $commandPath, DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, $nameParts), DIRECTORY_SEPARATOR, $handlerName, '.php'), $fileGenerator->generate()); $fileGenerator = FileGenerator::fromArray(['classes' => [$handlerFactoryGenerator]]); file_put_contents(sprintf('%s%s%s%s%s%s', $commandPath, DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, $nameParts), DIRECTORY_SEPARATOR, $handlerFactoryName, '.php'), $fileGenerator->generate()); return [sprintf('%s\\%s', $classGenerator->getNamespaceName(), $classGenerator->getName()), sprintf('%s\\%s', $handlerGenerator->getNamespaceName(), $handlerGenerator->getName()), sprintf('%s\\%s', $handlerFactoryGenerator->getNamespaceName(), $handlerFactoryGenerator->getName())]; }
require __DIR__ . "/../vendor/autoload.php"; $name = "Client"; $namespace = "CallFire\\Api"; $restNamespace = "Rest"; $extendedClass = "AbstractClient"; $swaggerUrl = 'https://www.callfire.com/api/1.1/wsdl/swagger'; $requestNamespacePart = RestGenerator::REQUEST_NAMESPACE_ALIAS; $requestNamespace = "{$namespace}\\Rest\\{$requestNamespacePart}"; $responseNamespacePart = RestGenerator::RESPONSE_NAMESPACE_ALIAS; $responseNamespace = "{$namespace}\\Rest\\{$responseNamespacePart}"; $structureNamespacePart = RestGenerator::STRUCTURE_NAMESPACE_ALIAS; $structureNamespace = "{$namespace}\\Rest\\{$structureNamespacePart}"; $sourceDirectory = realpath(__DIR__ . "/../src") . '/' . str_replace('\\', '/', $namespace); $generator = new RestGenerator($swaggerUrl); $classGenerator = new ClassGenerator($name, "{$namespace}\\{$restNamespace}\\Client", null, $extendedClass); $classGenerator->addUse("{$namespace}\\{$restNamespace}\\{$extendedClass}"); $generator->setClassGenerator($classGenerator); $generator->generateClasses($requestNamespace, $responseNamespace, $structureNamespace); $classFiles = $generator->generateClassFiles(); $requestClassFiles = $generator->generateRequestClassFiles(); if (!is_dir($sourceDirectory)) { mkdir($sourceDirectory, 0777, true); } if (!is_dir("{$sourceDirectory}/{$restNamespace}")) { mkdir("{$sourceDirectory}/{$restNamespace}", 0777, true); } if (!is_dir("{$sourceDirectory}/{$restNamespace}/Client")) { mkdir("{$sourceDirectory}/{$restNamespace}/Client", 0777, true); } if (!is_dir("{$sourceDirectory}/{$restNamespace}/Request")) { mkdir("{$sourceDirectory}/{$restNamespace}/Request", 0777, true);
/** * generates code for base grid and saves in file (overrides file if exists) * * @param DataSetDescriptorInterface $dataSet * @return string full name of generated class */ protected function generateBaseGrid(DataSetDescriptorInterface $dataSet) { $name = $dataSet->getName(); $className = "Base" . $this->underscoreToCamelCase->filter($name) . "Grid"; $namespace = $this->params->getParam("moduleName") . "\\Grid\\BaseGrid"; $fullClassName = '\\' . $namespace . '\\' . $className; $class = new ClassGenerator(); $class->setName($className); $class->setNamespaceName($namespace); $class->setExtendedClass($this->baseGridParent); foreach ($this->baseGridUses as $use) { $class->addUse($use); } $this->generateConfigProperty($class); $this->generateHeaderProperty($class, $dataSet); $this->generateInitMehod($class, $dataSet); $this->generateInitFiltersMehod($class, $dataSet); $file = new FileGenerator(); $docBlock = new \Zend\Code\Generator\DocblockGenerator(sprintf($this->codeLibrary()->get('filter.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'))); $file->setClass($class)->setDocBlock($docBlock); $modelClassFilePath = $this->moduleRoot() . "/src/" . $this->params->getParam("moduleName") . "/Grid/BaseGrid/" . $className . ".php"; file_put_contents($modelClassFilePath, $file->generate()); return $fullClassName; }
private function addCacheAnnotation(ClassGenerator $classGenerator) { $uses = $classGenerator->getUses(); if (!in_array(Cache::class, $uses)) { $classGenerator->addUse(Cache::class); } }
/** * 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; }
/** * Append methods to Api class * * @param Generator\ClassGenerator $class * @param string $operation * @param mixed $apiMetadata * @param FileGenerator $demoFile */ protected function generateApiOperationFromMetadata(Generator\ClassGenerator &$class, $httpMethod, $apiMetadata) { $console = $this->getServiceLocator()->get('console'); $modelClassName = 'Mailjet\\Model\\' . $class->getName(); $model = $class->getName(); $class->addUse('Zend\\Json\\Json')->addUse('Zend\\InputFilter'); $httpMethod = strtoupper($httpMethod); switch ($httpMethod) { case 'GET': if ($apiMetadata->Filters) { $class->addMethods(array(new Generator\MethodGenerator('getList', array(new Generator\ParameterGenerator('filters', 'array', array())), Generator\MethodGenerator::FLAG_PUBLIC, 'return parent::_list($filters);', new Generator\DocBlockGenerator("Return list of {$modelClassName}", "Return list of {$modelClassName} filtered by \$filters if provided" . PHP_EOL, array(new ParamTag(array('name' => 'filters', 'datatype' => 'array', 'description' => 'key/val filters')), new ReturnTag(array('datatype' => 'ResultSet\\ResultSet', 'description' => "List of {$modelClassName}"))))))); foreach ($apiMetadata->Filters as $filterInfo) { try { $filterName = $filterInfo->Name; $dataTypeInfos = $this->getNormalizedFilterOrProperty($filterInfo); $dataType = $dataTypeInfos['dataType']; foreach ($dataTypeInfos['uses'] as $use) { $class->addUse($use); } $isKey = $filterName == $apiMetadata->UniqueKey; if ($isKey) { $bodyMethod = sprintf('return $this->_get($%s);' . PHP_EOL, $filterName); } else { $bodyMethod = sprintf('$result = $this->getList(array(\'%s\' => $%s));' . PHP_EOL . 'return $result;', $filterName, $filterName); } $class->addMethods(array(new Generator\MethodGenerator('getBy' . $filterName, array(new Generator\ParameterGenerator($filterName, $dataType)), Generator\MethodGenerator::FLAG_PUBLIC, $bodyMethod, new Generator\DocBlockGenerator($isKey ? "Return {$modelClassName}" : "Return list of {$modelClassName} with {$filterName} = \${$filterName}", '', array(new ParamTag(array('name' => $filterName, 'datatype' => $dataType)), new ReturnTag(array('datatype' => $isKey ? $modelClassName : 'ResultSet\\ResultSet'))))))); } catch (\Exception $e) { $console->writeLine('[' . $class->getName() . ']' . $e->getMessage(), Color::YELLOW); } } $param = new Generator\ParameterGenerator('id', 'int'); $class->addMethods(array(new Generator\MethodGenerator('get', array($param), Generator\MethodGenerator::FLAG_PUBLIC, 'if (empty($id)) {' . PHP_EOL . ' throw new Exception\\InvalidArgumentException("You must specify the ID");' . PHP_EOL . '}' . PHP_EOL . PHP_EOL . 'return parent::_get($id);', new Generator\DocBlockGenerator("Return {$modelClassName} with id = \$id", '', array(new ParamTag(array('name' => 'id', 'datatype' => 'int', 'description' => 'Id of resource to get')), new ReturnTag(array('datatype' => $modelClassName))))))); } else { $class->addMethods(array(new Generator\MethodGenerator('current', array(), Generator\MethodGenerator::FLAG_PUBLIC, 'return parent::_get();', new Generator\DocBlockGenerator("Return current {$modelClassName}", '', array(new ReturnTag(array('datatype' => $modelClassName))))))); } break; case 'DELETE': $class->addMethods(array(new Generator\MethodGenerator('delete', array(new Generator\ParameterGenerator('id')), Generator\MethodGenerator::FLAG_PUBLIC, 'return parent::_delete($id);', new Generator\DocBlockGenerator("Delete the {$model} with id = \$id", '', array(new ParamTag(array('name' => 'id', 'datatype' => 'integer', 'description' => 'Id to delete')), new ReturnTag(array('datatype' => 'bool', 'description' => 'True on success'))))))); break; case 'POST': $modelParameter = new Generator\ParameterGenerator($model, $modelClassName); $modelParameter->setPassedByReference(true); $class->addMethods(array(new Generator\MethodGenerator('create', array($modelParameter), Generator\MethodGenerator::FLAG_PUBLIC, "return parent::_create(\${$model});", new Generator\DocBlockGenerator("Create a new {$model}", '', array(new ParamTag(array('name' => $model, 'datatype' => $modelClassName)), new ReturnTag(array('datatype' => "{$modelClassName}|false", 'description' => 'Object created or false'))))))); break; case 'PUT': $modelParameter = new Generator\ParameterGenerator($model, $modelClassName); $modelParameter->setPassedByReference(true); $class->addMethods(array(new Generator\MethodGenerator('update', array($modelParameter), Generator\MethodGenerator::FLAG_PUBLIC, "return parent::_update(\${$model});", new Generator\DocBlockGenerator("Update existing {$model}", '', array(new ParamTag(array('name' => $model, 'datatype' => $modelClassName)), new ReturnTag(array('datatype' => "{$modelClassName}|false", 'description' => 'Object created or false'))))))); break; default: break; } }
/** * @param Tag $tagItem * @return ClassGenerator */ protected function createClass(Tag $tagItem) { $className = ucfirst($this->stringToCamelCaseConverter->convert($tagItem->getName())); $class = new ClassGenerator(); $class->setNamespaceName('Flex\\Code\\Html\\Tag'); $class->setName($className); $class->addUse('Flex\\Code\\Html\\Tag\\Model\\AbstractTag'); $class->setExtendedClass('AbstractTag'); $implementedInterfaces = []; if ($tagItem->isGlobalAttributeAware()) { $implementedInterfaces[] = 'GlobalAttributeAwareInterface'; $class->addUse('Flex\\Code\\Html\\Tag\\Attribute\\GlobalAttributeAwareInterface'); $class->addUse('Flex\\Code\\Html\\Tag\\Attribute\\GlobalAttributeAwareTrait'); $class->addTrait('GlobalAttributeAwareTrait'); } if ($tagItem->isClipboardEventAware()) { $implementedInterfaces[] = 'ClipboardEventAwareInterface'; $class->addUse('Flex\\Code\\Html\\Tag\\Event\\ClipboardEventAwareInterface'); $class->addUse('Flex\\Code\\Html\\Tag\\Event\\ClipboardEventAwareTrait'); $class->addTrait('ClipboardEventAwareTrait'); } if ($tagItem->isFormEventAware()) { $implementedInterfaces[] = 'FormEventAwareInterface'; $class->addUse('Flex\\Code\\Html\\Tag\\Event\\FormEventAwareInterface'); $class->addUse('Flex\\Code\\Html\\Tag\\Event\\FormEventAwareTrait'); $class->addTrait('FormEventAwareTrait'); } if ($tagItem->isKeyboardEventAware()) { $implementedInterfaces[] = 'KeyboardEventAwareInterface'; $class->addUse('Flex\\Code\\Html\\Tag\\Event\\KeyboardEventAwareInterface'); $class->addUse('Flex\\Code\\Html\\Tag\\Event\\KeyboardEventAwareTrait'); $class->addTrait('KeyboardEventAwareTrait'); } if ($tagItem->isMediaEventAware()) { $implementedInterfaces[] = 'MediaEventAwareInterface'; $class->addUse('Flex\\Code\\Html\\Tag\\Event\\MediaEventAwareInterface'); $class->addUse('Flex\\Code\\Html\\Tag\\Event\\MediaEventAwareTrait'); $class->addTrait('MediaEventAwareTrait'); } if ($tagItem->isMiscEventAware()) { $implementedInterfaces[] = 'MiscEventAwareInterface'; $class->addUse('Flex\\Code\\Html\\Tag\\Event\\MiscEventAwareInterface'); $class->addUse('Flex\\Code\\Html\\Tag\\Event\\MiscEventAwareTrait'); $class->addTrait('MiscEventAwareTrait'); } if ($tagItem->isMouseEventAware()) { $implementedInterfaces[] = 'MouseEventAwareInterface'; $class->addUse('Flex\\Code\\Html\\Tag\\Event\\MouseEventAwareInterface'); $class->addUse('Flex\\Code\\Html\\Tag\\Event\\MouseEventAwareTrait'); $class->addTrait('MouseEventAwareTrait'); } if ($tagItem->isWindowEventAware()) { $implementedInterfaces[] = 'WindowEventAwareInterface'; $class->addUse('Flex\\Code\\Html\\Tag\\Event\\WindowEventAwareInterface'); $class->addUse('Flex\\Code\\Html\\Tag\\Event\\WindowEventAwareTrait'); $class->addTrait('WindowEventAwareTrait'); } $class->setImplementedInterfaces($implementedInterfaces); $docBlock = new DocBlockGenerator(); $docBlock->setTag(new GenericTag('author', 'elnebuloso/flex-code-html-generator')); $docBlock->setTag(new GenericTag('link', $tagItem->getLink())); if (!is_null($tagItem->getShortDescription())) { $docBlock->setShortDescription($tagItem->getShortDescription()); } if (!is_null($tagItem->getLongDescription())) { $docBlock->setLongDescription($tagItem->getLongDescription()); } $class->setDocBlock($docBlock); return $class; }
/** * @param string $sourceFile * @return string */ protected function generateClass($sourceFile) { $sourceContent = json_decode(file_get_contents($sourceFile)); $class = new ClassGenerator(); $className = null; $mappingClasses = array(); $propNameMap = $this->setPropNameMap($sourceContent); $isCollection = false; foreach ($sourceContent as $property => $value) { $ourPropertyName = array_search($property, $propNameMap); if ($ourPropertyName) { $property = $ourPropertyName; } if ($property === '@name') { //Class name $className = $value; if ($this->namespace) { $class->setNamespaceName($this->namespace); } $class->setName($value); } elseif ($property === '@type') { continue; } elseif ($value === 'number' || $value === 'int' || $value === 'integer') { //Create property type number $class->addProperty($property, null, PropertyGenerator::FLAG_PROTECTED); $class->addMethods(array(MethodGenerator::fromArray($this->generateGetMethod($property, 'int')), MethodGenerator::fromArray($this->generateSetMethod($property, 'int')))); } elseif ($value === 'float' || $value === 'double' || $value === 'real') { //Create property type number $class->addProperty($property, null, PropertyGenerator::FLAG_PROTECTED); $class->addMethods(array(MethodGenerator::fromArray($this->generateGetMethod($property, $value)), MethodGenerator::fromArray($this->generateSetMethod($property, $value)))); } elseif ($value === 'string') { //Create property type string $class->addProperty($property, null, PropertyGenerator::FLAG_PROTECTED); $class->addMethods(array(MethodGenerator::fromArray($this->generateGetMethod($property, $value)), MethodGenerator::fromArray($this->generateSetMethod($property, $value)))); } elseif ($value === 'date') { //Create property type date $class->addProperty($property, null, PropertyGenerator::FLAG_PROTECTED); $class->addMethods(array(MethodGenerator::fromArray($this->generateGetMethod($property, 'string')), MethodGenerator::fromArray($this->generateSetMethod($property, 'string')))); } elseif ($value === 'array') { //Create property type date $class->addProperty($property, null, PropertyGenerator::FLAG_PROTECTED); $class->addMethods(array(MethodGenerator::fromArray($this->generateGetMethod($property, 'array')), MethodGenerator::fromArray($this->generateSetMethod($property, 'array')))); } elseif ($value === 'boolean' || $value === 'bool') { //Create property type boolean $class->addProperty($property, null, PropertyGenerator::FLAG_PROTECTED); $class->addMethods(array(MethodGenerator::fromArray($this->generateGetMethod($property, $value)), MethodGenerator::fromArray($this->generateSetMethod($property, $value)))); } elseif ($property === "@model") { if ($this->namespace) { $class->addUse($this->namespace . '\\' . ucfirst($value)); } } elseif ($property === "@collection") { $isCollection = true; $class->addProperty('collection', array(), PropertyGenerator::FLAG_PROTECTED); $class->addMethods($this->getMethodsForCollection($value->model)); } elseif ($property === "@parent") { //"@parent": "\\Classes\\Items", $class->setExtendedClass($value); } elseif (strpos($value, '@') === 0) { if ($className !== ucfirst(substr($value, 1))) { if ($this->namespace) { $class->addUse($this->namespace . '\\' . ucfirst(substr($value, 1))); } } if ($this->namespace) { $mappingClasses[$property] = $this->namespace . '\\' . ucfirst(substr($value, 1)); } else { $mappingClasses[$property] = ucfirst(substr($value, 1)); } //Create property type Class $class->addProperty($property, null, PropertyGenerator::FLAG_PROTECTED); $class->addMethods(array(MethodGenerator::fromArray($this->generateGetMethod($property, ucfirst(substr($value, 1)))), MethodGenerator::fromArray($this->generateSetMethod($property, ucfirst(substr($value, 1)))))); } else { var_dump($value, $property); exit; } } if ($isCollection === true) { if ($this->rootClassNameForCollection) { $class->setExtendedClass($this->rootClassNameForCollection); $class->addUse($this->rootClassForCollectionNamespace); } } else { if ($this->rootClassName) { $class->setExtendedClass($this->rootClassName); $class->addUse($this->rootClassNamespace); } } $class->addProperty($this->mappingClassesPropertyName, $mappingClasses, PropertyGenerator::FLAG_PROTECTED); $class->addProperty($this->mappingPropertyName, $propNameMap, PropertyGenerator::FLAG_PROTECTED); $file = new FileGenerator(array('classes' => array($class))); $code = $file->generate(); $path = realpath($this->destinationDir) . '/' . ucfirst($className) . '.php'; $code = str_replace("\n\n}\n", '}', $code); file_put_contents($path, $code); return $path; }
/** * @group ZF2-151 */ public function testAddUses() { $classGenerator = new ClassGenerator(); $classGenerator->setName('My\Class'); $classGenerator->addUse('My\First\Use\Class'); $classGenerator->addUse('My\Second\Use\Class', 'MyAlias'); $generated = $classGenerator->generate(); $this->assertContains('use My\First\Use\Class;', $generated); $this->assertContains('use My\Second\Use\Class as MyAlias;', $generated); }
/** * @param string $className * @param string $namespace * * @return ClassGenerator * * @throws CliException */ protected function generate($className, $namespace = null) { $class = new ClassGenerator($className, $namespace, null, 'SimpleMigration', [], [], [new MethodGenerator('up', [], 'public', null, new DocBlockGenerator('Executed when migrating upwards.', 'TODO: implement')), new MethodGenerator('down', [], 'public', null, new DocBlockGenerator('Executed when migrating downwards / rolling back.', 'TODO: implement'))], new DocBlockGenerator($className . ' class', null, [new GenericTag('link', 'http://baleen.org')])); $class->addUse(SimpleMigration::class); return $class; }