public static function create($name, ReflectionMethod $method) { $result = new ckWsdlOperation(); $result->setName($name); $params = ckDocBlockParser::parseParameters($method->getDocComment()); $headers = ckDocBlockParser::parseHeader($method->getDocComment()); $return = ckDocBlockParser::parseReturn($method->getDocComment()); $result->input = new ckWsdlMessage($name . 'Request'); foreach ($params as $param) { $type = ckXsdType::get($param['type']); $result->input->addPart(new ckWsdlPart($param['name'], $type)); } foreach ($headers as $header) { $type = ckXsdType::get($header['type']); $type->setName($header['name']); $type->setIsElement(true); ckXsdType::set($header['name'], $type); ckXsdType::set($header['type'], null); $result->input->addPart(new ckWsdlPart($header['name'], $type, true)); } if (!empty($return)) { $type = ckXsdType::get($return['type']); $result->output = new ckWsdlMessage($name . 'Response'); $result->output->addPart(new ckWsdlPart('return', $type)); } return $result; }
private function createClassDefinition() { $fullClassName = $this->getClass(); if (class_exists($fullClassName)) { return; } $parts = explode('\\', $fullClassName); $shortName = array_pop($parts); $namespace = implode('\\', $parts); $properties = []; $parameters = []; $body = []; $getters = []; foreach ($this->method->getParameters() as $parameter) { $name = $parameter->getName(); $parameters[] = '$' . $name . ($parameter->isDefaultValueAvailable() ? ' = ' . var_export($parameter->getDefaultValue(), true) : ''); $body[] = '$this->' . $name . ' = $' . $name . ';'; $properties[] = 'private $' . $name . ';'; $hint = null; $matches = []; if ($parameter->getClass()) { $hint = $parameter->getClass()->getName(); } else { if (preg_match('/@param\\s+(\\S+)\\s+\\$' . $name . '/', $this->method->getDocComment(), $matches)) { $hint = $matches[1]; } } $getters[] = ($hint ? "/**\n * @return " . $hint . "\n */\n " : '') . 'function get' . ucfirst($name) . '() { return $this->' . $name . '; }'; } $code = ($namespace ? "namespace {$namespace};\n" : '') . "class {$shortName} {\n" . ' ' . implode("\n ", $properties) . "\n" . ' function __construct(' . implode(', ', $parameters) . ") {\n" . ' ' . implode("\n ", $body) . "\n" . ' }' . "\n" . ' ' . implode("\n ", $getters) . "\n" . '}'; eval($code); }
/** * @return IAnnotationReflection */ public function getAnnotationReflection() { if ($this->annotationReflection === null) { $this->annotationReflection = AnnotationReflection::build($this->reflectionMethod->getDocComment()); } return $this->annotationReflection; }
public function __construct(Controller $controller, $action) { $this->controller = $controller; $this->name = $action; $this->reflector = new \ReflectionMethod($controller, $action); $this->docComment = $this->reflector->getDocComment(); $this->parameters = $this->reflector->getParameters(); $this->initializeAttributes(); }
public function extractCommentWithoutLeadingShashesAndStars() { $this->comment = explode("\n", $this->reflector->getDocComment()); foreach ($this->comment as &$line) { $line = preg_replace('#^\\s*(/\\*+|\\*+/|\\*)\\s?#', '', $line); } $this->trimLeadingBlankLinesFromComment(); $this->trimTrailingBlankLinesFromComment(); }
private function getAnnotationType($annotation) { $matches = array(); $found = preg_match('/@' . $annotation . '\\s+(\\S+)/', $this->reflection->getDocComment(), $matches); if (!$found) { return new UnknownType(); } $type = new TypeFactory($this->reflection->getDeclaringClass()); return $type->fromTypeHints(explode("|", $matches[1])); }
/** * @return string|null */ public function description() { $lines = array_slice(explode("\n", $this->method->getDocComment()), 1, -1); $lines = array_map(function ($line) { return ltrim($line, ' *'); }, $lines); $lines = array_filter($lines, function ($line) { return substr($line, 0, 1) != '@'; }); return $this->parser->parse(trim(implode("\n", $lines))); }
/** * Returns an array with parsed lines from PHPDoc. * * @return array */ protected function getParsedDocs() { $lines_docs = explode("\n", $this->reflection->getDocComment()); // Remove first line (/**) array_shift($lines_docs); // Remove last line (*/) array_pop($lines_docs); return array_map(function ($item) { return ltrim($item, '* '); }, $lines_docs); }
public function handleMockSubscribers() { $reflection = new \ReflectionMethod(get_class($this), $this->getName()); if (false == ($mockFile = self::parseDocBlock($reflection->getDocComment()))) { return; } $mockPath = self::parseDocBlock($reflection->getDocComment(), self::ANNOTATION_PATH); $mockFilePath = $this->getTestFilePath($mockFile, $mockPath); if (file_exists($mockFilePath)) { $this->getClient()->getEventDispatcher()->removeListener('request.before_send', 'onRequestBeforeSend'); $this->addMockSubscriber($mockFilePath, 0); } }
/** * This method is used to return an iteration-friendly list of parameters for a given method. * * @param string $className * @param string $method * @return array */ protected function loadParameters($className, $method) { // dig for data on the chosen method, in the chosen class $parameters = array(); $reflectionMethod = new ReflectionMethod($className, $method); $PHPDoc = $reflectionMethod->getDocComment(); /* * This regex filters out all parameters, along with their PHPDoc. We use this instead * of $reflectionMethod->getParameters(), since that returns ReflectionParameter objects * that, rather shamefully, do not contain PHPDoc. */ preg_match_all('/@param[\\s\\t]+(.*)[\\s\\t]+\\$(.*)[\\s\\t]+(.*)$/Um', $PHPDoc, $matches); if (array_key_exists(0, $matches) && empty($matches[0])) { continue; } $phpdoc = array(); // we have to build up a custom stack of parameters foreach ($matches[0] as $i => $row) { $name = $matches[2][$i]; if ($name === 'language') { continue; } $parameters[] = array('name' => $name, 'label' => $name . '-' . rand(1, 99999), 'optional' => substr_count($matches[2][$i], '[optional]') > 0, 'description' => $matches[3][$i]); } return $parameters; }
/** * Test valid public function/method names. * * @return void */ public function testAutoload() { try { $object = new SQLI_CodeSniffer(); $this->assertTrue($object instanceof SQLI_CodeSniffer); } catch (Exception $e) { $this->fail('Autoload an SQLI_CodeSniffer Core class'); } try { $object = new PHP_CodeSniffer_Exception("test"); $this->assertTrue($object instanceof PHP_CodeSniffer_Exception); } catch (Exception $e) { $this->fail('Autoload a PHP_CodeSniffer Core class ' . $e->getMessage()); } try { $object = new Generic_Sniffs_Classes_DuplicateClassNameSniff(); // trick to recognize SQLI implemented sniffer $method = new ReflectionMethod('Generic_Sniffs_Classes_DuplicateClassNameSniff', 'process'); $this->assertContains('SQLI_CodeSniffer_File', $method->getDocComment()); } catch (Exception $e) { $this->fail('Autoload an SQLI_CodeSniffer sniffer'); } try { $object = new Generic_Sniffs_CodeAnalysis_UnnecessaryFinalModifierSniff(); // trick to recognize classical sniffer $method = new ReflectionMethod('Generic_Sniffs_CodeAnalysis_UnnecessaryFinalModifierSniff', 'process'); $this->assertContains('PHP_CodeSniffer_File', $method->getDocComment()); } catch (Exception $e) { $this->fail('Autoload a PHP_CodeSniffer sniffer'); } }
public function getActionAuthorization($class, $action) { $refMethod = new \ReflectionMethod($class, $action); $doc = $refMethod->getDocComment(); preg_match_all("/@Authorize/", $doc, $authorizations); return $authorizations[0]; }
public static function getDocAttribute(\ReflectionMethod $reflectionMethod, $attributeName) { $doc = $reflectionMethod->getDocComment(); if ($doc && preg_match('/\\* @' . $attributeName . '\\s?(.*)\\r?\\n/', $doc, $matches)) { return $matches[1]; } }
private function extractFeature(\PHPUnit_Framework_Test $test) { $class = get_class($test); $method = $test->getName(); $reflection = new \ReflectionMethod($class, $method); return $this->parseDocBlock($reflection->getDocComment(), '@feature'); }
/** * * @param GenerationContext $context * @param \Nucleus\IService\CommandLine\Consolable $annotation */ public function generate(GenerationContext $context, $annotation) { $docParser = new DocBlockParser(); $serviceName = $context->getServiceName(); $methodName = $context->getParsingContextName(); $definition = $context->getContainerBuilder()->getDefinition($serviceName); $shortDesc = 'N/A'; $reflectedMethod = new \ReflectionMethod($definition->getClass(), $methodName); $methodComment = $reflectedMethod->getDocComment(); if ($methodComment !== false) { $docMethod = $docParser->parse($methodComment); $shortDesc = $docMethod->getShortDesc(); } $paramsArray = array(); $paramArrayComments = self::extractParamDocComment($docMethod->getTag('param')); foreach ($reflectedMethod->getParameters() as $reflectionParameter) { $paramComment = 'N/A'; if (isset($paramArrayComments[$reflectionParameter->getName()])) { $paramComment = $paramArrayComments[$reflectionParameter->getName()]['comment']; } $paramsArray[$reflectionParameter->getName()]['optional'] = false; if ($reflectionParameter->isDefaultValueAvailable()) { $paramsArray[$reflectionParameter->getName()]['optional'] = true; } $paramsArray[$reflectionParameter->getName()]['comment'] = $paramComment; } if (!empty($annotation->name)) { $name = $annotation->name; } else { $name = $serviceName . ':' . $methodName; } $context->getContainerBuilder()->getDefinition("console")->addMethodCall("addCommand", array("applicatiomName" => $name, "serviceName" => $serviceName, "methodName" => $methodName, "shortDesc" => $shortDesc, "paramsMethod" => $paramsArray)); }
public function handleHttpRequest(Request $request) { try { $this->getRequest()->setHttpRequest($request); $this->getResponse()->setRequest($this->getRequest()); $method = $this->getRequest()->getMethod(); if (!method_exists($this->service, $method)) { throw new JsonRpcInvalidMethodException('Requested method does not exist'); } $reader = new \ReflectionMethod($this->service, $method); $doc = $reader->getDocComment(); if (!strpos($doc, '{JsonRpcMethod}')) { throw new JsonRpcInvalidMethodException('Requested method does not exist'); } $callingParams = []; $methodParams = $reader->getParameters(); foreach ($methodParams as $param) { if ($param->getClass()->isSubclassOf('RageJsonRpc\\JsonRpcRequest')) { $callingParams[] = $this->getRequest(); } elseif ($param->getClass()->isSubclassOf('RageJsonRpc\\JsonRpcResponse')) { $callingParams[] = $this->getResponse(); } else { throw new JsonRpcInvalidMethodException('Method definition is incorrect'); } } $result = call_user_func_array(array($this->service, $method), $callingParams); $this->getResponse()->setResult($result); } catch (JsonRpcException $e) { $this->getResponse()->setError($e->getMessage(), $e->getCode()); } return $this->getResponse()->getHttpResponse(); }
/** * Reads all supported method annotations. * * @param stirng $className * @param \ReflectionMethod $method * * @return array */ private function readMethodAnnotations($className, \ReflectionMethod $method) { $annotations = array(); // Read parent annotations. try { $prototype = $method->getPrototype(); $annotations = array_merge($annotations, $this->readMethodAnnotations($className, $prototype)); } catch (\ReflectionException $e) { } // Read method annotations. if ($docBlock = $method->getDocComment()) { $description = NULL; foreach (explode("\n", $docBlock) as $docLine) { $docLine = preg_replace('/^\\/\\*\\*\\s*|^\\s*\\*\\s*|\\s*\\*\\/$|\\s*$/', '', $docLine); if (preg_match('/^\\@(' . $this->availableAnnotations . ')\\s*(.*)?$/i', $docLine, $matches)) { $class = $this->annotationClasses[strtolower($matches[1])]; $callback = array($className, $method->getName()); if (isset($matches[2]) && !empty($matches[2])) { $annotation = new $class($callback, $matches[2]); } else { $annotation = new $class($callback); } if (NULL !== $description) { $annotation->setDescription($description); } $annotations[] = $annotation; } elseif (NULL === $description && '' !== $docLine && FALSE === strpos($docLine, '@')) { $description = $docLine; } } } return $annotations; }
/** * Método que busca anotaciones de enrutamientos y serializa su resultado * @param $pHmvcPath string Path de módulos hmvc * @param $pSerializePath string Path de rutas serializadas * @return void */ public function findRoutes($pHmvcPath, $pSerializePath) { $routesFind = []; // se recorren los controladores con biblioteca SPL // (no se lleva a cabo con \GlobIterator dado que en Windows sólo funciona con rutas absolutas) $controllers = new \RegexIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($pHmvcPath, \RecursiveDirectoryIterator::SKIP_DOTS | \RecursiveDirectoryIterator::UNIX_PATHS)), '/.*\\/Controller\\/.*\\.php/i'); foreach ($controllers as $file) { require $file; $namespaceClass = str_replace(['/', '.php'], ['\\', ''], $file); $namespaceSections = array_reverse(explode('\\', $namespaceClass)); $rc = new \ReflectionClass($namespaceClass); $methods = $rc->getMethods(); // se recorren los métodos del controlador foreach ($methods as $method) { $rm = new \ReflectionMethod($namespaceClass, $method->name); $commentsText = $rm->getDocComment(); $commentsLines = explode("\n", $commentsText); // se recuperan los tags de enrutamientos $routes = array_filter($commentsLines, function ($value) { return strpos($value, '@T_ROUTE') !== false; }); // se agregan los enrutamientos foreach ($routes as $route) { $route = trim(substr(str_replace('@T_ROUTE', '', trim($route)), 1)); $callback = $namespaceSections[2] . '|' . $namespaceSections[0] . '|' . $method->name; $routesFind[] = [$route, $callback]; } } } // se serializan los enrutamientos en un archivo de configuración if (count($routesFind) > 0) { $sz = serialize($routesFind); file_put_contents($pSerializePath . '/serialized.php', $sz); } }
public function getMethod($filePath, $ext = '') { $fileName = dirname($filePath); $className = basename(dirname(dirname($filePath))); if (!class_exists($className)) { helper::import($fileName); } $methodName = basename($filePath); $method = new ReflectionMethod($className . $ext, $methodName); $data = new stdClass(); $data->startLine = $method->getStartLine(); $data->endLine = $method->getEndLine(); $data->comment = $method->getDocComment(); $data->parameters = $method->getParameters(); $data->className = $className; $data->methodName = $methodName; $data->fileName = $fileName; $data->post = false; $file = file($fileName); for ($i = $data->startLine - 1; $i <= $data->endLine; $i++) { if (strpos($file[$i], '$this->post') or strpos($file[$i], 'fixer::input') or strpos($file[$i], '$_POST')) { $data->post = true; } } return $data; }
/** * @param object $object an object or classname * @param string $method the method which we want to inspect */ public function reflect($object, $method) { $reflection = new \ReflectionMethod($object, $method); $docs = $reflection->getDocComment(); // extract everything prefixed by @ and first letter uppercase preg_match_all('/@([A-Z]\\w+)/', $docs, $matches); $this->annotations = $matches[1]; // extract type parameter information preg_match_all('/@param\\h+(?P<type>\\w+)\\h+\\$(?P<var>\\w+)/', $docs, $matches); // this is just a fix for PHP 5.3 (array_combine raises warning if called with // two empty arrays if ($matches['var'] === array() && $matches['type'] === array()) { $this->types = array(); } else { $this->types = array_combine($matches['var'], $matches['type']); } // get method parameters foreach ($reflection->getParameters() as $param) { if ($param->isOptional()) { $default = $param->getDefaultValue(); } else { $default = null; } $this->parameters[$param->name] = $default; } }
public function getRouter() { $router = new Router(); foreach ($this->getActionRoutes() as $methodRoute) { list($route, $methodName) = $methodRoute; $method = new \ReflectionMethod($this, $methodName); $httpMethod = 'GET'; $hasRoute = false; if ($comment = $method->getDocComment()) { if (preg_match('~^[\\s*]*\\@method\\s([^\\s]+)~im', $comment, $match)) { $httpMethod = trim(strtoupper(array_pop($match))); } if (preg_match('~^[\\s*]*\\@route\\s([^\\s]+)~im', $comment, $match)) { $route = trim(array_pop($match)); $hasRoute = true; } } if (!$hasRoute) { foreach ($method->getParameters() as $parameter) { $route .= '/{' . ($parameter->isOptional() ? '?' : '') . $parameter->getName() . '}'; } } $router->add($httpMethod, $route, [get_class($this), $methodName]); } return $router; }
/** * @param object $object an object or classname * @param string $method the method which we want to inspect */ public function reflect($object, $method) { $reflection = new \ReflectionMethod($object, $method); $docs = $reflection->getDocComment(); // extract everything prefixed by @ and first letter uppercase preg_match_all('/@([A-Z]\\w+)/', $docs, $matches); $this->annotations = $matches[1]; // extract type parameter information preg_match_all('/@param\\h+(?P<type>\\w+)\\h+\\$(?P<var>\\w+)/', $docs, $matches); $this->types = array_combine($matches['var'], $matches['type']); foreach ($reflection->getParameters() as $param) { // extract type information from PHP 7 scalar types and prefer them // over phpdoc annotations if (method_exists($param, 'getType')) { $type = $param->getType(); if ($type !== null) { $this->types[$param->getName()] = (string) $type; } } if ($param->isOptional()) { $default = $param->getDefaultValue(); } else { $default = null; } $this->parameters[$param->name] = $default; } }
public function __construct(\ReflectionMethod $method) { $this->_method = $method; $comment = $method->getDocComment(); $comment = new DocBloc($comment); $this->_annotations = $comment->getAnnotations(); }
/** * Get doc keys from a method's docblock documentation * * @param \ReflectionMethod $reflection_method Reflected method * @return array|bool List of found keys, if there are none, false is returned */ public static function getDocKeys(\ReflectionMethod $reflection_method) { $doc_comment_string = $reflection_method->getDocComment(); $keys_as_array = array('url'); /** * The following RegExpr captures @annotation. It must start with an @ symbol following by a word of one or more * charaters. Optionally followed by a space or a tab and a string. And all these annotations must end in * a proper new line (\n, \r\n etc.) to seperate the findings. */ if (preg_match_all('/@(\\w+)([ \\t](.*?))?(?:\\n|\\r)+/', $doc_comment_string, $matches, PREG_SET_ORDER)) { $keys = array(); foreach ($matches as $match) { if (in_array($match[1], $keys_as_array)) { $keys[$match[1]][] = $match[3]; } else { if (!isset($match[2])) { $keys[$match[1]] = true; } else { $keys[$match[1]] = $match[3]; } } } return $keys; } return false; }
/** * 获取方法的功能说明 */ public function getMethodNote($module, $method) { $func = new \ReflectionMethod($module, $method); $tmp = $func->getDocComment(); preg_match("/@note(.*?)\n/", $tmp, $note); return trim($note[1]); }
/** * Create a new mock of the curlbuilder and return * the given filename as content * * @access public * @param PHPUnit_Framework_TestCase $instance * @return mock */ public static function create($instance) { $reflection = new \ReflectionMethod($instance, $instance->getName()); $doc_block = $reflection->getDocComment(); $responsefile = self::parseDocBlock($doc_block, '@responsefile'); $responsecode = self::parseDocBlock($doc_block, '@responsecode'); $defaultheaders = array("X-Ratelimit-Limit" => "1000", "X-Ratelimit-Remaining" => "998", "X-Varnish" => "4059929980"); $skipmock = self::parseDocBlock($doc_block, '@skipmock'); if (empty($responsecode)) { $responsecode = [201]; } if (empty($responsefile)) { $responsefile = [$instance->getName()]; } // Setup Curlbuilder mock $curlbuilder = $instance->getMockBuilder("\\DirkGroenen\\Pinterest\\Utils\\CurlBuilder")->getMock(); $curlbuilder->expects($instance->any())->method('create')->will($instance->returnSelf()); // Build response file path $responseFilePath = __DIR__ . '/../responses/' . (new \ReflectionClass($instance))->getShortName() . '/' . $responsefile[0] . ".json"; if (file_exists($responseFilePath)) { $curlbuilder->expects($instance->once())->method('execute')->will($instance->returnValue(file_get_contents($responseFilePath))); } $curlbuilder->expects($instance->any())->method('getInfo')->will($instance->returnValue($responsecode[0])); return $curlbuilder; }
private function parseDocBlock() { if (!$this->parsedDocBlock) { $parsed = ['description' => [], 'help' => [], 'param' => [], 'option' => []]; $tag = '@(?P<tag>[^ \\t]+)[ \\t]+'; $name = '\\$(?P<name>[^ \\t]+)[ \\t]+'; $type = '(?P<type>[^ \\t]+)[ \\t]+'; $description = '(?P<description>.*)'; $isTag = '/^\\*[* \\t]+@/'; $option = "/{$tag}{$name}{$description}/"; $argument1 = "/{$tag}{$type}{$name}{$description}/"; $argument2 = "/{$tag}{$name}{$type}{$description}/"; $null = []; $doc = $this->reflection->getDocComment(); if ($doc) { $current =& $parsed['description']; foreach (explode("\n", $doc) as $row) { $row = trim($row); if ($row == '/**' || $row == '*/') { continue; } // @option definitions if (stripos($row, '@option') !== false && preg_match($option, $row, $match)) { $parsed[$match['tag']][$match['name']] = [$match['description']]; $current =& $parsed[$match['tag']][$match['name']]; } elseif (stripos($row, '@param') !== false && preg_match($argument1, $row, $match)) { $parsed[$match['tag']][$match['name']] = [$match['description']]; $current =& $parsed[$match['tag']][$match['name']]; } elseif (stripos($row, '@param') !== false && preg_match($argument2, $row, $match)) { $parsed[$match['tag']][$match['name']] = [$match['description']]; $current =& $parsed[$match['tag']][$match['name']]; } elseif (!preg_match($isTag, $row)) { $current[] = substr(trim($row, '*/'), 1); if ($current === $parsed['description']) { $current =& $parsed['help']; } } else { $current =& $null; } } } $parsed['description'] = $this->combineParsedComment($parsed['description']); $parsed['help'] = trim($this->combineParsedComment($parsed['help'], true)); foreach ($parsed['param'] as &$param) { $param = $this->combineParsedComment($param); } foreach ($parsed['option'] as &$option) { $option = $this->combineParsedComment($option); } if (empty($parsed['description'])) { $parsed['description'] = null; } if (empty($parsed['help'])) { $parsed['help'] = null; } $this->parsedDocBlock = $parsed; } return $this->parsedDocBlock; }
/** * @param \ReflectionMethod $method * @return void */ protected function writeDocCommentOfMethod(\ReflectionMethod $method) { if ($method->getDocComment()) { $this->writeString(' '); $this->writeString($method->getDocComment()); $this->writeString(PHP_EOL); } }
public static function getMethodBodyAndDocComment($cls, $mtd) { $func = new \ReflectionMethod($cls, $mtd); $start_line = $func->getStartLine() + 1; $length = $func->getEndLine() - $start_line - 1; $lines = array_slice(file($func->getFileName()), $start_line, $length); return array(implode('', $lines), $func->getDocComment()); }
private function extractReturnTypeFromAnnotations(\ReflectionMethod $method) { $doc = $method->getDocComment(); if (preg_match('/@return(?:s)?\\s+([^\\s]+)/', $doc, $matches)) { return $matches[1]; } return null; }