1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Ctw\Middleware\TidyMiddleware; |
5
|
|
|
|
6
|
|
|
use Ctw\Middleware\AbstractMiddleware; |
7
|
|
|
|
8
|
|
|
abstract class AbstractTidyMiddleware extends AbstractMiddleware |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Default Tidy config (overwrite in site config) |
12
|
|
|
*/ |
13
|
|
|
private array $config |
14
|
|
|
= [ |
15
|
|
|
'char-encoding' => 'utf8', |
16
|
|
|
'doctype' => 'html5', |
17
|
|
|
//'new-blocklevel-tags' => 'article,header,footer,section,nav,aside', |
18
|
|
|
//'new-inline-tags' => 'video,audio,canvas,ruby,rt,rp', |
19
|
|
|
'bare' => true, |
20
|
|
|
'break-before-br' => true, |
21
|
|
|
'indent' => false, |
22
|
|
|
'indent-spaces' => 0, |
23
|
|
|
'logical-emphasis' => true, |
24
|
|
|
'numeric-entities' => true, |
25
|
|
|
'quiet' => true, |
26
|
|
|
'quote-ampersand' => false, |
27
|
|
|
'tidy-mark' => false, |
28
|
|
|
'uppercase-tags' => false, |
29
|
|
|
'vertical-space' => false, |
30
|
|
|
'wrap' => 10000, |
31
|
|
|
'wrap-attributes' => false, |
32
|
|
|
'write-back' => true, |
33
|
|
|
]; |
34
|
|
|
|
35
|
4 |
|
public function getConfig(): array |
36
|
|
|
{ |
37
|
4 |
|
return $this->config; |
38
|
|
|
} |
39
|
|
|
|
40
|
8 |
|
public function setConfig(array $config): self |
41
|
|
|
{ |
42
|
8 |
|
$this->config = $config; |
43
|
|
|
|
44
|
8 |
|
return $this; |
45
|
|
|
} |
46
|
|
|
|
47
|
4 |
|
protected function postProcess(string $htmlModified): string |
48
|
|
|
{ |
49
|
4 |
|
$htmlModified = $this->trim($htmlModified); |
50
|
|
|
|
51
|
4 |
|
return $this->doctype($htmlModified); |
52
|
|
|
} |
53
|
|
|
|
54
|
4 |
|
private function trim(string $htmlModified): string |
55
|
|
|
{ |
56
|
4 |
|
return trim($htmlModified); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Tidy removes the doctype when parsing HTML5 (bug?). |
61
|
|
|
* This causes the browser to switch to quirks mode, which is undesirable. |
62
|
|
|
* This method re-adds the doctype in the case of HTML5. |
63
|
|
|
*/ |
64
|
4 |
|
private function doctype(string $htmlModified): string |
65
|
|
|
{ |
66
|
4 |
|
$config = $this->getConfig(); |
67
|
|
|
|
68
|
4 |
|
if (!isset($config['doctype'])) { |
69
|
|
|
return $htmlModified; |
70
|
|
|
} |
71
|
|
|
|
72
|
4 |
|
if ('html5' !== $config['doctype']) { |
73
|
|
|
return $htmlModified; |
74
|
|
|
} |
75
|
|
|
|
76
|
4 |
|
$prefix = '<!DOCTYPE html>'; |
77
|
|
|
|
78
|
4 |
|
if (str_starts_with($htmlModified, $prefix)) { |
79
|
|
|
return $htmlModified; |
80
|
|
|
} |
81
|
|
|
|
82
|
4 |
|
return $prefix . PHP_EOL . $htmlModified; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|