xref: /webtrees/app/Module/ModuleMapAutocompleteTrait.php (revision a1cc6e7017d126647952c882e022435d06067914)
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\RequestException;
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     * @param string $place
37     *
38     * @return array<string>
39     */
40    public function searchPlaceNames(string $place): array
41    {
42        if (strlen($place) <= 2) {
43            return [];
44        }
45
46        $key   = $this->name() . $place;
47        $cache = Registry::cache()->file();
48        $ttl   = 86400;
49
50        try {
51            return $cache->remember($key, function () use ($place) {
52                $request = $this->createPlaceNameSearchRequest($place);
53
54                $client = new Client([
55                    'timeout' => 3,
56                ]);
57
58                $response = $client->send($request);
59
60                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
61                    return $this->parsePlaceNameSearchResponse($response);
62                }
63
64                return [];
65            }, $ttl);
66        } catch (RequestException $ex) {
67            // Service down?  Quota exceeded?
68            // Don't try for another hour.
69            $cache->remember($key, fn () => [], 3600);
70
71            return [];
72        }
73    }
74
75    /**
76     * @param string $place
77     *
78     * @return RequestInterface
79     */
80    protected function createPlaceNameSearchRequest(string $place): RequestInterface
81    {
82        return new Request('GET', '');
83    }
84
85    /**
86     * @param ResponseInterface $response
87     *
88     * @return array<string>
89     */
90    protected function parsePlaceNameSearchResponse(ResponseInterface $response): array
91    {
92        return [];
93    }
94}
95