Example #1
0
 /**
  * (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);
 }
Example #2
0
 public function getResponse($method, $uri)
 {
     foreach ($this->routes as $route) {
         if ($match = $route($method, $uri)) {
             if (is_callable($match[0])) {
                 if (empty($match[1])) {
                     return $match[0]();
                 }
                 // http://www.creapptives.com/post/26272336268/calling-php-functions-with-named-parameters
                 $ref = new \ReflectionFunction($match[0]);
                 $this->params = [];
                 foreach ($ref->getParameters() as $p) {
                     if (!$p->isOptional() and !isset($match[1][$p->name])) {
                         throw new \Exception("Missing parameter {$p->name}");
                     }
                     if (!isset($match[1][$p->name])) {
                         $this->params[$p->name] = $p->getDefaultValue();
                     } else {
                         $this->params[$p->name] = $match[1][$p->name];
                     }
                 }
                 return $ref->invokeArgs($this->params);
             }
             return $match[0];
         }
     }
     throw new \Exception($method . ':' . $uri . ' not found');
 }
Example #3
0
 function exec_function_array($o, array $B = array())
 {
     switch (count($B)) {
         case 0:
             return $o();
         case 1:
             return $o($B[0]);
         case 2:
             return $o($B[0], $B[1]);
         case 3:
             return $o($B[0], $B[1], $B[2]);
         case 4:
             return $o($B[0], $B[1], $B[2], $B[3]);
         case 5:
             return $o($B[0], $B[1], $B[2], $B[3], $B[4]);
         default:
             if (is_object($o)) {
                 $v = new ReflectionMethod($o, '__invoke');
                 return $v->invokeArgs($o, $B);
             } else {
                 if (is_callable($o)) {
                     $v = new ReflectionFunction($o);
                     return $v->invokeArgs($B);
                 }
             }
     }
 }
Example #4
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;
         }
     }
 }
Example #5
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']);
     }
 }
Example #6
0
 /**
  * 
  * @param   array   $arguments
  * 
  * @return  mixed
  */
 public function invoke($arguments = array())
 {
     if ($this->isMethod) {
         return $this->reflection->invokeArgs($this->thisObject, $arguments);
     }
     return $this->reflection->invokeArgs($arguments);
 }
Example #7
0
 /**
  * Packs 8-bit integers into a binary string
  *
  * @since 1.0
  * 
  * @param  int $ascii,... 8-bit unsigned integer
  * @return binary
  */
 public static function pack($ascii)
 {
     $packer = new \ReflectionFunction('pack');
     $args = func_get_args();
     array_unshift($args, 'C*');
     return $packer->invokeArgs($args);
 }
Example #8
0
 /**
  * @param \Closure $closure
  * @return mixed
  */
 public function call($closure)
 {
     $reflect = new \ReflectionFunction($closure);
     $parameters = $reflect->getParameters();
     $dependencies = $this->getDependencies($parameters);
     return $reflect->invokeArgs($dependencies);
 }
Example #9
0
function XLLoop_reflection_handler()
{
    try {
        $input = file_get_contents('php://input');
        $value = json_decode($input);
        if ($value != NULL) {
            $argc = count($value->args);
            $args = array();
            for ($i = 0; $i < $argc; $i++) {
                $args[$i] = XLLoop_decode($value->args[$i]);
            }
            $function = new ReflectionFunction($value->name);
            if ($function->isUserDefined()) {
                $reqArgc = $function->getNumberOfParameters();
                for ($i = $argc; $i < $reqArgc; $i++) {
                    $args[$i] = 0;
                }
                $result = $function->invokeArgs($args);
                $enc = XLLoop_encode($result);
                print json_encode($enc);
            } else {
                print json_encode(XLLoop_encode("#Function " . $value->name . "() does not exist"));
            }
        } else {
            print "<html><body><code>XLLoop function handler alive</code></body></html>";
        }
    } catch (Exception $e) {
        print json_encode(XLLoop_encode("#" . $e->getMessage()));
    }
}
Example #10
0
 /**
  * Asserts that a function is implemented and returns the expected result
  *
  * @param String $function The function name
  * @param Array  $params   The parameters
  * @param Mixed  $result   The expected result
  *
  * @dataProvider provideTestCheckAPI
  * @return void
  */
 public function testCheckAPI($function, array $params, $result)
 {
     $api = new OldPHPAPI_Test();
     $api->checkAPI();
     $this->assertTrue(function_exists($function), "Function {$function} is not defined.");
     $reflection = new ReflectionFunction($function);
     $this->assertEquals($result, $reflection->invokeArgs($params));
 }
Example #11
0
 public function callFunction($function)
 {
     /** @var \ReflectionFunction $reflectionFunction */
     $reflectionFunction = new \ReflectionFunction($function);
     $signatureParams = $reflectionFunction->getParameters();
     $calledFunctionArgs = $this->resolveParams($signatureParams);
     $reflectionFunction->invokeArgs($calledFunctionArgs);
 }
Example #12
0
 /**
  * @param $method
  * @param array $args
  * @param bool $singleton
  * @return mixed
  * @throws \Exception
  */
 public function execute($method, array $args = array(), $singleton = true)
 {
     if (is_array($method) && count($method) >= 2) {
         list($class, $name) = $method;
         $reflection = new \ReflectionMethod($class, $name);
     } elseif (is_callable($method)) {
         $reflection = new \ReflectionFunction($method);
     } else {
         throw new \RuntimeException();
     }
     $parameters = $reflection->getParameters();
     $args = $this->getReflectionValues($parameters, $args, $singleton);
     if ($reflection instanceof \ReflectionFunction) {
         return $reflection->invokeArgs($args);
     } else {
         return $reflection->invokeArgs($class, $args);
     }
 }
 private function prepareArgs($sql, $arguments = null)
 {
     if ($arguments != null && count($arguments) > 0) {
         $sprintfargs = array_merge(array($sql), $arguments);
         $sprintf = new \ReflectionFunction('sprintf');
         $sql = $sprintf->invokeArgs($sprintfargs);
     }
     return $sql;
 }
Example #14
0
 /**
  * 
  * @param string $callback
  * @param array $params
  * @return mixed
  */
 public static function invoke_function($callback, array $params = NULL)
 {
     $class = new ReflectionFunction($callback);
     if (empty($params)) {
         return $class->invoke();
     } else {
         return $class->invokeArgs($params);
     }
 }
Example #15
0
 /**
  * Execute the active controller
  */
 public function processController()
 {
     // closure
     if (is_callable($this->controller)) {
         $func = new \ReflectionFunction($this->controller);
         return $func->invokeArgs($this->controller_args);
     } else {
         return Controller::execute($this->controller, $this->controller_args);
     }
 }
Example #16
0
 protected function invokeClosure($targetValue)
 {
     if (is_callable($this->condition)) {
         $reflection = new \ReflectionFunction($this->condition);
         if (!$reflection->isClosure()) {
             throw new Exceptions\NotCallable("Specified condition is not closure, can't proceed");
         }
         return $reflection->invokeArgs(array($targetValue));
     }
     return false;
 }
Example #17
0
 /**
  * @param string   $type
  * @param callable $callback
  * @param array    $arguments
  *
  * @return bool|mixed
  */
 private function isType($type, callable $callback = null, array $arguments = array())
 {
     if ($type != $this->current) {
         return false;
     } elseif (is_callable($callback)) {
         $closure = new \ReflectionFunction($callback);
         return $closure->invokeArgs($arguments);
     } else {
         return true;
     }
 }
Example #18
0
 /**
  * Invokes the function and allows to pass its arguments as an array
  *
  * @param array<integer,mixed> $arguments
  *     Arguments
  * @return mixed
  *     Return value of the function invocation
  * @since PHP 5.1.0
  */
 public function invokeArgs(array $arguments)
 {
     /*
             return $this->forwardCallToReflectionSource( __FUNCTION__, array( $arguments ) );
             /*/
     if ($this->reflectionSource instanceof ReflectionFunction) {
         return $this->reflectionSource->invokeArgs($arguments);
     } else {
         return parent::invokeArgs($arguments);
     }
     //*/
 }
Example #19
0
 /**
  * Receive Message
  *
  * @param ConnectionInterface $from
  * @param string $message
  */
 public function onMessage(ConnectionInterface $from, $message)
 {
     $decrypted = $this->crypt->decrypt($message, $this->config['key'], $this->config['passphrase']);
     $msg = $this->decode($decrypted);
     if (is_array($msg)) {
         $lambda = new \ReflectionFunction($this->closure);
         $lambda->invokeArgs([$msg, $this->logger]);
     }
     if ($msg === false) {
         $this->logger->error('Message from ' . $from->remoteAddress . ' is invalid.');
     }
 }
Example #20
0
function nativeToFunction($f)
{
    $reflection = new \ReflectionFunction($f);
    $args = array();
    foreach ($reflection->getParameters() as $param) {
        $args[] = new RVar($param->getName());
    }
    $result = $reflection->invokeArgs($args);
    if (!(is_object($result) && is_subclass_of($result, "\\r\\Query"))) {
        throw new RqlDriverError("The function did not evaluate to a query (missing return? missing rxpr(...)?).");
    }
    return new RFunction($args, $result);
}
Example #21
0
 /**
  * {@inheritDoc}
  */
 public function apply(array $arguments = [])
 {
     if ($this->isFunction()) {
         return $this->reflection->invokeArgs($arguments);
     } elseif ($this->isMethodStatic()) {
         return $this->reflection->invokeArgs(null, $arguments);
     } elseif ($this->isMethod()) {
         if (!$this->object) {
             throw new \RuntimeException('The object is required for invoke method (ReflectionMethod::invokeArgs)');
         }
         return $this->reflection->invokeArgs($this->object, $arguments);
     } else {
         throw new \RuntimeException(sprintf('The reflection "%s" not supported.', get_class($this->getReflection())));
     }
 }
Example #22
0
 function andThen($f)
 {
     if (!is_callable($f)) {
         throw new Error('$f must be a function');
     }
     $new_cases = array();
     foreach ($this->cases as $k => $v) {
         $new_cases[] = new BFCase($v->condition, function () use($f, $v) {
             $args = func_get_args();
             $vf = new \ReflectionFunction($v->f);
             return $f($vf->invokeArgs($args));
         });
     }
     return new PartialFunction($new_cases);
 }
Example #23
0
 /**
  * @param $callable
  * @return mixed
  * @throws \Exception
  */
 public function call($callable)
 {
     if (is_callable($callable) && is_array($callable)) {
         $reflection = new \ReflectionClass($callable[0]);
         $method = $reflection->getMethod($callable[1]);
         return $method->invokeArgs($callable[0], $this->injectByFunctionArguments($method->getParameters()));
     } else {
         if (is_callable($callable)) {
             $reflection = new \ReflectionFunction($callable);
             return $reflection->invokeArgs($this->injectByFunctionArguments($reflection->getParameters()));
         } else {
             throw new InjectorException("Wrong type of argument");
         }
     }
 }
Example #24
0
 private function executeOperation(ImageInterface $image, string $operationName, array $args)
 {
     $operation = new \ReflectionFunction($this->getOperation($operationName));
     $callArgs = [];
     foreach ($operation->getParameters() as $parameter) {
         if ($parameter->getName() === 'image') {
             $callArgs[] = $image;
         } elseif (array_key_exists($parameter->getName(), $args)) {
             $callArgs[] = $args[$parameter->getName()];
         } else {
             throw new \RuntimeException('Parameter ' . $parameter->getName() . ' missing for image operation ' . $operationName);
         }
     }
     return $operation->invokeArgs($callArgs);
 }
Example #25
0
 public function route($method, $path)
 {
     $parser = new UriTemplate();
     $results = [];
     $routes = $this->table[strtoupper($method)];
     foreach ($routes as $route) {
         $args = $parser->extract($route[0], $path, true);
         if (isset($args)) {
             // reflect this function as late as possible, since *most* routes shouldn't be called
             $ref = new \ReflectionFunction($route[1]);
             $results[] = \Closure::bind(function () use($ref, $args) {
                 return $ref->invokeArgs($args);
             }, null);
         }
     }
     // always return a callable function inside an array
     return empty($results) ? [$this->emptyRoute] : $results;
 }
Example #26
0
 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     // создаем контекст, используя данные запроса
     $context = new RequestContext();
     $context->fromRequest($request);
     $matcher = new UrlMatcher($this->routes, $context);
     try {
         $attributes = $matcher->match($request->getPathInfo());
         $arguments = $attributes;
         unset($arguments['_route']);
         unset($arguments['controller']);
         $controller = $attributes['controller'];
         $function = new \ReflectionFunction($controller);
         $response = $function->invokeArgs($arguments);
     } catch (ResourceNotFoundException $e) {
         $response = new Response('Не найден!', Response::HTTP_NOT_FOUND);
     }
     return $response;
 }
Example #27
0
 static function call_user_func_named_array($method, $normal_arr, $named_att, $inlineContent)
 {
     $ref = new \ReflectionFunction($method);
     $params = [];
     foreach ($ref->getParameters() as $p) {
         $name = $p->name;
         if (isset($named_att[$name])) {
             $params[] = $named_att[$name];
         } elseif ($inlineContent && isset($inlineContent[$name]) && is_string($inlineContent[$name])) {
             $params[] = $inlineContent[$name];
         } elseif (!empty($normal_arr)) {
             $params[] = array_shift($normal_arr);
         } elseif ($p->isOptional()) {
             $params[] = $p->getDefaultValue();
         } else {
             throw new \Exception("Missing parameter {$p->name}");
         }
     }
     return $ref->invokeArgs($params);
 }
 /**
  * @param string $alias
  * @param array $arguments
  *
  * @throws MethodNotFoundException
  * @throws InvalidArgumentException
  * @throws RuntimeException
  *
  * @return mixed
  */
 public function invoke($alias, $arguments)
 {
     // if the method requested is available
     if (!isset($this->methodMap[$alias])) {
         throw new MethodNotFoundException($alias);
     }
     try {
         // reflect the global function
         $reflection = new \ReflectionFunction($this->methodMap[$alias]);
         // check the parameters in the reflection against what was sent in the request
         $arguments = $this->checkParams($reflection->getParameters(), $arguments);
         // return the result as an invoked call
         return $reflection->invokeArgs($arguments);
     } catch (\ReflectionException $rex) {
         // Propagate an appropriate exception
         throw new RuntimeException("Reflections failed on alias: {$alias}", 0, $rex);
     } catch (\Exception $ex) {
         throw new RuntimeException("Execution of method '{$alias}'  failed.", 0, $ex);
     }
 }
 /**
  * 调用全局函数
  *
  * @param string $method
  *        	函数名称
  * @param array $arr
  * @throws MissingArgumentException
  */
 static function call_user_func_named_array($method, array $arr = [])
 {
     $ref = new \ReflectionFunction($method);
     $params = [];
     foreach ($ref->getParameters() as $p) {
         if ($p->isOptional()) {
             if (isset($arr[$p->name])) {
                 $params[] = $arr[$p->name];
             } else {
                 $params[] = $p->getDefaultValue();
             }
         } else {
             if (isset($arr[$p->name])) {
                 $params[] = $arr[$p->name];
             } else {
                 throw new MissingArgumentException("Missing parameter {$p->name}");
             }
         }
     }
     return $ref->invokeArgs($params);
 }
Example #30
0
function nativeToFunction($f)
{
    if (is_object($f) && is_subclass_of($f, "\\r\\Query")) {
        return wrapImplicitVar($f);
    }
    $reflection = new \ReflectionFunction($f);
    $args = array();
    foreach ($reflection->getParameters() as $param) {
        $args[] = new RVar($param->getName());
    }
    $result = $reflection->invokeArgs($args);
    if (!(is_object($result) && is_subclass_of($result, "\\r\\Query"))) {
        if (!isset($result)) {
            // In case of null, assume that the user forgot to add a return.
            // If null is the intended value, r\expr() should be wrapped around the return value.
            throw new RqlDriverError("The function did not evaluate to a query (missing return?).");
        } else {
            $result = nativeToDatum($result);
        }
    }
    return new RFunction($args, $result);
}