setName() 공개 메소드

public setName ( string $name ) : self
$name string
리턴 self
 /**
  * Method for generate a new Filter
  * @param array $arrInfosFilter
  */
 public function createNewFilter(array $arrInfosFilter = array())
 {
     $this->init($arrInfosFilter);
     $this->newFilter->setName($this->getStrFilterNameWithPrefix())->setNamespaceName($this->getStrFilterNamespace())->setExtendedClass('Filter')->setDocBlock($this->getDocBlockFilter());
     $this->addMethodsForNewFilter();
     $this->addUseForNewFilter();
     $this->generateNewFilter();
 }
예제 #2
0
 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();
 }
 private function updateModuleConfig()
 {
     $dir = getcwd() . '/module/' . ucfirst($this->db) . '/config/';
     $filename = $dir . 'module.config.php';
     $moduleConfigArray = (include $filename);
     $keyCtrl = $this->getModuleName() . '\\' . $this->subDir . '\\' . $this->getClassName();
     if (!array_key_exists($keyCtrl, $moduleConfigArray['controllers']['invokables'])) {
         $moduleConfigArray['controllers']['invokables'][$keyCtrl] = $this->getModuleName() . '\\' . $this->subDir . '\\' . $this->getClassName();
     }
     $keyRoute = $this->tableName;
     if (!array_key_exists($keyRoute, $moduleConfigArray['router']['routes'])) {
         $moduleConfigArray['router']['routes'][$keyRoute] = array('type' => 'segment', 'options' => array('route' => '/' . $keyRoute . '[/:id]', 'defaults' => array('controller' => $keyCtrl)));
     }
     $newContent = '<? return ' . var_export($moduleConfigArray, true) . ';';
     // dir doesn't exist, make it
     if (!is_dir($dir)) {
         mkdir($dir);
         // ** Generate Module.php class ** //
         // Definitions
         $classGenerator = new ClassGenerator();
         $classGenerator->setName('Module');
         $classGenerator->setNamespaceName(ucfirst($this->db));
         // Methods
         $classGenerator->addMethods(array(new MethodGenerator('getConfig', [], MethodGenerator::FLAG_PUBLIC, "return include __DIR__ . '/config/module.config.php';"), new MethodGenerator('getAutoloaderConfig', [], MethodGenerator::FLAG_PUBLIC, "return array(\r                            'Zend\\Loader\\StandardAutoloader' => array(\r                                'namespaces' => array(\r                                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,\r                                ),\r                            ),\r                        );")));
         $this->fileCreate(getcwd() . '/module/' . ucfirst($this->db) . '/Module.php', $classGenerator);
         // ** Generate Module.php class ** //
     }
     file_put_contents($filename, $newContent);
 }
예제 #4
0
 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();
 }
 private function generate($version)
 {
     $generator = new ClassGenerator();
     $docblock = DocBlockGenerator::fromArray(array('shortDescription' => 'PDO Simple Migration Class', 'longDescription' => 'Add your queries below'));
     $generator->setName('PDOSimpleMigration\\Migrations\\Migration' . $version)->setExtendedClass('AbstractMigration')->addUse('PDOSimpleMigration\\Library\\AbstractMigration')->setDocblock($docblock)->addProperties(array(array('description', 'Migration description', PropertyGenerator::FLAG_STATIC)))->addMethods(array(MethodGenerator::fromArray(array('name' => 'up', 'parameters' => array(), 'body' => '//$this->addSql(/*Sql instruction*/);', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Migrate up', 'longDescription' => null)))), MethodGenerator::fromArray(array('name' => 'down', 'parameters' => array(), 'body' => '//$this->addSql(/*Sql instruction*/);', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Migrate down', 'longDescription' => null))))));
     $file = FileGenerator::fromArray(array('classes' => array($generator)));
     return $file->generate();
 }
예제 #6
0
 private function generateAutoLoaderClass()
 {
     $class = new ClassGenerator();
     $class->setName('AutoLoader');
     $class->setFinal(true);
     $class->setExtendedClass('BaseAutoLoader');
     $class->addProperties([$this->generatePSR4MapProp(), $this->generatePSR0MapProp(), $this->generateClassMapProp(), $this->generateFileIncludesProp(), $this->generateProxiesMapProp()]);
     return $class->generate();
 }
예제 #7
0
파일: ClassGen.php 프로젝트: shinichi81/sdk
 /**
  * @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;
 }
예제 #8
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $ymlParser = new Parser();
     $config = $ymlParser->parse(file_get_contents($input->getOption('config')));
     $path = $config['path'];
     $name = $input->getArgument('name');
     $classGen = new ClassGenerator();
     $content = $classGen->setName($name)->addMethod('getUpSql', array(), MethodGenerator::FLAG_PUBLIC, 'return \'\';')->addMethod('getDownSql', array(), MethodGenerator::FLAG_PUBLIC, 'return \'\';')->addMethod('preUp')->addMethod('postUp')->addMethod('preDown')->addMethod('postDown')->generate();
     file_put_contents(sprintf('%s/%s_%s.php', $path, date('YmdHis'), $name), sprintf("<?php\n%s", $content));
 }
 /**
  * Dynamically scope an audit class
  */
 public function loadClass($auditClassName, $type)
 {
     $foundClassName = false;
     foreach ($this->getAuditEntities() as $className => $classOptions) {
         if ($this->getAuditObjectManager()->getRepository('ZF\\Doctrine\\Audit\\Entity\\AuditEntity')->generateClassName($className) == $auditClassName) {
             $foundClassName = true;
             break;
         }
     }
     if (!$foundClassName) {
         return false;
     }
     // Get fields from target entity
     $metadataFactory = $this->getObjectManager()->getMetadataFactory();
     $auditedClassMetadata = $metadataFactory->getMetadataFor($className);
     $fields = $auditedClassMetadata->getFieldNames();
     $identifiers = $auditedClassMetadata->getFieldNames();
     $auditClass = new ClassGenerator();
     $auditClass->setNamespaceName("ZF\\Doctrine\\Audit\\RevisionEntity");
     $auditClass->setName(str_replace('\\', '_', $className));
     $auditClass->setExtendedClass('AbstractAudit');
     // Add revision reference getter and setter
     $auditClass->addProperty('revisionEntity', null, PropertyGenerator::FLAG_PROTECTED);
     $auditClass->addMethod('getRevisionEntity', array(), MethodGenerator::FLAG_PUBLIC, " return \$this->revisionEntity;");
     $auditClass->addMethod('setRevisionEntity', array('value'), MethodGenerator::FLAG_PUBLIC, " \$this->revisionEntity = \$value;\n\nreturn \$this;\n            ");
     // Generate audit entity
     foreach ($fields as $field) {
         $auditClass->addProperty($field, null, PropertyGenerator::FLAG_PROTECTED);
     }
     foreach ($auditedClassMetadata->getAssociationNames() as $associationName) {
         $auditClass->addProperty($associationName, null, PropertyGenerator::FLAG_PROTECTED);
         $fields[] = $associationName;
     }
     $auditClass->addMethod('getAssociationMappings', array(), MethodGenerator::FLAG_PUBLIC, "return unserialize('" . serialize($auditedClassMetadata->getAssociationMappings()) . "');");
     // Add exchange array method
     $setters = array();
     foreach ($fields as $fieldName) {
         $setters[] = '$this->' . $fieldName . ' = (isset($data["' . $fieldName . '"])) ? $data["' . $fieldName . '"]: null;';
         $arrayCopy[] = "    \"{$fieldName}\"" . ' => $this->' . $fieldName;
     }
     $auditClass->addMethod('getArrayCopy', array(), MethodGenerator::FLAG_PUBLIC, "return array(\n" . implode(",\n", $arrayCopy) . "\n);");
     $auditClass->addMethod('exchangeArray', array('data'), MethodGenerator::FLAG_PUBLIC, implode("\n", $setters));
     // Add function to return the entity class this entity audits
     $auditClass->addMethod('getAuditedEntityClass', array(), MethodGenerator::FLAG_PUBLIC, " return '" . addslashes($className) . "';");
     eval($auditClass->generate());
     return true;
 }
예제 #10
0
 /**
  * Create a skeleton class from the given XML type
  *
  * @param Type $type
  * @return \Zend\Code\Generator\ClassGenerator
  */
 protected function createClassFromType(Type $type)
 {
     $targetNamespace = $type->getSchema()->getTargetNamespace();
     $namespace = $this->namespaceInflector->inflectNamespace($type);
     // create the class
     $class = new ClassGenerator();
     $class->setName($type->getName());
     if ($namespace) {
         $class->setNamespaceName($namespace);
     }
     // set the class documentation
     $docDescription = new Html2Text($type->getDoc());
     $doc = new DocBlockGenerator($docDescription->getText());
     $doc->setTag(new GenericTag('xmlns', $targetNamespace));
     $class->setDocBlock($doc);
     return $class;
 }
예제 #11
0
 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;
     }
 }
 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;
 }
예제 #13
0
 /**
  * @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;
 }
예제 #14
0
 /**
  * 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;
 }
예제 #15
0
 /**
  * Generate Api and Model Classes
  *
  * @throws Exception\InvalidArgumentException
  */
 public function generateAction()
 {
     /* @var $request \Zend\Console\Request */
     /* @var $console \Zend\Console\AdapterInterface */
     $request = $this->getRequest();
     $console = $this->getServiceLocator()->get('console');
     $metadataFile = $request->getParam('metadata-file');
     if (!is_file($metadataFile)) {
         throw new Exception\InvalidArgumentException("Invalid metadata file path provided '{$metadataFile}'");
     } elseif (!is_readable(realpath($metadataFile))) {
         throw new Exception\InvalidArgumentException("Cannot read metadata file '{$metadataFile}'; aborting.");
     }
     try {
         $metadata = Json::decode(file_get_contents($metadataFile));
     } catch (JsonRuntimeException $e) {
         throw new Exception\InvalidArgumentException("Invalid metadata Json format; aborting." . PHP_EOL);
     }
     // Create Wrapper to consume apis
     $apiWrapperClass = new Generator\ClassGenerator();
     $apiWrapperClass->setName('Api')->setNamespaceName('Mailjet\\Api')->setExtendedClass('AbstractApi')->setDocBlock(new Generator\DocBlockGenerator('Mailjet Api', 'Wrapper used (as proxy) to consume apis', array(new Generator\DocBlock\Tag(array('name' => 'see', 'description' => sprintf('http://mjdemo.poxx.net/~shubham'))))));
     foreach ($metadata->Data as $metadata) {
         if (!$metadata->PublicOperations) {
             continue;
             // If not Public skip the generation
         }
         // Generate Api class
         $this->generateApiFromMetadata($metadata);
         // Generate Model class
         $this->generateModelFromMetadata($metadata);
         // Append proxy method to Wrapper
         $apiClassName = ucfirst($metadata->Name);
         $apiWrapperClass->addMethod($metadata->Name, array(), Generator\MethodGenerator::FLAG_PUBLIC, "return \$this->api('{$apiClassName}');", new Generator\DocBlockGenerator('Helper for ' . $metadata->Name . ' calls', null, array(new ReturnTag(array('datatype' => ucfirst($metadata->Name))))));
     }
     // Create and Write Wrapper Class File
     $file = new Generator\FileGenerator();
     $file->setClass($apiWrapperClass);
     $file->setFilename(dirname(__DIR__) . '/Api/' . $apiWrapperClass->getName() . '.php');
     if (file_put_contents($file->getFilename(), $file->generate())) {
         $console->writeLine("The Api Wrapper has been created.", Color::GREEN);
     } else {
         $console->writeLine("There was an error during Api Wrapper creation.", Color::RED);
     }
     $console->writeLine("DONE", Color::GREEN);
     $console->writeLine("Wrote api from '{$metadataFile}'", Color::LIGHT_WHITE);
 }
예제 #16
0
 /**
  * Construct, configure, and return a PHP class file code generation object
  *
  * Creates a Zend\Code\Generator\FileGenerator object that has
  * created the specified class and service locator methods.
  *
  * @param  null|string                         $filename
  * @throws \Zend\Di\Exception\RuntimeException
  * @return FileGenerator
  */
 public function getCodeGenerator($filename = null)
 {
     $injector = $this->injector;
     $im = $injector->instanceManager();
     $indent = '    ';
     $aliases = $this->reduceAliases($im->getAliases());
     $caseStatements = array();
     $getters = array();
     $definitions = $injector->definitions();
     $fetched = array_unique(array_merge($definitions->getClasses(), $im->getAliases()));
     foreach ($fetched as $name) {
         $getter = $this->normalizeAlias($name);
         $meta = $injector->get($name);
         $params = $meta->getParams();
         // Build parameter list for instantiation
         foreach ($params as $key => $param) {
             if (null === $param || is_scalar($param) || is_array($param)) {
                 $string = var_export($param, 1);
                 if (strstr($string, '::__set_state(')) {
                     throw new Exception\RuntimeException('Arguments in definitions may not contain objects');
                 }
                 $params[$key] = $string;
             } elseif ($param instanceof GeneratorInstance) {
                 /* @var $param GeneratorInstance */
                 $params[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName()));
             } else {
                 $message = sprintf('Unable to use object arguments when building containers. Encountered with "%s", parameter of type "%s"', $name, get_class($param));
                 throw new Exception\RuntimeException($message);
             }
         }
         // Strip null arguments from the end of the params list
         $reverseParams = array_reverse($params, true);
         foreach ($reverseParams as $key => $param) {
             if ('NULL' === $param) {
                 unset($params[$key]);
                 continue;
             }
             break;
         }
         // Create instantiation code
         $constructor = $meta->getConstructor();
         if ('__construct' != $constructor) {
             // Constructor callback
             $callback = var_export($constructor, 1);
             if (strstr($callback, '::__set_state(')) {
                 throw new Exception\RuntimeException('Unable to build containers that use callbacks requiring object instances');
             }
             if (count($params)) {
                 $creation = sprintf('$object = call_user_func(%s, %s);', $callback, implode(', ', $params));
             } else {
                 $creation = sprintf('$object = call_user_func(%s);', $callback);
             }
         } else {
             // Normal instantiation
             $className = '\\' . ltrim($name, '\\');
             $creation = sprintf('$object = new %s(%s);', $className, implode(', ', $params));
         }
         // Create method call code
         $methods = '';
         foreach ($meta->getMethods() as $methodData) {
             if (!isset($methodData['name']) && !isset($methodData['method'])) {
                 continue;
             }
             $methodName = isset($methodData['name']) ? $methodData['name'] : $methodData['method'];
             $methodParams = $methodData['params'];
             // Create method parameter representation
             foreach ($methodParams as $key => $param) {
                 if (null === $param || is_scalar($param) || is_array($param)) {
                     $string = var_export($param, 1);
                     if (strstr($string, '::__set_state(')) {
                         throw new Exception\RuntimeException('Arguments in definitions may not contain objects');
                     }
                     $methodParams[$key] = $string;
                 } elseif ($param instanceof GeneratorInstance) {
                     $methodParams[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName()));
                 } else {
                     $message = sprintf('Unable to use object arguments when generating method calls. Encountered with class "%s", method "%s", parameter of type "%s"', $name, $methodName, get_class($param));
                     throw new Exception\RuntimeException($message);
                 }
             }
             // Strip null arguments from the end of the params list
             $reverseParams = array_reverse($methodParams, true);
             foreach ($reverseParams as $key => $param) {
                 if ('NULL' === $param) {
                     unset($methodParams[$key]);
                     continue;
                 }
                 break;
             }
             $methods .= sprintf("\$object->%s(%s);\n", $methodName, implode(', ', $methodParams));
         }
         // Generate caching statement
         $storage = '';
         if ($im->hasSharedInstance($name, $params)) {
             $storage = sprintf("\$this->services['%s'] = \$object;\n", $name);
         }
         // Start creating getter
         $getterBody = '';
         // Create fetch of stored service
         if ($im->hasSharedInstance($name, $params)) {
             $getterBody .= sprintf("if (isset(\$this->services['%s'])) {\n", $name);
             $getterBody .= sprintf("%sreturn \$this->services['%s'];\n}\n\n", $indent, $name);
         }
         // Creation and method calls
         $getterBody .= sprintf("%s\n", $creation);
         $getterBody .= $methods;
         // Stored service
         $getterBody .= $storage;
         // End getter body
         $getterBody .= "return \$object;\n";
         $getterDef = new MethodGenerator();
         $getterDef->setName($getter);
         $getterDef->setBody($getterBody);
         $getters[] = $getterDef;
         // Get cases for case statements
         $cases = array($name);
         if (isset($aliases[$name])) {
             $cases = array_merge($aliases[$name], $cases);
         }
         // Build case statement and store
         $statement = '';
         foreach ($cases as $value) {
             $statement .= sprintf("%scase '%s':\n", $indent, $value);
         }
         $statement .= sprintf("%sreturn \$this->%s();\n", str_repeat($indent, 2), $getter);
         $caseStatements[] = $statement;
     }
     // Build switch statement
     $switch = sprintf("switch (%s) {\n%s\n", '$name', implode("\n", $caseStatements));
     $switch .= sprintf("%sdefault:\n%sreturn parent::get(%s, %s);\n", $indent, str_repeat($indent, 2), '$name', '$params');
     $switch .= "}\n\n";
     // Build get() method
     $nameParam = new ParameterGenerator();
     $nameParam->setName('name');
     $paramsParam = new ParameterGenerator();
     $paramsParam->setName('params')->setType('array')->setDefaultValue(array());
     $get = new MethodGenerator();
     $get->setName('get');
     $get->setParameters(array($nameParam, $paramsParam));
     $get->setBody($switch);
     // Create getters for aliases
     $aliasMethods = array();
     foreach ($aliases as $class => $classAliases) {
         foreach ($classAliases as $alias) {
             $aliasMethods[] = $this->getCodeGenMethodFromAlias($alias, $class);
         }
     }
     // Create class code generation object
     $container = new ClassGenerator();
     $container->setName($this->containerClass)->setExtendedClass('ServiceLocator')->addMethodFromGenerator($get)->addMethods($getters)->addMethods($aliasMethods);
     // Create PHP file code generation object
     $classFile = new FileGenerator();
     $classFile->setUse('Zend\\Di\\ServiceLocator')->setClass($container);
     if (null !== $this->namespace) {
         $classFile->setNamespace($this->namespace);
     }
     if (null !== $filename) {
         $classFile->setFilename($filename);
     }
     return $classFile;
 }
 /**
  * Dynamically scope an audit class
  *
  * @param  string $className
  * @return false|string
  */
 public function loadClass($className, $type)
 {
     $moduleOptions = \ZF\Doctrine\Audit\Module::getModuleOptions();
     if (!$moduleOptions) {
         return;
     }
     $entityManager = $moduleOptions->getEntityManager();
     $auditClass = new ClassGenerator();
     //  Build a discovered many to many join class
     $joinClasses = $moduleOptions->getJoinClasses();
     if (in_array($className, array_keys($joinClasses))) {
         $auditClass->setNamespaceName("ZF\\Doctrine\\Audit\\Entity");
         $auditClass->setName($className);
         $auditClass->setExtendedClass('AbstractAudit');
         $auditClass->addProperty('id', null, PropertyGenerator::FLAG_PROTECTED);
         $auditClass->addProperty('targetRevisionEntity', null, PropertyGenerator::FLAG_PROTECTED);
         $auditClass->addProperty('sourceRevisionEntity', null, PropertyGenerator::FLAG_PROTECTED);
         $auditClass->addMethod('getTargetRevisionEntity', array(), MethodGenerator::FLAG_PUBLIC, 'return $this->targetRevisionEntity;');
         $auditClass->addMethod('getSourceRevisionEntity', array(), MethodGenerator::FLAG_PUBLIC, 'return $this->sourceRevisionEntity;');
         $auditClass->addMethod('getId', array(), MethodGenerator::FLAG_PUBLIC, 'return $this->id;');
         $auditClass->addMethod('setTargetRevisionEntity', array(ParameterGenerator::fromArray(array('name' => 'value', 'type' => '\\ZF\\Doctrine\\Audit\\Entity\\RevisionEntity'))), MethodGenerator::FLAG_PUBLIC, '$this->targetRevisionEntity = $value;' . "\n" . 'return $this;');
         $auditClass->addMethod('setSourceRevisionEntity', array(ParameterGenerator::fromArray(array('name' => 'value', 'type' => '\\ZF\\Doctrine\\Audit\\Entity\\RevisionEntity'))), MethodGenerator::FLAG_PUBLIC, '$this->sourceRevisionEntity = $value;' . "\n" . 'return $this;');
         #            print_r($auditClass->generate());
         #            die();
         eval($auditClass->generate());
         return;
     }
     // Add revision reference getter and setter
     $auditClass->addProperty($moduleOptions->getRevisionEntityFieldName(), null, PropertyGenerator::FLAG_PROTECTED);
     $auditClass->addMethod('get' . $moduleOptions->getRevisionEntityFieldName(), array(), MethodGenerator::FLAG_PUBLIC, " return \$this->" . $moduleOptions->getRevisionEntityFieldName() . ";");
     $auditClass->addMethod('set' . $moduleOptions->getRevisionEntityFieldName(), array('value'), MethodGenerator::FLAG_PUBLIC, " \$this->" . $moduleOptions->getRevisionEntityFieldName() . " = \$value;\nreturn \$this;\r\n            ");
     // Verify this autoloader is used for target class
     #FIXME:  why is this sent work outside the set namespace?
     foreach ($moduleOptions->getAuditedClassNames() as $targetClass => $targetClassOptions) {
         $auditClassName = 'ZF\\Doctrine\\Audit\\Entity\\' . str_replace('\\', '_', $targetClass);
         if ($auditClassName == $className) {
             $currentClass = $targetClass;
         }
         $autoloadClasses[] = $auditClassName;
     }
     if (!in_array($className, $autoloadClasses)) {
         return;
     }
     // Get fields from target entity
     $metadataFactory = $entityManager->getMetadataFactory();
     $auditedClassMetadata = $metadataFactory->getMetadataFor($currentClass);
     $fields = $auditedClassMetadata->getFieldNames();
     $identifiers = $auditedClassMetadata->getFieldNames();
     $service = \ZF\Doctrine\Audit\Module::getModuleOptions()->getAuditService();
     // Generate audit entity
     foreach ($fields as $field) {
         $auditClass->addProperty($field, null, PropertyGenerator::FLAG_PROTECTED);
     }
     foreach ($auditedClassMetadata->getAssociationNames() as $associationName) {
         $auditClass->addProperty($associationName, null, PropertyGenerator::FLAG_PROTECTED);
         $fields[] = $associationName;
     }
     $auditClass->addMethod('getAssociationMappings', array(), MethodGenerator::FLAG_PUBLIC, "return unserialize('" . serialize($auditedClassMetadata->getAssociationMappings()) . "');");
     // Add exchange array method
     $setters = array();
     foreach ($fields as $fieldName) {
         $setters[] = '$this->' . $fieldName . ' = (isset($data["' . $fieldName . '"])) ? $data["' . $fieldName . '"]: null;';
         $arrayCopy[] = "    \"{$fieldName}\"" . ' => $this->' . $fieldName;
     }
     $auditClass->addMethod('getArrayCopy', array(), MethodGenerator::FLAG_PUBLIC, "return array(\n" . implode(",\n", $arrayCopy) . "\n);");
     $auditClass->addMethod('exchangeArray', array('data'), MethodGenerator::FLAG_PUBLIC, implode("\n", $setters));
     // Add function to return the entity class this entity audits
     $auditClass->addMethod('getAuditedEntityClass', array(), MethodGenerator::FLAG_PUBLIC, " return '" . addslashes($currentClass) . "';");
     $auditClass->setNamespaceName("ZF\\Doctrine\\Audit\\Entity");
     $auditClass->setName(str_replace('\\', '_', $currentClass));
     $auditClass->setExtendedClass('AbstractAudit');
     #    $auditedClassMetadata = $metadataFactory->getMetadataFor($currentClass);
     $auditedClassMetadata = $metadataFactory->getMetadataFor($currentClass);
     foreach ($auditedClassMetadata->getAssociationMappings() as $mapping) {
         if (isset($mapping['joinTable']['name'])) {
             $auditJoinTableClassName = "ZF\\Doctrine\\Audit\\Entity\\" . str_replace('\\', '_', $mapping['joinTable']['name']);
             $auditEntities[] = $auditJoinTableClassName;
             $moduleOptions->addJoinClass($auditJoinTableClassName, $mapping);
         }
     }
     #        if ($auditClass->getName() == 'AppleConnect_Entity_UserAuthenticationLog') {
     #            echo '<pre>';
     #            echo($auditClass->generate());
     #            die();
     #        }
     eval($auditClass->generate());
     #            die();
     return true;
 }
 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())];
 }
    /**
     * @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);
    }
예제 #20
0
    /**
     * Recurse the expose parameters - pass the entities full class name (including namespace)
     * @param array  $expose
     * @param string $fullClassName
     */
    protected function recurseParams(array $expose, $fullClassName)
    {
        // get ORM metadata for the current class
        $ormClassMetaData = $this->em->getClassMetadata($fullClassName);
        if (isset($this->classes[$fullClassName])) {
            $cg = $this->classes[$fullClassName];
        } else {
            $cg = new Generator\ClassGenerator();
            $cg->setName($fullClassName);
            $short = 'This class was generated by the drest-client tool, and should be treated as a plain data object';
            $long = <<<EOT
ANY ALTERATIONS WILL BE OVERWRITTEN if the classes are regenerated
The variables declared are exposed by the rest endpoint provided when generating these classes.
However depending on the operation (GET/POST/PUT etc) used some of these may not be populated / operational.
EOT;
            $docBlock = new Generator\DocBlockGenerator($short, $long);
            $cg->setDocBlock($docBlock);
            $cg->addMethods(array($this->getStaticCreateMethod($this->getTargetType($fullClassName))));
        }
        foreach ($expose as $key => $value) {
            if (is_array($value)) {
                if ($ormClassMetaData->hasAssociation($key)) {
                    $this->handleAssocProperty($key, $cg, $ormClassMetaData);
                    $assocMapping = $ormClassMetaData->getAssociationMapping($key);
                    $this->recurseParams($value, $assocMapping['targetEntity']);
                }
            } else {
                if ($ormClassMetaData->hasAssociation($value)) {
                    // This is an association field with no explicit include fields,
                    // include add data field (no relations)
                    $this->handleAssocProperty($value, $cg, $ormClassMetaData);
                    $assocMapping = $ormClassMetaData->getAssociationMapping($value);
                    $teCmd = $this->em->getClassMetadata($assocMapping['targetEntity']);
                    $this->recurseParams($teCmd->getColumnNames(), $assocMapping['targetEntity']);
                } else {
                    $this->handleNonAssocProperty($value, $cg);
                }
            }
        }
        // If the class is already set, overwrite it with it additional expose fields
        $this->classes[$fullClassName] = $cg;
    }
예제 #21
0
 /**
  * @group namespace
  */
 public function testPassingANamespacedClassnameShouldGenerateAClassnameWithoutItsNamespace()
 {
     $classGeneratorClass = new ClassGenerator();
     $classGeneratorClass->setName('My\Namespaced\FunClass');
     $received = $classGeneratorClass->generate();
     $this->assertContains('class FunClass', $received, $received);
 }
 /**
  * Generate the code for the given className and primaryKey and write it in a file.
  * @param string $className The class name.
  * @param string $primaryKey The primary key.
  */
 private function generateCode($className, $primaryKey)
 {
     $tags = $this->config->getTags();
     $class = new ClassGenerator();
     $docblock = DocBlockGenerator::fromArray(array('shortDescription' => ucfirst($className) . ' model class', 'longDescription' => 'This is a model class generated with DavidePastore\\ParisModelGenerator.', 'tags' => $tags));
     $idColumn = new PropertyGenerator('_id_column');
     $idColumn->setStatic(true)->setDefaultValue($primaryKey);
     $table = new PropertyGenerator('_table');
     $table->setStatic(true)->setDefaultValue($className);
     $tableUseShortName = new PropertyGenerator('_table_use_short_name');
     $tableUseShortName->setStatic(true)->setDefaultValue(true);
     $namespace = $this->config->getNamespace();
     $extendedClass = '\\Model';
     if (isset($namespace) && !empty($namespace)) {
         $class->setNamespaceName($this->config->getNamespace());
     }
     $class->setName(ucfirst($className))->setDocblock($docblock)->setExtendedClass($extendedClass)->addProperties(array($idColumn, $table, $tableUseShortName));
     $file = FileGenerator::fromArray(array('classes' => array($class), 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => ucfirst($className) . ' class file', 'longDescription' => null, 'tags' => $tags))));
     $generatedCode = $file->generate();
     $directory = $this->config->getDestinationFolder() . $namespace;
     if (!file_exists($directory)) {
         mkdir($directory, 0777, true);
     }
     $filePath = $directory . "/" . $class->getName() . ".php";
     if (file_exists($filePath) && !$this->force) {
         $helper = $this->getHelper('question');
         $realPath = realpath($filePath);
         $this->output->writeln("\n");
         $question = new ConfirmationQuestion('Do you want to overwrite the file "' . $realPath . '"?', false);
         if ($helper->ask($this->input, $this->output, $question)) {
             $this->writeInFile($filePath, $generatedCode);
         }
     } else {
         $this->writeInFile($filePath, $generatedCode);
     }
 }
예제 #23
0
 /**
  * Função geradora das entidades dos schemas e tabelas do banco de dados
  * 
  * @return \Cityware\Generator\Adapter\ModelAdapter
  */
 private function generatorClassEntity()
 {
     /* Lista os schemas do banco de dados */
     foreach ($this->oMetadata->getSchemas() as $valueSchema) {
         $tableNames = $this->oMetadata->getTableNames($valueSchema);
         $namespaceSchema = 'Orm\\' . $this->toCamelCase($valueSchema) . '\\Entities';
         /* Lista as tabelas do banco de dados */
         foreach ($tableNames as $tableName) {
             $multiPk = $primaryKey = $bodyExchangeArray = null;
             $class = new ClassGenerator();
             $class->setNamespaceName($namespaceSchema);
             $docBlockClass = DocBlockGenerator::fromArray(array('shortDescription' => 'Classe tipo model da tabela ' . $tableName . ' dentro do schema ' . $valueSchema, 'longDescription' => null));
             $class->setDocBlock($docBlockClass);
             $class->setName($this->toCamelCase($tableName));
             $class->addProperty('DBSCHEMA', $valueSchema, PropertyGenerator::FLAG_STATIC);
             $class->addProperty('DBTABLE', $tableName, PropertyGenerator::FLAG_STATIC);
             foreach ($this->oMetadata->getConstraints($tableName, $valueSchema) as $constraint) {
                 if (!$constraint->hasColumns()) {
                     continue;
                 }
                 if ($constraint->isPrimaryKey()) {
                     $columns = $constraint->getColumns();
                     if (count($columns) > 1) {
                         $multiPk = true;
                         $primaryKey = implode(', ', $columns);
                     } else {
                         $multiPk = false;
                         $primaryKey = $columns[0];
                     }
                     $class->addProperty('MULTIPK', $multiPk, PropertyGenerator::FLAG_STATIC);
                     $class->addProperty('PKCOLUMN', $primaryKey, PropertyGenerator::FLAG_STATIC);
                 }
             }
             /* Cria os metodos setter/getter e as variáveis das colunas da tabela */
             $table = $this->oMetadata->getTable($tableName, $valueSchema);
             /* Lista as colunas da tabela do banco de dados */
             foreach ($table->getColumns() as $column) {
                 $varName = $this->camelCase($column->getName());
                 $class->addProperty($varName, null, PropertyGenerator::FLAG_PRIVATE);
                 $methodGet = 'get' . $this->toCamelCase($column->getName());
                 $methodSet = 'set' . $this->toCamelCase($column->getName());
                 $docBlockSet = DocBlockGenerator::fromArray(array('shortDescription' => 'Setter da coluna ' . $column->getName(), 'longDescription' => null, 'tags' => array(new Tag\ParamTag($varName, $this->prepareSqlTypeDocBlock($column->getDataType())))));
                 $docBlockGet = DocBlockGenerator::fromArray(array('shortDescription' => 'Getter da coluna ' . $column->getName(), 'longDescription' => null, 'tags' => array(new Tag\ReturnTag(array('datatype' => $this->prepareSqlTypeDocBlock($column->getDataType()))))));
                 $bodyGet = 'return $this->' . $varName . ';';
                 $bodySet = '$this->' . $varName . ' = $' . $this->camelCase($column->getName()) . ';';
                 $class->addMethod($methodSet, array($this->camelCase($column->getName())), MethodGenerator::FLAG_PUBLIC, $bodySet, $docBlockSet);
                 $class->addMethod($methodGet, array(), MethodGenerator::FLAG_PUBLIC, $bodyGet, $docBlockGet);
                 $bodyExchangeArray .= '$this->' . $varName . ' = (isset($data["' . $column->getName() . '"])) ? $data["' . $column->getName() . '"] : null;' . "\n\n";
             }
             $docBlockExchangeArray = DocBlockGenerator::fromArray(array('shortDescription' => 'Função para settar todos os objetos por meio de array', 'longDescription' => null, 'tags' => array(new Tag\ParamTag('data', 'array'))));
             $class->addMethod('exchangeArray', array('data'), MethodGenerator::FLAG_PUBLIC, $bodyExchangeArray, $docBlockExchangeArray);
             $docBlockGetArrayCopy = DocBlockGenerator::fromArray(array('shortDescription' => 'Função para retornar os valores por meio de array dos objetos da classe', 'longDescription' => null, 'tags' => array(new Tag\ReturnTag(array('datatype' => 'mixed')))));
             $class->addMethod('getArrayCopy', array(), MethodGenerator::FLAG_PUBLIC, 'return get_object_vars($this);', $docBlockGetArrayCopy);
             $classCode = "<?php" . PHP_EOL;
             $classCode .= $class->generate();
             /*
              $idxConstraint = 0;
              foreach ($this->oMetadata->getConstraints($tableName, $valueSchema) as $constraint) {
             
              $typeConstraint = ($constraint->isPrimaryKey()) ? 'pk' : (($constraint->isForeignKey()) ? 'fk' : null);
              if (!empty($typeConstraint)) {
             
              $consName = $constraint->getName();
              $contraintObj = $this->oMetadata->getConstraint($consName, $tableName, $valueSchema);
             
              $constraintColumns = $contraintObj->getColumns();
              if (count($constraintColumns) > 1) {
              foreach ($constraintColumns as $valueConsColumns) {
              $this->aDatabase[$valueSchema][$tableName][$valueConsColumns]['constraints']['type'] = $typeConstraint;
              if ($typeConstraint === 'fk') {
              $this->aDatabase[$valueSchema][$tableName][$valueConsColumns]['constraints']['schemaRef'] = $contraintObj->getReferencedTableSchema();
              $this->aDatabase[$valueSchema][$tableName][$valueConsColumns]['constraints']['tableRef'] = $contraintObj->getReferencedTableName();
              $this->aDatabase[$valueSchema][$tableName][$valueConsColumns]['constraints']['columnsRef'] = $contraintObj->getReferencedColumns();
              }
              }
              } else {
              $this->aDatabase[$valueSchema][$tableName][$constraintColumns[0]]['constraints']['type'] = $typeConstraint;
              if ($typeConstraint === 'fk') {
              $this->aDatabase[$valueSchema][$tableName][$constraintColumns[0]]['constraints']['schemaRef'] = $contraintObj->getReferencedTableSchema();
              $this->aDatabase[$valueSchema][$tableName][$constraintColumns[0]]['constraints']['tableRef'] = $contraintObj->getReferencedTableName();
              $this->aDatabase[$valueSchema][$tableName][$constraintColumns[0]]['constraints']['columnsRef'] = $contraintObj->getReferencedColumns();
              }
              }
              }
             
              $idxConstraint++;
              }
             * 
             */
             file_put_contents($this->ormFolder . $this->toCamelCase($valueSchema) . DS . 'Entities' . DS . $this->toCamelCase($tableName) . '.php', $classCode);
             chmod($this->ormFolder . $this->toCamelCase($valueSchema) . DS . 'Entities' . DS . $this->toCamelCase($tableName) . '.php', 0644);
             $this->generatorClassEntityTable($valueSchema, $tableName);
         }
         //gera arquivo por tabela
     }
     return $this;
 }
 /**
  * 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;
 }
예제 #25
0
 public function generate(Generator\ClassGenerator $class, PHPClass $type)
 {
     $docblock = new DocBlockGenerator("Class representing " . $type->getName());
     if ($type->getDoc()) {
         $docblock->setLongDescription($type->getDoc());
     }
     $class->setNamespaceName($type->getNamespace() ?: NULL);
     $class->setName($type->getName());
     $class->setDocblock($docblock);
     if ($extends = $type->getExtends()) {
         if ($p = $this->isOneType($extends)) {
             $this->handleProperty($class, $p);
             $this->handleValueMethod($class, $p, $extends);
         } else {
             $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;
     }
 }
 /**
  * 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;
 }
예제 #27
0
 /**
  * @param null|string $module
  * @param null|string $migrationBody
  * @return string
  */
 public function create($module = null, $migrationBody = null)
 {
     $path = $this->getMigrationsDirectoryPath($module);
     list(, $mSec) = explode(".", microtime(true));
     $migrationName = date('Ymd_His_') . substr($mSec, 0, 2);
     $methodUp = array('name' => 'up', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Upgrade', 'longDescription' => null)));
     $methodDown = array('name' => 'down', 'docblock' => DocBlockGenerator::fromArray(array('shortDescription' => 'Degrade', 'longDescription' => null)));
     if ($migrationBody) {
         if (isset($migrationBody['up'])) {
             $upBody = '';
             foreach ($migrationBody['up'] as $query) {
                 $upBody .= '$this->query("' . $query . '");' . PHP_EOL;
             }
             $methodUp['body'] = $upBody;
         }
         if (isset($migrationBody['down'])) {
             $downBody = '';
             foreach ($migrationBody['down'] as $query) {
                 $downBody .= '$this->query("' . $query . '");' . PHP_EOL;
             }
             $methodDown['body'] = $downBody;
         }
     }
     $class = new ClassGenerator();
     $class->setName('Migration_' . $migrationName)->setExtendedClass('AbstractMigration')->addUse('ZFCTool\\Service\\Migration\\AbstractMigration')->addMethods(array(MethodGenerator::fromArray($methodUp), MethodGenerator::fromArray($methodDown)));
     $file = new FileGenerator(array('classes' => array($class)));
     $code = $file->generate();
     $migrationPath = $path . '/' . $migrationName . '.php';
     file_put_contents($migrationPath, $code);
     return $migrationPath;
 }
 /**
  * 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());
     }
 }
예제 #29
0
 private function buildClass($replacement)
 {
     $type = $this->splitNsandClass($replacement['originalFullyQualifiedType']);
     $class = new ClassGenerator();
     $class->setName($type['class']);
     $class->setNamespaceName($type['ns']);
     $class->setExtendedClass('\\Brads\\Ppm\\Proxy');
     $properties = [];
     $methods = [];
     $implementedInterfaces = [];
     foreach ($versions as $version => $info) {
         foreach ($info['files'] as $file) {
             echo "Parsing: " . $this->vendorDir . '/' . $package . '/' . $version . '/' . $file . "\n";
             $parsedFile = new ReflectionFile($this->vendorDir . '/' . $package . '/' . $version . '/' . $file);
             $parsedClass = $parsedFile->getFileNamespace($info['toNs'])->getClass($info['toNs'] . '\\' . $type['class']);
             if ($parsedClass->getInterfaceNames() != null) {
                 $implementedInterfaces = array_merge($implementedInterfaces, $parsedClass->getInterfaceNames());
             }
             foreach ($parsedClass->getMethods() as $method) {
                 if ($method->isPublic()) {
                     $generatedMethod = new MethodGenerator();
                     $generatedMethod->setName($method->name);
                     $generatedMethod->setBody('echo "Hello world!";');
                     $generatedMethod->setAbstract($method->isAbstract());
                     $generatedMethod->setFinal($method->isFinal());
                     $generatedMethod->setStatic($method->isStatic());
                     $generatedMethod->setVisibility(MethodGenerator::VISIBILITY_PUBLIC);
                     foreach ($method->getParameters() as $param) {
                         $generatedParam = new ParameterGenerator();
                         $generatedParam->setName($param->name);
                         if ($param->hasType()) {
                             $generatedParam->setType($param->getType());
                         }
                         //$generatedParam->setDefaultValue($param->getDefaultValue());
                         $generatedParam->setPosition($param->getPosition());
                         $generatedParam->setVariadic($param->isVariadic());
                         $generatedParam->setPassedByReference($param->isPassedByReference());
                         $generatedMethod->setParameter($generatedParam);
                     }
                     $existingMethod = Linq::from($methods)->firstOrDefault(null, function (MethodGenerator $v) use($method) {
                         return $v->getName() == $method->name;
                     });
                     if ($existingMethod != null) {
                         $existingParams = $existingMethod->getParameters();
                         foreach ($generatedMethod->getParameters() as $newParam) {
                             $existingParam = Linq::from($existingParams)->firstOrDefault(function (ParameterGenerator $v) {
                                 return $v->getName() == $newParam->getName();
                             });
                             if ($existingParam == null) {
                                 $existingMethod->setParameter($newParam);
                             }
                         }
                     } else {
                         $methods[] = $generatedMethod;
                     }
                 }
             }
             foreach ($parsedClass->getProperties() as $prop) {
                 //$properties[] = PropertyGenerator::fromReflection($prop);
             }
         }
     }
     $class->setImplementedInterfaces($implementedInterfaces);
     $class->addMethods($methods);
     $class->addProperties($properties);
     return (new FileGenerator(['classes' => [$class]]))->generate();
 }
예제 #30
0
 /**
  * @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;
 }