1<?php
2
3/*
4 * This file is part of the league/commonmark package.
5 *
6 * (c) Colin O'Dell <colinodell@gmail.com>
7 *
8 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
9 *  - (c) John MacFarlane
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 League\CommonMark\Inline\Parser;
16
17use League\CommonMark\Inline\Element\Newline;
18use League\CommonMark\Inline\Element\Text;
19use League\CommonMark\InlineParserContext;
20use League\CommonMark\Util\RegexHelper;
21
22final class EscapableParser implements InlineParserInterface
23{
24    public function getCharacters(): array
25    {
26        return ['\\'];
27    }
28
29    public function parse(InlineParserContext $inlineContext): bool
30    {
31        $cursor = $inlineContext->getCursor();
32        $nextChar = $cursor->peek();
33
34        if ($nextChar === "\n") {
35            $cursor->advanceBy(2);
36            $inlineContext->getContainer()->appendChild(new Newline(Newline::HARDBREAK));
37
38            return true;
39        } elseif ($nextChar !== null && RegexHelper::isEscapable($nextChar)) {
40            $cursor->advanceBy(2);
41            $inlineContext->getContainer()->appendChild(new Text($nextChar));
42
43            return true;
44        }
45
46        $cursor->advanceBy(1);
47        $inlineContext->getContainer()->appendChild(new Text('\\'));
48
49        return true;
50    }
51}
52