Completed
Pull Request — master (#3706)
by
unknown
06:48
created

AutoCompletePlace   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 48
c 1
b 0
f 1
dl 0
loc 86
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
B searchGazetteer() 0 47 7
A search() 0 18 2
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2021 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\Http\RequestHandlers;
21
22
use Fisharebest\Webtrees\I18N;
23
use Fisharebest\Webtrees\Place;
24
use Fisharebest\Webtrees\Services\UserService;
25
use Fisharebest\Webtrees\Site;
26
use Fisharebest\Webtrees\Tree;
27
use GuzzleHttp\Client;
28
use GuzzleHttp\Exception\RequestException;
29
use Illuminate\Support\Collection;
30
use Psr\Http\Message\ServerRequestInterface;
31
32
use function assert;
33
use function json_decode;
34
use function json_last_error;
35
use function rawurlencode;
36
37
use const JSON_ERROR_NONE;
38
39
/**
40
 * Autocomplete handler for places
41
 */
42
class AutoCompletePlace extends AbstractAutocompleteHandler
43
{
44
    // Gazetteer urls
45
    private const NOMINATIM_URL = 'https://nominatim.openstreetmap.org/search';
46
    private const OPENROUTE_URL = 'https://api.openrouteservice.org/geocode/autocomplete';
47
48
    // Options for fetching files using GuzzleHTTP
49
    private const GUZZLE_OPTIONS = [
50
        'connect_timeout' => 3,
51
        'read_timeout'    => 3,
52
        'timeout'         => 3,
53
    ];
54
55
    protected function search(ServerRequestInterface $request): Collection
56
    {
57
        $tree = $request->getAttribute('tree');
58
        assert($tree instanceof Tree);
59
60
        $query = $request->getAttribute('query');
61
62
        $data = $this->search_service
63
            ->searchPlaces($tree, $query, 0, static::LIMIT)
64
            ->map(static function (Place $place): string {
65
                return $place->gedcomName();
66
            });
67
68
        if ((bool) Site::getPreference('use_gazetteer')) {
69
            $data = $data->concat($this->searchGazetteer($query))->unique();
70
        }
71
72
        return new Collection($data->slice(0, static::LIMIT));
73
    }
74
75
    /**
76
     *
77
     * @param string $query
78
     *
79
     * @return Collection<string>
80
     */
81
    private function searchGazetteer($query): collection
82
    {
83
        $key          = Site::getPreference('openroute_key');
84
        $data         = new Collection();
85
        $user_service = new UserService();
86
87
        if ($key !== '') {
88
            $url   = self::OPENROUTE_URL;
89
            $qry = [
90
                'api_key' => $key,
91
                'text'    => rawurlencode($query),
92
                'layers'  => 'coarse',
93
                'size'    => static::LIMIT,
94
            ];
95
        } else {
96
            $url   = self::NOMINATIM_URL;
97
            $qry = [
98
                'q'               => rawurlencode($query),
99
                'format'          => 'jsonv2',
100
                'limit'           => static::LIMIT,
101
                'accept-language' => I18N::languageTag(),
102
                'featuretype'     => 'settlement',
103
                'email'           => rawurlencode($user_service->administrators()->first()->email()),
104
            ];
105
        }
106
107
        // Read from the URL
108
        $client = new Client();
109
        try {
110
            $json     = $client->get($url, array_merge(self::GUZZLE_OPTIONS, ['query' => $qry]))->getBody()->__toString();
111
            $results  = json_decode($json, false);
112
            if (json_last_error() === JSON_ERROR_NONE) {
113
                if ($key !== '') {
114
                    foreach ($results->features as $result) {
115
                        $data->add($result->properties->label);
116
                    }
117
                } else {
118
                    foreach ($results as $result) {
119
                        $data->add($result->display_name);
120
                    }
121
                }
122
            }
123
        } catch (RequestException $ex) {
124
            // Service down?  Quota exceeded?
125
        }
126
127
        return $data;
128
    }
129
}
130