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(); }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { $interfaces = array('ProxyManager\\Proxy\\GhostObjectInterface'); $publicProperties = new PublicPropertiesMap($originalClass); $publicPropsDefaults = new PublicPropertiesDefaults($originalClass); if ($originalClass->isInterface()) { $interfaces[] = $originalClass->getName(); } else { $classGenerator->setExtendedClass($originalClass->getName()); } $classGenerator->setImplementedInterfaces($interfaces); $classGenerator->addPropertyFromGenerator($initializer = new InitializerProperty()); $classGenerator->addPropertyFromGenerator($initializationTracker = new InitializationTracker()); $classGenerator->addPropertyFromGenerator($publicProperties); $classGenerator->addPropertyFromGenerator($publicPropsDefaults); $init = new CallInitializer($initializer, $publicPropsDefaults, $initializationTracker); $classGenerator->addMethodFromGenerator($init); foreach (ProxiedMethodsFilter::getProxiedMethods($originalClass) as $method) { $classGenerator->addMethodFromGenerator(LazyLoadingMethodInterceptor::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $initializer, $init)); } $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $initializer)); $classGenerator->addMethodFromGenerator(new MagicGet($originalClass, $initializer, $init, $publicProperties)); $classGenerator->addMethodFromGenerator(new MagicSet($originalClass, $initializer, $init, $publicProperties)); $classGenerator->addMethodFromGenerator(new MagicIsset($originalClass, $initializer, $init, $publicProperties)); $classGenerator->addMethodFromGenerator(new MagicUnset($originalClass, $initializer, $init, $publicProperties)); $classGenerator->addMethodFromGenerator(new MagicClone($originalClass, $initializer, $init)); $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $initializer, $init)); $classGenerator->addMethodFromGenerator(new SetProxyInitializer($initializer)); $classGenerator->addMethodFromGenerator(new GetProxyInitializer($initializer)); $classGenerator->addMethodFromGenerator(new InitializeProxy($initializer, $init)); $classGenerator->addMethodFromGenerator(new IsProxyInitialized($initializer)); }
/** * {@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) { $this->addCacheAnnotation($classGenerator); $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); }
/** * {@inheritDoc} */ public function setExtendedClass($extendedClass) : self { if ($extendedClass) { $extendedClass = '\\' . trim($extendedClass, '\\'); } return parent::setExtendedClass($extendedClass); }
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(); }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { $publicProperties = new PublicPropertiesMap($originalClass); $interfaces = array('ProxyManager\\Proxy\\AccessInterceptorInterface', 'ProxyManager\\Proxy\\ValueHolderInterface'); if ($originalClass->isInterface()) { $interfaces[] = $originalClass->getName(); } else { $classGenerator->setExtendedClass($originalClass->getName()); } $classGenerator->setImplementedInterfaces($interfaces); $classGenerator->addPropertyFromGenerator($valueHolder = new ValueHolderProperty()); $classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors()); $classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodSuffixInterceptors()); $classGenerator->addPropertyFromGenerator($publicProperties); foreach (ProxiedMethodsFilter::getProxiedMethods($originalClass) as $method) { $classGenerator->addMethodFromGenerator(InterceptedMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $valueHolder, $prefixInterceptors, $suffixInterceptors)); } $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors)); $classGenerator->addMethodFromGenerator(new GetWrappedValueHolderValue($valueHolder)); $classGenerator->addMethodFromGenerator(new SetMethodPrefixInterceptor($prefixInterceptors)); $classGenerator->addMethodFromGenerator(new SetMethodSuffixInterceptor($suffixInterceptors)); $classGenerator->addMethodFromGenerator(new MagicGet($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties)); $classGenerator->addMethodFromGenerator(new MagicSet($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties)); $classGenerator->addMethodFromGenerator(new MagicIsset($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties)); $classGenerator->addMethodFromGenerator(new MagicUnset($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties)); $classGenerator->addMethodFromGenerator(new MagicClone($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors)); $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $valueHolder)); $classGenerator->addMethodFromGenerator(new MagicWakeup($originalClass, $valueHolder)); }
public function getClass() { $classGenerator = new ClassGenerator($this->collection, $this->namespace); $classGenerator->addUse('ArangoOdm\\Document', 'ArangoDoc'); $classGenerator->setExtendedClass('ArangoDoc'); $classGenerator->addMethods($this->getMethods()); return '<?php' . "\n\n" . $classGenerator->generate(); }
public function generate(Generator\ClassGenerator $class, PHPClass $type) { if (!($extends = $type->getExtends()) && class_exists($type->getNamespace())) { $extendNamespace = $type->getNamespace(); $extendNamespace = explode('\\', $extendNamespace); $extendClass = array_pop($extendNamespace); $extendNamespace = implode('\\', $extendNamespace); $extends = new PHPClass(); $extends->setName($extendClass); $extends->setNamespace($extendNamespace); $class->setExtendedClass($extends); } if ($extends->getName() == "string" && $extends->getNamespace() == "" && class_exists($type->getNamespace() . '\\String')) { $extends->setName('String'); $extends->setNamespace($type->getNamespace()); } elseif ($extends->getName() == "string" && $extends->getNamespace() == "" && class_exists($type->getNamespace())) { $extendNamespace = $type->getNamespace(); $extendNamespace = explode('\\', $extendNamespace); $extendClass = array_pop($extendNamespace); $extendNamespace = implode('\\', $extendNamespace); $extends = new PHPClass(); $extends->setName($extendClass); $extends->setNamespace($extendNamespace); $class->setExtendedClass($extends); } $docblock = new DocBlockGenerator("Class representing " . $type->getName()); if ($type->getDoc()) { $docblock->setLongDescription($type->getDoc()); } $class->setNamespaceName($type->getNamespace()); $class->setName($type->getName()); $class->setDocblock($docblock); $class->setExtendedClass($extends->getName()); if ($extends->getNamespace() != $type->getNamespace()) { if ($extends->getName() == $type->getName()) { $class->addUse($type->getExtends()->getFullName(), $extends->getName() . "Base"); $class->setExtendedClass($extends->getName() . "Base"); } else { $class->addUse($extends->getFullName()); } } if ($this->handleBody($class, $type)) { return true; } }
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(); }
/** * Build generators * * @param State|\Scaffold\State $state * @return \Scaffold\State|void */ public function build(State $state) { $model = $state->getRepositoryModel(); $generator = new ClassGenerator($model->getName()); $generator->addUse('Doctrine\\ORM\\EntityRepository'); $generator->addUse($state->getEntityModel()->getName()); $generator->setExtendedClass('EntityRepository'); $this->buildFactory($generator); $model->setGenerator($generator); }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass, false); $classGenerator->setExtendedClass($originalClass->getName()); $classGenerator->setImplementedInterfaces([AccessInterceptorInterface::class]); $classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors()); $classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodSuffixInterceptors()); array_map(function (MethodGenerator $generatedMethod) use($originalClass, $classGenerator) { ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod); }, array_merge(array_map($this->buildMethodInterceptor($prefixInterceptors, $suffixInterceptors), ProxiedMethodsFilter::getProxiedMethods($originalClass, ['__get', '__set', '__isset', '__unset', '__clone', '__sleep'])), [new StaticProxyConstructor($originalClass, $prefixInterceptors, $suffixInterceptors), new BindProxyProperties($originalClass, $prefixInterceptors, $suffixInterceptors), new SetMethodPrefixInterceptor($prefixInterceptors), new SetMethodSuffixInterceptor($suffixInterceptors), new MagicGet($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicSet($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicIsset($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicUnset($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicSleep($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicClone($originalClass, $prefixInterceptors, $suffixInterceptors)])); }
/** * @param \ReflectionClass $originalClass * @param ClassGenerator $classGenerator */ public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator) { $classGenerator->setExtendedClass('\\' . $originalClass->getName()); if ($originalClass->isSubclassOf(Collection::class)) { $reflectionMethod = new \ReflectionMethod($originalClass->getName(), 'getMetadata'); $className = $originalClass->getName(); $metadata = $reflectionMethod->invoke(new $className()); foreach ($metadata as $fieldName => $mappingClass) { $classGenerator->addMethod('get' . ucfirst($fieldName), [], MethodGenerator::FLAG_PUBLIC, '$this->mapProperty(\'' . $fieldName . '\');' . "\n" . 'return parent::get' . ucfirst($fieldName) . '();', '@return ' . $mappingClass); } } }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass, false); $classGenerator->setExtendedClass($originalClass->getName()); $classGenerator->setImplementedInterfaces(array('ProxyManager\\Proxy\\AccessInterceptorInterface')); $classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors()); $classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodPrefixInterceptors()); array_map(function (MethodGenerator $generatedMethod) use($originalClass, $classGenerator) { ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod); }, array_merge(array_map(function (ReflectionMethod $method) use($prefixInterceptors, $suffixInterceptors) { return InterceptedMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $prefixInterceptors, $suffixInterceptors); }, ProxiedMethodsFilter::getProxiedMethods($originalClass, array('__get', '__set', '__isset', '__unset', '__clone', '__sleep'))), array(new Constructor($originalClass, $prefixInterceptors, $suffixInterceptors), new SetMethodPrefixInterceptor($prefixInterceptors), new SetMethodSuffixInterceptor($suffixInterceptors), new MagicGet($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicSet($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicIsset($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicUnset($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicSleep($originalClass, $prefixInterceptors, $suffixInterceptors), new MagicClone($originalClass, $prefixInterceptors, $suffixInterceptors)))); }
/** * 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; }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass); $interfaces = [RemoteObjectInterface::class]; if ($originalClass->isInterface()) { $interfaces[] = $originalClass->getName(); } else { $classGenerator->setExtendedClass($originalClass->getName()); } $classGenerator->setImplementedInterfaces($interfaces); $classGenerator->addPropertyFromGenerator($adapter = new AdapterProperty()); array_map(function (MethodGenerator $generatedMethod) use($originalClass, $classGenerator) { ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod); }, array_merge(array_map(function (ReflectionMethod $method) use($adapter, $originalClass) : RemoteObjectMethod { return RemoteObjectMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $adapter, $originalClass); }, ProxiedMethodsFilter::getProxiedMethods($originalClass, ['__get', '__set', '__isset', '__unset'])), [new StaticProxyConstructor($originalClass, $adapter), new MagicGet($originalClass, $adapter), new MagicSet($originalClass, $adapter), new MagicIsset($originalClass, $adapter), new MagicUnset($originalClass, $adapter)])); }
/** * Generates a dynamic class implementing specified interfaces (and ServiceAwareInterface). * @return string class name */ public function build() { $generator = new ClassGenerator(uniqid('Proxy_'), 'SoPhp\\Rpc\\Proxy'); $generator->setImplementedInterfaces($this->getImplements()); $generator->setExtendedClass('\\SoPhp\\Rpc\\Proxy\\ProxyAbstract'); $source = $generator->generate(); $className = $generator->getNamespaceName() . '\\' . $generator->getName(); try { eval($source); } catch (\Exception $e) { throw new BuildFailed("Could not evaluate source code for proxy. " . $source, 0, $e); } if (!class_exists($className, false)) { throw new BuildFailed("Proxy class `{$className}` does not exist"); } return $className; }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass); $interfaces = [VirtualProxyInterface::class]; $publicProperties = new PublicPropertiesMap(Properties::fromReflectionClass($originalClass)); if ($originalClass->isInterface()) { $interfaces[] = $originalClass->getName(); } else { $classGenerator->setExtendedClass($originalClass->getName()); } $classGenerator->setImplementedInterfaces($interfaces); $classGenerator->addPropertyFromGenerator($valueHolder = new ValueHolderProperty()); $classGenerator->addPropertyFromGenerator($initializer = new InitializerProperty()); $classGenerator->addPropertyFromGenerator($publicProperties); array_map(function (MethodGenerator $generatedMethod) use($originalClass, $classGenerator) { ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod); }, array_merge(array_map($this->buildLazyLoadingMethodInterceptor($initializer, $valueHolder), ProxiedMethodsFilter::getProxiedMethods($originalClass)), [new StaticProxyConstructor($initializer, Properties::fromReflectionClass($originalClass)), Constructor::generateMethod($originalClass, $valueHolder), new MagicGet($originalClass, $initializer, $valueHolder, $publicProperties), new MagicSet($originalClass, $initializer, $valueHolder, $publicProperties), new MagicIsset($originalClass, $initializer, $valueHolder, $publicProperties), new MagicUnset($originalClass, $initializer, $valueHolder, $publicProperties), new MagicClone($originalClass, $initializer, $valueHolder), new MagicSleep($originalClass, $initializer, $valueHolder), new MagicWakeup($originalClass), new SetProxyInitializer($initializer), new GetProxyInitializer($initializer), new InitializeProxy($initializer, $valueHolder), new IsProxyInitialized($valueHolder), new GetWrappedValueHolderValue($valueHolder)])); }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator, array $proxyOptions = []) { CanProxyAssertion::assertClassCanBeProxied($originalClass, false); $filteredProperties = Properties::fromReflectionClass($originalClass)->filter(isset($proxyOptions['skippedProperties']) ? $proxyOptions['skippedProperties'] : []); $publicProperties = new PublicPropertiesMap($filteredProperties); $privateProperties = new PrivatePropertiesMap($filteredProperties); $protectedProperties = new ProtectedPropertiesMap($filteredProperties); $classGenerator->setExtendedClass($originalClass->getName()); $classGenerator->setImplementedInterfaces([GhostObjectInterface::class]); $classGenerator->addPropertyFromGenerator($initializer = new InitializerProperty()); $classGenerator->addPropertyFromGenerator($initializationTracker = new InitializationTracker()); $classGenerator->addPropertyFromGenerator($publicProperties); $classGenerator->addPropertyFromGenerator($privateProperties); $classGenerator->addPropertyFromGenerator($protectedProperties); $init = new CallInitializer($initializer, $initializationTracker, $filteredProperties); array_map(function (MethodGenerator $generatedMethod) use($originalClass, $classGenerator) { ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod); }, array_merge($this->getAbstractProxiedMethods($originalClass), [$init, new StaticProxyConstructor($initializer, $filteredProperties), new MagicGet($originalClass, $initializer, $init, $publicProperties, $protectedProperties, $privateProperties, $initializationTracker), new MagicSet($originalClass, $initializer, $init, $publicProperties, $protectedProperties, $privateProperties), new MagicIsset($originalClass, $initializer, $init, $publicProperties, $protectedProperties, $privateProperties), new MagicUnset($originalClass, $initializer, $init, $publicProperties, $protectedProperties, $privateProperties), new MagicClone($originalClass, $initializer, $init, $publicProperties), new MagicSleep($originalClass, $initializer, $init, $publicProperties), new SetProxyInitializer($initializer), new GetProxyInitializer($initializer), new InitializeProxy($initializer, $init), new IsProxyInitialized($initializer)])); }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass); $interfaces = array('ProxyManager\\Proxy\\VirtualProxyInterface'); $publicProperties = new PublicPropertiesMap($originalClass); if ($originalClass->isInterface()) { $interfaces[] = $originalClass->getName(); } else { $classGenerator->setExtendedClass($originalClass->getName()); } $classGenerator->setImplementedInterfaces($interfaces); $classGenerator->addPropertyFromGenerator($valueHolder = new ValueHolderProperty()); $classGenerator->addPropertyFromGenerator($initializer = new InitializerProperty()); $classGenerator->addPropertyFromGenerator($publicProperties); array_map(function (MethodGenerator $generatedMethod) use($originalClass, $classGenerator) { ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod); }, array_merge(array_map(function (ReflectionMethod $method) use($initializer, $valueHolder) { return LazyLoadingMethodInterceptor::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $initializer, $valueHolder); }, ProxiedMethodsFilter::getProxiedMethods($originalClass)), array(new Constructor($originalClass, $initializer), new MagicGet($originalClass, $initializer, $valueHolder, $publicProperties), new MagicSet($originalClass, $initializer, $valueHolder, $publicProperties), new MagicIsset($originalClass, $initializer, $valueHolder, $publicProperties), new MagicUnset($originalClass, $initializer, $valueHolder, $publicProperties), new MagicClone($originalClass, $initializer, $valueHolder), new MagicSleep($originalClass, $initializer, $valueHolder), new MagicWakeup($originalClass), new SetProxyInitializer($initializer), new GetProxyInitializer($initializer), new InitializeProxy($initializer, $valueHolder), new IsProxyInitialized($valueHolder), new GetWrappedValueHolderValue($valueHolder)))); }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { $interfaces = array('ProxyManager\\Proxy\\RemoteObjectInterface'); if ($originalClass->isInterface()) { $interfaces[] = $originalClass->getName(); } else { $classGenerator->setExtendedClass($originalClass->getName()); } $classGenerator->setImplementedInterfaces($interfaces); $classGenerator->addPropertyFromGenerator($adapter = new AdapterProperty()); $methods = ProxiedMethodsFilter::getProxiedMethods($originalClass, array('__get', '__set', '__isset', '__unset')); foreach ($methods as $method) { $classGenerator->addMethodFromGenerator(RemoteObjectMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $adapter, $originalClass)); } $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $adapter)); $classGenerator->addMethodFromGenerator(new MagicGet($originalClass, $adapter)); $classGenerator->addMethodFromGenerator(new MagicSet($originalClass, $adapter)); $classGenerator->addMethodFromGenerator(new MagicIsset($originalClass, $adapter)); $classGenerator->addMethodFromGenerator(new MagicUnset($originalClass, $adapter)); }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass); $publicProperties = new PublicPropertiesMap(Properties::fromReflectionClass($originalClass)); $interfaces = [AccessInterceptorInterface::class, ValueHolderInterface::class]; if ($originalClass->isInterface()) { $interfaces[] = $originalClass->getName(); } else { $classGenerator->setExtendedClass($originalClass->getName()); } $classGenerator->setImplementedInterfaces($interfaces); $classGenerator->addPropertyFromGenerator($valueHolder = new ValueHolderProperty()); $classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors()); $classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodSuffixInterceptors()); $classGenerator->addPropertyFromGenerator($publicProperties); array_map(function (MethodGenerator $generatedMethod) use($originalClass, $classGenerator) { ClassGeneratorUtils::addMethodIfNotFinal($originalClass, $classGenerator, $generatedMethod); }, array_merge(array_map(function (ReflectionMethod $method) use($prefixInterceptors, $suffixInterceptors, $valueHolder) { return InterceptedMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $valueHolder, $prefixInterceptors, $suffixInterceptors); }, ProxiedMethodsFilter::getProxiedMethods($originalClass)), [Constructor::generateMethod($originalClass, $valueHolder), new StaticProxyConstructor($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors), new GetWrappedValueHolderValue($valueHolder), new SetMethodPrefixInterceptor($prefixInterceptors), new SetMethodSuffixInterceptor($suffixInterceptors), new MagicGet($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties), new MagicSet($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties), new MagicIsset($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties), new MagicUnset($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors, $publicProperties), new MagicClone($originalClass, $valueHolder, $prefixInterceptors, $suffixInterceptors), new MagicSleep($originalClass, $valueHolder), new MagicWakeup($originalClass, $valueHolder)])); }
/** * {@inheritDoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { if ($originalClass->isInterface()) { throw InvalidProxiedClassException::interfaceNotSupported($originalClass); } $classGenerator->setExtendedClass($originalClass->getName()); $classGenerator->setImplementedInterfaces(array('ProxyManager\\Proxy\\AccessInterceptorInterface')); $classGenerator->addPropertyFromGenerator($prefixInterceptors = new MethodPrefixInterceptors()); $classGenerator->addPropertyFromGenerator($suffixInterceptors = new MethodPrefixInterceptors()); $methods = ProxiedMethodsFilter::getProxiedMethods($originalClass, array('__get', '__set', '__isset', '__unset', '__clone', '__sleep')); foreach ($methods as $method) { $classGenerator->addMethodFromGenerator(InterceptedMethod::generateMethod(new MethodReflection($method->getDeclaringClass()->getName(), $method->getName()), $prefixInterceptors, $suffixInterceptors)); } $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $prefixInterceptors, $suffixInterceptors)); $classGenerator->addMethodFromGenerator(new SetMethodPrefixInterceptor($prefixInterceptors)); $classGenerator->addMethodFromGenerator(new SetMethodSuffixInterceptor($suffixInterceptors)); $classGenerator->addMethodFromGenerator(new MagicGet($originalClass, $prefixInterceptors, $suffixInterceptors)); $classGenerator->addMethodFromGenerator(new MagicSet($originalClass, $prefixInterceptors, $suffixInterceptors)); $classGenerator->addMethodFromGenerator(new MagicIsset($originalClass, $prefixInterceptors, $suffixInterceptors)); $classGenerator->addMethodFromGenerator(new MagicUnset($originalClass, $prefixInterceptors, $suffixInterceptors)); $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $prefixInterceptors, $suffixInterceptors)); $classGenerator->addMethodFromGenerator(new MagicClone($originalClass, $prefixInterceptors, $suffixInterceptors)); }
public function testExtendedClassAccessors() { $classGenerator = new ClassGenerator(); $classGenerator->setExtendedClass('ExtendedClass'); $this->assertEquals($classGenerator->getExtendedClass(), 'ExtendedClass'); }
use Zend\Code\Generator\ValueGenerator; 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() . ';');
/** * @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; }
/** * Create view helper class * * @return bool */ public function createViewHelper() { // get needed options to shorten code $moduleName = $this->requestOptions->getModuleName(); $viewHelperClass = $this->requestOptions->getViewHelperClass(); $viewHelperPath = $this->requestOptions->getViewHelperPath(); $viewHelperFile = $this->requestOptions->getViewHelperFile(); $viewHelperFilePath = $viewHelperPath . $viewHelperFile; // create dirs if (!file_exists($viewHelperPath)) { mkdir($viewHelperPath, 0777, true); } // create controller class with class generator $code = new ClassGenerator(); $code->setNamespaceName($moduleName . '\\View\\Helper'); $code->addUse('Zend\\View\\Helper\\AbstractHelper'); $code->setName($viewHelperClass); $code->setExtendedClass('AbstractHelper'); $code->addMethodFromGenerator($this->generateViewHelperMethod($viewHelperClass)); // add optional doc block if ($this->flagCreateApiDocs) { $code->setDocBlock(new DocBlockGenerator('View helper ' . $viewHelperClass, 'Please add a proper description for the ' . $viewHelperClass . ' view helper', 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($viewHelperFilePath, $file->generate())) { return false; } return true; }
/** * 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; }
/** * {@inheritDoc} * @throws InvalidProxiedClassException * @throws InvalidArgumentException */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass, false); $annotation = null; $forceLazyInitProperty = new ForceLazyInitProperty(); $sessionBeansProperty = new SessionBeansProperty(); $postProcessorsProperty = new BeanPostProcessorsProperty(); $parameterValuesProperty = new ParameterValuesProperty(); $beanFactoryConfigurationProperty = new BeanFactoryConfigurationProperty(); $aliasesProperty = new AliasesProperty(); $getParameterMethod = new GetParameter($originalClass, $parameterValuesProperty); $wrapBeanAsLazyMethod = new WrapBeanAsLazy($originalClass, $beanFactoryConfigurationProperty); try { $reader = new AnnotationReader(); $annotation = $reader->getClassAnnotation($originalClass, Configuration::class); } catch (Exception $e) { throw new InvalidProxiedClassException($e->getMessage(), $e->getCode(), $e); } if (null === $annotation) { throw new InvalidProxiedClassException(sprintf('"%s" seems not to be a valid configuration class. @Configuration annotation missing!', $originalClass->getName())); } $classGenerator->setExtendedClass($originalClass->getName()); $classGenerator->setImplementedInterfaces([AliasContainerInterface::class]); $classGenerator->addPropertyFromGenerator($forceLazyInitProperty); $classGenerator->addPropertyFromGenerator($sessionBeansProperty); $classGenerator->addPropertyFromGenerator($postProcessorsProperty); $classGenerator->addPropertyFromGenerator($parameterValuesProperty); $classGenerator->addPropertyFromGenerator($beanFactoryConfigurationProperty); $classGenerator->addPropertyFromGenerator($aliasesProperty); $postProcessorMethods = []; $aliases = []; $methods = $originalClass->getMethods(ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED); foreach ($methods as $method) { if (null !== $reader->getMethodAnnotation($method, BeanPostProcessor::class)) { $postProcessorMethods[] = $method->getName(); continue; } /* @var \bitExpert\Disco\Annotations\Bean $beanAnnotation */ $beanAnnotation = $reader->getMethodAnnotation($method, Bean::class); if (null === $beanAnnotation) { throw new InvalidProxiedClassException(sprintf('Method "%s" on "%s" is missing the @Bean annotation!', $method->getName(), $originalClass->getName())); } // if alias is defined append it to the aliases list if ($beanAnnotation->getAlias() !== '' && !isset($aliases[$beanAnnotation->getAlias()])) { $aliases[$beanAnnotation->getAlias()] = $method->getName(); } /* @var \bitExpert\Disco\Annotations\Parameters $parametersAnnotation */ $parametersAnnotation = $reader->getMethodAnnotation($method, Parameters::class); if (null === $parametersAnnotation) { $parametersAnnotation = new Parameters(); } $beanType = $method->getReturnType(); if (null === $beanType) { throw new InvalidProxiedClassException(sprintf('Method "%s" on "%s" is missing the return typehint!', $method->getName(), $originalClass->getName())); } $beanType = (string) $beanType; if (!in_array($beanType, ['array', 'callable', 'bool', 'float', 'int', 'string']) && !class_exists($beanType) && !interface_exists($beanType)) { throw new InvalidProxiedClassException(sprintf('Return type of method "%s" on "%s" cannot be found! Did you use the full qualified name?', $method->getName(), $originalClass->getName())); } $methodReflection = new MethodReflection($method->class, $method->getName()); $proxyMethod = BeanMethod::generateMethod($methodReflection, $beanAnnotation, $parametersAnnotation, $beanType, $forceLazyInitProperty, $sessionBeansProperty, $postProcessorsProperty, $beanFactoryConfigurationProperty, $getParameterMethod, $wrapBeanAsLazyMethod); $classGenerator->addMethodFromGenerator($proxyMethod); } $aliasesProperty->setDefaultValue($aliases); $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $parameterValuesProperty, $sessionBeansProperty, $beanFactoryConfigurationProperty, $postProcessorsProperty, $postProcessorMethods)); $classGenerator->addMethodFromGenerator($wrapBeanAsLazyMethod); $classGenerator->addMethodFromGenerator($getParameterMethod); $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $sessionBeansProperty)); $classGenerator->addMethodFromGenerator(new GetAlias($originalClass, $aliasesProperty)); $classGenerator->addMethodFromGenerator(new HasAlias($originalClass, $aliasesProperty)); }
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(); }