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