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; 16 17use League\CommonMark\Block\Element\AbstractBlock; 18 19/** 20 * @internal 21 */ 22class UnmatchedBlockCloser 23{ 24 /** 25 * @var ContextInterface 26 */ 27 private $context; 28 29 /** 30 * @var AbstractBlock 31 */ 32 private $oldTip; 33 34 /** 35 * @var AbstractBlock 36 */ 37 private $lastMatchedContainer; 38 39 /** 40 * @param ContextInterface $context 41 */ 42 public function __construct(ContextInterface $context) 43 { 44 $this->context = $context; 45 46 $this->resetTip(); 47 } 48 49 /** 50 * @param AbstractBlock $block 51 * 52 * @return void 53 */ 54 public function setLastMatchedContainer(AbstractBlock $block) 55 { 56 $this->lastMatchedContainer = $block; 57 } 58 59 /** 60 * @return void 61 */ 62 public function closeUnmatchedBlocks() 63 { 64 $endLine = $this->context->getLineNumber() - 1; 65 66 while ($this->oldTip !== $this->lastMatchedContainer) { 67 /** @var AbstractBlock $oldTip */ 68 $oldTip = $this->oldTip->parent(); 69 $this->oldTip->finalize($this->context, $endLine); 70 $this->oldTip = $oldTip; 71 } 72 } 73 74 /** 75 * @return void 76 */ 77 public function resetTip() 78 { 79 if ($this->context->getTip() === null) { 80 throw new \RuntimeException('No tip to reset to'); 81 } 82 83 $this->oldTip = $this->context->getTip(); 84 } 85 86 public function areAllClosed(): bool 87 { 88 return $this->context->getTip() === $this->lastMatchedContainer; 89 } 90} 91