1<?php
2
3declare(strict_types=1);
4
5/*
6 * This is part of the webuni/commonmark-attributes-extension package.
7 *
8 * (c) Martin Hasoň <martin.hason@gmail.com>
9 * (c) Webuni s.r.o. <info@webuni.cz>
10 *
11 * For the full copyright and license information, please view the LICENSE
12 * file that was distributed with this source code.
13 */
14
15namespace Webuni\CommonMark\AttributesExtension;
16
17use League\CommonMark\Inline\Parser\InlineParserInterface;
18use League\CommonMark\InlineParserContext;
19
20final class AttributesInlineParser implements InlineParserInterface
21{
22    public function getCharacters(): array
23    {
24        return [' ', '{'];
25    }
26
27    public function parse(InlineParserContext $inlineContext): bool
28    {
29        $cursor = $inlineContext->getCursor();
30        if ('{' !== $cursor->getNextNonSpaceCharacter()) {
31            return false;
32        }
33
34        $char = $cursor->getCharacter();
35        if ('{' === $char) {
36            $char = (string) $cursor->getCharacter($cursor->getPosition() - 1);
37        }
38
39        $attributes = AttributesUtils::parse($cursor);
40        if (empty($attributes)) {
41            return false;
42        }
43
44        if ('' === $char) {
45            $cursor->advanceToNextNonSpaceOrNewline();
46        }
47
48        $node = new AttributesInline($attributes, ' ' === $char || '' === $char);
49        $inlineContext->getContainer()->appendChild($node);
50
51        return true;
52    }
53}
54