mirror of
https://github.com/zhamao-robot/zhamao-framework.git
synced 2026-07-21 15:45:36 +08:00
add pipeline feature for middleware
This commit is contained in:
60
src/ZM/Middleware/Pipeline.php
Normal file
60
src/ZM/Middleware/Pipeline.php
Normal file
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace ZM\Middleware;
|
||||
|
||||
use ZM\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Pipeline Inspired by Laravel Framework
|
||||
*/
|
||||
class Pipeline
|
||||
{
|
||||
/** @var mixed */
|
||||
private $value;
|
||||
|
||||
/** @var array */
|
||||
private $middlewares;
|
||||
|
||||
/**
|
||||
* 向管道发送数据
|
||||
*
|
||||
* @param mixed $value 数据
|
||||
* @return $this
|
||||
*/
|
||||
public function send($value): Pipeline
|
||||
{
|
||||
$this->value = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定要过的中间件列表
|
||||
*
|
||||
* @param array $middlewares 要过的中间件(或者叫兼容管道的中间件也行)列表
|
||||
* @return $this
|
||||
*/
|
||||
public function through(array $middlewares): Pipeline
|
||||
{
|
||||
$this->middlewares = $middlewares;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接下来要调用的内容
|
||||
*
|
||||
* @param callable $callback 然后调用一个什么东西
|
||||
* @throws InvalidArgumentException
|
||||
* @return null|mixed 返回调用结果或null
|
||||
*/
|
||||
public function then(callable $callback)
|
||||
{
|
||||
$stack_id = middleware()->getStackId($callback);
|
||||
|
||||
// 遍历执行before并压栈,并在遇到返回false后停止
|
||||
$final_result = (middleware()->getPipeClosure($callback, $stack_id))($this->middlewares, $this->value);
|
||||
|
||||
return $final_result ?? null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user