Passed
Push — master ( 2e5326...ca9fd3 )
by Derek Stephen
07:05
created

LayoutMiddleware::process()   C

Complexity

Conditions 12
Paths 96

Size

Total Lines 43
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 25
c 2
b 0
f 0
dl 0
loc 43
rs 6.9666
cc 12
nc 96
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Bone\View\Middleware;
4
5
use Bone\Http\Response;
6
use Bone\Http\Response\LayoutResponse;
7
use Bone\Server\SiteConfig;
8
use Bone\View\ViewEngineInterface;
9
use Bone\Http\Response\HtmlResponse;
10
use Laminas\Diactoros\Stream;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
use Psr\Http\Server\MiddlewareInterface;
14
use Psr\Http\Server\RequestHandlerInterface;
15
16
class LayoutMiddleware implements MiddlewareInterface
17
{
18
    /** @var ViewEngineInterface $viewEngine */
19
    private $viewEngine;
20
21
    /** @var string $defaultLayout \ */
22
    private $defaultLayout;
23
24
    /** @var SiteConfig $config \ */
25
    private $config;
26
27
    /**
28
     * LayoutMiddleware constructor.
29
     * @param ViewEngineInterface $viewEngine
30
     * @param string $defaultLayout
31
     * @param SiteConfig $config
32
     */
33
    public function __construct(ViewEngineInterface $viewEngine, string $defaultLayout, SiteConfig $config)
34
    {
35
        $this->viewEngine = $viewEngine;
36
        $this->defaultLayout = $defaultLayout;
37
        $this->config = $config;
38
    }
39
40
    /**
41
     * @param ServerRequestInterface $request
42
     * @param RequestHandlerInterface $handler
43
     * @return ResponseInterface
44
     */
45
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
46
    {
47
        $response = $handler->handle($request);
48
        $layout = $this->defaultLayout;
49
50
        if ($response instanceof LayoutResponse) {
51
            $layout = $response->getLayout();
52
        } elseif ($response->hasHeader('layout')) {
53
            $layout = $response->getHeader('layout')[0];
54
            $layout = $layout === 'none' ? false : $layout;
55
            $response = $response->withoutHeader('header');
56
        }
57
58
        $contentType = $response->getHeader('Content-Type');
59
        $isHtmlResponse = $response instanceof HtmlResponse || get_class($response) === 'Laminas\Diactoros\Response\HtmlResponse';
60
        $hasHtmlContent = count($contentType) ? strstr($contentType[0], 'text/html') : true;
61
62
        if ((!$isHtmlResponse || !$hasHtmlContent || !$layout)) {
63
            return $response;
64
        }
65
66
        $body = [
67
            'content' => $response->getBody()->getContents(),
68
            'config' => $this->config,
69
            'user' => null,
70
            'vars' => [],
71
        ];
72
73
        if ($response instanceof Response) {
74
75
            if ($response->hasAttribute('user')) {
76
                $body['user'] = $response->getAttribute('user');
77
            }
78
79
            if ($response->hasAttribute('vars')) {
80
                $body['vars'] = $response->getAttribute('vars');
81
            }
82
83
        }
84
85
        $body = $this->viewEngine->render($layout, $body);
86
87
        return $this->getResponseWithBodyAndStatus($response, $body, $response->getStatusCode());
88
    }
89
90
91
    /**
92
     * @param ResponseInterface $response
93
     * @param string $body
94
     * @param int $status
95
     * @return ResponseInterface
96
     */
97
    private function getResponseWithBodyAndStatus(ResponseInterface $response, string $body, int $status = 200): ResponseInterface
98
    {
99
        $stream = new Stream('php://memory', 'r+');
100
        $stream->write($body);
101
        $response = $response->withStatus($status)->withBody($stream);
102
103
        return $response;
104
    }
105
}