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 <[email protected]> |
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\DefaultAttributes; |
15
|
|
|
|
16
|
|
|
use League\CommonMark\Configuration\ConfigurationAwareInterface; |
17
|
|
|
use League\CommonMark\Configuration\ConfigurationInterface; |
18
|
|
|
use League\CommonMark\Event\DocumentParsedEvent; |
19
|
|
|
use League\CommonMark\Extension\Attributes\Util\AttributesHelper; |
20
|
|
|
|
21
|
|
|
final class ApplyDefaultAttributesProcessor implements ConfigurationAwareInterface |
22
|
|
|
{ |
23
|
|
|
/** @var ConfigurationInterface */ |
24
|
|
|
private $config; |
25
|
|
|
|
26
|
12 |
|
public function onDocumentParsed(DocumentParsedEvent $event): void |
27
|
|
|
{ |
28
|
|
|
/** @var array<string, array<string, mixed>> $map */ |
29
|
12 |
|
$map = $this->config->get('default_attributes'); |
30
|
|
|
|
31
|
12 |
|
$document = $event->getDocument(); |
32
|
12 |
|
$walker = $document->walker(); |
33
|
12 |
|
while ($event = $walker->next()) { |
34
|
12 |
|
$node = $event->getNode(); |
35
|
|
|
|
36
|
|
|
// Only modify nodes when we first encounter them |
37
|
12 |
|
if (! $event->isEntering()) { |
38
|
12 |
|
continue; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
// Check to see if any default attributes were defined |
42
|
12 |
|
if (($attributesToApply = $map[\get_class($node)] ?? []) === []) { |
43
|
12 |
|
continue; |
44
|
|
|
} |
45
|
|
|
|
46
|
6 |
|
$newAttributes = []; |
47
|
6 |
|
foreach ($attributesToApply as $name => $value) { |
48
|
6 |
|
if (\is_callable($value)) { |
49
|
6 |
|
$value = $value($node); |
50
|
|
|
// Callables are allowed to return `null` indicating that no changes should be made |
51
|
6 |
|
if ($value !== null) { |
52
|
6 |
|
$newAttributes[$name] = $value; |
53
|
|
|
} |
54
|
|
|
} else { |
55
|
6 |
|
$newAttributes[$name] = $value; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
// Merge these attributes into the node |
60
|
6 |
|
if (\count($newAttributes) > 0) { |
61
|
6 |
|
$node->data->set('attributes', AttributesHelper::mergeAttributes($node, $newAttributes)); |
62
|
|
|
} |
63
|
|
|
} |
64
|
12 |
|
} |
65
|
|
|
|
66
|
12 |
|
public function setConfiguration(ConfigurationInterface $configuration): void |
67
|
|
|
{ |
68
|
12 |
|
$this->config = $configuration; |
69
|
12 |
|
} |
70
|
|
|
} |
71
|
|
|
|