xref: /webtrees/app/Factories/AbstractGedcomRecordFactory.php (revision 52550490b7095dd69811f3ec21ed5a3ca1a8968d)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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 <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Factories;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\DB;
24use Fisharebest\Webtrees\Gedcom;
25use Fisharebest\Webtrees\Registry;
26use Fisharebest\Webtrees\Tree;
27use Illuminate\Support\Collection;
28
29use function str_starts_with;
30
31/**
32 * Make a GedcomRecord object.
33 */
34abstract class AbstractGedcomRecordFactory
35{
36    /**
37     * @param Tree $tree
38     *
39     * @return Collection<array-key,string>
40     */
41    protected function pendingChanges(Tree $tree): Collection
42    {
43        // Only editors can see pending changes
44        if (!Auth::isEditor($tree)) {
45            return new Collection();
46        }
47
48        // Caution - this cache can be overwritten by GedcomExportService
49        return Registry::cache()
50            ->array()
51            ->remember(self::class . $tree->id(), static fn (): Collection => DB::table('change')
52                ->where('gedcom_id', '=', $tree->id())
53                ->where('status', '=', 'pending')
54                ->orderBy('change_id')
55                ->pluck('new_gedcom', 'xref'));
56    }
57
58    /**
59     * We may have searched for X123, but found the record for x123.
60     *
61     * @param string $gedcom
62     * @param string $xref
63     *
64     * @return string
65     */
66    protected function extractXref(string $gedcom, string $xref): string
67    {
68        if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@/', $gedcom, $match)) {
69            return $match[1];
70        }
71
72        if (str_starts_with($gedcom, '0 HEAD')) {
73            return 'HEAD';
74        }
75
76        return $xref;
77    }
78}
79