| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
declare(strict_types=1);
|
|
|
4 |
|
|
|
5 |
/*
|
|
|
6 |
* This file is part of the league/commonmark package.
|
|
|
7 |
*
|
|
|
8 |
* (c) Colin O'Dell <colinodell@gmail.com>
|
|
|
9 |
*
|
|
|
10 |
* For the full copyright and license information, please view the LICENSE
|
|
|
11 |
* file that was distributed with this source code.
|
|
|
12 |
*/
|
|
|
13 |
|
|
|
14 |
namespace League\CommonMark\Extension\DescriptionList\Event;
|
|
|
15 |
|
|
|
16 |
use League\CommonMark\Event\DocumentParsedEvent;
|
|
|
17 |
use League\CommonMark\Extension\DescriptionList\Node\Description;
|
|
|
18 |
use League\CommonMark\Extension\DescriptionList\Node\DescriptionList;
|
|
|
19 |
use League\CommonMark\Extension\DescriptionList\Node\DescriptionTerm;
|
|
|
20 |
use League\CommonMark\Node\Block\Paragraph;
|
|
|
21 |
use League\CommonMark\Node\Inline\Newline;
|
|
|
22 |
use League\CommonMark\Node\NodeIterator;
|
|
|
23 |
|
|
|
24 |
final class LooseDescriptionHandler
|
|
|
25 |
{
|
|
|
26 |
public function __invoke(DocumentParsedEvent $event): void
|
|
|
27 |
{
|
|
|
28 |
foreach ($event->getDocument()->iterator(NodeIterator::FLAG_BLOCKS_ONLY) as $description) {
|
|
|
29 |
if (! $description instanceof Description) {
|
|
|
30 |
continue;
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
// Does this description need to be added to a list?
|
|
|
34 |
if (! $description->parent() instanceof DescriptionList) {
|
|
|
35 |
$list = new DescriptionList();
|
|
|
36 |
// Taking any preceding paragraphs with it
|
|
|
37 |
if (($paragraph = $description->previous()) instanceof Paragraph) {
|
|
|
38 |
$list->appendChild($paragraph);
|
|
|
39 |
}
|
|
|
40 |
|
|
|
41 |
$description->replaceWith($list);
|
|
|
42 |
$list->appendChild($description);
|
|
|
43 |
}
|
|
|
44 |
|
|
|
45 |
// Is this description preceded by a paragraph that should really be a term?
|
|
|
46 |
if (! (($paragraph = $description->previous()) instanceof Paragraph)) {
|
|
|
47 |
continue;
|
|
|
48 |
}
|
|
|
49 |
|
|
|
50 |
// Convert the paragraph into one or more terms
|
|
|
51 |
$term = new DescriptionTerm();
|
|
|
52 |
$paragraph->replaceWith($term);
|
|
|
53 |
|
|
|
54 |
foreach ($paragraph->children() as $child) {
|
|
|
55 |
if ($child instanceof Newline) {
|
|
|
56 |
$newTerm = new DescriptionTerm();
|
|
|
57 |
$term->insertAfter($newTerm);
|
|
|
58 |
$term = $newTerm;
|
|
|
59 |
continue;
|
|
|
60 |
}
|
|
|
61 |
|
|
|
62 |
$term->appendChild($child);
|
|
|
63 |
}
|
|
|
64 |
}
|
|
|
65 |
}
|
|
|
66 |
}
|