/** * (non-PHPdoc) * @see \PHPFluent\EventManager\Listener::execute() */ public function execute(Event $event, array $context = array()) { $arguments = array($event, $context); $parameters = $this->reflection->getParameters(); $firstParameter = array_shift($parameters); if ($firstParameter instanceof \ReflectionParameter && $firstParameter->isArray()) { $arguments = array_reverse($arguments); } return $this->reflection->invokeArgs($arguments); }
/** * @return IParameterReflection[] */ public function getParameterList() { if ($this->parameterList === null) { $this->parameterList = []; foreach ($this->reflectionFunction->getParameters() as $reflectionParameter) { $this->parameterList[$reflectionParameter->getName()] = new ParameterReflection($reflectionParameter); } } return $this->parameterList; }
function main() { $rc = new ReflectionClass("Foo\\Bar\\A"); var_dump($rc->isInterface()); var_dump($rc->getMethod('set')->getParameters()[0]->getDefaultValue()); var_dump($rc->getMethod('set')->getParameters()[0]->getDefaultValueConstantName()); $rc = new \ReflectionFunction("Foo\\Bar\\foo"); var_dump($rc->getParameters()[0]->getDefaultValue()); var_dump($rc->getParameters()[0]->getDefaultValueConstantName()); Foo\Bar\foo(); }
/** * @return DependencyContainer */ private function collectDependencies() { $dependencies = new DependencyContainer(); if (!$this->invokableReflection) { return $dependencies; } foreach ($this->invokableReflection->getParameters() as $parameter) { $dependencies->addDependency($parameter); } return $dependencies; }
/** * @return \PHPStan\Reflection\ParameterReflection[] */ public function getParameters() : array { if ($this->parameters === null) { $this->parameters = array_map(function (\ReflectionParameter $reflection) { return new PhpParameterReflection($reflection); }, $this->reflection->getParameters()); if ($this->reflection->getName() === 'array_unique' && count($this->parameters) === 1) { // PHP bug #70960 $this->parameters[] = new DummyOptionalParameter('sort_flags', new IntegerType(false)); } } return $this->parameters; }
public function send(StreamInterface $stream) { if (!$stream->isWritable()) { throw new \InvalidArgumentException('Output stream must be writable'); } if (is_array($this->callback)) { $ref = (new \ReflectionClass(is_object($this->callback[0]) ? get_class($this->callback[0]) : $this->callback[0]))->getMethod($this->callback[1]); } elseif (is_object($this->callback) && !$this->callback instanceof \Closure) { $ref = new \ReflectionMethod(get_class($this->callback), '__invoke'); } else { $ref = new \ReflectionFunction($this->callback); } if ($ref->isGenerator()) { foreach (call_user_func($this->callback) as $chunk) { $stream->write($chunk); } return; } foreach ($ref->getParameters() as $param) { if (NULL !== ($type = $param->getClass())) { if ($type->name === StreamInterface::class || $type->implementsInterface(StreamInterface::class)) { call_user_func($this->callback, $stream); return; } } break; } $stream->write((string) call_user_func($this->callback)); }
function test() { $x = new ReflectionFunction('array_filter'); $params = $x->getParameters(); $p1 = $params[1]; var_dump($p1->getDefaultValueText()); }
/** * Modifies the ParamConverterManager instance. * * @param FilterControllerEvent $event A FilterControllerEvent instance */ public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); $request = $event->getRequest(); $configurations = array(); if ($configuration = $request->attributes->get('_converters')) { foreach (is_array($configuration) ? $configuration : array($configuration) as $configuration) { $configurations[$configuration->getName()] = $configuration; } } if (is_array($controller)) { $r = new \ReflectionMethod($controller[0], $controller[1]); } else { $r = new \ReflectionFunction($controller); } // automatically apply conversion for non-configured objects foreach ($r->getParameters() as $param) { if (!$param->getClass() || $param->getClass()->isInstance($request)) { continue; } $name = $param->getName(); if (!isset($configurations[$name])) { $configuration = new ParamConverter(array()); $configuration->setName($name); $configuration->setClass($param->getClass()->getName()); $configurations[$name] = $configuration; } elseif (null === $configurations[$name]->getClass()) { $configurations[$name]->setClass($param->getClass()->getName()); } $configurations[$name]->setIsOptional($param->isOptional()); } $this->manager->apply($request, $configurations); }
/** * get Closure info * @param Closure $c * @return array */ function closure_dump(Closure $c) { $str = 'function ('; $r = new ReflectionFunction($c); $params = array(); foreach ($r->getParameters() as $p) { $s = ''; if ($p->isArray()) { $s .= 'array '; } else { if ($p->getClass()) { $s .= $p->getClass()->name . ' '; } } if ($p->isPassedByReference()) { $s .= '&'; } $s .= '$' . $p->name; if ($p->isOptional()) { $s .= ' = ' . var_export($p->getDefaultValue(), TRUE); } $params[] = $s; } $str .= implode(', ', $params); $str .= '){' . PHP_EOL; $lines = file($r->getFileName()); for ($l = $r->getStartLine(); $l < $r->getEndLine(); $l++) { $str .= $lines[$l]; } $arr = ['file' => $r->getFileName(), 'line' => $r->getStartLine() . '-' . $r->getEndLine(), 'source' => $str]; return $arr; }
/** * @return Parameter[] */ public function getParameters() { foreach ($res = parent::getParameters() as $key => $val) { $res[$key] = new Parameter($this->value, $val->getName()); } return $res; }
static function castClosure($c) { $a = array(); if (!class_exists('ReflectionFunction', false)) { return $a; } $c = new \ReflectionFunction($c); foreach ($c->getParameters() as $p) { $n = ($p->isPassedByReference() ? '&$' : '$') . $p->getName(); if ($p->isDefaultValueAvailable()) { $a[$n] = $p->getDefaultValue(); } else { $a[] = $n; } } $m = self::META_PREFIX; $a = array($m . 'returnsRef' => true, $m . 'args' => $a); if (!$c->returnsReference()) { unset($a[$m . 'returnsRef']); } $a[$m . 'use'] = array(); if (false === ($a[$m . 'file'] = $c->getFileName())) { unset($a[$m . 'file']); } else { $a[$m . 'lines'] = $c->getStartLine() . '-' . $c->getEndLine(); } if (!($c = $c->getStaticVariables())) { unset($a[$m . 'use']); } else { foreach ($c as $p => &$c) { $a[$m . 'use']['$' . $p] =& $c; } } return $a; }
/** * Runs all the middlewares of given type. */ public static function runMiddlewares($type = self::BEFORE_REQUEST) { $apricot = static::getInstance(); $middlewares = $apricot->middlewares; /** @var \Exception */ $error = null; foreach ($middlewares as $key => $middleware) { $hasNextMiddleware = array_key_exists($key + 1, $middlewares); if ($type !== $middleware['type']) { continue; } $r = new \ReflectionFunction($middleware['callback']); $parameters = $r->getParameters(); $next = $hasNextMiddleware ? $middlewares[$key + 1] : function () { }; try { $r->invokeArgs(array($error, $next)); } catch (\Exception $e) { // If there is no more middleware to run, throw the exception. if (!$hasNextMiddleware) { throw $e; } $error = $e; } } }
public static function getNamedArgs() { $bt = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2); $frame = $bt[1]; if ($frame['function'] == '{closure}') { throw new \LogicException("This can't work inside a closure, sadly"); } if (isset($frame['class'])) { $rc = new \ReflectionClass($frame['class']); $rf = $rc->getMethod($frame['function']); } else { $rf = new \ReflectionFunction($frame['function']); } $named = []; $args = $frame['args']; foreach ($rf->getParameters() as $idx => $param) { $name = $param->getName(); if (!array_key_exists($idx, $args)) { if ($param->isDefaultValueAvailable()) { $named[$name] = $param->getDefaultValue(); } else { break; } } else { $named[$name] = $args[$idx]; } } return $named; }
private function shouldRun($callback, $controllerResult) { if (is_array($callback)) { $callbackReflection = new \ReflectionMethod($callback[0], $callback[1]); } elseif (is_object($callback) && !$callback instanceof \Closure) { $callbackReflection = new \ReflectionObject($callback); $callbackReflection = $callbackReflection->getMethod('__invoke'); } else { $callbackReflection = new \ReflectionFunction($callback); } if ($callbackReflection->getNumberOfParameters() > 0) { $parameters = $callbackReflection->getParameters(); $expectedControllerResult = $parameters[0]; if ($expectedControllerResult->getClass() && (!is_object($controllerResult) || !$expectedControllerResult->getClass()->isInstance($controllerResult))) { return false; } if ($expectedControllerResult->isArray() && !is_array($controllerResult)) { return false; } if (method_exists($expectedControllerResult, 'isCallable') && $expectedControllerResult->isCallable() && !is_callable($controllerResult)) { return false; } } return true; }
/** * Call closure. * * @param mixed $closure * @param array $parameters * * @return Closure */ protected function call_closure($closure, array $parameters = []) { if ($closure instanceof Closure) { $rc = new ReflectionFunction($closure); $args = $rc->getParameters(); $params = $parameters; $classes = [$this->get_class_prefix(get_class($this)), get_class($this), get_parent_class($this)]; foreach ($args as $index => $arg) { if ($arg->getClass() === null) { continue; } if (in_array($arg->getClass()->name, $classes)) { $parameters[$index] = $this; } else { if ($this->exists($arg->getClass()->name)) { $parameters[$index] = $this->make($arg->getClass()->name); } } } if (!empty($args) && empty($parameters)) { $parameters[0] = $this; } if (count($args) > count($parameters)) { $parameters = array_merge($parameters, $params); } return $this->call_closure(call_user_func_array($closure, $parameters), $parameters); } return $closure; }
function params2MethodArgs($method, $params) { $funcInfo = new ReflectionFunction($method); $args = array(); foreach ($funcInfo->getParameters() as $paramInfo) { $nm = $paramInfo->getName(); $val = null; if (!array_key_exists($nm, $params)) { if ($paramInfo->isDefaultValueAvailable()) { $val = $paramInfo->getDefaultValue(); } if (is_null($val) && !$paramInfo->isOptional()) { throw new Exception("Parameter [{$nm}] of [{$method}] can not be null"); } } else { $val = $params[$nm]; } $classInfo = $paramInfo->getClass(); if ($classInfo) { $val = eval("return new " . $classInfo->getName() . "('{$val}');"); } $args[] = $val; } return $args; }
public function parse(&$var, Kint_Object &$o) { if (!$var instanceof Closure || !$o instanceof Kint_Object_Instance || !$this->parseChildren($o)) { return; } $o = $o->transplant(new Kint_Object_Closure()); $o->removeRepresentation('properties'); $closure = new ReflectionFunction($var); $o->filename = $closure->getFileName(); $o->startline = $closure->getStartLine(); foreach ($closure->getParameters() as $param) { $o->parameters[] = new Kint_Object_Parameter($param); } $p = new Kint_Object_Representation('Parameters'); $p->contents =& $o->parameters; $o->addRepresentation($p, 0); $statics = array(); if (method_exists($closure, 'getClosureThis') && ($v = $closure->getClosureThis())) { $statics = array('this' => $v); } if (count($statics = $statics + $closure->getStaticVariables())) { foreach ($statics as $name => &$static) { $obj = Kint_Object::blank('$' . $name); $obj->depth = $o->depth + 1; $static = $this->parser->parse($static, $obj); if ($static->value === null) { $static->access_path = null; } } $r = new Kint_Object_Representation('Uses'); $r->contents = $statics; $o->addRepresentation($r, 0); } }
function phpio_argnames($function) { static $arg_name; $key = $function; if (is_array($function)) { list($class, $method) = $function; $key = "{$class}::{$method}"; } if (isset($arg_name[$key])) { return $arg_name[$key]; } try { if (isset($class)) { if (class_exists("PHPIO_Reflection_{$class}", false)) { $class = "PHPIO_Reflection_{$class}"; } $rf = new ReflectionMethod($class, $method); } else { $rf = new ReflectionFunction($function); } $arg_name[$key] = array(); foreach ($rf->getParameters() as $param) { $arg_name[$key][] = $param->getName(); } return $arg_name[$key]; } catch (Exception $e) { echo $e; } }
public static function updateClassMethodHash($className, $methodName, $closure) { $methodName = strtolower($methodName); if (isset(self::$specialMethods[$methodName]) && self::$specialMethods[$methodName] == 1) { $methodName = "phlexmock_" . $methodName; } $closureRF = new \ReflectionFunction($closure); $paramStr = "()"; $params = []; $closureParams = $closureRF->getParameters(); if (count($closureParams) > 0) { foreach ($closureParams as $closureParam) { $params[] = '$' . $closureParam->getName(); } $paramStr = "(" . implode(",", $params) . ")"; } $sl = $closureRF->getStartLine(); $el = $closureRF->getEndLine(); $closureContainerScript = $closureRF->getFileName(); if (!isset(self::$closureContainerScriptLines[$closureContainerScript])) { self::$closureContainerScriptLines[$closureContainerScript] = explode("\n", file_get_contents($closureRF->getFileName())); } $lines = self::$closureContainerScriptLines[$closureContainerScript]; $code = '$func = function' . $paramStr . ' { ' . implode("\n", array_slice($lines, $sl, $el - $sl - 1)) . ' };'; self::$classMethodHash[$className][$methodName] = $code; }
/** * @param array $defaultStrategies * @param array $strategyMap * @param \FusePump\Cli\Inputs $inputs * @param array $arguments * @return callable */ function strategyFactory($defaultStrategies, $strategyMap = array(), $inputs = null, $arguments = array()) { $strategyList = array(function () { return false; }); $addStrategy = function ($strategy) use(&$strategyList, $arguments) { $args = array(); $reflection = new \ReflectionFunction($strategy); foreach ($reflection->getParameters() as $param) { if ($param->getName() === 'patchFile') { continue; } elseif ($param->getName() === 'superStrategy') { $args[] = end($strategyList); } elseif (array_key_exists($param->getName(), $arguments)) { $args[] = $arguments[$param->getName()]; } else { $args[] = null; } } $strategyList[] = function ($patchFile) use($strategy, $args) { return call_user_func_array($strategy, array_merge(array($patchFile), $args)); }; }; foreach ($strategyMap as $option => $strategy) { if ($inputs->get($option)) { $addStrategy($strategy); } } if (count($strategyList) < 2) { foreach ($defaultStrategies as $strategy) { $addStrategy($strategy); } } return end($strategyList); }
/** * Execute handler * @param Client $client * @param $data * @return mixed|null */ public function execute(Client $client, $data) { $this->_client = $client; $this->_data = $data; // Execute handler object if (!empty($this->_object)) { $class = new ReflectionClass(get_class($this->_object)); $method = $class->getMethod($this->_method); $parameters = $this->prepareParameters($method->getParameters()); if (empty($parameters)) { $parameters[] = $data; } return call_user_func_array([$this->_object, $this->_method], $parameters); } // Execute closure handler if (!empty($this->_closure)) { $function = new \ReflectionFunction($this->_closure); $parameters = $this->prepareParameters($function->getParameters()); if (empty($parameters)) { $parameters[] = $data; } return call_user_func_array($this->_closure, $parameters); } return null; }
/** * Returns the parameters of the function as ezcReflectionParameter objects * * @return ezcReflectionParameter[] Parameters of the Function * @since PHP 5.1.0 */ function getParameters() { $params = $this->docParser->getParamAnnotations(); $extParams = array(); if ($this->reflectionSource instanceof ReflectionFunction) { $apiParams = $this->reflectionSource->getParameters(); } else { $apiParams = parent::getParameters(); } foreach ($apiParams as $param) { $type = null; foreach ($params as $annotation) { if ($annotation instanceof ezcReflectionAnnotationParam and $annotation->getParamName() == $param->getName()) { $type = $annotation->getTypeName(); break; } } if ($this->reflectionSource instanceof ReflectionFunction) { $extParams[] = new ezcReflectionParameter(null, $param, $type); } else { // slightly increase performance and save some memory $extParams[] = new ezcReflectionParameter($this->getName(), $param->getPosition(), $type); } } return $extParams; }
public function parse(&$variable) { if (!$variable instanceof Closure) { return false; } $this->name = 'Closure'; $reflection = new ReflectionFunction($variable); $ret = array('Parameters' => array()); if ($val = $reflection->getParameters()) { foreach ($val as $parameter) { // todo http://php.net/manual/en/class.reflectionparameter.php $ret['Parameters'][] = $parameter->name; } } if ($val = $reflection->getStaticVariables()) { $ret['Uses'] = $val; } if (method_exists($reflection, 'getClousureThis') && ($val = $reflection->getClosureThis())) { $ret['Uses']['$this'] = $val; } if ($val = $reflection->getFileName()) { $this->value = Kint::shortenPath($val) . ':' . $reflection->getStartLine(); } return $ret; }
public static function ipExecuteController_70($info) { if (!is_callable($info['action'])) { $controllerClass = $info['controllerClass']; $controller = new $controllerClass(); $callableAction = array($controller, $info['action']); $reflection = new \ReflectionMethod($controller, $info['action']); } else { $callableAction = $info['action']; $reflection = new \ReflectionFunction($callableAction); } $parameters = $reflection->getParameters(); $arguments = array(); $routeParameters = array(); foreach ($parameters as $parameter) { $name = $parameter->getName(); if (isset($info[$name])) { $arguments[] = $info[$name]; } elseif ($parameter->isOptional()) { $arguments[] = $parameter->getDefaultValue(); } else { throw new \Ip\Exception("Controller action requires " . esc($name) . " parameter", array('route' => $info, 'requiredParameter' => $name)); } $routeParameters[$parameter->getName()] = end($arguments); } iproute()->setParameters($routeParameters); return call_user_func_array($callableAction, $arguments); }
/** * {@inheritdoc} */ public function capture(callable $onRejected) : Awaitable { return $this->then(null, function (\Throwable $exception) use($onRejected) { if ($onRejected instanceof \Closure) { // Closure. $reflection = new \ReflectionFunction($onRejected); } elseif (is_array($onRejected)) { // Methods passed as an array. $reflection = new \ReflectionMethod($onRejected[0], $onRejected[1]); } elseif (is_object($onRejected)) { // Callable objects. $reflection = new \ReflectionMethod($onRejected, '__invoke'); } elseif (is_string($onRejected) && strrpos($onRejected, '::', -1)) { // ClassName::methodName strings. $reflection = new \ReflectionMethod($onRejected); } else { // Everything else. $reflection = new \ReflectionFunction($onRejected); } $parameters = $reflection->getParameters(); if (empty($parameters)) { // No parameters defined. return $onRejected($exception); // Providing argument in case func_get_args() is used in function. } $class = $parameters[0]->getClass(); if (null === $class || $class->isInstance($exception)) { // None or matching type declaration. return $onRejected($exception); } return $this; // Type declaration does not match. }); }
function generate($path) { $filepath = GENERATE_MODULE . "module_" . $path; $modulepath = _SYSTEM_DIR_ . "module/" . $path; if (file_exists($filepath) && filemtime($filepath) >= filemtime($modulepath)) { return; } $classname = "module_" . substr(basename($path), 0, strpos(basename($path), ".")); $tmp = array(); $tmp[] = "<?php /* auto generate module class " . date("Y-m-d H:i:s") . "*/"; $tmp[] = "/* original file:" . $modulepath . " */"; $tmp[] = "class " . $classname . " {"; foreach ($this->_binds as $method => $func) { $ref = new \ReflectionFunction($func); $params = $ref->getParameters(); $method_params = array(); foreach ($params as $a) { /* @var $a ReflectionParameter */ $line = '$' . $a->getName() . ($a->isDefaultValueAvailable() ? '=\'' . $a->getDefaultValue() . '\'' : ''); try { $class = $a->getClass(); if ($class) { $line = $class->getName() . " " . $line; } } catch (Exception $e) { } $method_params[] = $line; } $tmp[] = "public function " . $method . "(" . implode(", ", $method_params) . "){}"; } $tmp[] = "}"; file_put_contents($filepath, implode("\n", $tmp)); }
public function exec($key) { //匿名函数 if ($this->route[$key]['callback'] instanceof Closure) { //反射分析闭包 $reflectionFunction = new \ReflectionFunction($this->route[$key]['callback']); $gets = $this->route[$key]['get']; $args = []; foreach ($reflectionFunction->getParameters() as $k => $p) { if (isset($gets[$p->name])) { //如果GET变量中存在则将GET变量值赋予,也就是说GET优先级高 $args[$p->name] = $gets[$p->name]; } else { //如果类型为类时分析类 if ($dependency = $p->getClass()) { $args[$p->name] = App::build($dependency->name); } else { //普通参数时获取默认值 $args[$p->name] = App::resolveNonClass($p); } } } echo $reflectionFunction->invokeArgs($args); } else { //设置控制器与方法 Request::set('get.' . c('http.url_var'), $this->route[$key]['callback']); Controller::run($this->route[$key]['get']); } }
/** * Modifies the ParamConverterManager instance. * * @param FilterControllerEvent $event A FilterControllerEvent instance */ public function onCoreController(FilterControllerEvent $event) { $controller = $event->getController(); $request = $event->getRequest(); $configurations = array(); if ($configuration = $request->attributes->get('_converters')) { $configurations = is_array($configuration) ? $configuration : array($configuration); } if (is_array($controller)) { $r = new \ReflectionMethod($controller[0], $controller[1]); } else { $r = new \ReflectionFunction($controller); } // automatically apply conversion for non-configured objects foreach ($r->getParameters() as $param) { if ($param->getClass() && !$request->attributes->get($param->getName())) { $configuration = new ParamConverter(array()); $configuration->setName($param->getName()); $configuration->setClass($param->getClass()->getName()); $configuration->setIsOptional($param->isOptional()); $configurations[] = $configuration; } } $this->manager->apply($request, $configurations); }
/** * Format a list of Closure parameters. * * @param \Closure $value * * @return string */ protected function formatParams(\Closure $value, $color = false) { $r = new \ReflectionFunction($value); $method = $color ? 'formatParamColor' : 'formatParam'; $params = array_map(array($this, $method), $r->getParameters()); return implode(', ', $params); }
/** * @return self */ public static function from($from) : self { if (is_string($from) && strpos($from, '::')) { $from = new \ReflectionMethod($from); } elseif (is_array($from)) { $from = new \ReflectionMethod($from[0], $from[1]); } elseif (!$from instanceof \ReflectionFunctionAbstract) { $from = new \ReflectionFunction($from); } $method = new static(); $method->name = $from->isClosure() ? NULL : $from->getName(); foreach ($from->getParameters() as $param) { $method->parameters[$param->getName()] = Parameter::from($param); } if ($from instanceof \ReflectionMethod) { $method->static = $from->isStatic(); $method->visibility = $from->isPrivate() ? 'private' : ($from->isProtected() ? 'protected' : NULL); $method->final = $from->isFinal(); $method->abstract = $from->isAbstract() && !$from->getDeclaringClass()->isInterface(); $method->body = $from->isAbstract() ? FALSE : ''; } $method->returnReference = $from->returnsReference(); $method->variadic = PHP_VERSION_ID >= 50600 && $from->isVariadic(); $method->comment = $from->getDocComment() ? preg_replace('#^\\s*\\* ?#m', '', trim($from->getDocComment(), "/* \r\n\t")) : NULL; if (PHP_VERSION_ID >= 70000 && $from->hasReturnType()) { $returnType = $from->getReturnType(); $method->returnType = $returnType->isBuiltin() ? (string) $returnType : '\\' . $returnType; } return $method; }