|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Shoot\Shoot\Middleware; |
|
5
|
|
|
|
|
6
|
|
|
use Psr\Container\ContainerExceptionInterface; |
|
7
|
|
|
use Psr\Container\ContainerInterface; |
|
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
9
|
|
|
use Shoot\Shoot\HasPresenterInterface; |
|
10
|
|
|
use Shoot\Shoot\MiddlewareInterface; |
|
11
|
|
|
use Shoot\Shoot\PresenterInterface; |
|
12
|
|
|
use Shoot\Shoot\View; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Resolves presenters for presentation models implementing the HasPresenterInterface using a PSR-11 compliant |
|
16
|
|
|
* container. |
|
17
|
|
|
*/ |
|
18
|
|
|
final class PresenterMiddleware implements MiddlewareInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** @var ContainerInterface */ |
|
21
|
|
|
private $container; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Constructs a new instance of PresenterMiddleware. Requires a PSR-11 compliant container capable of resolving |
|
25
|
|
|
* your presenters. |
|
26
|
|
|
* |
|
27
|
|
|
* @param ContainerInterface $container |
|
28
|
|
|
*/ |
|
29
|
14 |
|
public function __construct(ContainerInterface $container) |
|
30
|
|
|
{ |
|
31
|
14 |
|
$this->container = $container; |
|
32
|
14 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Process the view within the context of the current HTTP request, either before or after calling the next |
|
36
|
|
|
* middleware. Returns the processed view. |
|
37
|
|
|
* |
|
38
|
|
|
* @param View $view |
|
39
|
|
|
* @param ServerRequestInterface $request |
|
40
|
|
|
* @param callable $next |
|
41
|
|
|
* |
|
42
|
|
|
* @return View |
|
43
|
|
|
*/ |
|
44
|
13 |
|
public function process(View $view, ServerRequestInterface $request, callable $next): View |
|
45
|
|
|
{ |
|
46
|
13 |
|
$presentationModel = $view->getPresentationModel(); |
|
47
|
|
|
|
|
48
|
13 |
|
if ($presentationModel instanceof HasPresenterInterface) { |
|
49
|
11 |
|
$presenter = $this->loadPresenter($presentationModel); |
|
50
|
11 |
|
$presentationModel = $presenter->present($request, $presentationModel); |
|
51
|
9 |
|
$view = $view->withPresentationModel($presentationModel); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
12 |
|
return $next($view); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param HasPresenterInterface $hasPresenter |
|
59
|
|
|
* |
|
60
|
|
|
* @return PresenterInterface |
|
61
|
|
|
* |
|
62
|
|
|
* @throws ContainerExceptionInterface |
|
63
|
|
|
*/ |
|
64
|
11 |
|
private function loadPresenter(HasPresenterInterface $hasPresenter): PresenterInterface |
|
65
|
|
|
{ |
|
66
|
11 |
|
return $this->container->get($hasPresenter->getPresenterName()); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|