Example #1
0
 public function testToString()
 {
     $classReflection = new ClassReflection('ZendTest\\Code\\Reflection\\TestAsset\\TestSampleClass5');
     $classDocBlock = $classReflection->getDocBlock();
     $expectedString = 'DocBlock [ /* DocBlock */ ] {' . PHP_EOL . PHP_EOL . '  - Tags [3] {' . PHP_EOL . '    DocBlock Tag [ * @author ]' . PHP_EOL . '    DocBlock Tag [ * @method ]' . PHP_EOL . '    DocBlock Tag [ * @property ]' . PHP_EOL . '  }' . PHP_EOL . '}' . PHP_EOL;
     $this->assertEquals($expectedString, (string) $classDocBlock);
 }
 /**
  * Build a Code Generation Php Object from a Class Reflection
  *
  * @param  ClassReflection $classReflection
  * @return InterfaceGenerator
  */
 public static function fromReflection(ClassReflection $classReflection)
 {
     if (!$classReflection->isInterface()) {
         throw new Exception\InvalidArgumentException(sprintf('Class %s is not a interface', $classReflection->getName()));
     }
     // class generator
     $cg = new static($classReflection->getName());
     $methods = [];
     $cg->setSourceContent($cg->getSourceContent());
     $cg->setSourceDirty(false);
     if ($classReflection->getDocComment() != '') {
         $cg->setDocBlock(DocBlockGenerator::fromReflection($classReflection->getDocBlock()));
     }
     // set the namespace
     if ($classReflection->inNamespace()) {
         $cg->setNamespaceName($classReflection->getNamespaceName());
     }
     foreach ($classReflection->getMethods() as $reflectionMethod) {
         $className = $cg->getNamespaceName() ? $cg->getNamespaceName() . '\\' . $cg->getName() : $cg->getName();
         if ($reflectionMethod->getDeclaringClass()->getName() == $className) {
             $methods[] = MethodGenerator::fromReflection($reflectionMethod);
         }
     }
     foreach ($classReflection->getConstants() as $name => $value) {
         $cg->addConstant($name, $value);
     }
     $cg->addMethods($methods);
     return $cg;
 }
 public function testAllowsMultipleParsingStrategies()
 {
     $genericParser = new Annotation\Parser\GenericAnnotationParser();
     $genericParser->registerAnnotation(__NAMESPACE__ . '\\TestAsset\\Foo');
     $doctrineParser = new Annotation\Parser\DoctrineAnnotationParser();
     $doctrineParser->registerAnnotation(__NAMESPACE__ . '\\TestAsset\\DoctrineAnnotation');
     $this->manager->attach($genericParser);
     $this->manager->attach($doctrineParser);
     $reflection = new Reflection\ClassReflection(__NAMESPACE__ . '\\TestAsset\\EntityWithMixedAnnotations');
     $prop = $reflection->getProperty('test');
     $annotations = $prop->getAnnotations($this->manager);
     $this->assertTrue($annotations->hasAnnotation(__NAMESPACE__ . '\\TestAsset\\Foo'));
     $this->assertTrue($annotations->hasAnnotation(__NAMESPACE__ . '\\TestAsset\\DoctrineAnnotation'));
     $this->assertFalse($annotations->hasAnnotation(__NAMESPACE__ . '\\TestAsset\\Bar'));
     foreach ($annotations as $annotation) {
         switch (get_class($annotation)) {
             case __NAMESPACE__ . '\\TestAsset\\Foo':
                 $this->assertEquals('first', $annotation->content);
                 break;
             case __NAMESPACE__ . '\\TestAsset\\DoctrineAnnotation':
                 $this->assertEquals(array('foo' => 'bar', 'bar' => 'baz'), $annotation->value);
                 break;
             default:
                 $this->fail('Received unexpected annotation "' . get_class($annotation) . '"');
         }
     }
 }
 /**
  * Generate view content
  *
  * @param string          $moduleName
  * @param ClassReflection $loadedEntity
  */
 protected function addContent($moduleName, ClassReflection $loadedEntity)
 {
     // prepare some params
     $moduleIdentifier = $this->filterCamelCaseToUnderscore($moduleName);
     $entityName = $loadedEntity->getShortName();
     $entityParam = lcfirst($entityName);
     $formParam = lcfirst(str_replace('Entity', '', $loadedEntity->getShortName())) . 'DataForm';
     $moduleRoute = $this->filterCamelCaseToDash($moduleName);
     // set action body
     $body = [];
     $body[] = 'use ' . $loadedEntity->getName() . ';';
     $body[] = '';
     $body[] = '/** @var ' . $entityName . ' $' . $entityParam . ' */';
     $body[] = '$' . $entityParam . ' = $this->' . $entityParam . ';';
     $body[] = '';
     $body[] = '$this->h1(\'' . $moduleIdentifier . '_title_update\');';
     $body[] = '';
     $body[] = '$this->' . $formParam . '->setAttribute(\'action\', $this->url(\'' . $moduleRoute . '/update\', [\'id\' => $' . $entityParam . '->getIdentifier()]));';
     $body[] = '';
     $body[] = 'echo $this->bootstrapForm($this->' . $formParam . ');';
     $body[] = '?>';
     $body[] = '<p>';
     $body[] = '    <a class="btn btn-primary" href="<?php echo $this->url(\'' . $moduleRoute . '\'); ?>">';
     $body[] = '        <i class="fa fa-table"></i>';
     $body[] = '        <?php echo $this->translate(\'' . $moduleIdentifier . '_action_index\'); ?>';
     $body[] = '    </a>';
     $body[] = '</p>';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // add method
     $this->setContent($body);
 }
Example #5
0
    public function testRetrievingMethodsShouldReturnClassMethodObjects()
    {
        $methods = $this->parser->getMethods();

        $this->assertEquals(count($this->class->getMethods(\ReflectionMethod::IS_PUBLIC)), count($methods));
        foreach ($methods as $method) {
            $this->assertInstanceOf('Zend\DocBook\ClassMethod', $method);
        }
    }
 /**
  * Generate code to cache from class reflection.
  *
  * @todo maybe move some of this into Zend\Code
  *
  * @param  ClassReflection $classReflection
  * @return string
  */
 public function getCacheCode(ClassReflection $classReflection)
 {
     $useString = $this->fileReflectionService->getUseString($classReflection->getDeclaringFile());
     $declaration = $this->classDeclarationService->getClassDeclaration($classReflection);
     $classContents = $classReflection->getContents(false);
     $classFileDir = dirname($classReflection->getFileName());
     $classContents = trim(str_replace('__DIR__', sprintf("'%s'", $classFileDir), $classContents));
     $return = "\nnamespace " . $classReflection->getNamespaceName() . " {\n" . $useString . $declaration . "\n" . $classContents . "\n}\n";
     return $return;
 }
Example #7
0
 /**
  * @return AnnotationCollection
  */
 public function getAnnotations()
 {
     $reflection = new ClassReflection($this->getObject());
     try {
         $reflectionMethod = $reflection->getMethod($this->getMethod());
         return $reflectionMethod->getAnnotations($this->getAnnotationManager());
     } catch (\ReflectionException $e) {
         return false;
     }
 }
 /**
  * @param ClassReflection $class
  * @return bool
  */
 public function isSatisfiedBy(ClassReflection $class)
 {
     $docBlock = $class->getDocBlock();
     if ($docBlock) {
         if ($docBlock->getTags('Annotation')) {
             return true;
         }
     }
     return false;
 }
Example #9
0
 /**
  * Build a Code Generation Php Object from a Class Reflection
  *
  * @param  ClassReflection $classReflection
  * @return TraitGenerator
  */
 public static function fromReflection(ClassReflection $classReflection)
 {
     // class generator
     $cg = new static($classReflection->getName());
     $cg->setSourceContent($cg->getSourceContent());
     $cg->setSourceDirty(false);
     if ($classReflection->getDocComment() != '') {
         $cg->setDocBlock(DocBlockGenerator::fromReflection($classReflection->getDocBlock()));
     }
     // set the namespace
     if ($classReflection->inNamespace()) {
         $cg->setNamespaceName($classReflection->getNamespaceName());
     }
     $properties = array();
     foreach ($classReflection->getProperties() as $reflectionProperty) {
         if ($reflectionProperty->getDeclaringClass()->getName() == $classReflection->getName()) {
             $properties[] = PropertyGenerator::fromReflection($reflectionProperty);
         }
     }
     $cg->addProperties($properties);
     $methods = array();
     foreach ($classReflection->getMethods() as $reflectionMethod) {
         $className = $cg->getNamespaceName() ? $cg->getNamespaceName() . '\\' . $cg->getName() : $cg->getName();
         if ($reflectionMethod->getDeclaringClass()->getName() == $className) {
             $methods[] = MethodGenerator::fromReflection($reflectionMethod);
         }
     }
     $cg->addMethods($methods);
     return $cg;
 }
 /**
  * Generate view content
  *
  * @param string          $moduleName
  * @param ClassReflection $loadedEntity
  */
 protected function addContent($moduleName, ClassReflection $loadedEntity)
 {
     // prepare some params
     $moduleIdentifier = $this->filterCamelCaseToUnderscore($moduleName);
     $entityName = $loadedEntity->getShortName();
     $entityParam = lcfirst($entityName);
     $listParam = lcfirst(str_replace('Entity', '', $entityName)) . 'List';
     $moduleRoute = $this->filterCamelCaseToDash($moduleName);
     // set action body
     $body = [];
     $body[] = 'use ' . $loadedEntity->getName() . ';';
     $body[] = '';
     $body[] = '$this->h1(\'' . $moduleIdentifier . '_title_index\');';
     $body[] = '?>';
     $body[] = '<table class="table table-bordered table-striped">';
     $body[] = '    <thead>';
     $body[] = '    <tr>';
     foreach ($loadedEntity->getProperties() as $property) {
         $body[] = '        <th><?php echo $this->translate(\'' . $moduleIdentifier . '_label_' . $this->filterCamelCaseToUnderscore($property->getName()) . '\'); ?></th>';
     }
     $body[] = '        <th width="95">';
     $body[] = '            <a class="btn btn-default btn-xs" href="<?php echo $this->url(\'' . $moduleRoute . '/create\'); ?>" title="<?php echo $this->translate(\'' . $moduleIdentifier . '_action_create\'); ?>">';
     $body[] = '                <i class="fa fa-plus"></i>';
     $body[] = '            </a>';
     $body[] = '        </th>';
     $body[] = '    </tr>';
     $body[] = '    </thead>';
     $body[] = '    <tbody>';
     $body[] = '    <?php /** @var ' . $entityName . ' $' . $entityParam . ' */ ?>';
     $body[] = '    <?php foreach ($this->' . $listParam . ' as $' . $entityParam . '): ?>';
     $body[] = '        <tr>';
     foreach ($loadedEntity->getProperties() as $property) {
         $methodName = 'get' . ucfirst($property->getName());
         $body[] = '            <td><?php echo $' . $entityParam . '->' . $methodName . '() ?></td>';
     }
     $body[] = '            <td>';
     $body[] = '                <a class="btn btn-default btn-xs" href="<?php echo $this->url(\'' . $moduleRoute . '/show\', [\'id\' => $' . $entityParam . '->getIdentifier()]); ?>" title="<?php echo $this->translate(\'' . $moduleIdentifier . '_action_show\'); ?>">';
     $body[] = '                    <i class="fa fa-search"></i>';
     $body[] = '                </a>';
     $body[] = '                <a class="btn btn-default btn-xs" href="<?php echo $this->url(\'' . $moduleRoute . '/update\', [\'id\' => $' . $entityParam . '->getIdentifier()]); ?>" title="<?php echo $this->translate(\'' . $moduleIdentifier . '_action_update\'); ?>">';
     $body[] = '                    <i class="fa fa-pencil"></i>';
     $body[] = '                </a>';
     $body[] = '                <a class="btn btn-default btn-xs" href="<?php echo $this->url(\'' . $moduleRoute . '/delete\', [\'id\' => $' . $entityParam . '->getIdentifier()]); ?>" title="<?php echo $this->translate(\'' . $moduleIdentifier . '_action_delete\'); ?>">';
     $body[] = '                    <i class="fa fa-trash"></i>';
     $body[] = '                </a>';
     $body[] = '            </td>';
     $body[] = '        </tr>';
     $body[] = '    <?php endforeach; ?>';
     $body[] = '    </tbody>';
     $body[] = '</table>';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // add method
     $this->setContent($body);
 }
Example #11
0
 private function shouldSkip(ClassReflection $class)
 {
     if ($class->isInternal()) {
         return true;
     }
     foreach ($this->skip as $prefix) {
         if (strpos($class->getName(), $prefix) === 0) {
             return true;
         }
     }
     return false;
 }
 private function getParentName(ClassReflection $classReflection)
 {
     $parentName = false;
     if (($parent = $classReflection->getParentClass()) && $classReflection->getNamespaceName()) {
         $parentName = $this->classUseNameService->getClassUseName($classReflection, $parent);
     } else {
         if ($parent && !$classReflection->getNamespaceName()) {
             $parentName = '\\' . $parent->getName();
         }
     }
     return $parentName;
 }
Example #13
0
 /**
  * Process the command
  *
  * @return integer
  */
 public function processCommandTask()
 {
     // initialize action list
     $loadedActions = [];
     // loop through controllers by module
     foreach ($this->params->loadedControllers as $moduleKey => $controllerTypes) {
         $loadedActions[$moduleKey] = [];
         $moduleViewPath = $this->filterCamelCaseToDash($moduleKey);
         // loop through controllers by controller type
         foreach ($controllerTypes as $controllerList) {
             // loop through controllers
             foreach ($controllerList as $controllerKey => $controllerClass) {
                 $loadedActions[$moduleKey][$controllerKey] = [];
                 // start class reflection
                 $classReflection = new ClassReflection($controllerClass);
                 // convert method name to get dashed action
                 $controllerName = substr($classReflection->getShortName(), 0, -10);
                 $controllerName = $this->filterCamelCaseToDash($controllerName);
                 // get public methods
                 $methods = $classReflection->getMethods(ReflectionMethod::IS_PUBLIC);
                 // loop through methods
                 foreach ($methods as $method) {
                     // get class and method name
                     $methodClass = $method->getDeclaringClass()->getName();
                     $methodName = $method->name;
                     // continue for methods from extended class
                     if ($methodClass != $controllerClass) {
                         continue;
                     }
                     // continue for no-action methods
                     if (substr($methodName, -6) != 'Action') {
                         continue;
                     }
                     // convert method name to get dashed action
                     $actionName = substr($methodName, 0, -6);
                     $actionName = $this->filterCamelCaseToDash($actionName);
                     // build action file
                     $actionFile = '/module/' . $moduleKey . '/view/' . $moduleViewPath . '/' . $controllerName . '/' . $actionName . '.phtml';
                     // check action file exists
                     if (!file_exists($this->params->workingPath . $actionFile)) {
                         $actionFile = false;
                     }
                     // add action to list
                     $loadedActions[$moduleKey][$controllerKey][$actionName] = $actionFile;
                 }
             }
         }
     }
     // set loaded modules
     $this->params->loadedActions = $loadedActions;
     return 0;
 }
Example #14
0
 /**
  * Retrieve parsed methods for this class
  *
  * @return ClassMethod[] Array of ClassMethod objects
  */
 public function getMethods()
 {
     if (null !== $this->methods) {
         return $this->methods;
     }
     $rMethods = $this->reflection->getMethods(ReflectionMethod::IS_PUBLIC);
     $methods = array();
     foreach ($rMethods as $method) {
         $methods[] = new ClassMethod($method);
     }
     $this->methods = $methods;
     return $this->methods;
 }
 /**
  * @inheritDoc
  */
 public function __invoke($fcqn, $namespace, $commandName)
 {
     $commandName = ucfirst($commandName);
     $reflectionClass = new ClassReflection($fcqn);
     $fileGenerator = FileGenerator::fromReflectedFileName($reflectionClass->getFileName());
     $fileGenerator->setFilename($reflectionClass->getFileName());
     $fileGenerator->setUse(ltrim($namespace, '\\') . '\\' . $commandName);
     $classGenerator = $fileGenerator->getClass();
     // workaround for import namespace
     if ($classToExtend = $classGenerator->getExtendedClass()) {
         $classGenerator->setExtendedClass(substr($classToExtend, strrpos($classToExtend, '\\') + 1));
     }
     $classGenerator->addMethodFromGenerator($this->methodWhenEvent($commandName));
     return $fileGenerator;
 }
 /**
  * Generate view content
  *
  * @param string          $moduleName
  * @param ClassReflection $loadedEntity
  */
 protected function addContent($moduleName, ClassReflection $loadedEntity)
 {
     // prepare some params
     $moduleIdentifier = $this->filterCamelCaseToUnderscore($moduleName);
     $entityName = $loadedEntity->getShortName();
     $entityParam = lcfirst($entityName);
     $formParam = lcfirst(str_replace('Entity', '', $loadedEntity->getShortName())) . 'DeleteForm';
     $moduleRoute = $this->filterCamelCaseToDash($moduleName);
     $deleteMessage = $moduleRoute . '_message_' . $moduleRoute . '_deleting_possible';
     // set action body
     $body = [];
     $body[] = 'use ' . $loadedEntity->getName() . ';';
     $body[] = '';
     $body[] = '/** @var ' . $entityName . ' $' . $entityParam . ' */';
     $body[] = '$' . $entityParam . ' = $this->' . $entityParam . ';';
     $body[] = '';
     $body[] = '$this->h1(\'' . $moduleIdentifier . '_title_delete\');';
     $body[] = '';
     $body[] = '$this->' . $formParam . '->setAttribute(\'action\', $this->url(\'' . $moduleRoute . '/delete\', [\'id\' => $' . $entityParam . '->getIdentifier()]));';
     $body[] = '';
     $body[] = '?>';
     $body[] = '<div class="well">';
     $body[] = '    <table class="table">';
     $body[] = '        <tbody>';
     foreach ($loadedEntity->getProperties() as $property) {
         $methodName = 'get' . ucfirst($property->getName());
         $body[] = '            <tr>';
         $body[] = '                <th class="col-sm-2 text-right"><?php echo $this->translate(\'' . $moduleIdentifier . '_label_' . $this->filterCamelCaseToUnderscore($property->getName()) . '\'); ?></th>';
         $body[] = '                <td class="col-sm-10"><?php echo $' . $entityParam . '->' . $methodName . '() ?></td>';
         $body[] = '            </tr>';
     }
     $body[] = '            <tr>';
     $body[] = '                <th class="col-sm-2 text-right">&nbsp;</th>';
     $body[] = '                <td class="col-sm-10"><?php echo $this->form($this->' . $formParam . '); ?></td>';
     $body[] = '            </tr>';
     $body[] = '        </tbody>';
     $body[] = '    </table>';
     $body[] = '</div>';
     $body[] = '<p>';
     $body[] = '    <a class="btn btn-primary" href="<?php echo $this->url(\'' . $moduleRoute . '\'); ?>">';
     $body[] = '        <i class="fa fa-table"></i>';
     $body[] = '        <?php echo $this->translate(\'' . $moduleIdentifier . '_action_index\'); ?>';
     $body[] = '    </a>';
     $body[] = '</p>';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // add method
     $this->setContent($body);
 }
Example #17
0
    /**
     * @group prototype
     */
    public function testCorrectlyBuildsArgumentPrototypeContainingClassNames()
    {
        $r      = $this->class->getMethod('action2');
        $method = new ClassMethod($r);

        $this->assertEquals('null|Zend\Loader\PluginClassLoader $loader', $method->getPrototype());
    }
 public function getClassUseName(ClassReflection $currentClass, ClassReflection $useClass)
 {
     $useNames = $this->fileReflectionUseStatementService->getUseNames($currentClass->getDeclaringFile());
     $fullUseClassName = $useClass->getName();
     $classUseName = null;
     if (array_key_exists($fullUseClassName, $useNames)) {
         $classUseName = $useNames[$fullUseClassName] ?: $useClass->getShortName();
     } else {
         if (0 === strpos($fullUseClassName, $currentClass->getNamespaceName())) {
             $classUseName = substr($fullUseClassName, strlen($currentClass->getNamespaceName()) + 1);
         } else {
             $classUseName = '\\' . $fullUseClassName;
         }
     }
     return $classUseName;
 }
Example #19
0
 /**
  * fromReflection() - build a Code Generation Php Object from a Class Reflection
  *
  * @param ReflectionClass $classReflection
  * @return ClassGenerator
  */
 public static function fromReflection(ClassReflection $classReflection)
 {
     // class generator
     $cg = new static($classReflection->getName());
     $cg->setSourceContent($cg->getSourceContent());
     $cg->setSourceDirty(false);
     if ($classReflection->getDocComment() != '') {
         $cg->setDocblock(DocblockGenerator::fromReflection($classReflection->getDocblock()));
     }
     $cg->setAbstract($classReflection->isAbstract());
     // set the namespace
     if ($classReflection->inNamespace()) {
         $cg->setNamespaceName($classReflection->getNamespaceName());
     }
     /* @var $parentClass \Zend\Code\Reflection\ReflectionClass */
     if ($parentClass = $classReflection->getParentClass()) {
         $cg->setExtendedClass($parentClass->getName());
         $interfaces = array_diff($classReflection->getInterfaces(), $parentClass->getInterfaces());
     } else {
         $interfaces = $classReflection->getInterfaces();
     }
     $interfaceNames = array();
     foreach ($interfaces as $interface) {
         /* @var $interface \Zend\Code\Reflection\ReflectionClass */
         $interfaceNames[] = $interface->getName();
     }
     $cg->setImplementedInterfaces($interfaceNames);
     $properties = array();
     foreach ($classReflection->getProperties() as $reflectionProperty) {
         /* @var $reflectionProperty \PropertyReflection\Code\Reflection\ReflectionProperty */
         if ($reflectionProperty->getDeclaringClass()->getName() == $cg->getName()) {
             $properties[] = PropertyGenerator::fromReflection($reflectionProperty);
         }
     }
     $cg->setProperties($properties);
     $methods = array();
     foreach ($classReflection->getMethods() as $reflectionMethod) {
         /* @var $reflectionMethod \MethodReflection\Code\Reflection\ReflectionMethod */
         if ($reflectionMethod->getDeclaringClass()->getName() == $cg->getName()) {
             $methods[] = MethodGenerator::fromReflection($reflectionMethod);
         }
     }
     $cg->setMethods($methods);
     return $cg;
 }
 /**
  * Build a Code Generation Php Object from a Class Reflection
  *
  * @param  ClassReflection $classReflection
  * @return ClassGenerator
  */
 public static function fromReflection(ClassReflection $classReflection)
 {
     $cg = new static($classReflection->getName());
     $cg->setSourceContent($cg->getSourceContent());
     $cg->setSourceDirty(false);
     if ($classReflection->getDocComment() != '') {
         $cg->setDocBlock(DocBlockGenerator::fromReflection($classReflection->getDocBlock()));
     }
     $cg->setAbstract($classReflection->isAbstract());
     // set the namespace
     if ($classReflection->inNamespace()) {
         $cg->setNamespaceName($classReflection->getNamespaceName());
     }
     /* @var \Zend\Code\Reflection\ClassReflection $parentClass */
     $parentClass = $classReflection->getParentClass();
     $interfaces = $classReflection->getInterfaces();
     if ($parentClass) {
         $cg->setExtendedClass($parentClass->getName());
         $interfaces = array_diff($interfaces, $parentClass->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()) {
             $properties[] = PropertyGenerator::fromReflection($reflectionProperty);
         }
     }
     $cg->addProperties($properties);
     $constants = array();
     foreach ($classReflection->getConstants() as $name => $value) {
         $constants[] = array('name' => $name, 'value' => $value);
     }
     $cg->addConstants($constants);
     $methods = array();
     foreach ($classReflection->getMethods() as $reflectionMethod) {
         $className = $cg->getNamespaceName() ? $cg->getNamespaceName() . "\\" . $cg->getName() : $cg->getName();
         if ($reflectionMethod->getDeclaringClass()->getName() == $className) {
             $methods[] = MethodGenerator::fromReflection($reflectionMethod);
         }
     }
     $cg->addMethods($methods);
     return $cg;
 }
 /**
  * Retrieve a class's `implements` statement
  *
  * @param ClassReflection $reflection
  * @return string
  */
 public function getInterfaceStatement(ClassReflection $reflection)
 {
     $interfaceStatement = '';
     $parent = $reflection->getParentClass();
     $interfaces = array_diff($reflection->getInterfaceNames(), $parent ? $parent->getInterfaceNames() : array());
     if (!count($interfaces)) {
         return $interfaceStatement;
     }
     foreach ($interfaces as $interface) {
         $iReflection = new ClassReflection($interface);
         $interfaces = array_diff($interfaces, $iReflection->getInterfaceNames());
     }
     $interfaceStatement .= $reflection->isInterface() ? ' extends ' : ' implements ';
     $classUseNameService = $this->classUseNameService;
     $interfaceStatement .= implode(', ', array_map(function ($interface) use($classUseNameService, $reflection) {
         $interfaceReflection = new ClassReflection($interface);
         return $classUseNameService->getClassUseName($reflection, $interfaceReflection);
     }, $interfaces));
     return $interfaceStatement;
 }
Example #22
0
 /**
  * Process method parameters
  *
  * @param array $def
  * @param Reflection\ClassReflection $rClass
  * @param Reflection\MethodReflection $rMethod
  */
 protected function processParams(&$def, Reflection\ClassReflection $rClass, Reflection\MethodReflection $rMethod)
 {
     if (count($rMethod->getParameters()) === 0) {
         return;
     }
     $methodName = $rMethod->getName();
     // @todo annotations here for alternate names?
     $def['parameters'][$methodName] = array();
     foreach ($rMethod->getParameters() as $p) {
         /** @var $p \ReflectionParameter  */
         $actualParamName = $p->getName();
         $fqName = $rClass->getName() . '::' . $rMethod->getName() . ':' . $p->getPosition();
         $def['parameters'][$methodName][$fqName] = array();
         // set the class name, if it exists
         $def['parameters'][$methodName][$fqName][] = $actualParamName;
         $def['parameters'][$methodName][$fqName][] = $p->getClass() !== null ? $p->getClass()->getName() : null;
         $def['parameters'][$methodName][$fqName][] = !$p->isOptional();
         $def['parameters'][$methodName][$fqName][] = $p->isOptional() && $p->isDefaultValueAvailable() ? $p->getDefaultValue() : null;
     }
 }
 /**
  * Generate view content
  *
  * @param string          $moduleName
  * @param ClassReflection $loadedEntity
  */
 protected function addContent($moduleName, ClassReflection $loadedEntity)
 {
     // prepare some params
     $moduleIdentifier = $this->filterCamelCaseToUnderscore($moduleName);
     $entityName = $loadedEntity->getShortName();
     $entityParam = lcfirst($entityName);
     $moduleRoute = $this->filterCamelCaseToDash($moduleName);
     // set action body
     $body = [];
     $body[] = 'use ' . $loadedEntity->getName() . ';';
     $body[] = '';
     $body[] = '/** @var ' . $entityName . ' $' . $entityParam . ' */';
     $body[] = '$' . $entityParam . ' = $this->' . $entityParam . ';';
     $body[] = '';
     $body[] = '$this->h1(\'' . $moduleIdentifier . '_title_show\');';
     $body[] = '?>';
     $body[] = '<table class="table table-bordered">';
     $body[] = '    <tbody>';
     foreach ($loadedEntity->getProperties() as $property) {
         $methodName = 'get' . ucfirst($property->getName());
         $body[] = '        <tr>';
         $body[] = '            <th><?php echo $this->translate(\'' . $moduleIdentifier . '_label_' . $this->filterCamelCaseToUnderscore($property->getName()) . '\'); ?></th>';
         $body[] = '            <td><?php echo $' . $entityParam . '->' . $methodName . '() ?></td>';
         $body[] = '        </tr>';
     }
     $body[] = '    </tbody>';
     $body[] = '</table>';
     $body[] = '<p>';
     $body[] = '    <a class="btn btn-primary" href="<?php echo $this->url(\'' . $moduleRoute . '\'); ?>">';
     $body[] = '        <i class="fa fa-table"></i>';
     $body[] = '        <?php echo $this->translate(\'' . $moduleIdentifier . '_action_index\'); ?>';
     $body[] = '    </a>';
     $body[] = '</p>';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // add method
     $this->setContent($body);
 }
 /**
  * Determine the class type (abstract, final, interface, class)
  *
  * @param ClassReflection $reflection
  * @return string
  */
 public function getClassType(ClassReflection $reflection)
 {
     $classType = '';
     if ($reflection->isAbstract() && !$reflection->isInterface()) {
         $classType .= 'abstract ';
     }
     if ($reflection->isFinal()) {
         $classType .= 'final ';
     }
     if ($reflection->isInterface()) {
         $classType .= 'interface ';
     }
     if (!$reflection->isInterface()) {
         $classType .= 'class ';
     }
     return $classType;
 }
Example #25
0
 private function getDeclaration()
 {
     $class = $this->getClass();
     $declaration = '';
     if ($class->isAbstract() && !$class->isInterface() && !$class->isTrait()) {
         $declaration .= 'abstract ';
     }
     if ($class->isFinal()) {
         $declaration .= 'final ';
     }
     $declaration .= $this->getClassType() . ' ';
     $declaration .= $class->getShortName();
     $interfacesNames = $class->getInterfaceNames();
     /*
      * parent
      */
     $parentClass = $class->getParentClass();
     if ($parentClass instanceof ClassReflection) {
         // using the absolute namespace + classname work, even if the class has an use alias defined (absolute are unique)
         $declaration .= ' extends \\' . $parentClass->getName();
         $interfacesNames = array_diff($interfacesNames, $parentClass->getInterfaceNames());
     }
     /*
      * interfaces
      */
     if (count($interfacesNames) > 0) {
         $interfacesNamesResult = $interfacesNames;
         foreach ($interfacesNames as $key => $interfaceName) {
             $interface = new ClassReflection($interfaceName);
             $interfacesNamesResult = array_diff($interfacesNamesResult, $interface->getInterfaceNames());
         }
         $declaration .= $class->isInterface() ? ' extends ' : ' implements ';
         // using the absolute namespace + classname work, even if the class has an use alias defined (absolute are unique)
         $declaration .= '\\' . implode(', \\', $interfacesNamesResult);
     }
     return $declaration;
 }
Example #26
0
 /**
  * Get forms for a module
  *
  * @param $moduleObject
  *
  * @return array
  */
 protected function loadPluginsForModule($moduleObject)
 {
     // initialize plugins
     $plugins = array();
     // check for configuration
     if (!method_exists($moduleObject, 'getConfig')) {
         return $plugins;
     }
     // get module configuration
     $moduleConfig = $moduleObject->getConfig();
     // check for no configured plugins
     if (!isset($moduleConfig['controller_plugins'])) {
         return $plugins;
     }
     // loop through plugins
     foreach ($moduleConfig['controller_plugins'] as $type => $loadedPlugins) {
         // skip if not invokable nor factory
         if (!in_array($type, array('invokables', 'factories'))) {
             continue;
         }
         // initialize plugin type
         $plugins[$type] = array();
         // loop through plugin list
         foreach ($loadedPlugins as $pluginKey => $pluginClass) {
             // check if plugin class or factory does not exist
             if (!class_exists($pluginClass)) {
                 continue;
             }
             // check for factory
             if (in_array('Zend\\ServiceManager\\FactoryInterface', class_implements($pluginClass))) {
                 // start class reflection
                 $classReflection = new ClassReflection($pluginClass);
                 // get create method and doc block
                 $method = $classReflection->getMethod('createService');
                 $docBlock = $method->getDocBlock();
                 // check doc block for return tag and use class
                 if ($docBlock) {
                     // loop through all doc blocks
                     foreach ($docBlock->getTags() as $tag) {
                         /** @var $tag ReturnTag */
                         if ($tag->getName() != 'return') {
                             continue;
                         }
                         $pluginClass = $classReflection->getNamespaceName() . '\\' . $tag->getTypes()[0];
                     }
                 } else {
                     // try to read plugin instantiation from method
                     preg_match_all('^\\$plugin\\s*=\\s*new\\s*([a-zA-z0-9]+)\\(\\)\\;^', $method->getContents(), $matches);
                     $pluginClass = $classReflection->getNamespaceName() . '\\' . $matches[1][0];
                 }
             }
             // check for class existence
             if (!class_exists($pluginClass)) {
                 break;
             }
             // add plugin class for type
             $plugins[$type][$pluginKey] = $pluginClass;
         }
     }
     // loop through plugins
     foreach ($plugins as $type => $pluginList) {
         // check if any plugin exists for type
         if (empty($pluginList)) {
             unset($plugins[$type]);
             // otherwise sort plugins
         } else {
             ksort($plugins[$type]);
         }
     }
     return $plugins;
 }
 /**
  * Creates and returns a form specification for use with a factory
  *
  * Parses the object provided, and processes annotations for the class and
  * all properties. Information from annotations is then used to create
  * specifications for a form, its elements, and its input filter.
  *
  * @param  string|object $entity Either an instance or a valid class name for an entity
  * @throws Exception\InvalidArgumentException if $entity is not an object or class name
  * @return ArrayObject
  */
 public function getFormSpecification($entity)
 {
     if (!is_object($entity)) {
         if (is_string($entity) && !class_exists($entity) || !is_string($entity)) {
             throw new Exception\InvalidArgumentException(sprintf('%s expects an object or valid class name; received "%s"', __METHOD__, var_export($entity, 1)));
         }
     }
     $this->entity = $entity;
     $annotationManager = $this->getAnnotationManager();
     $formSpec = new ArrayObject();
     $filterSpec = new ArrayObject();
     $reflection = new ClassReflection($entity);
     $annotations = $reflection->getAnnotations($annotationManager);
     if ($annotations instanceof AnnotationCollection) {
         $this->configureForm($annotations, $reflection, $formSpec, $filterSpec);
     }
     foreach ($reflection->getProperties() as $property) {
         $annotations = $property->getAnnotations($annotationManager);
         if ($annotations instanceof AnnotationCollection) {
             $this->configureElement($annotations, $property, $formSpec, $filterSpec);
         }
     }
     if (!isset($formSpec['input_filter'])) {
         $formSpec['input_filter'] = $filterSpec;
     }
     return $formSpec;
 }
Example #28
0
 /**
  * Generate code to cache from class reflection.
  *
  * This is a total mess, I know. Just wanted to flesh out the logic.
  * @todo Refactor into a class, clean up logic, DRY it up, maybe move
  *       some of this into Zend\Code
  * @param  ClassReflection $r
  * @return string
  */
 protected static function getCacheCode(ClassReflection $r)
 {
     $useString = '';
     $usesNames = array();
     if (count($uses = $r->getDeclaringFile()->getUses())) {
         foreach ($uses as $use) {
             $usesNames[$use['use']] = $use['as'];
             $useString .= "use {$use['use']}";
             if ($use['as']) {
                 $useString .= " as {$use['as']}";
             }
             $useString .= ";\n";
         }
     }
     $declaration = '';
     if ($r->isAbstract() && !$r->isInterface()) {
         $declaration .= 'abstract ';
     }
     if ($r->isFinal()) {
         $declaration .= 'final ';
     }
     if ($r->isInterface()) {
         $declaration .= 'interface ';
     }
     if (!$r->isInterface()) {
         $declaration .= 'class ';
     }
     $declaration .= $r->getShortName();
     $parentName = false;
     if (($parent = $r->getParentClass()) && $r->getNamespaceName()) {
         $parentName = array_key_exists($parent->getName(), $usesNames) ? $usesNames[$parent->getName()] ?: $parent->getShortName() : (0 === strpos($parent->getName(), $r->getNamespaceName()) ? substr($parent->getName(), strlen($r->getNamespaceName()) + 1) : '\\' . $parent->getName());
     } else {
         if ($parent && !$r->getNamespaceName()) {
             $parentName = '\\' . $parent->getName();
         }
     }
     if ($parentName) {
         $declaration .= " extends {$parentName}";
     }
     $interfaces = array_diff($r->getInterfaceNames(), $parent ? $parent->getInterfaceNames() : array());
     if (count($interfaces)) {
         foreach ($interfaces as $interface) {
             $iReflection = new ClassReflection($interface);
             $interfaces = array_diff($interfaces, $iReflection->getInterfaceNames());
         }
         $declaration .= $r->isInterface() ? ' extends ' : ' implements ';
         $declaration .= implode(', ', array_map(function ($interface) use($usesNames, $r) {
             $iReflection = new ClassReflection($interface);
             return array_key_exists($iReflection->getName(), $usesNames) ? $usesNames[$iReflection->getName()] ?: $iReflection->getShortName() : (0 === strpos($iReflection->getName(), $r->getNamespaceName()) ? substr($iReflection->getName(), strlen($r->getNamespaceName()) + 1) : '\\' . $iReflection->getName());
         }, $interfaces));
     }
     $classContents = $r->getContents(false);
     $classFileDir = dirname($r->getFileName());
     $classContents = trim(str_replace('__DIR__', sprintf("'%s'", $classFileDir), $classContents));
     $return = "\nnamespace " . $r->getNamespaceName() . " {\n" . $useString . $declaration . "\n" . $classContents . "\n}\n";
     return $return;
 }
Example #29
0
 /**
  * Use reflection to load the method information
  *
  * @param string $interfaceName
  * @return array
  */
 private function getMethodMapViaReflection($interfaceName)
 {
     $methodMap = [];
     $class = new ClassReflection($interfaceName);
     $baseClassMethods = false;
     foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
         // Include all the methods of classes inheriting from AbstractExtensibleObject.
         // Ignore all the methods of AbstractExtensibleModel's parent classes
         if ($method->class === self::BASE_MODEL_CLASS) {
             $baseClassMethods = true;
         } elseif ($baseClassMethods) {
             // ReflectionClass::getMethods() sorts the methods by class (lowest in inheritance tree first)
             // then by the order they are defined in the class definition
             break;
         }
         if ($this->isSuitableMethod($method)) {
             $methodMap[$method->getName()] = $this->typeProcessor->getGetterReturnType($method);
         }
     }
     return $methodMap;
 }
Example #30
0
 /**
  * Determine if a class implements a given interface
  *
  * For PHP versions >= 5.3.7, uses is_subclass_of; otherwise, uses 
  * reflection to determine the interfaces implemented.
  * 
  * @param  string $class 
  * @param  string $type 
  * @return bool
  */
 protected function isSubclassOf($class, $type)
 {
     if (version_compare(PHP_VERSION, '5.3.7', 'gte')) {
         return is_subclass_of($class, $type);
     }
     $r = new ClassReflection($class);
     $interfaces = $r->getInterfaceNames();
     return in_array($type, $interfaces);
 }