xref: /webtrees/app/CommonMark/XrefParser.php (revision 0115bc1678cafd957052cd2d256563ad3e242cc1)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\CommonMark;
19
20use Fisharebest\Webtrees\Gedcom;
21use Fisharebest\Webtrees\GedcomRecord;
22use Fisharebest\Webtrees\Tree;
23use League\CommonMark\Inline\Element\Link;
24use League\CommonMark\Inline\Parser\AbstractInlineParser;
25use League\CommonMark\InlineParserContext;
26
27/**
28 * Convert XREFs within markdown text to links
29 */
30class XrefParser extends AbstractInlineParser
31{
32    /** @var Tree - match XREFs in this tree */
33    private $tree;
34
35    /**
36     * MarkdownXrefParser constructor.
37     *
38     * @param Tree $tree
39     */
40    public function __construct(Tree $tree)
41    {
42        $this->tree = $tree;
43    }
44
45    /**
46     * We are only interested in text that begins with '@'.
47     *
48     * @return string[]
49     */
50    public function getCharacters(): array
51    {
52        return ['@'];
53    }
54
55    /**
56     * @param InlineParserContext $context
57     *
58     * @return bool
59     */
60    public function parse(InlineParserContext $context): bool
61    {
62        // The cursor should be positioned on the opening '@'.
63        $cursor = $context->getCursor();
64
65        // If this isn't the start of an XREF, we'll need to rewind.
66        $previous_state = $cursor->saveState();
67
68        $handle = $cursor->match('/@' . Gedcom::REGEX_XREF . '@/');
69        if (empty($handle)) {
70            // Not an XREF?
71            $cursor->restoreState($previous_state);
72
73            return false;
74        }
75
76        $xref = trim($handle, '@');
77
78        $record = GedcomRecord::getInstance($xref, $this->tree);
79
80        if ($record === null) {
81            // Linked record does not exist?
82            $cursor->restoreState($previous_state);
83
84            return false;
85        }
86
87        $url   = $record->url();
88        $label = $handle;
89        $title = strip_tags($record->getFullName());
90        $context->getContainer()->appendChild(new Link($url, $label, $title));
91
92        return true;
93    }
94}
95