Completed
Push — master ( 612227...7394c2 )
by Dev
14:55
created

HtmlHelper::isFullHtmlDocument()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
/**
4
 * PHP TableOfContents Library.
5
 *
6
 * @license http://opensource.org/licenses/MIT
7
 *
8
 * @see https://github.com/caseyamcl/toc
9
 *
10
 * @version 2
11
 *
12
 * @author Casey McLaughlin <[email protected]>
13
 *
14
 * For the full copyright and license information, please view the LICENSE.md
15
 * file that was distributed with this source code.
16
 *
17
 * ------------------------------------------------------------------
18
 */
19
20
declare(strict_types=1);
21
22
namespace PiedWeb\CMSBundle\Service\toc;
23
24
use ArrayIterator;
25
use DOMDocument;
26
use DomElement;
27
use DOMXPath;
28
29
/**
30
 * Trait that helps with HTML-related operations.
31
 */
32
trait HtmlHelper
33
{
34
    /**
35
     * Convert a topLevel and depth to H1..H6 tags array.
36
     *
37
     * @return array|string[] Array of header tags; ex: ['h1', 'h2', 'h3']
38
     */
39
    protected function determineHeaderTags(int $topLevel, int $depth): array
40
    {
41
        $desired = range((int) $topLevel, (int) $topLevel + ((int) $depth - 1));
42
        $allowed = [1, 2, 3, 4, 5, 6];
43
44
        return array_map(function ($val) {
45
            return 'h'.$val;
46
        }, array_intersect($desired, $allowed));
47
    }
48
49
    /**
50
     * Traverse Header Tags in DOM Document.
51
     *
52
     * @return ArrayIterator|DomElement[]
53
     */
54
    protected function traverseHeaderTags(DOMDocument $domDocument, int $topLevel, int $depth): ArrayIterator
55
    {
56
        $xpath = new DOMXPath($domDocument);
57
58
        $xpathQuery = sprintf(
59
            '//*[%s]',
60
            implode(' or ', array_map(function ($v) {
61
                return sprintf('local-name() = "%s"', $v);
62
            }, $this->determineHeaderTags($topLevel, $depth)))
63
        );
64
65
        $nodes = [];
66
        foreach ($xpath->query($xpathQuery) as $node) {
67
            $nodes[] = $node;
68
        }
69
70
        return new ArrayIterator($nodes);
71
    }
72
73
    /**
74
     * Is this a full HTML document.
75
     *
76
     * Guesses, based on presence of <body>...</body> tags
77
     */
78
    protected function isFullHtmlDocument(string $markup): bool
79
    {
80
        return false !== strpos($markup, '<body') && false !== strpos($markup, '</body>');
81
    }
82
}
83