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\Module; 21 22use Fig\Http\Message\StatusCodeInterface; 23use Fisharebest\Webtrees\Registry; 24use GuzzleHttp\Client; 25use GuzzleHttp\Exception\GuzzleException; 26use GuzzleHttp\Psr7\Request; 27use Psr\Http\Message\RequestInterface; 28use Psr\Http\Message\ResponseInterface; 29 30/** 31 * Trait ModuleMapAutocompleteTrait - default implementation of ModuleMapAutocompleteInterface 32 */ 33trait ModuleMapAutocompleteTrait 34{ 35 /** 36 * A unique internal name for this module (based on the installation folder). 37 * 38 * @return string 39 */ 40 abstract public function name(): string; 41 42 /** 43 * @param string $place 44 * 45 * @return array<string> 46 */ 47 public function searchPlaceNames(string $place): array 48 { 49 if (strlen($place) <= 2) { 50 return []; 51 } 52 53 $key = $this->name() . $place; 54 $cache = Registry::cache()->file(); 55 $ttl = 86400; 56 57 try { 58 return $cache->remember($key, function () use ($place) { 59 $request = $this->createPlaceNameSearchRequest($place); 60 61 $client = new Client([ 62 'timeout' => 3, 63 ]); 64 65 $response = $client->send($request); 66 67 if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) { 68 return $this->parsePlaceNameSearchResponse($response); 69 } 70 71 return []; 72 }, $ttl); 73 } catch (GuzzleException $ex) { 74 // Service down? Quota exceeded? 75 // Don't try for another hour. 76 $cache->remember($key, fn () => [], 3600); 77 78 return []; 79 } 80 } 81 82 /** 83 * @param string $place 84 * 85 * @return RequestInterface 86 */ 87 protected function createPlaceNameSearchRequest(/** @scrutinizer ignore-unused */ string $place): RequestInterface 88 { 89 return new Request('GET', ''); 90 } 91 92 /** 93 * @param ResponseInterface $response 94 * 95 * @return array<string> 96 */ 97 protected function parsePlaceNameSearchResponse(/** @scrutinizer ignore-unused */ ResponseInterface $response): array 98 { 99 return []; 100 } 101} 102