Completed
Push — master ( a09c74...b4437a )
by Gabor
03:33
created

DispatcherMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * WebHemi.
4
 *
5
 * PHP version 5.6
6
 *
7
 * @copyright 2012 - 2016 Gixx-web (http://www.gixx-web.com)
8
 * @license   https://opensource.org/licenses/MIT The MIT License (MIT)
9
 *
10
 * @link      http://www.gixx-web.com
11
 */
12
namespace WebHemi\Middleware;
13
14
use Psr\Http\Message\StreamInterface;
15
use RuntimeException;
16
use WebHemi\Adapter\Http\ResponseInterface;
17
use WebHemi\Adapter\Http\ServerRequestInterface;
18
use WebHemi\Adapter\Renderer\RendererAdapterInterface;
19
20
/**
21
 * Class DispatcherMiddleware.
22
 */
23
class DispatcherMiddleware implements MiddlewareInterface
24
{
25
    /** @var RendererAdapterInterface */
26
    private $templateRenderer;
27
28
    /**
29
     * DispatcherMiddleware constructor.
30
     *
31
     * @param RendererAdapterInterface $templateRenderer
32
     */
33 5
    public function __construct(RendererAdapterInterface $templateRenderer)
34
    {
35 5
        $this->templateRenderer = $templateRenderer;
36 5
    }
37
38
    /**
39
     * From the request data renders an output for the response, or sets an error status code.
40
     *
41
     * @param ServerRequestInterface $request
42
     * @param ResponseInterface      $response
43
     *
44
     * @throws RuntimeException
45
     *
46
     * @return ResponseInterface
47
     */
48 5
    public function __invoke(ServerRequestInterface &$request, ResponseInterface $response)
49
    {
50
        /** @var MiddlewareInterface $actionMiddleware */
51 5
        $actionMiddleware = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_ACTION_MIDDLEWARE);
52
53
        // If there is a valid action Middleware, then dispatch it.
54 5
        if (!is_null($actionMiddleware) && $actionMiddleware instanceof MiddlewareActionInterface) {
55 3
            $response = $actionMiddleware($request, $response);
56
57
            /** @var string $template */
58 2
            $template = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_TEMPLATE);
59
            /** @var array $data */
60 2
            $data = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA);
61
            /** @var StreamInterface $body */
62 2
            $body = $this->templateRenderer->render($template, $data);
63 2
            $response = $response->withBody($body);
64
        } else {
65 2
            throw new RuntimeException(sprintf('The given attribute is not a valid Action Middleware.'));
66
        }
67
68 2
        return $response;
69
    }
70
}
71