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