1 | <?php |
||
5 | class HtmlHeadingNormalizer |
||
6 | { |
||
7 | public static function demote($html, $levels) |
||
11 | |||
12 | public static function promote($html, $levels) |
||
16 | |||
17 | private static function normalize($html, $levels) |
||
18 | { |
||
19 | $normalizationIsRequired = ((abs($levels) > 0) && self::containsHeadings($html)); |
||
20 | |||
21 | if (!$normalizationIsRequired) { |
||
22 | return $html; |
||
23 | } |
||
24 | |||
25 | $domDocument = new \DOMDocument(); |
||
26 | $domDocument->loadHTML($html); |
||
27 | |||
28 | $originalHeadings = self::getHeadings($domDocument); |
||
29 | $normalizedHeadings = self::normalizeHeadings($originalHeadings, $levels); |
||
30 | |||
31 | self::replaceHeadings( |
||
32 | $originalHeadings, |
||
33 | $normalizedHeadings |
||
34 | ); |
||
35 | |||
36 | return $domDocument->saveHTML(); |
||
37 | return self::formatResult($domDocument, $html); |
||
|
|||
38 | } |
||
39 | |||
40 | private static function getHeadings(\DOMDocument $domDocument) |
||
41 | { |
||
42 | $tagNames = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'); |
||
43 | $headings = array(); |
||
44 | |||
45 | foreach ($tagNames as $tagName) { |
||
46 | foreach ($domDocument->getElementsByTagName($tagName) as $heading) { |
||
47 | $headings[] = $heading; |
||
48 | } |
||
49 | } |
||
50 | |||
51 | return $headings; |
||
52 | } |
||
53 | |||
54 | private static function normalizeHeadings(array $originalHeadings, $levelDelta) |
||
67 | |||
68 | private static function replaceHeadings(array $needles, array $replacements) |
||
74 | |||
75 | private static function containsHeadings($html) |
||
82 | |||
83 | private static function tagNameToLevel($tagName) |
||
87 | |||
88 | private static function levelToTagName($level) |
||
92 | |||
93 | private static function cloneHeading(\DOMElement $sourceHeading, $newLevel) |
||
94 | { |
||
103 | |||
104 | private static function copyAttributes(\DOMElement $source, \DOMElement $target) |
||
110 | |||
111 | private static function moveChildNodes(\DOMElement $source, \DOMElement $target) |
||
118 | |||
119 | private static function formatResult(\DOMDocument $domDocument, $originalHtml) |
||
136 | |||
137 | private static function containsDocType($html) |
||
141 | |||
142 | private static function stringContains($string, $needle) |
||
146 | |||
147 | private static function containsHtmlTag($html) |
||
151 | } |
||
152 |
This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.
Unreachable code is most often the result of
return
,die
orexit
statements that have been added for debug purposes.In the above example, the last
return false
will never be executed, because a return statement has already been met in every possible execution path.