1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Http; |
6
|
|
|
|
7
|
|
|
use Psr\EventDispatcher\EventDispatcherInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
11
|
|
|
use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher; |
12
|
|
|
use Yiisoft\Yii\Http\Event\AfterEmit; |
13
|
|
|
use Yiisoft\Yii\Http\Event\AfterRequest; |
14
|
|
|
use Yiisoft\Yii\Http\Event\ApplicationShutdown; |
15
|
|
|
use Yiisoft\Yii\Http\Event\ApplicationStartup; |
16
|
|
|
use Yiisoft\Yii\Http\Event\BeforeRequest; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Application is the entry point for an HTTP application. |
20
|
|
|
* |
21
|
|
|
* For more details and usage information on Application, see the guide article on applications: |
22
|
|
|
* |
23
|
|
|
* @see https://github.com/yiisoft/docs/blob/master/guide/en/structure/application.md. |
24
|
|
|
*/ |
25
|
|
|
final class Application |
26
|
|
|
{ |
27
|
|
|
private MiddlewareDispatcher $dispatcher; |
28
|
|
|
private EventDispatcherInterface $eventDispatcher; |
29
|
|
|
private RequestHandlerInterface $fallbackHandler; |
30
|
|
|
|
31
|
8 |
|
public function __construct( |
32
|
|
|
MiddlewareDispatcher $dispatcher, |
33
|
|
|
EventDispatcherInterface $eventDispatcher, |
34
|
|
|
RequestHandlerInterface $fallbackHandler |
35
|
|
|
) { |
36
|
8 |
|
$this->dispatcher = $dispatcher; |
37
|
8 |
|
$this->eventDispatcher = $eventDispatcher; |
38
|
8 |
|
$this->fallbackHandler = $fallbackHandler; |
39
|
8 |
|
} |
40
|
|
|
|
41
|
1 |
|
public function start(): void |
42
|
|
|
{ |
43
|
1 |
|
$this->eventDispatcher->dispatch(new ApplicationStartup()); |
44
|
1 |
|
} |
45
|
|
|
|
46
|
1 |
|
public function shutdown(): void |
47
|
|
|
{ |
48
|
1 |
|
$this->eventDispatcher->dispatch(new ApplicationShutdown()); |
49
|
1 |
|
} |
50
|
|
|
|
51
|
2 |
|
public function afterEmit(?ResponseInterface $response): void |
52
|
|
|
{ |
53
|
2 |
|
$this->eventDispatcher->dispatch(new AfterEmit($response)); |
54
|
2 |
|
} |
55
|
|
|
|
56
|
4 |
|
public function handle(ServerRequestInterface $request): ResponseInterface |
57
|
|
|
{ |
58
|
4 |
|
$this->eventDispatcher->dispatch(new BeforeRequest($request)); |
59
|
|
|
|
60
|
|
|
try { |
61
|
4 |
|
return $response = $this->dispatcher->dispatch($request, $this->fallbackHandler); |
62
|
|
|
} finally { |
63
|
4 |
|
$this->eventDispatcher->dispatch(new AfterRequest($response ?? null)); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|