AbstractTidyAdapter::postProcess()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Ctw\Middleware\HtmlMinifierMiddleware\Adapter\TidyAdapter;
5
6
use Ctw\Middleware\HtmlMinifierMiddleware\Adapter\AbstractAdapter as ParentAbstractAdapter;
7
8
class AbstractTidyAdapter extends ParentAbstractAdapter
9
{
10
    protected function postProcess(string $htmlMinified): string
11
    {
12
        $htmlMinified = $this->trim($htmlMinified);
13
14
        return $this->doctype($htmlMinified);
15
    }
16
17
    /**
18
     * Tidy removes the doctype when parsing HTML5 (bug?).
19
     * This causes the browser to switch to quirks mode, which is undesirable.
20
     * This method re-adds the doctype in the case of HTML5.
21
     */
22
    private function doctype(string $html): string
23
    {
24
        $config = $this->getConfig();
25
26
        if (!isset($config['doctype'])) {
27
            return $html;
28
        }
29
30
        if ('html5' !== $config['doctype']) {
31
            return $html;
32
        }
33
34
        if (str_starts_with($html, $prefix = '<!DOCTYPE html>')) {
35
            return $html;
36
        }
37
38
        return $prefix . PHP_EOL . $html;
39
    }
40
}
41