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 private ModuleService $module_service; 48 49 /** 50 * @param SearchService $search_service 51 */ 52 public function __construct(SearchService $search_service, ModuleService $module_service) 53 { 54 parent::__construct($search_service); 55 56 $this->module_service = $module_service; 57 } 58 59 /** 60 * @param ServerRequestInterface $request 61 * 62 * @return Collection<string> 63 */ 64 protected function search(ServerRequestInterface $request): Collection 65 { 66 $tree = $request->getAttribute('tree'); 67 assert($tree instanceof Tree); 68 69 $query = $request->getQueryParams()['query'] ?? ''; 70 71 $data = $this->search_service 72 ->searchPlaces($tree, $query, 0, static::LIMIT) 73 ->map(static function (Place $place): string { 74 return $place->gedcomName(); 75 }); 76 77 // No place found? Use external gazetteers. 78 foreach ($this->module_service->findByInterface(ModuleMapAutocompleteInterface::class) as $module) { 79 if ($data->isEmpty()) { 80 $data = $data->concat($module->searchPlaceNames($query))->sort(); 81 } 82 } 83 84 return $data; 85 } 86} 87