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