Passed
Pull Request — main (#4307)
by David
07:22
created

PlaceHierarchyListModule::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2022 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
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Module;
21
22
use Fisharebest\Webtrees\Auth;
23
use Fisharebest\Webtrees\Family;
24
use Fisharebest\Webtrees\Http\Exceptions\HttpNotFoundException;
25
use Fisharebest\Webtrees\Http\RequestHandlers\MapDataEdit;
26
use Fisharebest\Webtrees\I18N;
27
use Fisharebest\Webtrees\Individual;
28
use Fisharebest\Webtrees\Location;
29
use Fisharebest\Webtrees\Place;
30
use Fisharebest\Webtrees\PlaceLocation;
31
use Fisharebest\Webtrees\Registry;
32
use Fisharebest\Webtrees\Services\LeafletJsService;
33
use Fisharebest\Webtrees\Services\ModuleService;
34
use Fisharebest\Webtrees\Services\SearchService;
35
use Fisharebest\Webtrees\Tree;
36
use Fisharebest\Webtrees\Validator;
37
use Illuminate\Database\Capsule\Manager as DB;
38
use Illuminate\Database\Query\Builder;
39
use Illuminate\Database\Query\JoinClause;
40
use Psr\Http\Message\ResponseInterface;
41
use Psr\Http\Message\ServerRequestInterface;
42
use Psr\Http\Server\RequestHandlerInterface;
43
44
use function array_chunk;
45
use function array_pop;
46
use function array_reverse;
47
use function ceil;
48
use function count;
49
use function redirect;
50
use function route;
51
use function view;
52
53
/**
54
 * Class IndividualListModule
55
 */
56
class PlaceHierarchyListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
57
{
58
    use ModuleListTrait;
59
60
    protected const ROUTE_URL = '/tree/{tree}/place-list';
61
62
    /** @var int The default access level for this module.  It can be changed in the control panel. */
63
    protected int $access_level = Auth::PRIV_USER;
64
65
    private LeafletJsService $leaflet_js_service;
66
67
    private ModuleService $module_service;
68
69
    private SearchService $search_service;
70
71
    /**
72
     * PlaceHierarchy constructor.
73
     *
74
     * @param LeafletJsService $leaflet_js_service
75
     * @param ModuleService    $module_service
76
     * @param SearchService    $search_service
77
     */
78
    public function __construct(LeafletJsService $leaflet_js_service, ModuleService $module_service, SearchService $search_service)
79
    {
80
        $this->leaflet_js_service = $leaflet_js_service;
81
        $this->module_service     = $module_service;
82
        $this->search_service     = $search_service;
83
    }
84
85
    /**
86
     * Initialization.
87
     *
88
     * @return void
89
     */
90
    public function boot(): void
91
    {
92
        Registry::routeFactory()->routeMap()
93
            ->get(static::class, static::ROUTE_URL, $this);
94
    }
95
96
    /**
97
     * How should this module be identified in the control panel, etc.?
98
     *
99
     * @return string
100
     */
101
    public function title(): string
102
    {
103
        /* I18N: Name of a module/list */
104
        return I18N::translate('Place hierarchy');
105
    }
106
107
    /**
108
     * A sentence describing what this module does.
109
     *
110
     * @return string
111
     */
112
    public function description(): string
113
    {
114
        /* I18N: Description of the “Place hierarchy” module */
115
        return I18N::translate('The place hierarchy.');
116
    }
117
118
    /**
119
     * CSS class for the URL.
120
     *
121
     * @return string
122
     */
123
    public function listMenuClass(): string
124
    {
125
        return 'menu-list-plac';
126
    }
127
128
    /**
129
     * @return array<string>
130
     */
131
    public function listUrlAttributes(): array
132
    {
133
        return [];
134
    }
135
136
    /**
137
     * @param Tree $tree
138
     *
139
     * @return bool
140
     */
141
    public function listIsEmpty(Tree $tree): bool
142
    {
143
        return !DB::table('places')
144
            ->where('p_file', '=', $tree->id())
145
            ->exists();
146
    }
147
148
    /**
149
     * Handle URLs generated by older versions of webtrees
150
     *
151
     * @param ServerRequestInterface $request
152
     *
153
     * @return ResponseInterface
154
     */
155
    public function getListAction(ServerRequestInterface $request): ResponseInterface
156
    {
157
        $tree = Validator::attributes($request)->tree();
158
159
        return redirect($this->listUrl($tree, $request->getQueryParams()));
160
    }
161
162
    /**
163
     * @param Tree $tree
164
     * @param array<bool|int|string|array<string>|null> $parameters
165
     *
166
     * @return string
167
     */
168
    public function listUrl(Tree $tree, array $parameters = []): string
169
    {
170
        $parameters['tree'] = $tree->name();
171
172
        return route(static::class, $parameters);
173
    }
174
175
    /**
176
     * @param ServerRequestInterface $request
177
     *
178
     * @return ResponseInterface
179
     */
180
    public function handle(ServerRequestInterface $request): ResponseInterface
181
    {
182
        $tree = Validator::attributes($request)->tree();
183
        $user = Validator::attributes($request)->user();
184
185
        Auth::checkComponentAccess($this, ModuleListInterface::class, $tree, $user);
186
187
        $place_id = Validator::queryParams($request)->integer('place_id', 0);
188
        $place    = Place::find($place_id, $tree);
189
190
        // Request for a non-existent place?
191
        if ($place_id !== $place->id()) {
192
            throw new HttpNotFoundException(I18N::translate('The place with ID %s does not exist', (string) $place_id));
193
        }
194
195
        $map_providers = $this->module_service->findByInterface(ModuleMapProviderInterface::class);
196
        $use_map       = $map_providers->isNotEmpty();
197
198
        if ($use_map) {
199
            $content = view('modules/place-hierarchy/map', [
200
                'leaflet_config' => $this->leaflet_js_service->config(),
201
                'start_place_id' => $place_id,
202
            ]);
203
        } else {
204
            $content = view('modules/place-hierarchy/hierarchy', $this->getHierarchy($place));
205
        }
206
207
        return $this->viewResponse('modules/place-hierarchy/page', [
208
            'breadcrumbs'   => $this->breadcrumbs($place),
209
            'content'       => $content,
210
            'title'         => I18N::translate('Place hierarchy'),
211
            'tree'          => $tree,
212
            'use_map'       => $use_map,
213
            'place_summary' => $this->placeSummary($place),
214
        ]);
215
    }
216
217
    /**
218
     * @param Place $place
219
     *
220
     * @return array<mixed>
221
     */
222
    private function placeSummary($place): array
223
    {
224
        return [
225
            'id'   => $place->id(),
226
            'link' =>  I18N::translate('View table of events occurring in %s', $place->fullName()),
227
        ];
228
    }
229
230
    /**
231
     * @param Place $placeObj
232
     *
233
     * @return array<mixed>
234
     */
235
    protected function mapData(Place $placeObj): array
236
    {
237
        $places   = $placeObj->getChildPlaces();
238
        $features = [];
239
        $sidebar  = '';
240
241
        if ($places === []) {
242
            $places[] = $placeObj;
243
        }
244
245
        foreach ($places as $id => $place) {
246
            $location = new PlaceLocation($place->gedcomName());
247
248
            if ($location->latitude() === null || $location->longitude() === null) {
249
                $sidebar_class = 'unmapped';
250
            } else {
251
                $sidebar_class = 'mapped';
252
                $features[]    = [
253
                    'type'     => 'Feature',
254
                    'id'       => $id,
255
                    'geometry' => [
256
                        'type'        => 'Point',
257
                        'coordinates' => [$location->longitude(), $location->latitude()],
258
                    ],
259
                    'properties' => [
260
                        'tooltip' => $place->gedcomName(),
261
                        'popup'   => view('modules/place-hierarchy/popup', [
262
                            'place'     => $place,
263
                            'latitude'  => $location->latitude(),
264
                            'longitude' => $location->longitude(),
265
                        ]),
266
                    ],
267
                ];
268
            }
269
270
            $stats = [
271
                Family::RECORD_TYPE     => $this->familyPlaceLinks($place)->count(),
272
                Individual::RECORD_TYPE => $this->individualPlaceLinks($place)->count(),
273
                Location::RECORD_TYPE   => $this->locationPlaceLinks($place)->count(),
274
            ];
275
276
            $sidebar .= view('modules/place-hierarchy/sidebar', [
277
                'num_children'  => count($place->getChildPlaces()),
278
                'id'            => $id,
279
                'place'         => $place,
280
                'sidebar_class' => $sidebar_class,
281
                'stats'         => $stats,
282
                'geo_link'      => Auth::isAdmin() ? route(MapDataEdit::class, ['place_id'  => $location->id()]) : '',
283
            ]);
284
        }
285
286
        return [
287
            'sidebar' => $sidebar,
288
            'markers' => [
289
                'type'     => 'FeatureCollection',
290
                'features' => $features,
291
            ],
292
        ];
293
    }
294
295
    /**
296
     * @param Place $place
297
     *
298
     * @return array<mixed>
299
     */
300
    private function getHierarchy(Place $place): array
301
    {
302
        $places   = $place->getChildPlaces();
303
        $numfound = count($places);
304
        $divisor  = $numfound > 20 ? 3 : 2;
305
306
        if ($numfound > 0) {
307
            $columns = ceil($numfound / $divisor);
308
        } else {
309
            $columns = 1;
310
            $places  = [$place];
311
        }
312
313
        return [
314
            'col_class' => 'w-' . ($divisor > 2 ? '50' : '25'),
315
            'columns'   => array_chunk($places, (int) $columns),
316
        ];
317
    }
318
319
    /**
320
     * @param Place $place
321
     *
322
     * @return string
323
     */
324
    private function breadcrumbs(Place $place): string
325
    {
326
        $place_hierarchy = [];
327
        if ($place->gedcomName() !== '') {
328
            $place_hierarchy[] = $place;
329
            $parent_place      = $place->parent();
330
            while ($parent_place->gedcomName() !== '') {
331
                $place_hierarchy[] = $parent_place;
332
                $parent_place      = $parent_place->parent();
333
            }
334
            $place_hierarchy = array_reverse($place_hierarchy);
335
            $current         = array_pop($place_hierarchy);
336
        } else {
337
            $current = null;
338
        }
339
340
        return view('modules/place-hierarchy/breadcrumbs', [
341
            'place_hierarchy' => $place_hierarchy,
342
            'current'         => $current,
343
        ]);
344
    }
345
346
    /**
347
     * @param ServerRequestInterface $request
348
     *
349
     * @return ResponseInterface
350
     */
351
    public function postUpdateDataAction(ServerRequestInterface $request): ResponseInterface
352
    {
353
        $tree     = Validator::attributes($request)->tree();
354
        $place_id = Validator::parsedBody($request)->integer('placeId', 0);
355
        $type     = Validator::parsedBody($request)->string('type', '');
356
        $place    = Place::find($place_id, $tree);
357
358
        switch ($type) {
359
            case 'map':
360
                $data = $this->mapData($place);
361
                break;
362
            case 'events':
363
                $data = view('modules/place-hierarchy/events', [
364
                    'indilist' => $this->search_service->searchIndividualsInPlace($place),
365
                    'famlist'  => $this->search_service->searchFamiliesInPlace($place),
366
                    'tree'     => $tree,
367
                ]);
368
                break;
369
            default: // hierarchy
370
                $data = view('modules/place-hierarchy/hierarchy', $this->getHierarchy($place));
371
        }
372
373
        return response([
374
            'data'          => $data,
375
            'breadcrumbs'   => $this->breadcrumbs($place),
376
            'place_summary' => $this->placeSummary($place),
377
        ]);
378
    }
379
380
    /**
381
     * @param Place $place
382
     *
383
     * @return Builder
384
     */
385
    private function placeLinks(Place $place): Builder
386
    {
387
        return DB::table('places')
388
            ->join('placelinks', static function (JoinClause $join): void {
389
                $join
390
                    ->on('pl_file', '=', 'p_file')
391
                    ->on('pl_p_id', '=', 'p_id');
392
            })
393
            ->where('p_file', '=', $place->tree()->id())
394
            ->where('p_id', '=', $place->id());
395
    }
396
397
    /**
398
     * @param Place $place
399
     *
400
     * @return Builder
401
     */
402
    private function familyPlaceLinks(Place $place): Builder
403
    {
404
        return $this->placeLinks($place)
405
            ->join('families', static function (JoinClause $join): void {
406
                $join
407
                    ->on('pl_file', '=', 'f_file')
408
                    ->on('pl_gid', '=', 'f_id');
409
            });
410
    }
411
412
    /**
413
     * @param Place $place
414
     *
415
     * @return Builder
416
     */
417
    private function individualPlaceLinks(Place $place): Builder
418
    {
419
        return $this->placeLinks($place)
420
            ->join('individuals', static function (JoinClause $join): void {
421
                $join
422
                    ->on('pl_file', '=', 'i_file')
423
                    ->on('pl_gid', '=', 'i_id');
424
            });
425
    }
426
427
    /**
428
     * @param Place $place
429
     *
430
     * @return Builder
431
     */
432
    private function locationPlaceLinks(Place $place): Builder
433
    {
434
        return $this->placeLinks($place)
435
            ->join('other', static function (JoinClause $join): void {
436
                $join
437
                    ->on('pl_file', '=', 'o_file')
438
                    ->on('pl_gid', '=', 'o_id');
439
            })
440
            ->where('o_type', '=', Location::RECORD_TYPE);
441
    }
442
}
443