public function testDocblockTags()
 {
     $classReflection = new ClassReflection('ZendTest\\Code\\Reflection\\TestAsset\\TestSampleClass5');
     $this->assertEquals(1, count($classReflection->getDocblock()->getTags()));
     $this->assertEquals(1, count($classReflection->getDocblock()->getTags('author')));
     $this->assertFalse($classReflection->getDocblock()->getTag('version'));
     $this->assertTrue($classReflection->getMethod('doSomething')->getDocblock()->hasTag('return'));
     $returnTag = $classReflection->getMethod('doSomething')->getDocblock()->getTag('return');
     $this->assertInstanceOf('Zend\\Code\\Reflection\\DocBlock\\Tag', $returnTag);
     $this->assertEquals('mixed', $returnTag->getType());
 }
 /**
  * Converts the provided input array from key-value format to a list of parameters suitable for the specified
  * class / method.
  *
  * The input array should have the field name as the key, and the value will either be a primitive or another
  * key-value array.  The top level of this array needs keys that match the names of the parameters on the
  * service method.
  *
  * Mismatched types are caught by the PHP runtime, not explicitly checked for by this code.
  *
  * @param string $serviceClassName name of the service class that we are trying to call
  * @param string $serviceMethodName name of the method that we are trying to call
  * @param array $inputArray data to send to method in key-value format
  * @return array list of parameters that can be used to call the service method
  */
 public function getInputData($serviceClassName, $serviceMethodName, array $inputArray)
 {
     /** TODO: Reflection causes performance degradation when used in runtime. Should be optimized via caching */
     $serviceClass = new ClassReflection($serviceClassName);
     /** @var MethodReflection $serviceMethod */
     $serviceMethod = $serviceClass->getMethod($serviceMethodName);
     /** @var ParameterReflection[] $params */
     $params = $serviceMethod->getParameters();
     $inputData = [];
     foreach ($params as $param) {
         $paramName = $param->getName();
         $snakeCaseParamName = strtolower(preg_replace("/(?<=\\w)(?=[A-Z])/", "_\$1", $paramName));
         if (isset($inputArray[$paramName]) || isset($inputArray[$snakeCaseParamName])) {
             $paramValue = isset($inputArray[$paramName]) ? $inputArray[$paramName] : $inputArray[$snakeCaseParamName];
             if ($this->_isArrayParam($param)) {
                 $paramType = "{$param->getType()}[]";
             } else {
                 $paramType = $param->getType();
             }
             $inputData[] = $this->_convertValue($paramValue, $paramType);
         } else {
             $inputData[] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
         }
     }
     return $inputData;
 }
Exemple #3
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 testMethodReturns()
 {
     $reflectionClass = new ClassReflection('ZendTest\\Code\\Reflection\\TestAsset\\TestSampleClass2');
     $methodByName = $reflectionClass->getMethod('getProp1');
     $this->assertEquals('Zend\\Code\\Reflection\\MethodReflection', get_class($methodByName));
     $methodsAll = $reflectionClass->getMethods();
     $this->assertEquals(3, count($methodsAll));
     $firstMethod = array_shift($methodsAll);
     $this->assertEquals('getProp1', $firstMethod->getName());
 }
Exemple #5
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;
     }
 }
Exemple #6
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;
 }
 /**
  * Checks if method is defined
  *
  * Case sensitivity of the method is taken into account.
  *
  * @param ClassReflection $class
  * @param string $methodName
  * @return bool
  */
 protected function classHasMethod(ClassReflection $class, $methodName)
 {
     return $class->hasMethod($methodName) && $class->getMethod($methodName)->getName() == $methodName;
 }
 public function testGetParameterDescription()
 {
     $class = new ClassReflection("\\Magento\\Framework\\Reflection\\Test\\Unit\\DataObject");
     $methodReflection = $class->getMethod('setName');
     $paramsReflection = $methodReflection->getParameters();
     $this->assertEquals('Name of the attribute', $this->_typeProcessor->getParamDescription($paramsReflection[0]));
 }
 /**
  * Retrieve requested service method params metadata.
  *
  * @param string $serviceClassName
  * @param string $serviceMethodName
  * @return array
  */
 protected function getMethodParams($serviceClassName, $serviceMethodName)
 {
     $cacheId = self::CACHE_ID_PREFIX . hash('md5', $serviceClassName . $serviceMethodName);
     $params = $this->cache->load($cacheId);
     if ($params !== false) {
         return unserialize($params);
     }
     $serviceClass = new ClassReflection($serviceClassName);
     /** @var MethodReflection $serviceMethod */
     $serviceMethod = $serviceClass->getMethod($serviceMethodName);
     $params = [];
     /** @var ParameterReflection $paramReflection */
     foreach ($serviceMethod->getParameters() as $paramReflection) {
         $isDefaultValueAvailable = $paramReflection->isDefaultValueAvailable();
         $params[] = [
             'name' => $paramReflection->getName(),
             'type' => $this->typeProcessor->getParamType($paramReflection),
             'isDefaultValueAvailable' => $isDefaultValueAvailable,
             'defaultValue' => $isDefaultValueAvailable ? $paramReflection->getDefaultValue() : null
         ];
     }
     $this->cache->save(serialize($params), $cacheId, [WebapiCache::CACHE_TAG]);
     return $params;
 }
 public function testAutodetectAction()
 {
     $configBuilder = new RouteConfigBuilder();
     /* @var $parser ControllerAnnotationParser */
     $parser = $this->serviceManager->get('parser');
     $classReflection = new ClassReflection(new NoBaseController());
     $method = $classReflection->getMethod('noActionAction');
     $annotations = $parser->getMethodAnnotations($method);
     /* @var $route Route */
     $route = $annotations[0];
     $parser->autodetectMissingFields($route, $method, 'controllerkey');
     $configBuilder->addPart($route);
     $routeArray = array('no-action' => array('type' => 'literal', 'options' => array('route' => '/no-action', 'defaults' => array('controller' => 'controllerkey', 'action' => 'no-action'), 'constraints' => null), 'may_terminate' => true));
     $this->assertEquals($routeArray, $configBuilder->toArray());
 }
 /**
  * Retrieve requested service method params metadata.
  *
  * @param string $serviceClassName
  * @param string $serviceMethodName
  * @return array
  */
 public function getMethodParams($serviceClassName, $serviceMethodName)
 {
     $cacheId = self::SERVICE_METHOD_PARAMS_CACHE_PREFIX . hash('md5', $serviceClassName . $serviceMethodName);
     $params = $this->cache->load($cacheId);
     if ($params !== false) {
         return unserialize($params);
     }
     $serviceClass = new ClassReflection($serviceClassName);
     /** @var MethodReflection $serviceMethod */
     $serviceMethod = $serviceClass->getMethod($serviceMethodName);
     $params = [];
     /** @var ParameterReflection $paramReflection */
     foreach ($serviceMethod->getParameters() as $paramReflection) {
         $isDefaultValueAvailable = $paramReflection->isDefaultValueAvailable();
         $params[] = [self::METHOD_META_NAME => $paramReflection->getName(), self::METHOD_META_TYPE => $this->typeProcessor->getParamType($paramReflection), self::METHOD_META_HAS_DEFAULT_VALUE => $isDefaultValueAvailable, self::METHOD_META_DEFAULT_VALUE => $isDefaultValueAvailable ? $paramReflection->getDefaultValue() : null];
     }
     $this->cache->save(serialize($params), $cacheId, [ReflectionCache::CACHE_TAG]);
     return $params;
 }
Exemple #12
0
    /**
     * @group ZF-8307
     */
    public function testReturnClassWithNamespace()
    {
        $classReflection = new Reflection\ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass7');

        $paramTag = $classReflection->getMethod('doSomething')->getDocBlock()->getTag('return');

        $this->assertEquals('Zend\Code\Reflection\DocBlock', $paramTag->getType());
    }
 /**
  * Create a new subclass and factory to override a factory-generated
  * service.
  *
  * @param mixed  $factory Factory configuration for class to extend
  * @param string $module  Module in which to create the new factory
  *
  * @return string
  * @throws \Exception
  */
 protected function cloneFactory($factory, $module)
 {
     // Make sure we can figure out how to handle the factory; it should
     // either be a [controller, method] array or a "controller::method"
     // string; anything else will cause a problem.
     $parts = is_string($factory) ? explode('::', $factory) : $factory;
     if (!is_array($parts) || count($parts) != 2 || !class_exists($parts[0]) || !method_exists($parts[0], $parts[1])) {
         throw new \Exception('Unexpected factory configuration format.');
     }
     list($factoryClass, $factoryMethod) = $parts;
     $newFactoryClass = $this->generateLocalClassName($factoryClass, $module);
     if (!class_exists($newFactoryClass)) {
         $this->createClassInModule($newFactoryClass, $module);
         $skipBackup = true;
     } else {
         $skipBackup = false;
     }
     if (method_exists($newFactoryClass, $factoryMethod)) {
         throw new \Exception("{$newFactoryClass}::{$factoryMethod} already exists.");
     }
     $oldReflection = new ClassReflection($factoryClass);
     $newReflection = new ClassReflection($newFactoryClass);
     $generator = ClassGenerator::fromReflection($newReflection);
     $method = MethodGenerator::fromReflection($oldReflection->getMethod($factoryMethod));
     $this->createServiceClassAndUpdateFactory($method, $oldReflection->getNamespaceName(), $module);
     $generator->addMethodFromGenerator($method);
     $this->writeClass($generator, $module, true, $skipBackup);
     return $newFactoryClass . '::' . $factoryMethod;
 }
Exemple #14
0
 /**
  * Checks if method is defined
  *
  * Case sensitivity of the method is taken into account.
  *
  * @param ClassReflection $class
  * @param string $methodName
  * @return bool
  */
 public function hasMethod(ClassReflection $class, $methodName)
 {
     return $class->hasMethod($methodName) && $class->getMethod($methodName)->getName() == $methodName;
 }