xref: /webtrees/app/PlaceLocation.php (revision 5bd13fbbb0904e682044d9a60b119ce8cb8d7138)
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        return $gedcom_service->readLatitude($this->details()->pl_lati ?? '');
169    }
170
171    /**
172     * Latitude of the longitude.
173     *
174     * @return float
175     */
176    public function longitude(): float
177    {
178        $gedcom_service = new GedcomService();
179
180        return $gedcom_service->readLongitude($this->details()->pl_long ?? '');
181    }
182
183    /**
184     * The icon for the location.
185     *
186     * @return string
187     */
188    public function icon(): string
189    {
190        return (string) $this->details()->pl_icon;
191    }
192
193    /**
194     * Zoom level for the location.
195     *
196     * @return int
197     */
198    public function zoom(): int
199    {
200        return (int) $this->details()->pl_zoom;
201    }
202
203    /**
204     * @return string
205     */
206    public function locationName(): string
207    {
208        return (string) $this->parts->first();
209    }
210
211    /**
212     * Find a rectangle that (approximately) encloses this place.
213     *
214     * @return array<array<float>>
215     */
216    public function boundingRectangle(): array
217    {
218        $latitude  = $this->latitude();
219        $longitude = $this->longitude();
220
221        // No co-ordinates for this place? Try the parent place.
222        $tmp = $this;
223        while ($latitude === 0.0 && $longitude === 0.0 && $tmp->id() !== 0) {
224            $tmp       = $tmp->parent();
225            $latitude  = $tmp->latitude();
226            $longitude = $tmp->longitude();
227        }
228
229        // Show this number of degrees around the centre.
230        if ($latitude === 0.0 && $longitude === 0.0 || $this->id() === 0) {
231            // World
232            $degrees = 180.0;
233        } elseif ($this->parts->count() === 1) {
234            // Countries
235            $degrees = 10.0;
236        } elseif ($this->parts->count() === 2) {
237            // Regions
238            $degrees = 3.0;
239        } else {
240            // Towns, cities and villages
241            $degrees = 1.0;
242        }
243
244        return [
245            [
246                max($latitude - $degrees, -90.0),
247                max($longitude - $degrees, -180.0),
248            ],
249            [
250                min($latitude + $degrees, 90.0),
251                min($longitude + $degrees, 180.0),
252            ],
253        ];
254    }
255}
256