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

MarkupFixer::__construct()   A

Complexity

Conditions 2
Paths 1

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 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
// Todo, manage it via composer when sonata admin is upgraded to v4 (knp-menu is blocking)
4
5
/*
6
 * PHP TableOfContents Library.
7
 *
8
 * @license http://opensource.org/licenses/MIT
9
 *
10
 * @see https://github.com/caseyamcl/toc
11
 *
12
 * @version 2
13
 *
14
 * @author Casey McLaughlin <[email protected]>
15
 *
16
 * For the full copyright and license information, please view the LICENSE.md
17
 * file that was distributed with this source code.
18
 *
19
 * ------------------------------------------------------------------
20
 */
21
22
declare(strict_types=1);
23
24
namespace PiedWeb\CMSBundle\Service\toc;
25
26
use Masterminds\HTML5;
27
use RuntimeException;
28
29
/**
30
 * TOC Markup Fixer adds `id` attributes to all H1...H6 tags where they do not
31
 * already exist.
32
 *
33
 * @author Casey McLaughlin <[email protected]>
34
 */
35
class MarkupFixer
36
{
37
    use HtmlHelper;
38
39
    /**
40
     * @var HTML5
41
     */
42
    private $htmlParser;
43
44
    /**
45
     * Constructor.
46
     *
47
     * @param HTML5 $htmlParser
48
     */
49
    public function __construct(HTML5 $htmlParser = null)
50
    {
51
        $this->htmlParser = $htmlParser ?: new HTML5();
52
    }
53
54
    /**
55
     * Fix markup.
56
     *
57
     * @return string Markup with added IDs
58
     *
59
     * @throws RuntimeException
60
     */
61
    public function fix(string $markup, int $topLevel = 1, int $depth = 6): string
62
    {
63
        if (!$this->isFullHtmlDocument($markup)) {
64
            $partialID = uniqid('toc_generator_');
65
            $markup = sprintf("<body id='%s'>%s</body>", $partialID, $markup);
66
        }
67
68
        $domDocument = $this->htmlParser->loadHTML($markup);
69
        $domDocument->preserveWhiteSpace = true; // do not clobber whitespace
70
71
        $sluggifier = new UniqueSluggifier();
72
73
        /** @var \DOMElement $node */
74
        foreach ($this->traverseHeaderTags($domDocument, $topLevel, $depth) as $node) {
75
            if ($node->getAttribute('id')) {
76
                continue;
77
            }
78
79
            $node->setAttribute('id', $sluggifier->slugify($node->getAttribute('title') ?: $node->textContent));
80
        }
81
82
        return $this->htmlParser->saveHTML(
83
            (isset($partialID)) ? $domDocument->getElementById($partialID)->childNodes : $domDocument
84
        );
85
    }
86
}
87