1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Jnjxp\Molniya; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
9
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
11
|
|
|
use Zend\Expressive\Flash; |
12
|
|
|
use Zend\Expressive\Template\TemplateRendererInterface; |
13
|
|
|
|
14
|
|
|
class MessageMiddleware implements MiddlewareInterface |
15
|
|
|
{ |
16
|
|
|
public const VIEW_KEY = 'messages'; |
17
|
|
|
|
18
|
|
|
protected $template; |
19
|
|
|
|
20
|
|
|
protected $factory; |
21
|
|
|
|
22
|
|
|
protected $flashKey; |
23
|
|
|
|
24
|
|
|
protected $viewKey; |
25
|
|
|
|
26
|
5 |
|
public function __construct( |
27
|
|
|
TemplateRendererInterface $template, |
28
|
|
|
string $helper = MessageViewHelper::class, |
29
|
|
|
string $flashKey = Flash\FlashMessageMiddleware::FLASH_ATTRIBUTE, |
30
|
|
|
string $viewKey = self::VIEW_KEY |
31
|
|
|
) { |
32
|
5 |
|
if (! class_exists($helper) |
33
|
5 |
|
|| ! in_array(MessageViewHelperInterface::class, class_implements($helper), true) |
34
|
|
|
) { |
35
|
2 |
|
throw new \Exception($helper); |
36
|
|
|
} |
37
|
|
|
|
38
|
3 |
|
$this->factory = [$helper, 'createFromFlash']; |
39
|
3 |
|
$this->template = $template; |
40
|
3 |
|
$this->flashKey = $flashKey; |
41
|
3 |
|
$this->viewKey = $viewKey; |
42
|
3 |
|
} |
43
|
|
|
|
44
|
2 |
|
public function process( |
45
|
|
|
ServerRequestInterface $request, |
46
|
|
|
RequestHandlerInterface $handler |
47
|
|
|
) : ResponseInterface { |
48
|
|
|
|
49
|
2 |
|
$flash = $request->getAttribute($this->flashKey, false); |
50
|
|
|
|
51
|
2 |
|
if (! $flash instanceof Flash\FlashMessagesInterface) { |
52
|
1 |
|
throw new \Exception('Flash not available'); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
$helper = ($this->factory)($flash); |
56
|
1 |
|
$this->addToView($helper); |
57
|
|
|
|
58
|
1 |
|
return $handler->handle($request); |
59
|
|
|
} |
60
|
|
|
|
61
|
1 |
|
protected function addToView(MessageViewHelperInterface $helper) : void |
62
|
|
|
{ |
63
|
1 |
|
$this->template->addDefaultParam( |
64
|
1 |
|
TemplateRendererInterface::TEMPLATE_ALL, |
65
|
1 |
|
$this->viewKey, |
66
|
|
|
$helper |
67
|
|
|
); |
68
|
1 |
|
} |
69
|
|
|
} |
70
|
|
|
|