public function enterNode(\PHPParser_Node $node)
 {
     // Determine info about the closure's location
     if (!$this->closureNode) {
         if ($node instanceof \PHPParser_Node_Stmt_Namespace) {
             $this->location->namespace = is_array($node->name->parts) ? implode('\\', $node->name->parts) : null;
         }
         if ($node instanceof \PHPParser_Node_Stmt_Trait) {
             $this->location->trait = $this->location->namespace . '\\' . $node->name;
             $this->location->class = null;
         } elseif ($node instanceof \PHPParser_Node_Stmt_Class) {
             $this->location->class = $this->location->namespace . '\\' . $node->name;
             $this->location->trait = null;
         }
     }
     // Locate the node of the closure
     if ($node instanceof \PHPParser_Node_Expr_Closure) {
         if ($node->getAttribute('startLine') == $this->reflection->getStartLine()) {
             if ($this->closureNode) {
                 throw new \RuntimeException('Two closures were declared on the same line of code. Cannot determine ' . 'which closure was the intended target.');
             } else {
                 $this->closureNode = $node;
             }
         }
     }
 }
Example #2
0
 protected function export($var, $return = false)
 {
     if ($var instanceof Closure) {
         /* dump anonymous function in to plain code.*/
         $ref = new ReflectionFunction($var);
         $file = new SplFileObject($ref->getFileName());
         $file->seek($ref->getStartLine() - 1);
         $result = '';
         while ($file->key() < $ref->getEndLine()) {
             $result .= $file->current();
             $file->next();
         }
         $begin = strpos($result, 'function');
         $end = strrpos($result, '}');
         $result = substr($result, $begin, $end - $begin + 1);
     } elseif (is_object($var)) {
         /* dump object with construct function. */
         $result = 'new ' . get_class($var) . '(' . $this->export(get_object_vars($var), true) . ')';
     } elseif (is_array($var)) {
         /* dump array in plain array.*/
         $array = array();
         foreach ($var as $k => $v) {
             $array[] = var_export($k, true) . ' => ' . $this->export($v, true);
         }
         $result = 'array(' . implode(', ', $array) . ')';
     } else {
         $result = var_export($var, true);
     }
     if (!$return) {
         print $result;
     }
     return $result;
 }
 /**
  * Recursively traverses and wraps all Closure objects within the value.
  *
  * NOTE: THIS MAY NOT WORK IN ALL USE CASES, SO USE AT YOUR OWN RISK.
  *
  * @param mixed $data Any variable that contains closures.
  * @param SerializerInterface $serializer The serializer to use.
  */
 public static function wrapClosures(&$data, SerializerInterface $serializer)
 {
     if ($data instanceof \Closure) {
         // Handle and wrap closure objects.
         $reflection = new \ReflectionFunction($data);
         if ($binding = $reflection->getClosureThis()) {
             self::wrapClosures($binding, $serializer);
             $scope = $reflection->getClosureScopeClass();
             $scope = $scope ? $scope->getName() : 'static';
             $data = $data->bindTo($binding, $scope);
         }
         $data = new SerializableClosure($data, $serializer);
     } elseif (is_array($data) || $data instanceof \stdClass || $data instanceof \Traversable) {
         // Handle members of traversable values.
         foreach ($data as &$value) {
             self::wrapClosures($value, $serializer);
         }
     } elseif (is_object($data) && !$data instanceof \Serializable) {
         // Handle objects that are not already explicitly serializable.
         $reflection = new \ReflectionObject($data);
         if (!$reflection->hasMethod('__sleep')) {
             foreach ($reflection->getProperties() as $property) {
                 if ($property->isPrivate() || $property->isProtected()) {
                     $property->setAccessible(true);
                 }
                 $value = $property->getValue($data);
                 self::wrapClosures($value, $serializer);
                 $property->setValue($data, $value);
             }
         }
     }
 }
 function getReflectedMinimumParams($name)
 {
     // Reflection gets this one wrong.
     if (strcasecmp($name, 'define') == 0) {
         return 2;
     }
     if (strcasecmp($name, 'strtok') == 0) {
         return 1;
     }
     if (strcasecmp($name, 'implode') == 0) {
         return 1;
     }
     if (strcasecmp($name, "sprintf") == 0) {
         return 1;
     }
     if (strcasecmp($name, "array_merge") == 0) {
         return 1;
     }
     if (strcasecmp($name, "stream_set_timeout") == 0) {
         return 2;
     }
     try {
         $func = new \ReflectionFunction($name);
         return $func->getNumberOfRequiredParameters();
     } catch (\ReflectionException $e) {
         return -1;
     }
 }
Example #5
0
/**
 * @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);
}
Example #6
0
 /**
  * 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;
 }
Example #7
0
 public function import(\ReflectionFunction $function)
 {
     $this->name = $function->name;
     $this->function = $function->getShortName();
     $this->namespace = $function->getNamespaceName();
     $this->_importFromReflection($function);
 }
Example #8
0
 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;
 }
Example #9
0
 /**
  * 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;
 }
Example #10
0
 /**
  * 
  * @param Model_Job $job
  * @return void
  */
 public function run(Model_Job $job)
 {
     if (Kohana::$profiling === TRUE) {
         $benchmark = Profiler::start('Rub job', $job->name);
     }
     $this->values(array('job_id' => $job->id))->create();
     $this->set_status(Model_Job::STATUS_RUNNING);
     try {
         $job = $job->job;
         $minion_task = Minion_Task::convert_task_to_class_name($job);
         if (is_array($job)) {
             $passed = call_user_func($job);
         } elseif (class_exists($minion_task)) {
             Minion_Task::factory(array($job))->execute();
             $passed = TRUE;
         } elseif (strpos($job, '::') === FALSE) {
             $function = new ReflectionFunction($job);
             $passed = $function->invoke();
         } else {
             list($class, $method) = explode('::', $job, 2);
             $method = new ReflectionMethod($class, $method);
             $passed = $method->invoke(NULL);
         }
     } catch (Exception $e) {
         $this->failed();
         return;
     }
     $this->complete();
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
 }
Example #11
0
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;
}
Example #12
0
 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);
     }
 }
 /**
  * @link http://php.net/manual/en/serializable.serialize.php
  */
 public function serialize()
 {
     // prepare code
     $file = new SplFileObject($this->reflection->getFileName());
     $file->seek($this->reflection->getStartLine() - 1);
     $code = '';
     while ($file->key() < $this->reflection->getEndLine()) {
         $code .= $file->current();
         $file->next();
     }
     $start = strpos($code, 'function');
     $code = substr($code, $start, strpos($code, '}') - $start + 1);
     // prepare variables
     $variables = [];
     $index = stripos($code, 'use');
     // if 'use' keyword found
     if (false !== $index) {
         // get the names of the variables inside the use statement
         $start = strpos($code, '(', $index) + 1;
         $end = strpos($code, ')', $start);
         $use_variables = explode(',', substr($code, $start, $end - $start));
         $static_variables = $this->reflection->getStaticVariables();
         // keep only the variables that appeared in both scopes
         foreach ($use_variables as $variable) {
             $variable = trim($variable, '$&');
             $variables[$variable] = $static_variables[$variable];
         }
     }
     return serialize(['code' => $code, 'variables' => $variables]);
 }
Example #14
0
 /**
  * 代码执行过程回溯信息
  *
  * @static
  * @access public
  */
 public static function debugBacktrace()
 {
     $skipFunc[] = 'Error->debugBacktrace';
     $show = $log = '';
     $debugBacktrace = debug_backtrace();
     ksort($debugBacktrace);
     foreach ($debugBacktrace as $k => $error) {
         if (!isset($error['file'])) {
             try {
                 if (isset($error['class'])) {
                     $reflection = new \ReflectionMethod($error['class'], $error['function']);
                 } else {
                     $reflection = new \ReflectionFunction($error['function']);
                 }
                 $error['file'] = $reflection->getFileName();
                 $error['line'] = $reflection->getStartLine();
             } catch (Exception $e) {
                 continue;
             }
         }
         $file = str_replace(rootPath(), '', $error['file']);
         $func = isset($error['class']) ? $error['class'] : '';
         $func .= isset($error['type']) ? $error['type'] : '';
         $func .= isset($error['function']) ? $error['function'] : '';
         if (in_array($func, $skipFunc)) {
             break;
         }
         $error['line'] = sprintf('%04d', $error['line']);
         $show .= '<li>[Line: ' . $error['line'] . ']' . $file . '(' . $func . ')</li>';
         $log .= !empty($log) ? ' -> ' : '';
         $log .= $file . ':' . $error['line'];
     }
     return array($show, $log);
 }
Example #15
0
function test()
{
    $x = new ReflectionFunction('array_filter');
    $params = $x->getParameters();
    $p1 = $params[1];
    var_dump($p1->getDefaultValueText());
}
Example #16
0
 public function call($group, $hook, $parameters = null, $action = null)
 {
     if (!isset($action)) {
         $action = 'execute';
     }
     if (!isset($this->hooks[$this->site][$group][$hook][$action])) {
         $this->register($group, $hook, $action);
     }
     $calls = [];
     if (isset($this->hooks[$this->site][$group][$hook][$action])) {
         $calls = $this->hooks[$this->site][$group][$hook][$action];
     }
     if (isset($this->watches[$this->site][$group][$hook][$action])) {
         $calls = array_merge($calls, $this->watches[$this->site][$group][$hook][$action]);
     }
     $result = [];
     foreach ($calls as $code) {
         $bait = null;
         if (is_string($code)) {
             $class = Apps::getModuleClass($code, 'Hooks');
             $obj = new $class();
             $bait = $obj->{$action}($parameters);
         } else {
             $ref = new \ReflectionFunction($code);
             if ($ref->isClosure()) {
                 $bait = $code($parameters);
             }
         }
         if (!empty($bait)) {
             $result[] = $bait;
         }
     }
     return $result;
 }
Example #17
0
 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;
 }
Example #18
0
 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);
 }
Example #19
0
 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;
 }
Example #20
0
 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));
 }
Example #21
0
 /**
  * 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;
         }
     }
 }
 function executeInSubprocess($includeStderr = false)
 {
     // Get the path to the ErrorControlChain class
     $classpath = SS_ClassLoader::instance()->getItemPath('ErrorControlChain');
     $suppression = $this->suppression ? 'true' : 'false';
     // Start building a PHP file that will execute the chain
     $src = '<' . "?php\nrequire_once '{$classpath}';\n\n\$chain = new ErrorControlChain();\n\n\$chain->setSuppression({$suppression});\n\n\$chain\n";
     // For each step, use reflection to pull out the call, stick in the the PHP source we're building
     foreach ($this->steps as $step) {
         $func = new ReflectionFunction($step['callback']);
         $source = file($func->getFileName());
         $start_line = $func->getStartLine() - 1;
         $end_line = $func->getEndLine();
         $length = $end_line - $start_line;
         $src .= implode("", array_slice($source, $start_line, $length)) . "\n";
     }
     // Finally add a line to execute the chain
     $src .= "->execute();";
     // Now stick it in a temporary file & run it
     $codepath = TEMP_FOLDER . '/ErrorControlChainTest_' . sha1($src) . '.php';
     if ($includeStderr) {
         $null = '&1';
     } else {
         $null = is_writeable('/dev/null') ? '/dev/null' : 'NUL';
     }
     file_put_contents($codepath, $src);
     exec("php {$codepath} 2>{$null}", $stdout, $errcode);
     unlink($codepath);
     return array(implode("\n", $stdout), $errcode);
 }
Example #23
0
 /**
  * {@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.
     });
 }
 /**
  * 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);
 }
Example #25
0
 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 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 the route information for a given route.
  *
  * @param  \Illuminate\Routing\Route $route
  * @return array
  */
 protected function getRouteInformation($route)
 {
     if (!is_a($route, 'Illuminate\\Routing\\Route')) {
         return array();
     }
     $uri = head($route->methods()) . ' ' . $route->uri();
     $action = $route->getAction();
     $result = array('uri' => $uri ?: '-');
     $result = array_merge($result, $action);
     if (isset($action['controller']) && strpos($action['controller'], '@') !== false) {
         list($controller, $method) = explode('@', $action['controller']);
         if (class_exists($controller) && method_exists($controller, $method)) {
             $reflector = new \ReflectionMethod($controller, $method);
         }
         unset($result['uses']);
     } elseif (isset($action['uses']) && $action['uses'] instanceof \Closure) {
         $reflector = new \ReflectionFunction($action['uses']);
         $result['uses'] = $this->formatVar($result['uses']);
     }
     if (isset($reflector)) {
         $filename = ltrim(str_replace(base_path(), '', $reflector->getFileName()), '/');
         $result['file'] = $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine();
     }
     if ($before = $this->getBeforeFilters($route)) {
         $result['before'] = $before;
     }
     if ($after = $this->getAfterFilters($route)) {
         $result['after'] = $after;
     }
     return $result;
 }
Example #28
0
 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));
 }
Example #29
0
 /**
  * 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);
 }
Example #30
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;
    }
}