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