PresenterMiddleware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 10
c 1
b 0
f 0
dl 0
loc 49
ccs 12
cts 12
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A loadPresenter() 0 3 1
A process() 0 11 2
A __construct() 0 3 1
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