xref: /webtrees/app/PlaceLocation.php (revision 69c8946332401be67c1761bd02d603f949c1873d)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 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;
21
22use Fisharebest\Webtrees\Services\GedcomService;
23use Illuminate\Database\Capsule\Manager as DB;
24use Illuminate\Support\Collection;
25use stdClass;
26
27use function app;
28use function max;
29use function min;
30use function preg_split;
31
32/**
33 * Class PlaceLocation
34 */
35class PlaceLocation
36{
37    /** @var string e.g. "Westminster, London, England" */
38    private $location_name;
39
40    /** @var Collection|string[] The parts of a location name, e.g. ["Westminster", "London", "England"] */
41    private $parts;
42
43    /**
44     * Create a place-location.
45     *
46     * @param string $location_name
47     */
48    public function __construct(string $location_name)
49    {
50        // Ignore any empty parts in location names such as "Village, , , Country".
51        $this->parts = (new Collection(preg_split(Gedcom::PLACE_SEPARATOR_REGEX, $location_name)))
52            ->filter();
53
54        // Rebuild the location name in the correct format.
55        $this->location_name = $this->parts->implode(Gedcom::PLACE_SEPARATOR);
56    }
57
58    /**
59     * Get the higher level location.
60     *
61     * @return PlaceLocation
62     */
63    public function parent(): PlaceLocation
64    {
65        return new self($this->parts->slice(1)->implode(Gedcom::PLACE_SEPARATOR));
66    }
67
68    /**
69     * The database row that contains this location.
70     * Note that due to database collation, both "Quebec" and "Québec" will share the same row.
71     *
72     * @return int
73     */
74    public function id(): int
75    {
76        return app('cache.array')->remember('location-' . $this->location_name, function () {
77            // The "top-level" location won't exist in the database.
78            if ($this->parts->isEmpty()) {
79                return 0;
80            }
81
82            $parent_location_id = $this->parent()->id();
83
84            $location_id = (int) DB::table('placelocation')
85                ->where('pl_place', '=', $this->parts->first())
86                ->where('pl_parent_id', '=', $parent_location_id)
87                ->value('pl_id');
88
89            if ($location_id === 0) {
90                $location = $this->parts->first();
91
92                $location_id = 1 + (int) DB::table('placelocation')->max('pl_id');
93
94                DB::table('placelocation')->insert([
95                    'pl_id'        => $location_id,
96                    'pl_place'     => $location,
97                    'pl_parent_id' => $parent_location_id,
98                    'pl_level'     => $this->parts->count() - 1,
99                    'pl_lati'      => '',
100                    'pl_long'      => '',
101                    'pl_icon'      => '',
102                    'pl_zoom'      => 2,
103                ]);
104            }
105
106            return $location_id;
107        });
108    }
109
110    /**
111     * Does this location exist in the database?  Note that calls to PlaceLocation::id() will
112     * create the row, so this function is only meaningful when called before a call to PlaceLocation::id().
113     *
114     * @return bool
115     */
116    public function exists(): bool
117    {
118        $location_id = 0;
119
120        $this->parts->reverse()->each(static function (string $place) use (&$location_id) {
121            if ($location_id !== null) {
122                $location_id = DB::table('placelocation')
123                    ->where('pl_parent_id', '=', $location_id)
124                    ->where('pl_place', '=', $place)
125                    ->value('pl_id');
126            }
127        });
128
129        return $location_id !== null;
130    }
131
132    /**
133     * @return stdClass
134     */
135    private function details(): stdClass
136    {
137        return app('cache.array')->remember('location-details-' . $this->id(), function () {
138            // The "top-level" location won't exist in the database.
139            if ($this->parts->isEmpty()) {
140                return (object) [
141                    'pl_id'        => '0',
142                    'pl_parent_id' => '0',
143                    'pl_level' => null,
144                    'pl_place' => '',
145                    'pl_lati' => null,
146                    'pl_long' => null,
147                    'pl_zoom' => null,
148                    'pl_icon' => null,
149                    'pl_media' => null,
150                ];
151            }
152
153            return DB::table('placelocation')
154                ->where('pl_id', '=', $this->id())
155                ->first();
156        });
157    }
158
159    /**
160     * Latitude of the location.
161     *
162     * @return float
163     */
164    public function latitude(): float
165    {
166        $gedcom_service = new GedcomService();
167
168        $tmp = $this;
169        do {
170            $pl_lati = (string) $tmp->details()->pl_lati;
171            $tmp = $tmp->parent();
172        } while ($pl_lati === '' && $tmp->id() !== 0);
173
174        return $gedcom_service->readLatitude($pl_lati);
175    }
176
177    /**
178     * Latitude of the longitude.
179     *
180     * @return float
181     */
182    public function longitude(): float
183    {
184        $gedcom_service = new GedcomService();
185
186        $tmp = $this;
187        do {
188            $pl_long = (string) $tmp->details()->pl_long;
189            $tmp = $tmp->parent();
190        } while ($pl_long === '' && $tmp->id() !== 0);
191
192        return $gedcom_service->readLongitude($pl_long);
193    }
194
195    /**
196     * The icon for the location.
197     *
198     * @return string
199     */
200    public function icon(): string
201    {
202        return (string) $this->details()->pl_icon;
203    }
204
205    /**
206     * Zoom level for the location.
207     *
208     * @return int
209     */
210    public function zoom(): int
211    {
212        return (int) $this->details()->pl_zoom ?: 2;
213    }
214
215    /**
216     * @return string
217     */
218    public function locationName(): string
219    {
220        return (string) $this->parts->first();
221    }
222
223    /**
224     * Find a rectangle that (approximately) encloses this place.
225     *
226     * @return array<array<float>>
227     */
228    public function boundingRectangle(): array
229    {
230        if ($this->id() === 0) {
231            return [[-180.0, -90.0], [180.0, 90.0]];
232        }
233
234        // Find our own co-ordinates and those of any child places
235        $latitudes = DB::table('placelocation')
236            ->where('pl_parent_id', '=', $this->id())
237            ->orWhere('pl_id', '=', $this->id())
238            ->pluck('pl_lati')
239            ->filter()
240            ->map(static function (string $x): float {
241                return (new GedcomService())->readLatitude($x);
242            });
243
244        $longitudes = DB::table('placelocation')
245            ->where('pl_parent_id', '=', $this->id())
246            ->orWhere('pl_id', '=', $this->id())
247            ->pluck('pl_long')
248            ->filter()
249            ->map(static function (string $x): float {
250                return (new GedcomService())->readLongitude($x);
251            });
252
253        if ($latitudes->count() > 1 || $longitudes->count() > 1) {
254            return [[$latitudes->min(), $longitudes->min()], [$latitudes->max(), $longitudes->max()]];
255        }
256
257        return $this->parent()->boundingRectangle();
258    }
259}
260