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\TableOfContents; 15 16use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder; 17use League\CommonMark\Parser\Block\AbstractBlockContinueParser; 18use League\CommonMark\Parser\Block\BlockContinue; 19use League\CommonMark\Parser\Block\BlockContinueParserInterface; 20use League\CommonMark\Parser\Block\BlockStart; 21use League\CommonMark\Parser\Block\BlockStartParserInterface; 22use League\CommonMark\Parser\Cursor; 23use League\CommonMark\Parser\MarkdownParserStateInterface; 24use League\Config\ConfigurationAwareInterface; 25use League\Config\ConfigurationInterface; 26 27final class TableOfContentsPlaceholderParser extends AbstractBlockContinueParser 28{ 29 /** @psalm-readonly */ 30 private TableOfContentsPlaceholder $block; 31 32 public function __construct() 33 { 34 $this->block = new TableOfContentsPlaceholder(); 35 } 36 37 public function getBlock(): TableOfContentsPlaceholder 38 { 39 return $this->block; 40 } 41 42 public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue 43 { 44 return BlockContinue::none(); 45 } 46 47 public static function blockStartParser(): BlockStartParserInterface 48 { 49 return new class () implements BlockStartParserInterface, ConfigurationAwareInterface { 50 /** @psalm-readonly-allow-private-mutation */ 51 private ConfigurationInterface $config; 52 53 public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart 54 { 55 $placeholder = $this->config->get('table_of_contents/placeholder'); 56 if ($placeholder === null) { 57 return BlockStart::none(); 58 } 59 60 // The placeholder must be the only thing on the line 61 if ($cursor->match('/^' . \preg_quote($placeholder, '/') . '$/') === null) { 62 return BlockStart::none(); 63 } 64 65 return BlockStart::of(new TableOfContentsPlaceholderParser())->at($cursor); 66 } 67 68 public function setConfiguration(ConfigurationInterface $configuration): void 69 { 70 $this->config = $configuration; 71 } 72 }; 73 } 74} 75