/** * Run the application */ public function run() { // Determine the client-side path to root if (!empty($_SERVER['REQUEST_URI'])) { $this->rootPath = preg_replace('/(index\\.php)?(\\?.*)?$/', '', $_SERVER['REQUEST_URI']); if (!empty($_GET['q'])) { $this->rootPath = preg_replace('/' . preg_quote($_GET['q'], '/') . '$/', '', $this->rootPath); } } // Extract controller name, view name, action name and arguments from URL $controllerName = 'Index'; if (!empty($_GET['q'])) { $this->args = explode('/', $_GET['q']); if ($this->args) { $controllerName = str_replace(' ', '/', ucwords(str_replace('_', ' ', str_replace('-', '', array_shift($this->args))))); } if ($action = $this->args ? array_shift($this->args) : '') { $this->action = str_replace('-', '', $action); } } if (!is_file('Swiftlet/Controllers/' . $controllerName . '.php')) { $controllerName = 'Error404'; } $this->view = new View($this, strtolower($controllerName)); // Instantiate the controller $controllerName = 'Swiftlet\\Controllers\\' . basename($controllerName); $this->controller = new $controllerName($this, $this->view); // Load plugins if ($handle = opendir('Swiftlet/Plugins')) { while (($file = readdir($handle)) !== FALSE) { if (is_file('Swiftlet/Plugins/' . $file) && preg_match('/^(.+)\\.php$/', $file, $match)) { $pluginName = 'Swiftlet\\Plugins\\' . $match[1]; $this->plugins[$pluginName] = array(); foreach (get_class_methods($pluginName) as $methodName) { $method = new \ReflectionMethod($pluginName, $methodName); if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) { $this->plugins[$pluginName][] = $methodName; } } } } ksort($this->plugins); closedir($handle); } // Call the controller action $this->registerHook('actionBefore'); if (method_exists($this->controller, $this->action)) { $method = new \ReflectionMethod($this->controller, $this->action); if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor()) { $this->controller->{$this->action}(); } else { $this->controller->notImplemented(); } } else { $this->controller->notImplemented(); } $this->registerHook('actionAfter'); return array($this->view, $this->controller); }
/** * Returns whether this method is final * * @return boolean TRUE if this method is final */ public function isFinal() { if ($this->reflectionSource instanceof ReflectionMethod) { return $this->reflectionSource->isFinal(); } else { return parent::isFinal(); } }
/** * Determines if the method is suitable to be used by the processor. * (see \Magento\Framework\Reflection\MethodsMap::isSuitableMethod) * * @param \ReflectionMethod $method * @return bool */ public function _isSuitableMethod(\ReflectionMethod $method) { /* '&&' usage is shorter then '||', if first part is 'false' then all equity is false */ $isSuitableMethodType = !$method->isStatic() && !$method->isFinal() && !$method->isConstructor() && !$method->isDestructor(); $isExcludedMagicMethod = strpos($method->getName(), '__') === 0; $result = $isSuitableMethodType && !$isExcludedMagicMethod; return $result; }
private function generateMethodCode(\ReflectionMethod $method) { $name = $method->getName(); if ($method->isStatic() || $method->isFinal() || $name == '__construct') { return ''; } $params = array(); foreach ($method->getParameters() as $parameter) { $params[] = $this->getParameterInfo($parameter); } return SurrogateMethodGenerator::generateDelegators($name, $params); }
public static function fromReflection(\ReflectionMethod $ref) { $method = new static($ref->name); $method->setFinal($ref->isFinal())->setAbstract($ref->isAbstract())->setStatic($ref->isStatic())->setVisibility($ref->isPublic() ? self::VISIBILITY_PUBLIC : ($ref->isProtected() ? self::VISIBILITY_PROTECTED : self::VISIBILITY_PRIVATE))->setReferenceReturned($ref->returnsReference())->setBody(ReflectionUtils::getFunctionBody($ref)); $docblock = new Docblock($ref); $method->setDocblock($docblock); $method->setDescription($docblock->getShortDescription()); $method->setLongDescription($docblock->getLongDescription()); foreach ($ref->getParameters() as $param) { $method->addParameter(static::createParameter($param)); } return $method; }
public static function fromReflection(\ReflectionMethod $ref) { $method = new static(); $method->setFinal($ref->isFinal())->setAbstract($ref->isAbstract())->setStatic($ref->isStatic())->setVisibility($ref->isPublic() ? self::VISIBILITY_PUBLIC : ($ref->isProtected() ? self::VISIBILITY_PROTECTED : self::VISIBILITY_PRIVATE))->setReferenceReturned($ref->returnsReference())->setName($ref->name); if ($docComment = $ref->getDocComment()) { $method->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment)); } foreach ($ref->getParameters() as $param) { $method->addParameter(static::createParameter($param)); } // FIXME: Extract body? return $method; }
/** * @param \ReflectionMethod $method * @return \Phpy\Method\Method */ public function method(\ReflectionMethod $method) { $phpyMethod = new Method($method->getName()); $phpyMethod->setStatic($method->isStatic())->setFinal($method->isFinal())->setAbstract($method->isAbstract()); if ($method->isPublic()) { $phpyMethod->setVisibility('public'); } elseif ($method->isProtected()) { $phpyMethod->setVisibility('protected'); } else { $phpyMethod->setVisibility('private'); } foreach ($method->getParameters() as $refParameter) { $phpyMethod->addParameter($this->parameter($refParameter)); } return $phpyMethod; }
/** * Initializes method prophecy. * * @param ObjectProphecy $objectProphecy * @param string $methodName * @param null|Argument\ArgumentsWildcard|array $arguments * * @throws \Prophecy\Exception\Doubler\MethodNotFoundException If method not found */ public function __construct(ObjectProphecy $objectProphecy, $methodName, $arguments = null) { $double = $objectProphecy->reveal(); if (!method_exists($double, $methodName)) { throw new MethodNotFoundException(sprintf('Method `%s::%s()` is not defined.', get_class($double), $methodName), get_class($double), $methodName, $arguments); } $this->objectProphecy = $objectProphecy; $this->methodName = $methodName; $reflectedMethod = new \ReflectionMethod($double, $methodName); if ($reflectedMethod->isFinal()) { throw new MethodProphecyException(sprintf("Can not add prophecy for a method `%s::%s()`\n" . "as it is a final method.", get_class($double), $methodName), $this); } if (null !== $arguments) { $this->withArguments($arguments); } }
/** * Initializes method prophecy. * * @param ObjectProphecy $objectProphecy * @param string $methodName * @param null|Argument\ArgumentsWildcard|array $arguments * * @throws \Prophecy\Exception\Doubler\MethodNotFoundException If method not found */ public function __construct(ObjectProphecy $objectProphecy, $methodName, $arguments = null) { $double = $objectProphecy->reveal(); if (!method_exists($double, $methodName)) { throw new MethodNotFoundException(sprintf('Method `%s::%s()` is not defined.', get_class($double), $methodName), get_class($double), $methodName, $arguments); } $this->objectProphecy = $objectProphecy; $this->methodName = $methodName; $reflectedMethod = new \ReflectionMethod($double, $methodName); if ($reflectedMethod->isFinal()) { throw new MethodProphecyException(sprintf("Can not add prophecy for a method `%s::%s()`\n" . "as it is a final method.", get_class($double), $methodName), $this); } if (null !== $arguments) { $this->withArguments($arguments); } if (version_compare(PHP_VERSION, '7.0', '>=') && true === $reflectedMethod->hasReturnType()) { $type = (string) $reflectedMethod->getReturnType(); $this->will(function () use($type) { switch ($type) { case 'string': return ''; case 'float': return 0.0; case 'int': return 0; case 'bool': return false; case 'array': return array(); case 'callable': case 'Closure': return function () { }; case 'Traversable': case 'Generator': // Remove eval() when minimum version >=5.5 /** @var callable $generator */ $generator = eval('return function () { yield; };'); return $generator(); default: $prophet = new Prophet(); return $prophet->prophesize($type)->reveal(); } }); } }
function reflectMethod($class, $method) { $methodInfo = new ReflectionMethod($class, $method); echo "**********************************\n"; echo "Reflecting on method {$class}::{$method}()\n\n"; echo "\nisFinal():\n"; var_dump($methodInfo->isFinal()); echo "\nisAbstract():\n"; var_dump($methodInfo->isAbstract()); echo "\nisPublic():\n"; var_dump($methodInfo->isPublic()); echo "\nisPrivate():\n"; var_dump($methodInfo->isPrivate()); echo "\nisProtected():\n"; var_dump($methodInfo->isProtected()); echo "\nisStatic():\n"; var_dump($methodInfo->isStatic()); echo "\nisConstructor():\n"; var_dump($methodInfo->isConstructor()); echo "\nisDestructor():\n"; var_dump($methodInfo->isDestructor()); echo "\n**********************************\n"; }
function methodData(ReflectionMethod $method) { $details = ""; $name = $method->getName(); if ($method->isUserDefined()) { $details .= "{$name} is user defined\n"; } if ($method->isInternal()) { $details .= "{$name} is built-in\n"; } if ($method->isAbstract()) { $details .= "{$name} is abstract\n"; } if ($method->isPublic()) { $details .= "{$name} is public\n"; } if ($method->isProtected()) { $details .= "{$name} is protected\n"; } if ($method->isPrivate()) { $details .= "{$name} is private\n"; } if ($method->isStatic()) { $details .= "{$name} is static\n"; } if ($method->isFinal()) { $details .= "{$name} is final\n"; } if ($method->isConstructor()) { $details .= "{$name} is the constructor\n"; } if ($method->returnsReference()) { $details .= "{$name} returns a reference (as opposed to a value)\n"; } return $details; }
/** * Determine if the given method may be proxied. * * Since it is not possible to reflect a * - constructor * - final method * - static method * those will cause this method to return false. * Also methods registered in the blacklist will cause this * method to return false. * * @param \ReflectionMethod $method Name of the method to be reflected. * * @return boolean True, if the given method may be reflected, else false. */ protected static function canProxyMethod(\ReflectionMethod $method) { if ($method->isConstructor() || $method->isFinal() || $method->isStatic() || isset(self::$blacklistedMethodNames[$method->getName()])) { return false; } elseif ($method->isProtected()) { return true; } return false; }
/** * @param ReflectionMethod $method * @return boolean */ protected static function canMockMethod(ReflectionMethod $method) { if ($method->isConstructor() || $method->isFinal() || isset(self::$blacklistedMethodNames[$method->getName()])) { return FALSE; } return TRUE; }
public function scan() { require_once $this->path; $ns = ""; $_ns = ""; $ns_bracket = false; $aliases = []; $tokens = new Tokenizer(FS::get($this->path)); while ($tokens->valid()) { if ($tokens->is(T_NAMESPACE)) { $ns = ""; $_ns = ""; $tokens->next(); if ($tokens->is(T_STRING)) { $ns = $this->_parseName($tokens); if ($tokens->is('{')) { $tokens->skip(); $ns_bracket = true; } else { $tokens->skipIf(';'); } $_ns = $ns . '\\'; } elseif ($tokens->is('{')) { $ns_bracket = true; $tokens->next(); } } elseif ($tokens->is(T_USE)) { do { $tokens->next(); $name = $this->_parseName($tokens); if ($tokens->is(T_AS)) { $aliases[$tokens->next()->get(T_STRING)] = $name; $tokens->next(); } else { if (strpos($name, '\\') === false) { $aliases[$name] = $name; } else { $aliases[ltrim('\\', strrchr($name, '\\'))] = $name; } } } while ($tokens->is(',')); $tokens->need(';')->next(); } elseif ($tokens->is(T_CONST)) { $name = $tokens->next()->get(T_STRING); $constant = new EntityConstant($_ns . $name); $constant->setValue(constant($_ns . $name)); $constant->setLine($this->line($tokens->getLine())); $this->constants[$_ns . $name] = $constant; $tokens->forwardTo(';')->next(); } elseif ($tokens->is(T_FUNCTION)) { $name = $tokens->next()->get(T_STRING); $function = new EntityFunction($_ns . $name); $function->setLine($this->line($tokens->getLine())); $function->setAliases($aliases); $this->parseCallable($function, new \ReflectionFunction($function->name)); $function->setBody($tokens->forwardTo('{')->getScope()); $tokens->next(); $this->functions[$function->name] = $function; } elseif ($tokens->is(T_FINAL, T_ABSTRACT, T_INTERFACE, T_TRAIT, T_CLASS)) { $tokens->forwardTo(T_STRING); $name = $tokens->current(); $class = new EntityClass($_ns . $name); $ref = new \ReflectionClass($class->name); $doc = $ref->getDocComment(); // if($name == "NamesInterface") { // drop($ref); // } if ($ref->isInterface()) { $class->addFlag(Flags::IS_INTERFACE); } elseif ($ref->isTrait()) { $class->addFlag(Flags::IS_TRAIT); } else { $class->addFlag(Flags::IS_CLASS); } if ($ref->isAbstract()) { $class->addFlag(Flags::IS_ABSTRACT); } elseif ($ref->isFinal()) { $class->addFlag(Flags::IS_FINAL); } if ($doc) { $info = ToolKit::parseDoc($doc); $class->setDescription($info['desc']); $class->addOptions($info['options']); } $class->setAliases($aliases); $class->setLine($this->line($tokens->getLine())); $tokens->next(); if ($tokens->is(T_EXTENDS)) { // process 'extends' keyword do { $tokens->next(); $root = $tokens->is(T_NS_SEPARATOR); $parent = $this->_parseName($tokens); if ($root) { // extends from root namespace $class->setParent($parent, $class->isInterface()); } elseif (isset($aliases[$parent])) { $class->setParent($aliases[$parent], $class->isInterface()); } else { $class->setParent($_ns . $parent, $class->isInterface()); } } while ($tokens->is(',')); } if ($tokens->is(T_IMPLEMENTS)) { // process 'implements' keyword do { $tokens->next(); $root = $tokens->is(T_NS_SEPARATOR); $parent = $this->_parseName($tokens); if ($root) { // extends from root namespace $class->addInterface($parent); } elseif (isset($aliases[$parent])) { $class->addInterface($aliases[$parent]); } else { $class->addInterface($_ns . $parent); } } while ($tokens->is(',')); } $tokens->forwardTo('{')->next(); while ($tokens->forwardTo(T_CONST, T_FUNCTION, '{', '}', T_VARIABLE) && $tokens->valid()) { switch ($tokens->key()) { case T_CONST: $constant = new EntityConstant($class->name . '::' . $tokens->next()->get(T_STRING)); $constant->setValue(constant($constant->name)); $constant->setLine(new Line($this, $tokens->getLine())); $class->addConstant($constant); break; case T_VARIABLE: $property = new EntityProperty(ltrim($tokens->getAndNext(), '$')); $ref = new \ReflectionProperty($class->name, $property->name); $doc = $ref->getDocComment(); if ($doc) { $property->setDescription(ToolKit::parseDoc($doc)['desc']); } if ($ref->isPrivate()) { $property->addFlag(Flags::IS_PRIVATE); } elseif ($ref->isProtected()) { $property->addFlag(Flags::IS_PROTECTED); } else { $property->addFlag(Flags::IS_PUBLIC); } if ($ref->isStatic()) { $property->addFlag(Flags::IS_STATIC); } if ($ref->isDefault()) { $property->setValue($ref->getDeclaringClass()->getDefaultProperties()[$property->name]); } $class->addProperty($property); break; case T_FUNCTION: $method = new EntityMethod($name . '::' . $tokens->next()->get(T_STRING)); $method->setLine($this->line($tokens->getLine())); $this->parseCallable($method, $ref = new \ReflectionMethod($class->name, $method->short)); if ($ref->isPrivate()) { $method->addFlag(Flags::IS_PRIVATE); } elseif ($ref->isProtected()) { $method->addFlag(Flags::IS_PROTECTED); } else { $method->addFlag(Flags::IS_PUBLIC); } if ($ref->isStatic()) { $method->addFlag(Flags::IS_STATIC); } if ($ref->isAbstract()) { $method->addFlag(Flags::IS_ABSTRACT); $method->addFlag(Flags::IS_ABSTRACT_IMPLICIT); } elseif ($ref->isFinal()) { $method->addFlag(Flags::IS_FINAL); } if (isset($method->options['deprecated'])) { $method->addFlag(Flags::IS_DEPRECATED); } $tokens->forwardTo(')')->next(); if ($tokens->is('{')) { $method_body = $tokens->getScope(); $method->setBody($method_body); } $tokens->next(); $class->addMethod($method); break; case '{': // use traits scope $tokens->forwardTo('}')->next(); break; case '}': // end of class $tokens->next(); $this->classes[$class->name] = $class; break 2; } } } elseif ($tokens->is('}') && $ns_bracket) { $tokens->next(); $ns_bracket = false; } else { drop($tokens->curr); if ($tokens->valid()) { throw new UnexpectedTokenException($tokens); } break; } } }
/** * @param ReflectionMethod $method * * @return bool */ private function canMockMethod(ReflectionMethod $method) { if ($method->isConstructor() || $method->isFinal() || $method->isPrivate() || $this->isMethodNameBlacklisted($method->getName())) { return false; } return true; }
<pre> <?php class Counter { private static $c = 0; public static final function increment() { return ++self::$c; } } // Создание экземпляра класса ReflectionMethod $method = new ReflectionMethod('Counter', 'increment'); // exit; // Вывод основной информации printf("===> %s%s%s%s%s%s%s метод '%s' (который является %s)\n" . " объявлен в %s\n" . " строки с %d по %d\n" . " имеет модификаторы %d[%s]\n", $method->isInternal() ? 'Встроенный' : 'Пользовательский', $method->isAbstract() ? ' абстрактный' : '', $method->isFinal() ? ' финальный' : '', $method->isPublic() ? ' public' : '', $method->isPrivate() ? ' private' : '', $method->isProtected() ? ' protected' : '', $method->isStatic() ? ' статический' : '', $method->getName(), $method->isConstructor() ? 'конструктором' : 'обычным методом', $method->getFileName(), $method->getStartLine(), $method->getEndline(), $method->getModifiers(), implode(' ', Reflection::getModifierNames($method->getModifiers()))); // Вывод статических переменных, если они есть if ($statics = $method->getStaticVariables()) { printf("---> Статическая переменная: %s\n", var_export($statics, 1)); } // Вызов метода printf("---> Результат вызова: "); $result = $method->invoke(3); echo $result; ?> </pre>
protected function canMockMethod(ReflectionMethod $method) { $className = $method->getDeclaringClass()->getName(); $methodName = $method->getName(); if ($method->isFinal() || $methodName == '__construct' || $methodName == $className || $methodName == '__destruct' || $method->getName() == '__clone') { return FALSE; } return TRUE; }
/** * Determines if the method is suitable to be used by the processor. * * @param \ReflectionMethod $method * @return bool */ private function isSuitableMethod($method) { $isSuitableMethodType = !($method->isConstructor() || $method->isFinal() || $method->isStatic() || $method->isDestructor()); $isExcludedMagicMethod = strpos($method->getName(), '__') === 0; return $isSuitableMethodType && !$isExcludedMagicMethod; }
/** * @return bool */ public function isFinal() { return $this->reflectionMethod->isFinal(); }
/** * @param ReflectionMethod $method * * @return boolean */ protected function canMockMethod(ReflectionMethod $method) { if ($method->isConstructor() || $method->isFinal() || $method->isPrivate() || isset($this->blacklistedMethodNames[$method->getName()])) { return false; } return true; }
/** * Whether method is intercepted * * @param \ReflectionMethod $method * @return bool */ protected function isInterceptedMethod(\ReflectionMethod $method) { return !($method->isConstructor() || $method->isFinal() || $method->isStatic() || $method->isDestructor()) && !in_array($method->getName(), ['__sleep', '__wakeup', '__clone']); }
/** * Check if the specified method should be used during generation builder generation. * * @param \ReflectionMethod $method * @return bool */ protected function canUseMethodForGeneration($method) { $isGetter = substr($method->getName(), 0, 3) == 'get' || substr($method->getName(), 0, 2) == 'is'; $isSuitableMethodType = !($method->isConstructor() || $method->isFinal() || $method->isStatic() || $method->isDestructor()); $isMagicMethod = in_array($method->getName(), ['__sleep', '__wakeup', '__clone']); $isPartOfExtensibleInterface = in_array($method->getName(), $this->getExtensibleInterfaceMethods()); return $isGetter && $isSuitableMethodType && !$isMagicMethod && !$isPartOfExtensibleInterface; }
class Counter { private static $c = 0; /** * Increment counter * * @final * @static * @access public * @return int */ public static final function increment() { return ++self::$c; } } // Create an instance of the ReflectionMethod class $method = new ReflectionMethod('Counter', 'increment'); // Print out basic information printf("===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" . " declared in %s\n" . " lines %d to %d\n" . " having the modifiers %d[%s]\n", $method->isInternal() ? 'internal' : 'user-defined', $method->isAbstract() ? ' abstract' : '', $method->isFinal() ? ' final' : '', $method->isPublic() ? ' public' : '', $method->isPrivate() ? ' private' : '', $method->isProtected() ? ' protected' : '', $method->isStatic() ? ' static' : '', $method->getName(), $method->isConstructor() ? 'the constructor' : 'a regular method', $method->getFileName(), $method->getStartLine(), $method->getEndline(), $method->getModifiers(), implode(' ', Reflection::getModifierNames($method->getModifiers()))); echo "\n"; // Print documentation comment printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1)); // Print static variables if existant if ($statics = $method->getStaticVariables()) { printf("---> Static variables: %s\n", var_export($statics, 1)); } echo "\n"; // Invoke the method printf("---> Invocation results in: "); var_dump($method->invoke(NULL));
function methodData(ReflectionMethod $method) { $details = ""; $name = $method->getName(); if ($method->isUserDefined()) { $details .= "{$name} -- метод определён пользователем<br>"; } if ($method->isInternal()) { $details .= "{$name} -- внутренний метод<br>"; } if ($method->isAbstract()) { $details .= "{$name} -- абстрактный метод<br>"; } if ($method->isPublic()) { $details .= "{$name} -- публичный метод<br>"; } if ($method->isProtected()) { $details .= "{$name} -- защищенный метод<br>"; } if ($method->isPrivate()) { $details .= "{$name} -- закрытый метод метод<br>"; } if ($method->isStatic()) { $details .= "{$name} -- статичный метод<br>"; } if ($method->isFinal()) { $details .= "{$name} -- финальный метод<br>"; } if ($method->isConstructor()) { $details .= "{$name} -- метод конструктора<br>"; } if ($method->returnsReference()) { $details .= "{$name} -- метод возвращает ссылку а не значение<br>"; } return $details; }
/** * Load listeners * @return App */ public function loadListeners() { // Load listeners if ($handle = opendir($this->vendorPath . str_replace('\\', '/', $this->vendor . '/Listeners'))) { while (($file = readdir($handle)) !== false) { $listenerClass = $this->vendor . '\\Listeners\\' . preg_replace('/\\.php$/', '', $file); if (is_file($this->vendorPath . str_replace('\\', '/', $listenerClass) . '.php')) { $this->listeners[$listenerClass] = array(); $reflection = new \ReflectionClass($listenerClass); $parentClass = $reflection->getParentClass(); foreach (get_class_methods($listenerClass) as $methodName) { $method = new \ReflectionMethod($listenerClass, $methodName); if ($method->isPublic() && !$method->isFinal() && !$method->isConstructor() && !$parentClass->hasMethod($methodName)) { $this->listeners[$listenerClass][] = $methodName; } } } } ksort($this->listeners); closedir($handle); } return $this; }
protected function __new__($class_package, $class_name, ReflectionMethod $method = null) { if (isset($method)) { $self_class = $method->getDeclaringClass()->getName(); $this->name($method->getName()); $this->pure_perm($method->isPublic() ? "public" : ($method->isProtected() ? "protected" : "private")); $this->perm($this->name[0] == "_" ? "private" : ($method->isPublic() ? "public" : ($method->isProtected() ? "protected" : "private"))); $this->static($method->isStatic()); $this->final($method->isFinal()); $this->extends($class_name !== $self_class); $this->class_package = $class_package; foreach ($method->getParameters() as $p) { $this->param[$p->getName()] = new InfoAt($p->getName(), $this->class_package); $this->param[$p->getName()]->reference($p->isPassedByReference()); if ($p->isDefaultValueAvailable()) { $this->param[$p->getName()]->default($p->getDefaultValue()); } } $class_path = $method->getDeclaringClass()->getFileName(); if ($class_path !== false) { $this->line($method->getStartLine()); if (!isset($source[$class_path])) { $source[$class_path] = file($class_path); } $msrc = implode(array_slice($source[$class_path], $method->getStartLine(), $method->getEndLine() - $method->getStartLine())); if (is_subclass_of($self_class, 'Flow') || $self_class == 'Flow') { if (preg_match_all('/\\$this->in_vars\\((["\'])(.+?)\\1/', $msrc, $match)) { foreach ($match[2] as $n) { $this->request[$n] = new InfoAt($n, $this->class_package); $this->context[$n] = new InfoAt($n, $this->class_package); } } if (preg_match_all('/\\$this->rm_vars\\((["\'])(.+?)\\1/', $msrc, $match)) { foreach ($match[2] as $n) { $this->rm_context($n); } } if (preg_match_all('/\\$this->vars\\((["\'])(.+?)\\1/', $msrc, $match)) { foreach ($match[2] as $n) { $this->context[$n] = new InfoAt($n, $this->class_package); } } if (preg_match_all('/\\$this->(map_arg|redirect_by_map)\\((["\'])(.+?)\\2/', $msrc, $match)) { foreach ($match[3] as $n) { $this->arg[$n] = new InfoAt($n, $this->class_package); } } } if (preg_match_all('/throw new[\\s]+([\\w]+)/', $msrc, $match)) { foreach ($match[1] as $n) { $p = new InfoAt(); $p->set($n, $this->class_package); $this->exception[$p->type()] = $p; } } if (preg_match_all("/->call_module\\(([\"'])(.+?)\\1/", $msrc, $match)) { foreach ($match[2] as $v) { $this->module[$v] = new InfoAt($v, $this->class_package); } } $this->test = InfoDoctest::get($msrc, $self_class, $this->class_package, $method->getStartLine(), $this->name()); if (preg_match_all("/(\\/\\/|#)[\\s]*TODO[\t ]+(.+)/", $msrc, $todos)) { foreach ($todos[2] as $v) { $this->tasks[] = trim($v); } } } $this->document(trim(preg_replace("/^[\\s]*\\*[\\s]{0,1}/m", "", str_replace(array("/" . "**", "*" . "/"), "", $method->getDocComment())))); } }
/** * Runs first found registered handler that matches request URI * * @param string $uri Request URI * @throws NotFoundException if handler for request method not registered * @throws UnknownMethodException if request method is not allowed * @throws ForbiddenException if user is not authorized */ public function dispatch($uri) { $method = $this->Request->getMethod(); if (!$this->authorize($method, $uri)) { throw new ForbiddenException("Not allowed"); } // try to match ReST controller first $controller = $this->createController($method, $uri); if ($controller !== NULL) { if (method_exists($controller, $method)) { $reflection = new \ReflectionMethod($controller, $method); if ($reflection->isFinal()) { $out = $controller->{$method}(); } else { // unsupported HTTP request method or corresponding controller // method is not declared final throw new \Stream\Exception\UnknownMethodException("Hacker?"); } } else { throw new NotFoundException('Page `$uri` not found'); } if ($controller->redirect()) { header('Location: ' . $controller->redirect()); } return $this->serialize($out); } $headers = $this->Request->getHeaders(); $revalidate = !empty($headers['Cache-Control']) && strpos($headers['Cache-Control'], 'max-age=0') !== FALSE ? true : false; $cached = $this->Cache->fetch($uri); // cached and valid if (!$revalidate && $method === 'GET' && !empty($cached)) { echo $cached; return; } $controller = $this->createDomainController($uri); ob_start(function ($buffer) use($uri, $method) { if ($method == 'GET') { $this->Cache->store($uri, $buffer, $this->cache_ttl); } return $buffer; }); if ($controller instanceof DomainControllerInterface) { try { $out = $controller->dispatch($uri); } catch (NotFoundException $e) { ob_end_clean(); throw $e; } if ($controller->redirect()) { header('Location: ' . $controller->redirect()); ob_end_clean(); return; } ob_end_flush(); return $out; } else { switch ($method) { case 'POST': $handlers =& $this->post_handlers; break; case 'GET': $handlers =& $this->get_handlers; break; case 'DELETE': $handlers =& $this->delete_handlers; break; case 'PUT': $handlers =& $this->put_handlers; break; default: ob_end_clean(); throw new UnknownMethodException($method . " not allowed"); } $handler = null; foreach ($handlers as $regexp => $func) { $params = $this->match($regexp, $uri); if (is_array($params)) { $handler = $func; break; } } if ($handler === null) { ob_end_clean(); if (is_callable($this->hook('hook.notFound'))) { // php < 7 complains $_f = $this->hook('hook.notFound'); return $_f($uri); } else { throw new NotFoundException("Could not " . $method . ' ' . $uri); } } if (is_callable($handler)) { $handler($params); } } ob_end_flush(); }
} catch (TypeError $re) { echo "Ok - " . $re->getMessage() . PHP_EOL; } try { new ReflectionMethod('a', 'b', 'c'); } catch (TypeError $re) { echo "Ok - " . $re->getMessage() . PHP_EOL; } class C { public function f() { } } $rm = new ReflectionMethod('C', 'f'); var_dump($rm->isFinal(1)); var_dump($rm->isAbstract(1)); var_dump($rm->isPrivate(1)); var_dump($rm->isProtected(1)); var_dump($rm->isPublic(1)); var_dump($rm->isStatic(1)); var_dump($rm->isConstructor(1)); var_dump($rm->isDestructor(1)); var_dump($rm->getModifiers(1)); var_dump($rm->isInternal(1)); var_dump($rm->isUserDefined(1)); var_dump($rm->getFileName(1)); var_dump($rm->getStartLine(1)); var_dump($rm->getEndLine(1)); var_dump($rm->getStaticVariables(1)); var_dump($rm->getName(1));
/** * Imports a method that is obtained via reflection. * * @param \ReflectionMethod $method Method that is to be imported. * * @see self::reflectInternalClass for a complete description. * * @return \DOMElement|null */ protected function importReflectedMethod(\ReflectionMethod $method) { if ($method->isPrivate()) { return null; } $class_name = $method->getDeclaringClass()->getName(); $methods = $this->getMethods(); if (in_array($method->getName(), array_keys($methods))) { $methods[$method->getName()]->getNode()->appendChild(new \DOMElement('overrides-from', $class_name)); return $methods[$method->getName()]->getNode(); } $method_node = new \DOMElement('method'); $this->node->appendChild($method_node); $node_name = new \DOMElement('name', $method->getName()); $method_node->appendChild($node_name); $method_node->setAttribute('final', $method->isFinal() ? 'true' : 'false'); $method_node->setAttribute('abstract', $method->isAbstract() ? 'true' : 'false'); $method_node->setAttribute('static', $method->isStatic() ? 'true' : 'false'); $method_node->setAttribute('visibility', $method->isPublic() ? 'public' : 'protected'); $method_obj = new MethodNode($method_node, $this->nodes, $this); $inherited_from = new \DOMElement('tag'); $method_obj->getDocBlock()->getNode()->appendChild($inherited_from); $inherited_from->setAttribute('name', 'inherited_from'); $inherited_from->setAttribute('refers', $method->getDeclaringClass()->getName() . '::' . $method->getName() . '()'); $inherited_from->setAttribute('description', $method->getDeclaringClass()->getName() . '::' . $method->getName() . '()'); return $method_node; }
/** * Override parent method with joinpoint invocation * * @param Method|ParsedMethod $method Method reflection */ protected function overrideMethod($method) { // temporary disable override of final methods if (!$method->isFinal() && !$method->isAbstract()) { $this->override($method->name, $this->getJoinpointInvocationBody($method)); } }