获取切片 从外往里的中间件 (through)

@return Closure
338334
public function getSlice()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                // 管道是一个闭包, 直接调用
                if ($pipe instanceof Closure) {
                    return call_user_func($pipe, $passable, $stack);
                }
                elseif (!is_object($pipe)) {
                    $pipe = new $pipe;
                }

                // 传递给中间件的参数
                // todo 传递其它参数
                $parameters = [$passable, $stack];

                return call_user_func_array([$pipe, 'handle'], $parameters);
            };
        };
    }
590423
public function getRouter()
    {
        $method = strtoupper($this->env->method());
        $url = $this->env->getPathinfo();
        //默认首页
        $url = rtrim($url, '/');
        $url = $url ? $url : '/';
        return $this->match($method, $url);
    }
397576
protected function carry()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                if (is_callable($pipe)) {
                    // If the pipe is an instance of a Closure, we will just call it directly but
                    // otherwise we'll resolve the pipes out of the container and call it with
                    // the appropriate method and arguments, returning the results back out.
                    return $pipe($passable, $stack);
                } elseif (! is_object($pipe)) {
                    [$name, $parameters] = $this->parsePipeString($pipe);

                    // If the pipe is a string we will parse the string and resolve the class out
                    // of the dependency injection container. We can then build a callable and
                    // execute the pipe function giving in the parameters that are required.
                    $pipe = $this->getContainer()->make($name);

                    $parameters = array_merge([$passable, $stack], $parameters);
                } else {
                    // If the pipe is already an object we'll just make a callable and pass it to
                    // the pipe as-is. There is no need to do any extra parsing and formatting
                    // since the object we're given was already a fully instantiated object.
                    $parameters = [$passable, $stack];
                }

                $response = method_exists($pipe, $this->method)
                                ? $pipe->{$this->method}(...$parameters)
                                : $pipe(...$parameters);

                return $response instanceof Responsable
                            ? $response->toResponse($this->getContainer()->make(Request::class))
                            : $response;
            };
        };
    }
103156
protected function getSlice()
	{
		return function($stack, $pipe)
		{
			return function($passable) use ($stack, $pipe)
			{
				// If the pipe is an instance of a Closure, we will just call it directly but
				// otherwise we'll resolve the pipes out of the container and call it with
				// the appropriate method and arguments, returning the results back out.
				if ($pipe instanceof Closure)
				{
					return call_user_func($pipe, $passable, $stack);
				}
				else
				{
					return $this->container->make($pipe)
							->{$this->method}($passable, $stack);
				}
			};
		};
	}
669313
function out()
    {
        if (php_sapi_name() == 'cli'){
            echo self::Format($this, false, $trace_buf = [], '  ')."\n";
        }else{
            echo '<pre>'.self::Format($this).'</pre>';
        }
        return $this;
    }
237672
public function via()
    {
        $args = func_get_args();
        $this->methods = array_merge($this->methods, $args);

        return $this;
    }
1263270
public static function method() {
        // $this->methodParam 默认值为 '_method'
        // 如果指定 $_POST['_method'] ，表示使用POST请求来模拟其他方法的请求。
        // 此时 $_POST['_method'] 即为所模拟的请求类型。
        if (isset($_POST[$this->methodParam])) {
            return strtoupper($_POST[$this->methodParam]);
            // 或者使用 $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] 的值作为方法名。
        } elseif (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
            return strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
            // 或者使用 $_SERVER['REQUEST_METHOD'] 作为方法名，未指定时，默认为 GET 方法
        } else {
            return isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET';
        }
    }
320904
public function get()
    {
        //获取保存值
        $raw = parent::getRaw();
        if (is_null($raw)) {
            return null;
        }

        //JSON解码
        $decoded = json_decode($raw);

        //如果解码失败,返回原始内容
        if (is_null($decoded)) {
            return $raw;
        }

        return $decoded;
    }
796856
public function proceed()
    {
        if (isset($this->advices[$this->current])) {
            $currentInterceptor = $this->advices[$this->current++];

            return $currentInterceptor->invoke($this);
        }

        // Fill the closure only once if it's empty
        if ($this->closureToCall === null) {
            $this->closureToCall    = $this->reflectionMethod->getClosure($this->instance);
            $this->previousInstance = $this->instance;
        }

        // Rebind the closure if instance was changed since last time
        if ($this->previousInstance !== $this->instance) {
            $this->closureToCall    = $this->closureToCall->bindTo($this->instance, $this->reflectionMethod->class);
            $this->previousInstance = $this->instance;
        }

        return ($this->closureToCall)(...$this->arguments);
    }
429964
protected function carry()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                try {
                    $slice = parent::carry();

                    return \call_user_func($slice($stack, $pipe), $passable);
                } catch (Exception $e) {
                    return $this->handleException($passable, $e);
                } catch (Throwable $e) {
                    return $this->handleException($passable, new FatalThrowableError($e));
                }
            };
        };
    }
676221
function last(callable $closure = null) {
        if($closure === null) {
            if(empty($this->data)) {
                return null;
            }
            
            $keys = \array_keys($this->data);
            return $this->data[$keys[(\count($keys) - 1)]];
        }
        
        $data = null;
        foreach($this->data as $key => $val) {
            $feed = $closure($val, $key);
            if($feed) {
                $data = $val;
            }
        }
        
        return $data;
    }
763152
public function log() : \Closure
    {
        $logger    = $this->logger;
        $formatter = $this->formatter;

        return function (callable $handler) use ($logger, $formatter) {

            return function ($request, array $options) use ($handler, $logger, $formatter) {
                // generate id that will be used to supplement the log with information
                $requestId = uniqid('eight_points_guzzle_');

                // initial registration of log
                $logger->info('', compact('request', 'requestId'));

                // this id will be used by RequestTimeMiddleware
                $options['request_id'] = $requestId;

                return $handler($request, $options)->then(

                    function ($response) use ($logger, $request, $formatter, $requestId) {

                        $message = $formatter->format($request, $response);
                        $context = compact('request', 'response', 'requestId');

                        $logger->info($message, $context);

                        return $response;
                    },

                    function ($reason) use ($logger, $request, $formatter, $requestId) {

                        $response = $reason instanceof RequestException ? $reason->getResponse() : null;
                        $message  = $formatter->format($request, $response, $reason);
                        $context  = compact('request', 'response', 'requestId');

                        $logger->notice($message, $context);

                        return \GuzzleHttp\Promise\rejection_for($reason);
                    }
                );
            };
        };
    }
347735
function getTo(): \Closure {
    return function($value, \Mustache_LambdaHelper $helper) {
      $args = $this->parseArguments($helper->render($value), 'url', ['scheme' => false]);
      return UrlHelper::to($args['url'], $args['scheme']);
    };
  }
1094877
public function self()
    {
        $result = $this->itemIterator ? $this->itemIterator->current() : $this->item;
        $this->resetLocalScope();

        return $result;
    }
1344816
public function autoTrans(Closure $Closure) : bool
    {
        $this->Driver->beginTransaction();
        $this->isTrans = true; //事务开始标记
        $r             = $Closure($this); //闭包只有一层

        //执行事务
        $success = true;
        foreach ($this->transResult as $result) {
            if (!$result) {
                $success = false;
                break;
            }
        }
        if ($success) {
            $this->Driver->commit();
        } else {
            $this->Driver->rollBack(); //若任一操作执行失败，则自动回滚
        }

        $this->transResult = []; //清空事务结果
        $this->isTrans     = false;
        return $success;
    }
953157
public static function dispatch()
    {
        $currentRoute = isset($_GET[self::$name]) ? $_GET[self::$name] : '/';
        $found_route = false;
        $method = strtolower($_SERVER['REQUEST_METHOD']);
        foreach (self::$routes as $v) {
            if (!empty($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $currentRoute && ($v2['method'] == $method || $v2['method']=='any')) {
                        $found_route = true;
                        $_GET['r'] = $currentRoute;
                        // Call closure
                        $refFunc = new \ReflectionFunction($v2['callBack']);
                        $params = [];
                        foreach ($refFunc->getParameters() as $v3) {
                            if (isset($_REQUEST[$v3->name])) {
                                $params[$v3->name] = $_REQUEST[$v3->name];
                            }else{
                                //参数是否有默认值
                                if($v3->isDefaultValueAvailable()){
                                    $params[$v3->name] = $v3->getDefaultValue();
                                }else{
                                    //参数是否是个对象
                                    $classRef = $v3->getClass();
                                    if($classRef){
                                        $classProperties = $classRef->getProperties();
                                        /**
                                         * @var $class Model
                                         */
                                        $class = $classRef->newInstance();
                                        if($classProperties){
                                           foreach($classProperties as $v4){
                                               $propertyName  = $v4->name;
                                               if(isset($_REQUEST[$propertyName])){
                                                   $class->$propertyName = $_REQUEST[$propertyName];
                                               }
                                           }
                                        }
                                        //验证参数
                                        if($classRef->hasMethod('validate')){
                                            if(!$class->validate()){
                                                throw new \Exception(json_encode($class->getErrors(),JSON_UNESCAPED_UNICODE));
                                            }
                                        }
                                        $params = [$class];
                                    }else{
                                        throw new \Exception('参数不存在：'.$v3->name,400);
                                    }
                                }
                            }
                        }
                        //将post or get 参数传入
                        if (!empty($params)) {
                            return call_user_func_array($v2['callBack'], $params);
                        } else {
                            return call_user_func($v2['callBack']);
                        }
                       break;
                    }
                }
            }
        }

        if ($found_route == false) {
            header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
            if (self::$error_callback) {
                return call_user_func(self::$error_callback, ['message' => '404 Not Found']);;
            }
        }
        return false;

    }
40149
public function count()
    {
        if ( !$this->count ) return $this->iterator->count();

        if ($this->count instanceOf \Closure) {
            $this->count = $this->count->__invoke();
        }

        return $this->count;
    }