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