/** * @param \ReflectionMethod $method * @return bool */ private function isAutoloadMethod(\ReflectionMethod $method) { if (strpos($method->getName(), KnotConsts::AUTOLOAD_METHOD_PREFIX) !== 0 || $method->getNumberOfParameters() != 1 || $method->getNumberOfRequiredParameters() != 1 || $method->isStatic() || $method->isAbstract() || !Extractor::instance()->has($method, KnotConsts::AUTOLOAD_ANNOTATIONS)) { return false; } return true; }
/** * @param App\Request $request * @return App\IResponse */ public function run(App\Request $request) { $this->request = $request; $this->startup(); if (!$this->startupCheck) { $class = (new \ReflectionClass($this))->getMethod('startup')->getDeclaringClass()->getName(); throw new Nette\InvalidStateException("'{$class}::startup()' or its descendant does not call parent method"); } try { $rm = new \ReflectionMethod($this, $this->getAction()); } catch (\ReflectionException $e) { } if (isset($e) || $rm->isAbstract() || $rm->isStatic() || !$rm->isPublic()) { throw new App\BadRequestException("Method '{$request->getMethod()}' not allowed", 405); } $params = $this->getParameters(); $args = App\UI\PresenterComponentReflection::combineArgs($rm, $params); $response = $rm->invokeArgs($this, $args); if ($response === null) { $response = new Responses\NullResponse(); } elseif (!$response instanceof App\IResponse) { throw new Nette\InvalidStateException("Action '{$this->getAction(true)}' does not return instance of Nette\\Application\\IResponse"); } return $response; }
/** * Returns whether this method is abstract * * @return boolean TRUE if this method is abstract */ public function isAbstract() { if ($this->reflectionSource instanceof ReflectionMethod) { return $this->reflectionSource->isAbstract(); } else { return parent::isAbstract(); } }
/** * @inheritdoc */ public function condition(\ReflectionMethod $method) { if ($method->isPublic() && !($method->isAbstract() || $method->isConstructor() || $method->isDestructor())) { if ($this->isTest || strlen($method->name) > 4 && substr($method->name, 0, 4) === 'test') { return true; } } return false; }
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; }
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; }
/** * @param \ReflectionMethod $reflectionMethod * @param \Donquixote\HastyReflectionCommon\Reflection\FunctionLike\MethodReflectionInterface $methodReflection */ private function assertEqualMethods(\ReflectionMethod $reflectionMethod, MethodReflectionInterface $methodReflection) { $this->assertEquals($reflectionMethod->isAbstract(), $methodReflection->isAbstract()); $this->assertEquals($reflectionMethod->getDeclaringClass()->getName(), $methodReflection->getDeclaringClassName()); $this->assertEquals($reflectionMethod->getDocComment(), $methodReflection->getDocComment()); $this->assertEquals($reflectionMethod->getShortName(), $methodReflection->getName()); $this->assertEquals($reflectionMethod->getName(), $methodReflection->getName()); $this->assertEquals($reflectionMethod->class . '::' . $reflectionMethod->getName(), $methodReflection->getQualifiedName()); $this->assertEquals($reflectionMethod->returnsReference(), $methodReflection->isByReference()); $this->assertEquals($reflectionMethod->isPrivate(), $methodReflection->isPrivate()); $this->assertEquals($reflectionMethod->isProtected(), $methodReflection->isProtected()); $this->assertEquals($reflectionMethod->isPublic(), $methodReflection->isPublic()); $this->assertEquals($reflectionMethod->isStatic(), $methodReflection->isStatic()); }
/** * Resolve if callable is class method * * @param $callable * @return Invokable */ public static function ofClassMethod($callable) { // parse class::method to [class, method] if (is_string($callable) and strpos($callable, '::') !== false) { $callable = explode('::', $callable); } // resolve [class, method] if (is_array($callable) and count($callable) === 2) { $reflector = new \ReflectionMethod($callable[0], $callable[1]); if ($reflector->isPublic() and !$reflector->isStatic() and !$reflector->isAbstract()) { $annotations = array_merge(Annotation::ofClass($callable[0]), Annotation::ofMethod($callable[0], $callable[1])); return new Invokable($callable, Invokable::CLASS_METHOD, $annotations, $reflector); } } }
/** * @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; }
/** * * @param Closure|string $action * @return string * */ public static function getType($action) { if ($action instanceof \Closure) { return static::TYPE_CLOSURE; } elseif (function_exists($action)) { return static::TYPE_FUNCTION; } if (strpos($action, '::') === false) { throw new \UnexpectedValueException('Invalid value for action'); } $reflection = new \ReflectionMethod($action); if ($reflection->isAbstract() || !$reflection->isPublic()) { throw new \UnexpectedValueException('Action cannot use abstract or private methods'); } if ($reflection->isStatic()) { return static::TYPE_STATIC_METHOD; } return static::TYPE_DINAMIC_METHOD; }
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; }
} 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));
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; } } }
/** * Given a user-defined PHP class or php object, map its methods onto a list of * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server * object and called from remote clients (as well as their corresponding signature info). * * @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class * @param array $extra_options see the docs for wrap_php_method for more options * string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance * @return array or false on failure * * @todo get_class_methods will return both static and non-static methods. * we have to differentiate the action, depending on wheter we recived a class name or object */ function wrap_php_class($classname, $extra_options = array()) { $methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : ''; $methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto'; if (version_compare(phpversion(), '5.0.3') == -1) { // up to php 5.0.3 some useful reflection methods were missing error_log('XML-RPC: cannot not wrap php functions unless running php version bigger than 5.0.3'); return false; } $result = array(); $mlist = get_class_methods($classname); foreach ($mlist as $mname) { if ($methodfilter == '' || preg_match($methodfilter, $mname)) { // echo $mlist."\n"; $func = new ReflectionMethod($classname, $mname); if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) { if ($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || $methodtype == 'auto' && is_string($classname)) || !$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || $methodtype == 'auto' && is_object($classname))) { $methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options); if ($methodwrap) { $result[$methodwrap['function']] = $methodwrap['function']; } } } } } return $result; }
/** * Is a method callable? It means class is instantiable and method has * public visibility, is non-static and non-abstract. * @param string method name * @return bool */ public function hasCallableMethod($method) { $class = $this->getName(); $cache =& self::$mcCache[strtolower($class . ':' . $method)]; if ($cache === NULL) { try { $cache = FALSE; $rm = new \ReflectionMethod($class, $method); $cache = $this->isInstantiable() && $rm->isPublic() && !$rm->isAbstract() && !$rm->isStatic(); } catch (\ReflectionException $e) { } } return $cache; }
<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>
/** * Will add the given method to the list of available methods. * * @param \ReflectionMethod $method The currently reflected method * @param array(\ReflectionMethod) $result List with already found methods. * * @return array(\ReflectionMethod) */ private function _collectMethodFromParentClass(\ReflectionMethod $method, array $result) { $name = strtolower($method->getName()); if (!isset($result[$name])) { $result[$name] = $method; } else { if ($result[$name]->isAbstract() && !$method->isAbstract()) { $result[$name] = $method; } } return $result; }
/** * 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)); } }
/** * Render document method with it's parameters and return type fetched from doc comment. * * @param \ReflectionMethod $method */ protected function renderMethod(\ReflectionMethod $method) { $parameters = []; foreach ($method->getParameters() as $parameter) { $type = ''; if ($parameter->isArray()) { $type = 'array'; } if (!empty($parameter->getClass())) { $type = $parameter->getClass()->getShortName(); } $parameters[] = ltrim($type . ' ' . $parameter->getName()); } $prefix = ''; if ($method->isAbstract()) { $prefix .= '{abstract} '; } if ($method->isStatic()) { $prefix .= '{static} '; } $accessLevel = $this->access[$this->accessLevel($method)]; $returnValue = $this->returnValue($method); $this->line($prefix . $accessLevel . ' ' . $returnValue . ' ' . $method->getName() . '(' . join(', ', $parameters) . ')', 1); }
/** * 调用类/对象方法 * * @param object/class $clsobj 对象/类 * @param string $method 方法名 * @param array $args 参数数组,长度限制5个元素及以下 * @return mixed 执行结果,没有找到可执行方法时返回null */ function exec_method_array($clsobj, $method, array $args = array()) { if (is_object($clsobj)) { switch (count($args)) { case 0: return $clsobj->{$method}(); case 1: return $clsobj->{$method}($args[0]); case 2: return $clsobj->{$method}($args[0], $args[1]); case 3: return $clsobj->{$method}($args[0], $args[1], $args[2]); case 4: return $clsobj->{$method}($args[0], $args[1], $args[2], $args[3]); case 5: return $clsobj->{$method}($args[0], $args[1], $args[2], $args[3], $args[4]); } } if (method_exists($clsobj, $method)) { $ref = new ReflectionMethod($clsobj, $method); if ($ref->isPublic() && !$ref->isAbstract()) { if ($ref->isStatic()) { return $ref->invokeArgs(null, $args); } else { return $ref->invokeArgs($clsobj, $args); } } } }
/** * @param \ReflectionMethod $reflection */ public function setAbstractFromReflection(\ReflectionMethod $reflection) { $this->setAbstract($reflection->isAbstract()); }
/** * @return bool */ public function isAbstract() { return $this->reflectionMethod->isAbstract(); }
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; }
if (isset($_REQUEST[$param_key])) { $param_class = new $param_class_name($_REQUEST[$param_key]); array_push($params, $param_class); } elseif ($param->isDefaultValueAvailable()) { array_push($params, $param->getDefaultValue()); } else { header("status: 403 Forbidden"); die("Missing {$param_key} parameter."); } } else { $param_class = new $param_class_name(); foreach ($_REQUEST as $key => $value) { $_method_name = 'set' . $key; if (method_exists($param_class, $_method_name)) { $_method_ref = new ReflectionMethod($param_class, $_method_name); if ($_method_ref->isPublic() && !$_method_ref->isStatic() && !$_method_ref->isAbstract()) { $_method_params_ref = $_method_ref->getParameters(); if (count($_method_params_ref) == 1) { if ($_method_params_ref[0]->getClass() != null) { $_method_params_class_name = $_method_params_ref[0]->getClass()->getName(); $_method_params_class = new $_method_params_class_name($_REQUEST[$param_key]); $param_class->{$_method_name}($_method_params_class); } else { $param_class->{$_method_name}($value); } } } } elseif (property_exists($param_class, $key)) { $_property_ref = new ReflectionProperty($param_class, $key); if ($_property_ref->isPublic() && !$_property_ref->isStatic()) { $param_class->{$key} = $value;
/** * Given a user-defined PHP class or php object, map its methods onto a list of * PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc server * object and called from remote clients (as well as their corresponding signature info). * * @param string|object $className the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class * @param array $extraOptions see the docs for wrapPhpMethod for basic options, plus * - string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on whether $className is a class name or object instance * - string method_filter a regexp used to filter methods to wrap based on their names * - string prefix used for the names of the xmlrpc methods created * * @return array|false false on failure */ public function wrapPhpClass($className, $extraOptions = array()) { $methodFilter = isset($extraOptions['method_filter']) ? $extraOptions['method_filter'] : ''; $methodType = isset($extraOptions['method_type']) ? $extraOptions['method_type'] : 'auto'; $prefix = isset($extraOptions['prefix']) ? $extraOptions['prefix'] : ''; $results = array(); $mList = get_class_methods($className); foreach ($mList as $mName) { if ($methodFilter == '' || preg_match($methodFilter, $mName)) { $func = new \ReflectionMethod($className, $mName); if (!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract()) { if ($func->isStatic() && ($methodType == 'all' || $methodType == 'static' || $methodType == 'auto' && is_string($className)) || !$func->isStatic() && ($methodType == 'all' || $methodType == 'nonstatic' || $methodType == 'auto' && is_object($className))) { $methodWrap = $this->wrapPhpFunction(array($className, $mName), '', $extraOptions); if ($methodWrap) { if (is_object($className)) { $realClassName = get_class($className); } else { $realClassName = $className; } $results[$prefix . "{$realClassName}.{$mName}"] = $methodWrap; } } } } } return $results; }
function transformMethod(ReflectionMethod $method) { $is_internal = $method->isInternal() ? 'internal' : 'user-defined'; $is_abstract = $method->isAbstract() ? ' abstract' : ''; $is_final = $method->isFinal() ? ' final' : ''; $is_public = $method->isPublic() ? ' public' : ''; $is_private = $method->isPrivate() ? ' private' : ''; $is_protected = $method->isProtected() ? ' protected' : ''; $is_static = $method->isStatic() ? ' static' : ''; $name = $method->getName(); $class = $method->getDeclaringClass()->name; $is_constructor = $method->isConstructor() ? 'the constructor' : 'a regular method'; $modifiers = Reflection::getModifierNames($method->getModifiers()); extract($this->transformDocBlock($method->getDocComment())); $parameters = array(); $parameters_concat = ""; $_optional_count = 0; foreach ($method->getParameters() as $_param) { $parameters[$_param->getName()] = $this->transformParameter($_param, @$param[$_param->getName()]); if ($_param->isOptional()) { $parameters_concat .= " [ "; $_optional_count++; } if ($parameters_concat != "" && $parameters_concat != " [ ") { $parameters_concat .= ", "; } $parameters_concat .= $parameters[$_param->getName()]; } $parameters_concat .= str_repeat(" ] ", $_optional_count); ob_start(); include "templates/" . $this->template . "/method.tmpl.php"; return ob_get_clean(); }
public function formatMethod(\ReflectionMethod $method) { $str = ''; if ($method->isFinal()) { $str .= 'final '; } if ($method->isStatic()) { $str .= 'static '; } if ($method->isAbstract() && !$method->getDeclaringClass()->isInterface()) { $str .= 'abstract '; } if ($method->isPrivate()) { $str .= 'private '; } if ($method->isProtected()) { $str .= 'protected '; } if ($method->isPublic()) { $str .= 'public '; } $str .= sprintf('function %s(%s) {}', $method->getName(), $this->formatParameters($method->getParameters())); return $str . "\n"; }
/** * 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; }
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));