-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MiddlewareStack.php
65 lines (53 loc) · 1.74 KB
/
MiddlewareStack.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\HttpHandler;
use Closure;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use SonsOfPHP\Contract\HttpHandler\MiddlewareStackInterface;
/**
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class MiddlewareStack implements MiddlewareStackInterface
{
private array $middlewares = [];
//private $resolver;
//public function __construct($resolver)
//{
// $this->resolver = $resolver;
//}
/**
* Adds a new middleware to the stack. Middlewares can be prioritized and
* will be ordered from the lowest number to the highest number (ascending
* order).
*/
public function add(MiddlewareInterface|Closure $middleware, int $priority = 0): self
{
$this->middlewares[$priority][] = $middleware;
ksort($this->middlewares);
return $this;
}
public function next(): MiddlewareInterface
{
$priorityStack = array_shift($this->middlewares);
$middleware = array_shift($priorityStack);
if ([] !== $priorityStack) {
array_unshift($this->middlewares, $priorityStack);
}
if ($middleware instanceof Closure) {
return new class ($middleware) implements MiddlewareInterface {
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
return $this->closure($request, $handler);
}
};
}
return $middleware;
}
public function count(): int
{
return count($this->middlewares);
}
}