xref: /webtrees/app/Http/RequestHandlers/MapDataDelete.php (revision 9f9acdbc09170c04c1e150c36ee57d49027e314a)
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\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Services\MapDataService;
23use Illuminate\Database\Capsule\Manager as DB;
24use Psr\Http\Message\ResponseInterface;
25use Psr\Http\Message\ServerRequestInterface;
26use Psr\Http\Server\RequestHandlerInterface;
27
28use function redirect;
29use function route;
30
31/**
32 * Delete a place location from the control panel.
33 */
34class MapDataDelete implements RequestHandlerInterface
35{
36    /** @var MapDataService */
37    private $map_data_service;
38
39    /**
40     * Dependency injection.
41     *
42     * @param MapDataService $map_data_service
43     */
44    public function __construct(MapDataService $map_data_service)
45    {
46        $this->map_data_service = $map_data_service;
47    }
48
49    /**
50     * @param ServerRequestInterface $request
51     *
52     * @return ResponseInterface
53     */
54    public function handle(ServerRequestInterface $request): ResponseInterface
55    {
56        $place_id  = (int) $request->getQueryParams()['place_id'];
57
58        $place  = $this->map_data_service->findById($place_id);
59        $parent = $place->parent();
60
61        if ($place_id !== 0) {
62            $this->map_data_service->deleteRecursively($place_id);
63        }
64
65        // If after deleting there are no more places at this level then go up a level
66        $siblings = DB::table('placelocation')
67            ->where('pl_parent_id', '=', $parent->id())
68            ->count();
69
70        if ($siblings === 0) {
71            $parent_id = $parent->parent()->id();
72        }
73
74        $url = route(MapDataList::class, ['parent_id' => $parent->id()]);
75
76        return redirect($url);
77    }
78}
79