HtmlMinifierMiddleware::getAdapter()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Ctw\Middleware\HtmlMinifierMiddleware;
5
6
use Ctw\Middleware\HtmlMinifierMiddleware\Adapter\AdapterInterface;
7
use Middlewares\Utils\Factory;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
12
class HtmlMinifierMiddleware extends AbstractHtmlMinifierMiddleware
13
{
14
    protected AdapterInterface $adapter;
15
16
    public function getAdapter(): AdapterInterface
17
    {
18
        return $this->adapter;
19
    }
20
21
    public function setAdapter(AdapterInterface $adapter): self
22
    {
23
        $this->adapter = $adapter;
24
25
        return $this;
26
    }
27
28
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
29
    {
30
        $response = $handler->handle($request);
31
32
        if (!$this->containsHtml($response)) {
33
            return $response;
34
        }
35
36
        $htmlSource = $response->getBody()
37
            ->getContents();
38
39
        if ('' === $htmlSource) {
40
            return $response;
41
        }
42
43
        $htmlMinified = $this->getAdapter()
44
            ->minify($htmlSource);
45
46
        [$in, $out, $diff] = $this->getSuffixStatistics($htmlSource, $htmlMinified);
47
48
        $htmlMinified .= PHP_EOL . sprintf(self::HTML_SUFFIX, $in, $out, $diff);
49
50
        $body = Factory::getStreamFactory()->createStream($htmlMinified);
51
52
        return $response->withBody($body);
53
    }
54
}
55