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\Block\Element;
16
17use League\CommonMark\ContextInterface;
18use League\CommonMark\Cursor;
19
20class IndentedCode extends AbstractStringContainerBlock
21{
22    public function canContain(AbstractBlock $block): bool
23    {
24        return false;
25    }
26
27    public function isCode(): bool
28    {
29        return true;
30    }
31
32    public function matchesNextLine(Cursor $cursor): bool
33    {
34        if ($cursor->isIndented()) {
35            $cursor->advanceBy(Cursor::INDENT_LEVEL, true);
36        } elseif ($cursor->isBlank()) {
37            $cursor->advanceToNextNonSpaceOrTab();
38        } else {
39            return false;
40        }
41
42        return true;
43    }
44
45    public function finalize(ContextInterface $context, int $endLineNumber)
46    {
47        parent::finalize($context, $endLineNumber);
48
49        $reversed = \array_reverse($this->strings->toArray(), true);
50        foreach ($reversed as $index => $line) {
51            if ($line === '' || $line === "\n" || \preg_match('/^(\n *)$/', $line)) {
52                unset($reversed[$index]);
53            } else {
54                break;
55            }
56        }
57        $fixed = \array_reverse($reversed);
58        $tmp = \implode("\n", $fixed);
59        if (\substr($tmp, -1) !== "\n") {
60            $tmp .= "\n";
61        }
62
63        $this->finalStringContents = $tmp;
64    }
65
66    public function handleRemainingContents(ContextInterface $context, Cursor $cursor)
67    {
68        /** @var self $tip */
69        $tip = $context->getTip();
70        $tip->addLine($cursor->getRemainder());
71    }
72}
73