CMSMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
4
namespace TheCodingMachine\CMS\Middleware;
5
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 TheCodingMachine\CMS\Block\BlockRenderer;
12
use TheCodingMachine\CMS\Block\CacheableBlock;
13
use TheCodingMachine\CMS\Page\PageRegistryInterface;
14
use Zend\Diactoros\Response;
15
16
class CMSMiddleware implements MiddlewareInterface
17
{
18
    /**
19
     * @var PageRegistryInterface
20
     */
21
    private $pageRegistry;
22
    /**
23
     * @var BlockRenderer
24
     */
25
    private $blockRenderer;
26
27
    public function __construct(PageRegistryInterface $pageRegistry, BlockRenderer $blockRenderer)
28
    {
29
        $this->pageRegistry = $pageRegistry;
30
        $this->blockRenderer = $blockRenderer;
31
    }
32
33
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
34
    {
35
        // Let's only deal with GET requests.
36
        if ($request->getMethod() !== 'GET') {
37
            return $handler->handle($request);
38
        }
39
40
        $page = $this->pageRegistry->getPage($request);
41
42
        if ($page === null) {
43
            return $handler->handle($request);
44
        }
45
46
        $stream = $this->blockRenderer->renderBlock($page);
47
48
        $response = new Response($stream);
49
50
        if ($page instanceof CacheableBlock) {
51
            $response = $response->withHeader('Expires', gmdate('D, d M Y H:i:s T', time() + $page->getTtl()));
52
        }
53
54
        return $response;
55
    }
56
}
57