Passed
Push — main ( f2efe3...53dc0a )
by smiley
10:15
created

RecursiveDispatcher.php$0 ➔ handle()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Class RecursiveDispatcher
4
 *
5
 * A simple middleware dispatcher based on Slim
6
 *
7
 * @see https://github.com/slimphp/Slim/blob/de07f779d229ec06080259a816b0740de830438c/Slim/MiddlewareDispatcher.php
8
 *
9
 * @filesource   RecursiveDispatcher.php
10
 * @created      15.04.2020
11
 * @package      chillerlan\HTTP\Psr15;
12
 * @author       smiley <[email protected]>
13
 * @copyright    2020 smiley
14
 * @license      MIT
15
 */
16
17
namespace chillerlan\HTTP\Psr15;;
18
19
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
20
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};
21
22
class RecursiveDispatcher implements RequestHandlerInterface{
23
24
	/**
25
	 * Tip of the middleware call stack
26
	 */
27
	protected RequestHandlerInterface $tip;
28
29
	/**
30
	 * RecursiveDispatcher constructor.
31
	 */
32
	public function __construct(RequestHandlerInterface $kernel){
33
		$this->tip = $kernel;
34
	}
35
36
	/**
37
	 * Add a new middleware to the stack
38
	 *
39
	 * Middleware are organized as a stack. That means middleware
40
	 * that have been added before will be executed after the newly
41
	 * added one (last in, first out).
42
	 */
43
	public function add(MiddlewareInterface $middleware):RecursiveDispatcher{
44
45
		$this->tip = new class ($middleware, $this->tip) implements RequestHandlerInterface{
46
47
			private MiddlewareInterface $middleware;
48
			private RequestHandlerInterface $next;
49
50
			public function __construct(MiddlewareInterface $middleware, RequestHandlerInterface $next){
51
				$this->middleware = $middleware;
52
				$this->next       = $next;
53
			}
54
55
			public function handle(ServerRequestInterface $request):ResponseInterface{
56
				return $this->middleware->process($request, $this->next);
57
			}
58
		};
59
60
		return $this;
61
	}
62
63
	/**
64
	 * @param \Psr\Http\Server\MiddlewareInterface[] $middlewareStack
65
	 *
66
	 * @return \chillerlan\HTTP\Psr15\RecursiveDispatcher
67
	 * @throws \chillerlan\HTTP\Psr15\MiddlewareException
68
	 */
69
	public function addStack(iterable $middlewareStack):RecursiveDispatcher{
70
71
		foreach($middlewareStack as $middleware){
72
73
			if(!$middleware instanceof MiddlewareInterface){
74
				throw new MiddlewareException('invalid middleware');
75
			}
76
77
			$this->add($middleware);
78
		}
79
80
		return $this;
81
	}
82
83
	/**
84
	 * @inheritDoc
85
	 */
86
	public function handle(ServerRequestInterface $request):ResponseInterface{
87
		return $this->tip->handle($request);
88
	}
89
90
}
91