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 |
|
$body = $response->getBody(); |
23
|
|
|
|
24
|
6 |
|
$htmlOriginal = $body->getContents(); |
25
|
|
|
|
26
|
6 |
|
if ('' === $htmlOriginal) { |
27
|
2 |
|
return $response; |
28
|
|
|
} |
29
|
|
|
|
30
|
4 |
|
$minifier = tidy_parse_string($htmlOriginal, $this->getConfig(), 'utf8'); |
31
|
4 |
|
assert($minifier instanceof tidy); |
32
|
|
|
|
33
|
4 |
|
if (!tidy_clean_repair($minifier)) { |
34
|
|
|
return $response; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
// @phpstan-ignore-next-line |
38
|
4 |
|
$htmlModified = (string) $minifier->html(); |
39
|
4 |
|
$htmlModified = $this->postProcess($htmlModified); |
40
|
|
|
|
41
|
4 |
|
[$in, $out, $diff] = $this->getSuffixStatistics($htmlOriginal, $htmlModified); |
42
|
|
|
|
43
|
4 |
|
$htmlModified .= PHP_EOL . sprintf(self::HTML_SUFFIX, $in, $out, $diff); |
44
|
|
|
|
45
|
4 |
|
unset($minifier, $htmlOriginal); |
46
|
|
|
|
47
|
4 |
|
$body = Factory::getStreamFactory()->createStream($htmlModified); |
48
|
|
|
|
49
|
4 |
|
return $response->withBody($body); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|