Passed
Pull Request — master (#3706)
by
unknown
08:53
created

AutoCompletePlace::search()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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