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