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); }
/** * {@inheritdoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass); $classGenerator->setExtendedClass($originalClass->getName()); $additionalInterfaces = ['OpenClassrooms\\ServiceProxy\\ServiceProxyInterface']; $additionalProperties['proxy_realSubject'] = new PropertyGenerator('proxy_realSubject', null, PropertyGenerator::FLAG_PRIVATE); $additionalMethods['setProxy_realSubject'] = new MethodGenerator('setProxy_realSubject', [['name' => 'realSubject']], MethodGenerator::FLAG_PUBLIC, '$this->proxy_realSubject = $realSubject;'); $methods = $originalClass->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $preSource = ''; $postSource = ''; $exceptionSource = ''; $methodAnnotations = $this->annotationReader->getMethodAnnotations($method); foreach ($methodAnnotations as $methodAnnotation) { if ($methodAnnotation instanceof Cache) { $additionalInterfaces['cache'] = 'OpenClassrooms\\ServiceProxy\\ServiceProxyCacheInterface'; $response = $this->cacheStrategy->execute($this->serviceProxyStrategyRequestBuilder->create()->withAnnotation($methodAnnotation)->withClass($originalClass)->withMethod($method)->build()); foreach ($response->getMethods() as $methodToAdd) { $additionalMethods[$methodToAdd->getName()] = $methodToAdd; } foreach ($response->getProperties() as $propertyToAdd) { $additionalProperties[$propertyToAdd->getName()] = $propertyToAdd; } $preSource .= $response->getPreSource(); $postSource .= $response->getPostSource(); $exceptionSource .= $response->getExceptionSource(); } } $classGenerator->addMethodFromGenerator($this->generateProxyMethod($method, $preSource, $postSource, $exceptionSource)); } $classGenerator->setImplementedInterfaces($additionalInterfaces); $classGenerator->addProperties($additionalProperties); $classGenerator->addMethods($additionalMethods); }
public function getClass() { $classGenerator = new ClassGenerator($this->collection, $this->namespace); $classGenerator->addUse('ArangoOdm\\Document', 'ArangoDoc'); $classGenerator->setExtendedClass('ArangoDoc'); $classGenerator->addMethods($this->getMethods()); return '<?php' . "\n\n" . $classGenerator->generate(); }
public function testMethodAccessors() { $classGenerator = new ClassGenerator(); $classGenerator->addMethods(array( 'methodOne', new MethodGenerator('methodTwo') )); $methods = $classGenerator->getMethods(); $this->assertEquals(count($methods), 2); $this->isInstanceOf(current($methods), '\Zend\Code\Generator\PhpMethod'); $method = $classGenerator->getMethod('methodOne'); $this->isInstanceOf($method, '\Zend\Code\Generator\PhpMethod'); $this->assertEquals($method->getName(), 'methodOne'); // add a new property $classGenerator->addMethod('methodThree'); $this->assertEquals(count($classGenerator->getMethods()), 3); }
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(); }
/** * Handle an associative property field * @param string $name - name of the field * @param \Zend\Code\Generator\ClassGenerator $cg - The class generator object to attach to * @param \Doctrine\ORM\Mapping\ClassMetadata $ormClassMetaData - The ORM class meta data */ private function handleAssocProperty($name, Generator\ClassGenerator &$cg, ORMClassMetadata $ormClassMetaData) { $assocMapping = $ormClassMetaData->getAssociationMapping($name); $property = $this->createProperty($name); if ($assocMapping['type'] & $ormClassMetaData::TO_MANY) { // This is a collection (should be an Array) $property->setDocBlock('@var array $' . $name); $property->setDefaultValue(array()); $paramType = self::PARAM_TYPE_RELATION_COLLECTION; } else { // This is a single relation $property->setDocBlock('@var ' . $assocMapping['targetEntity'] . ' $' . $name); $paramType = self::PARAM_TYPE_RELATION_SINGLE; } if (!$cg->hasProperty($name)) { $cg->addProperties(array($property)); $cg->addMethods($this->getSetterMethods($cg, $name, $paramType, $assocMapping['targetEntity'])); } }
/** * @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; }
protected function handleSecondClassElements(CodeGenerator\ClassGenerator $classGenerator, array &$map, DOMNodeList $secondClassElements, DOMNode $element, DOMXPath $xpath) { foreach ($secondClassElements as $secondClassElement) { $maxOccursNode = $xpath->query('@maxOccurs', $secondClassElement)->item(0); $maxOccurs = $maxOccursNode ? $maxOccursNode->textContent : null; $unbounded = $maxOccurs == 'unbounded'; $hydrationModifier = '#'; $secondClassElementName = null; $secondClassElementNameNode = $xpath->query('@name', $secondClassElement)->item(0); if ($secondClassElementNameNode) { $secondClassElementName = $secondClassElementNameNode->textContent; $this->generateResource($secondClassElement); } else { $secondClassElementNameNode = $xpath->query('@ref', $secondClassElement)->item(0); if ($secondClassElementNameNode) { if (substr($secondClassElementNameNode->textContent, 0, 4) == "tns:") { $secondClassElementName = substr($secondClassElementNameNode->textContent, 4); } elseif (substr($secondClassElementNameNode->textContent, 0, 5) == "data:") { $secondClassElementName = substr($secondClassElementNameNode->textContent, 5); } } } if (!$secondClassElementName) { continue; } $secondClassElementType = $secondClassElementName; if ($unbounded) { $secondClassElementType .= "[]"; } $propertyName = lcfirst($secondClassElementName); if ($unbounded) { $propertyName .= 's'; } $secondClassElementProperty = clone $this->getPropertyGenerator(); $secondClassElementProperty->setName($propertyName); if ($unbounded) { $secondClassElementProperty->setDefaultValue(new CodeGenerator\PropertyValueGenerator(array())); $hydrationModifier .= '@'; $mapKeyName = "{$secondClassElementName}s"; } else { $mapKeyName = $secondClassElementName; } if ($secondClassElementType) { $secondClassElementPropertyDocblock = clone $this->getPropertyDocblockGenerator(); $secondClassElementProperty->setDocBlock($secondClassElementPropertyDocblock); $typeTag = new CodeGenerator\DocBlock\Tag(); $typeTag->setName('var'); $typeTag->setDescription($secondClassElementType); $secondClassElementPropertyDocblock->setTag($typeTag); } $classGenerator->addPropertyFromGenerator($secondClassElementProperty); $getterGenerator = $this->generatePropertyGetter($propertyName); $setterGenerator = $this->generatePropertySetter($propertyName); $classGenerator->addMethods(array($getterGenerator, $setterGenerator)); $map["{$hydrationModifier}{$mapKeyName}"] = "_:{$secondClassElementName}"; } }
/** * Append methods to Api class * * @param Generator\ClassGenerator $class * @param string $operation * @param mixed $apiMetadata * @param FileGenerator $demoFile */ protected function generateApiOperationFromMetadata(Generator\ClassGenerator &$class, $httpMethod, $apiMetadata) { $console = $this->getServiceLocator()->get('console'); $modelClassName = 'Mailjet\\Model\\' . $class->getName(); $model = $class->getName(); $class->addUse('Zend\\Json\\Json')->addUse('Zend\\InputFilter'); $httpMethod = strtoupper($httpMethod); switch ($httpMethod) { case 'GET': if ($apiMetadata->Filters) { $class->addMethods(array(new Generator\MethodGenerator('getList', array(new Generator\ParameterGenerator('filters', 'array', array())), Generator\MethodGenerator::FLAG_PUBLIC, 'return parent::_list($filters);', new Generator\DocBlockGenerator("Return list of {$modelClassName}", "Return list of {$modelClassName} filtered by \$filters if provided" . PHP_EOL, array(new ParamTag(array('name' => 'filters', 'datatype' => 'array', 'description' => 'key/val filters')), new ReturnTag(array('datatype' => 'ResultSet\\ResultSet', 'description' => "List of {$modelClassName}"))))))); foreach ($apiMetadata->Filters as $filterInfo) { try { $filterName = $filterInfo->Name; $dataTypeInfos = $this->getNormalizedFilterOrProperty($filterInfo); $dataType = $dataTypeInfos['dataType']; foreach ($dataTypeInfos['uses'] as $use) { $class->addUse($use); } $isKey = $filterName == $apiMetadata->UniqueKey; if ($isKey) { $bodyMethod = sprintf('return $this->_get($%s);' . PHP_EOL, $filterName); } else { $bodyMethod = sprintf('$result = $this->getList(array(\'%s\' => $%s));' . PHP_EOL . 'return $result;', $filterName, $filterName); } $class->addMethods(array(new Generator\MethodGenerator('getBy' . $filterName, array(new Generator\ParameterGenerator($filterName, $dataType)), Generator\MethodGenerator::FLAG_PUBLIC, $bodyMethod, new Generator\DocBlockGenerator($isKey ? "Return {$modelClassName}" : "Return list of {$modelClassName} with {$filterName} = \${$filterName}", '', array(new ParamTag(array('name' => $filterName, 'datatype' => $dataType)), new ReturnTag(array('datatype' => $isKey ? $modelClassName : 'ResultSet\\ResultSet'))))))); } catch (\Exception $e) { $console->writeLine('[' . $class->getName() . ']' . $e->getMessage(), Color::YELLOW); } } $param = new Generator\ParameterGenerator('id', 'int'); $class->addMethods(array(new Generator\MethodGenerator('get', array($param), Generator\MethodGenerator::FLAG_PUBLIC, 'if (empty($id)) {' . PHP_EOL . ' throw new Exception\\InvalidArgumentException("You must specify the ID");' . PHP_EOL . '}' . PHP_EOL . PHP_EOL . 'return parent::_get($id);', new Generator\DocBlockGenerator("Return {$modelClassName} with id = \$id", '', array(new ParamTag(array('name' => 'id', 'datatype' => 'int', 'description' => 'Id of resource to get')), new ReturnTag(array('datatype' => $modelClassName))))))); } else { $class->addMethods(array(new Generator\MethodGenerator('current', array(), Generator\MethodGenerator::FLAG_PUBLIC, 'return parent::_get();', new Generator\DocBlockGenerator("Return current {$modelClassName}", '', array(new ReturnTag(array('datatype' => $modelClassName))))))); } break; case 'DELETE': $class->addMethods(array(new Generator\MethodGenerator('delete', array(new Generator\ParameterGenerator('id')), Generator\MethodGenerator::FLAG_PUBLIC, 'return parent::_delete($id);', new Generator\DocBlockGenerator("Delete the {$model} with id = \$id", '', array(new ParamTag(array('name' => 'id', 'datatype' => 'integer', 'description' => 'Id to delete')), new ReturnTag(array('datatype' => 'bool', 'description' => 'True on success'))))))); break; case 'POST': $modelParameter = new Generator\ParameterGenerator($model, $modelClassName); $modelParameter->setPassedByReference(true); $class->addMethods(array(new Generator\MethodGenerator('create', array($modelParameter), Generator\MethodGenerator::FLAG_PUBLIC, "return parent::_create(\${$model});", new Generator\DocBlockGenerator("Create a new {$model}", '', array(new ParamTag(array('name' => $model, 'datatype' => $modelClassName)), new ReturnTag(array('datatype' => "{$modelClassName}|false", 'description' => 'Object created or false'))))))); break; case 'PUT': $modelParameter = new Generator\ParameterGenerator($model, $modelClassName); $modelParameter->setPassedByReference(true); $class->addMethods(array(new Generator\MethodGenerator('update', array($modelParameter), Generator\MethodGenerator::FLAG_PUBLIC, "return parent::_update(\${$model});", new Generator\DocBlockGenerator("Update existing {$model}", '', array(new ParamTag(array('name' => $model, 'datatype' => $modelClassName)), new ReturnTag(array('datatype' => "{$modelClassName}|false", 'description' => 'Object created or false'))))))); break; default: break; } }
/** * Method for add methods for new form * For add more methods, add after $this->createMethodConstruct() */ private function addMethodsForNewFilter() { $this->newFilter->addMethods([$this->createMethodConstruct()]); }
/** * 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; }