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); }
/** * 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; }
/** * 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; }
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; } }
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())]; }
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(); }
/** * @param $classFQCN * @return ClassGenerator */ private function createStub($classFQCN) { $class = new ClassGenerator($this->getProxyName($classFQCN)); $class->setNamespaceName($this->proxyNamespace)->setExtendedClass('\\' . $classFQCN)->setFinal(true)->addUse('ObjRef\\C')->addUse('ObjRef\\HostInterface')->addUse('ObjRef\\Proxy\\ManagerInterface')->addProperty('manager', null, PropertyGenerator::FLAG_PRIVATE)->addProperty('host', null, PropertyGenerator::FLAG_PRIVATE)->addProperty('ref', null, PropertyGenerator::FLAG_PRIVATE)->setDocBlock(new DocBlockGenerator('Remote Proxy for class ' . $classFQCN, 'This file is auto generated by ObjRef.')); return $class; }
/** * @return ClassGenerator[] */ private function getTypesCode() { $generator = $this; return array_map(function (Structure\TypeStructure $type) use($generator) { $code = new ClassGenerator($type->getClassName()); $code->setNamespaceName($generator->getFullNamespace($type->getClassName(), true)); foreach ($type->getMembers() as $member) { $tag = new Tag(); $tag->setName('var'); if ($member->isPrimitive()) { $tag->setDescription($member->getType()); } else { $tag->setDescription("\\" . $generator->getFullNamespace($member->getType())); } $docBlock = new DocBlockGenerator(null, null, [$tag]); $property = new PropertyGenerator(); $property->setName($member->getName()); $property->setDocBlock($docBlock); $code->addPropertyFromGenerator($property); } return $code; }, $this->service->getTypes()->getArrayCopy()); }
/** * 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); } }
/** * Copied from ClassGenerator::fromReflection and tweaked slightly * @param ClassReflection $classReflection * * @return ClassGenerator */ public function getGeneratorFromReflection(ClassReflection $classReflection) { // class generator $cg = new ClassGenerator($classReflection->getName()); $cg->setSourceContent($cg->getSourceContent()); $cg->setSourceDirty(false); if ($classReflection->getDocComment() != '') { $docblock = DocBlockGenerator::fromReflection($classReflection->getDocBlock()); $docblock->setIndentation(Generator::$indentation); $cg->setDocBlock($docblock); } $cg->setAbstract($classReflection->isAbstract()); // set the namespace if ($classReflection->inNamespace()) { $cg->setNamespaceName($classReflection->getNamespaceName()); } /* @var \Zend\Code\Reflection\ClassReflection $parentClass */ $parentClass = $classReflection->getParentClass(); if ($parentClass) { $cg->setExtendedClass('\\' . ltrim($parentClass->getName(), '\\')); $interfaces = array_diff($classReflection->getInterfaces(), $parentClass->getInterfaces()); } else { $interfaces = $classReflection->getInterfaces(); } $interfaceNames = array(); foreach ($interfaces as $interface) { /* @var \Zend\Code\Reflection\ClassReflection $interface */ $interfaceNames[] = $interface->getName(); } $cg->setImplementedInterfaces($interfaceNames); $properties = array(); foreach ($classReflection->getProperties() as $reflectionProperty) { if ($reflectionProperty->getDeclaringClass()->getName() == $classReflection->getName()) { $property = PropertyGenerator::fromReflection($reflectionProperty); $property->setIndentation(Generator::$indentation); $properties[] = $property; } } $cg->addProperties($properties); $methods = array(); foreach ($classReflection->getMethods() as $reflectionMethod) { $className = $cg->getNamespaceName() ? $cg->getNamespaceName() . "\\" . $cg->getName() : $cg->getName(); if ($reflectionMethod->getDeclaringClass()->getName() == $className) { $method = MethodGenerator::fromReflection($reflectionMethod); $method->setBody(preg_replace("/^\\s+/m", '', $method->getBody())); $method->setIndentation(Generator::$indentation); $methods[] = $method; } } $cg->addMethods($methods); return $cg; }
/** * @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; }
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; }
/** * @param $className * @param $nameSpace * @return ClassGenerator */ private function initClass($className, $nameSpace) { $user = $this->getCurrentStaff()->getStaffName(); $date = date('Y-m-d H:i:s', time()); $class = new ClassGenerator($className); $class->setDocBlock(DocBlockGenerator::fromArray(array('shortDescription' => 'System Generated Code', 'longDescription' => "User : {$user}\nDate : {$date}", 'tags' => array(array('name' => 'package', 'description' => $nameSpace))))); $class->setNamespaceName($nameSpace); return $class; }
public function buildRepository($model) { $class = new ClassGenerator($model->config->name . 'Repository'); $class->setExtendedClass('\\Doctrine\\ORM\\EntityRepository'); $class->setNamespaceName('app\\resources\\repository'); 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; }
private function buildProxyClass(string $entityInterfaceName, string $proxyNamespace, string $proxyClassName) : string { $reflectionClass = new ReflectionClass($entityInterfaceName); if (!$reflectionClass->isInterface()) { throw InvalidInterfaceException::fromInvalidInterface($entityInterfaceName); } $classGenerator = new ClassGenerator(); $classGenerator->setNamespaceName($proxyNamespace); $classGenerator->setName($proxyClassName); $classGenerator->setImplementedInterfaces([$entityInterfaceName, ProxyInterface::class]); $classGenerator->addProperty('initializer', null, PropertyGenerator::FLAG_PRIVATE); $classGenerator->addProperty('relationId', null, PropertyGenerator::FLAG_PRIVATE); $classGenerator->addProperty('realEntity', null, PropertyGenerator::FLAG_PRIVATE); $constructorGenerator = new MethodGenerator('__construct', [['name' => 'initializer', 'type' => 'callable'], ['name' => 'relationId']]); $constructorGenerator->setBody(' $this->initializer = $initializer; $this->relationId = $relationId; '); $classGenerator->addMethodFromGenerator($constructorGenerator); $getRelationIdGenerator = new MethodGenerator('__getRelationId'); $getRelationIdGenerator->setBody(' return $this->relationId; '); $classGenerator->addMethodFromGenerator($getRelationIdGenerator); $getRealEntityGenerator = new MethodGenerator('__getRealEntity'); $getRealEntityGenerator->setBody(' if (null === $this->realEntity) { $this->realEntity = ($this->initializer)(); \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class); }; return $this->realEntity; '); $classGenerator->addMethodFromGenerator($getRealEntityGenerator); foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) { $parameters = []; $parameterGenerators = []; $returnType = $reflectionMethod->getReturnType(); foreach ($reflectionMethod->getParameters() as $reflectionParameter) { $parameterGenerator = new ParameterGenerator($reflectionParameter->getName(), $reflectionParameter->getType(), $reflectionParameter->isDefaultValueAvailable() ? $reflectionParameter->getDefaultValue() : null); $parameterGenerator->setVariadic($reflectionParameter->isVariadic()); $parameterGenerators[] = $parameterGenerator; if ($reflectionParameter->isVariadic()) { $parameters[] = '...$' . $reflectionParameter->getName(); } else { $parameters[] = '$' . $reflectionParameter->getName(); } } $methodGenerator = new MethodGenerator(); $methodGenerator->setName($reflectionMethod->getName()); $methodGenerator->setVisibility(MethodGenerator::VISIBILITY_PUBLIC); $methodGenerator->setParameters($parameterGenerators); $methodGenerator->setReturnType($returnType); $body = ' if (null === $this->realEntity) { $this->realEntity = ($this->initializer)(); \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class); }; '; if ('void' !== $returnType) { $body .= 'return '; } $body .= '$this->realEntity->' . $reflectionMethod->getName() . '(' . implode(', ', $parameters) . ');'; $methodGenerator->setBody($body); $classGenerator->addMethodFromGenerator($methodGenerator); } $fileGenerator = new FileGenerator(); $fileGenerator->setClass($classGenerator); $filename = null === $this->proxyFolder ? tempnam(sys_get_temp_dir(), $proxyClassName) : sprintf('%s/%s.php', $this->proxyFolder, $proxyClassName); $fileGenerator->setFilename($filename); $fileGenerator->write(); return $filename; }
/** * 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; }
/** * 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; }
use DOMDocument; require __DIR__ . "/../vendor/autoload.php"; $namespace = "CallFire\\Common\\Resource"; $extendedClass = "AbstractResource"; $xsdUrl = 'https://www.callfire.com/api/1.1/wsdl/callfire-data.xsd'; $sourceDirectory = realpath(__DIR__ . "/../src") . '/' . str_replace('\\', '/', $namespace); $queryMapPath = realpath(__DIR__ . "/../src") . '/CallFire/Api/Rest/querymap.php'; $xsdContent = file_get_contents($xsdUrl); $xsdDocument = new DOMDocument(); $xsdDocument->loadXML($xsdContent); unset($xsdContent); $resourceGenerator = new ResourceGenerator(); $resourceGenerator->setXsd($xsdDocument); $resourceClassGenerator = new ClassGenerator(); $resourceClassGenerator->setExtendedClass($extendedClass); $resourceClassGenerator->setNamespaceName($namespace); $resourceGenerator->setClassGenerator($resourceClassGenerator); $resourceGenerator->generate(); $resourceFiles = $resourceGenerator->generateResourceFiles(); $queryMap = $resourceGenerator->getQueryMap(); if (!is_dir($sourceDirectory)) { mkdir($sourceDirectory, 0777, true); } foreach ($resourceFiles as $resourceFile) { $resourceFile->setFilename("{$sourceDirectory}/{$resourceFile->getClass()->getName()}.php"); $resourceFile->write(); } $queryMapFile = new FileGenerator(); $queryMapFile->setFilename($queryMapPath); $queryMapFile->setBody('return ' . (new ValueGenerator($queryMap))->generate() . ';'); $queryMapFile->write();
/** * generates file with target grid (if not exists yet) * * @param DataSetDescriptorInterface $dataSet * @param string $extends * base class for grid * @return string full name of generated class */ protected function generateGrid(DataSetDescriptorInterface $dataSet, $extends) { $name = $dataSet->getName(); $className = $this->underscoreToCamelCase->filter($name) . "Grid"; $namespace = $this->params->getParam("moduleName") . "\\Grid"; $fullClassName = '\\' . $namespace . '\\' . $className; $gridClassFilePath = $this->moduleRoot() . "/src/" . $this->params->getParam("moduleName") . "/Grid/" . $className . ".php"; if (file_exists($gridClassFilePath)) { return $fullClassName; } $class = new ClassGenerator(); $class->setName($className); $class->setNamespaceName($namespace); $class->setExtendedClass($extends); $file = new FileGenerator(); $docBlock = new \Zend\Code\Generator\DocblockGenerator(sprintf($this->codeLibrary()->get('grid.standardConfigDescription'), $name)); $docBlock->setTag(new GenericTag('author', $this->params->getParam('author')))->setTag(new GenericTag('project', $this->params->getParam('project')))->setTag(new GenericTag('license', $this->params->getParam('license')))->setTag(new GenericTag('copyright', $this->params->getParam('copyright'))); $file->setClass($class)->setDocBlock($docBlock); file_put_contents($gridClassFilePath, $file->generate()); return $fullClassName; }
public function controllerAction() { $console = $this->getServiceLocator()->get('console'); $tmpDir = sys_get_temp_dir(); $request = $this->getRequest(); $name = $request->getParam('name'); $module = $request->getParam('module'); $path = $request->getParam('path', '.'); if (!file_exists("{$path}/module") || !file_exists("{$path}/config/application.config.php")) { return $this->sendError("The path {$path} doesn't contain a ZF2 application. I cannot create a module here."); } if (file_exists("{$path}/module/{$module}/src/{$module}/Controller/{$name}")) { return $this->sendError("The controller {$name} already exists in module {$module}."); } $ucName = ucfirst($name); $ctrlPath = $path . '/module/' . $module . '/src/' . $module . '/Controller/' . $ucName . 'Controller.php'; $controller = $ucName . 'Controller'; $code = new Generator\ClassGenerator(); $code->setNamespaceName(ucfirst($module) . '\\Controller')->addUse('Zend\\Mvc\\Controller\\AbstractActionController')->addUse('Zend\\View\\Model\\ViewModel'); $code->setName($controller)->addMethods(array(new Generator\MethodGenerator('indexAction', array(), Generator\MethodGenerator::FLAG_PUBLIC, 'return new ViewModel();')))->setExtendedClass('AbstractActionController'); $file = new Generator\FileGenerator(array('classes' => array($code))); $filter = new CamelCaseToDashFilter(); $viewfolder = strtolower($filter->filter($module)); $dir = $path . "/module/{$module}/view/{$viewfolder}/" . strtolower($filter->filter($name)); if (!file_exists($dir)) { mkdir($dir, 0777, true); } $phtml = false; $phtmlPath = $dir . "/index.phtml"; if (file_put_contents($phtmlPath, 'Action "index", controller "' . $ucName . '", module "' . $module . '".')) { $phtml = true; } if (file_put_contents($ctrlPath, $file->generate()) && $phtml == true) { $console->writeLine("The controller {$name} has been created in module {$module}.", Color::GREEN); } else { $console->writeLine("There was an error during controller creation.", Color::RED); } }
/** * 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; }
$dirName = dirname($filename); if (!is_dir($dirName)) { mkdir($dirName . '/', 0777, true); } return file_put_contents($filename, $data, $flags); } /********** FILE UTILS ************/ public function generate() { // Definitions $classGenerator = new ClassGenerator(); $classGenerator->setName($this->getClassName()); $classGenerator->setDocblock($this->getDocBlock()); $classGenerator->setNamespaceName($this->getClassNameSpace()); $classGenerator->setExtendedClass($this->extendedClass); // Properties $classGenerator->addProperties($this->getProperties());