xref: /webtrees/app/CommonMark/XrefParser.php (revision 67994fb087e1b24564a780e4ae8aeff801733e35)
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\GedcomRecord;
21use Fisharebest\Webtrees\Tree;
22use League\CommonMark\Inline\Element\Link;
23use League\CommonMark\Inline\Parser\AbstractInlineParser;
24use League\CommonMark\InlineParserContext;
25
26/**
27 * Convert XREFs within markdown text to links
28 */
29class XrefParser extends AbstractInlineParser
30{
31    /** @var Tree - match XREFs in this tree */
32    private $tree;
33
34    /**
35     * MarkdownXrefParser constructor.
36     *
37     * @param Tree $tree
38     */
39    public function __construct(Tree $tree)
40    {
41        $this->tree = $tree;
42    }
43
44    /**
45     * We are only interested in text that begins with '@'.
46     *
47     * @return string[]
48     */
49    public function getCharacters(): array
50    {
51        return ['@'];
52    }
53
54    /**
55     * @param InlineParserContext $context
56     *
57     * @return bool
58     */
59    public function parse(InlineParserContext $context): bool
60    {
61        // The cursor should be positioned on the opening '@'.
62        $cursor = $context->getCursor();
63
64        // If this isn't the start of an XREF, we'll need to rewind.
65        $previous_state = $cursor->saveState();
66
67        $handle = $cursor->match('/@' . WT_REGEX_XREF . '@/');
68        if (empty($handle)) {
69            // Not an XREF?
70            $cursor->restoreState($previous_state);
71
72            return false;
73        }
74
75        $xref = trim($handle, '@');
76
77        $record = GedcomRecord::getInstance($xref, $this->tree);
78
79        if ($record === null) {
80            // Linked record does not exist?
81            $cursor->restoreState($previous_state);
82
83            return false;
84        }
85
86        $url   = $record->url();
87        $label = $handle;
88        $title = strip_tags($record->getFullName());
89        $context->getContainer()->appendChild(new Link($url, $label, $title));
90
91        return true;
92    }
93}
94