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 18declare(strict_types=1); 19 20namespace Fisharebest\Webtrees\Http\RequestHandlers; 21 22use Fisharebest\Webtrees\I18N; 23use Fisharebest\Webtrees\Module\ModuleMapAutocompleteInterface; 24use Fisharebest\Webtrees\Place; 25use Fisharebest\Webtrees\Services\ModuleService; 26use Fisharebest\Webtrees\Services\SearchService; 27use Fisharebest\Webtrees\Site; 28use Fisharebest\Webtrees\Tree; 29use GuzzleHttp\Client; 30use GuzzleHttp\Exception\RequestException; 31use Illuminate\Support\Collection; 32use Iodev\Whois\Modules\Module; 33use Psr\Http\Message\ServerRequestInterface; 34 35use function assert; 36use function is_array; 37use function json_decode; 38use function rawurlencode; 39 40use const JSON_THROW_ON_ERROR; 41 42/** 43 * Autocomplete handler for places 44 */ 45class AutoCompletePlace extends AbstractAutocompleteHandler 46{ 47 // Options for fetching files using GuzzleHTTP 48 private const GUZZLE_OPTIONS = [ 49 'connect_timeout' => 3, 50 'read_timeout' => 3, 51 'timeout' => 3, 52 ]; 53 54 private ModuleService $module_service; 55 56 /** 57 * @param SearchService $search_service 58 */ 59 public function __construct(SearchService $search_service, ModuleService $module_service) 60 { 61 parent::__construct($search_service); 62 63 $this->module_service = $module_service; 64 } 65 66 protected function search(ServerRequestInterface $request): Collection 67 { 68 $tree = $request->getAttribute('tree'); 69 assert($tree instanceof Tree); 70 71 $query = $request->getAttribute('query'); 72 73 $data = $this->search_service 74 ->searchPlaces($tree, $query, 0, static::LIMIT) 75 ->map(static function (Place $place): string { 76 return $place->gedcomName(); 77 }); 78 79 // No place found? Use external gazetteers. 80 foreach ($this->module_service->findByInterface(ModuleMapAutocompleteInterface::class) as $module) { 81 if ($data->isEmpty()) { 82 $data = $data->concat($module->searchPlaceNames($query))->sort(); 83 } 84 } 85 86 return $data; 87 } 88} 89