Completed
Push — 1.5 ( 93aa3f...fe2226 )
by Colin
01:05
created

TableOfContentsBuilder::getMinAndMaxHeadingLevels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace League\CommonMark\Extension\TableOfContents;
13
14
use League\CommonMark\Block\Element\Document;
15
use League\CommonMark\Block\Element\Heading;
16
use League\CommonMark\Event\DocumentParsedEvent;
17
use League\CommonMark\Exception\InvalidOptionException;
18
use League\CommonMark\Extension\HeadingPermalink\HeadingPermalink;
19
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, League\CommonMark\Extens...ontents\TableOfContents.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
20
use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder;
21
use League\CommonMark\Util\ConfigurationAwareInterface;
22
use League\CommonMark\Util\ConfigurationInterface;
23
24
final class TableOfContentsBuilder implements ConfigurationAwareInterface
25
{
26
    /**
27
     * @deprecated Use TableOfContentsGenerator::STYLE_BULLET instead
28
     */
29
    public const STYLE_BULLET = TableOfContentsGenerator::STYLE_BULLET;
30
31
    /**
32
     * @deprecated Use TableOfContentsGenerator::STYLE_ORDERED instead
33
     */
34
    public const STYLE_ORDERED = TableOfContentsGenerator::STYLE_ORDERED;
35
36
    /**
37
     * @deprecated Use TableOfContentsGenerator::NORMALIZE_DISABLED instead
38
     */
39
    public const NORMALIZE_DISABLED = TableOfContentsGenerator::NORMALIZE_DISABLED;
40
41
    /**
42
     * @deprecated Use TableOfContentsGenerator::NORMALIZE_RELATIVE instead
43
     */
44
    public const NORMALIZE_RELATIVE = TableOfContentsGenerator::NORMALIZE_RELATIVE;
45
46
    /**
47
     * @deprecated Use TableOfContentsGenerator::NORMALIZE_FLAT instead
48
     */
49
    public const NORMALIZE_FLAT = TableOfContentsGenerator::NORMALIZE_FLAT;
50
51
    public const POSITION_TOP = 'top';
52
    public const POSITION_BEFORE_HEADINGS = 'before-headings';
53
    public const POSITION_PLACEHOLDER = 'placeholder';
54
55
    /** @var ConfigurationInterface */
56
    private $config;
57
58 36
    public function onDocumentParsed(DocumentParsedEvent $event): void
59
    {
60 36
        $document = $event->getDocument();
61
62 36
        $generator = new TableOfContentsGenerator(
63 36
            $this->config->get('table_of_contents/style', TableOfContentsGenerator::STYLE_BULLET),
64 36
            $this->config->get('table_of_contents/normalize', TableOfContentsGenerator::NORMALIZE_RELATIVE),
65 36
            (int) $this->config->get('table_of_contents/min_heading_level', 1),
66 36
            (int) $this->config->get('table_of_contents/max_heading_level', 6)
67
        );
68
69 36
        $toc = $generator->generate($document);
70 36
        if ($toc === null) {
71
            // No linkable headers exist, so no TOC could be generated
72 6
            return;
73
        }
74
75
        // Add custom CSS class(es), if defined
76 33
        $class = $this->config->get('table_of_contents/html_class', 'table-of-contents');
77 33
        if (!empty($class)) {
78 33
            $toc->data['attributes']['class'] = $class;
79
        }
80
81
        // Add the TOC to the Document
82 33
        $position = $this->config->get('table_of_contents/position', self::POSITION_TOP);
83 33
        if ($position === self::POSITION_TOP) {
84 27
            $document->prependChild($toc);
85 6
        } elseif ($position === self::POSITION_BEFORE_HEADINGS) {
86 3
            $this->insertBeforeFirstLinkedHeading($document, $toc);
87 3
        } elseif ($position === self::POSITION_PLACEHOLDER) {
88 3
            $this->replacePlaceholders($document, $toc);
89
        } else {
90
            throw new InvalidOptionException(\sprintf('Invalid config option "%s" for "table_of_contents/position"', $position));
91
        }
92 33
    }
93
94 3
    private function insertBeforeFirstLinkedHeading(Document $document, TableOfContents $toc): void
95
    {
96 3
        $walker = $document->walker();
97 3
        while ($event = $walker->next()) {
98 3
            if ($event->isEntering() && ($node = $event->getNode()) instanceof HeadingPermalink && ($parent = $node->parent()) instanceof Heading) {
99 3
                $parent->insertBefore($toc);
100
101 3
                return;
102
            }
103
        }
104
    }
105
106 3
    private function replacePlaceholders(Document $document, TableOfContents $toc): void
107
    {
108 3
        $walker = $document->walker();
109 3
        while ($event = $walker->next()) {
110
            // Add the block once we find a placeholder (and we're about to leave it)
111 3
            if (!$event->getNode() instanceof TableOfContentsPlaceholder) {
112 3
                continue;
113
            }
114
115 3
            if ($event->isEntering()) {
116 3
                continue;
117
            }
118
119 3
            $event->getNode()->replaceWith(clone $toc);
120
        }
121 3
    }
122
123 36
    public function setConfiguration(ConfigurationInterface $config)
124
    {
125 36
        $this->config = $config;
126 36
    }
127
}
128