ApplyDefaultAttributesProcessor.php
2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\DefaultAttributes;
use League\CommonMark\Event\DocumentParsedEvent;
use League\CommonMark\Extension\Attributes\Util\AttributesHelper;
use League\Config\ConfigurationAwareInterface;
use League\Config\ConfigurationInterface;
final class ApplyDefaultAttributesProcessor implements ConfigurationAwareInterface
{
private ConfigurationInterface $config;
public function onDocumentParsed(DocumentParsedEvent $event): void
{
/** @var array<string, array<string, mixed>> $map */
$map = $this->config->get('default_attributes');
// Don't bother iterating if no default attributes are configured
if (! $map) {
return;
}
foreach ($event->getDocument()->iterator() as $node) {
// Check to see if any default attributes were defined
if (($attributesToApply = $map[\get_class($node)] ?? []) === []) {
continue;
}
$newAttributes = [];
foreach ($attributesToApply as $name => $value) {
if (\is_callable($value)) {
$value = $value($node);
// Callables are allowed to return `null` indicating that no changes should be made
if ($value !== null) {
$newAttributes[$name] = $value;
}
} else {
$newAttributes[$name] = $value;
}
}
// Merge these attributes into the node
if (\count($newAttributes) > 0) {
$node->data->set('attributes', AttributesHelper::mergeAttributes($node, $newAttributes));
}
}
}
public function setConfiguration(ConfigurationInterface $configuration): void
{
$this->config = $configuration;
}
}