1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Lit\Voltage; |
6
|
|
|
|
7
|
|
|
use Lit\Nimo\Handlers\AbstractHandler; |
8
|
|
|
use Lit\Nimo\Middlewares\MiddlewarePipe; |
9
|
|
|
use Lit\Voltage\Interfaces\ThrowableResponseInterface; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
12
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* App is a complete PSR-15 application, including a middleware pipe and a concrete business handler. |
16
|
|
|
*/ |
17
|
|
|
class App extends AbstractHandler |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var MiddlewarePipe |
21
|
|
|
*/ |
22
|
|
|
protected $middlewarePipe; |
23
|
|
|
/** |
24
|
|
|
* @var RequestHandlerInterface |
25
|
|
|
*/ |
26
|
|
|
protected $businessLogicHandler; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* App constructor |
30
|
|
|
* |
31
|
|
|
* @param RequestHandlerInterface $handler The concrete request handler. |
32
|
|
|
* @param MiddlewareInterface|null $middleware Optional. A middleware pipe will be created if this is not |
33
|
|
|
* instance of MiddlewarePipe. |
34
|
|
|
*/ |
35
|
|
|
public function __construct(RequestHandlerInterface $handler, MiddlewareInterface $middleware = null) |
36
|
|
|
{ |
37
|
|
|
$this->businessLogicHandler = $handler; |
38
|
|
|
$this->middlewarePipe = $middleware |
39
|
|
|
? ($middleware instanceof MiddlewarePipe ? $middleware : (new MiddlewarePipe())->append($middleware)) |
40
|
|
|
: new MiddlewarePipe(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Getter for middleware pipe |
45
|
|
|
* |
46
|
|
|
* @return MiddlewarePipe |
47
|
|
|
*/ |
48
|
|
|
public function getMiddlewarePipe(): MiddlewarePipe |
49
|
|
|
{ |
50
|
|
|
return $this->middlewarePipe; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @return ResponseInterface |
55
|
|
|
*/ |
56
|
|
|
protected function main(): ResponseInterface |
57
|
|
|
{ |
58
|
|
|
try { |
59
|
|
|
return $this->middlewarePipe->process($this->request, $this->businessLogicHandler); |
60
|
|
|
} catch (ThrowableResponseInterface $e) { |
61
|
|
|
return $e->getResponse(); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|