Passed
Push — master ( 2da0ed...204ae9 )
by Jonathan
03:08
created

TidyMiddleware::process()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 34
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4.0027

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 4
nop 2
dl 0
loc 34
ccs 17
cts 18
cp 0.9444
crap 4.0027
rs 9.7
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Ctw\Middleware\TidyMiddleware;
5
6
use Middlewares\Utils\Factory;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use tidy;
11
12
class TidyMiddleware extends AbstractTidyMiddleware
13
{
14 8
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
15
    {
16 8
        $response = $handler->handle($request);
17
18 8
        if (!$this->containsHtml($response)) {
19 2
            return $response;
20
        }
21
22 6
        $htmlOriginal = $response->getBody()->getContents();
23
24 6
        if (0 === strlen($htmlOriginal)) {
25 2
            return $response;
26
        }
27
28 4
        $minifier = tidy_parse_string($htmlOriginal, $this->getConfig(), 'utf8');
29 4
        assert($minifier instanceof tidy);
30
31 4
        if (!tidy_clean_repair($minifier)) {
32
            return $response;
33
        }
34
35
        // @phpstan-ignore-next-line
36 4
        $htmlModified = (string) $minifier->html();
37 4
        $htmlModified = trim($htmlModified);
38
39 4
        [$in, $out, $diff] = $this->getSuffixStatistics($htmlOriginal, $htmlModified);
40
41 4
        $htmlModified .= PHP_EOL . sprintf(self::SUFFIX, $in, $out, $diff);
42
43 4
        unset($minifier, $htmlOriginal);
44
45 4
        $body = Factory::getStreamFactory()->createStream($htmlModified);
46
47 4
        return $response->withBody($body);
48
    }
49
}
50