|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of laravel.su package. |
|
4
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
5
|
|
|
* file that was distributed with this source code. |
|
6
|
|
|
*/ |
|
7
|
|
|
declare(strict_types=1); |
|
8
|
|
|
|
|
9
|
|
|
namespace App\Services\ContentRenderer\Support; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Class HeadersNormalizer. |
|
13
|
|
|
*/ |
|
14
|
|
|
trait HeadersNormalizer |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var int |
|
18
|
|
|
*/ |
|
19
|
|
|
private $maxHeaderLevel = 2; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var int |
|
23
|
|
|
*/ |
|
24
|
|
|
private $minHeaderLevel = 6; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @var string |
|
28
|
|
|
*/ |
|
29
|
|
|
private $pattern = '/^(#+)\s+(.*?)\s*$/mius'; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @return \Closure |
|
33
|
|
|
*/ |
|
34
|
|
|
protected function normalizeHeaders(): \Closure |
|
35
|
|
|
{ |
|
36
|
|
|
return function (string $body) { |
|
37
|
|
|
$delta = $this->getMaxHeaderLevel($body) - $this->maxHeaderLevel; |
|
38
|
|
|
|
|
39
|
|
|
return preg_replace_callback('/^(#+)\s+(.*?)\s*$/mius', function (array $matches) use ($delta) { |
|
40
|
|
|
[$body, $tag, $title] = $matches; |
|
|
|
|
|
|
41
|
|
|
|
|
42
|
|
|
$level = $this->mdTagToLevel($tag); |
|
43
|
|
|
$level += $delta; |
|
44
|
|
|
$level = min($this->minHeaderLevel, max($this->maxHeaderLevel, $level)); |
|
45
|
|
|
|
|
46
|
|
|
return str_repeat('#', $level) . ' ' . $title; |
|
47
|
|
|
}, $body); |
|
48
|
|
|
}; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param string $body |
|
53
|
|
|
* @return int|mixed |
|
54
|
|
|
*/ |
|
55
|
|
|
private function getMaxHeaderLevel(string $body) |
|
56
|
|
|
{ |
|
57
|
|
|
$max = $this->minHeaderLevel; |
|
58
|
|
|
|
|
59
|
|
|
preg_match_all($this->pattern, $body, $matches); |
|
60
|
|
|
|
|
61
|
|
|
for ($i = 0, $len = count($matches[0]); $i < $len; $i++) { |
|
62
|
|
|
$max = min($max, $this->mdTagToLevel($matches[1][$i])); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return $max; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @param string $tag |
|
70
|
|
|
* @return int |
|
71
|
|
|
*/ |
|
72
|
|
|
private function mdTagToLevel(string $tag): int |
|
73
|
|
|
{ |
|
74
|
|
|
$level = strlen(trim($tag)); |
|
75
|
|
|
|
|
76
|
|
|
return max(1, min($this->minHeaderLevel, $level)); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.