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\SmartPunct;
15
16use League\CommonMark\Event\DocumentParsedEvent;
17use League\CommonMark\Node\Inline\AdjacentTextMerger;
18use League\CommonMark\Node\Inline\Text;
19use League\CommonMark\Node\Query;
20
21/**
22 * Identifies any lingering Quote nodes that were missing pairs and converts them into Text nodes
23 */
24final class ReplaceUnpairedQuotesListener
25{
26    public function __invoke(DocumentParsedEvent $event): void
27    {
28        $query = (new Query())->where(Query::type(Quote::class));
29        foreach ($query->findAll($event->getDocument()) as $quote) {
30            \assert($quote instanceof Quote);
31
32            $literal = $quote->getLiteral();
33            if ($literal === Quote::SINGLE_QUOTE) {
34                $literal = Quote::SINGLE_QUOTE_CLOSER;
35            } elseif ($literal === Quote::DOUBLE_QUOTE) {
36                $literal = Quote::DOUBLE_QUOTE_OPENER;
37            }
38
39            $quote->replaceWith($new = new Text($literal));
40            AdjacentTextMerger::mergeWithDirectlyAdjacentNodes($new);
41        }
42    }
43}
44