Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
Nominatim
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 1
 geocoding
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * Jingga
4 *
5 * PHP Version 8.1
6 *
7 * @package   phpOMS\Api\Geocoding
8 * @copyright Dennis Eichhorn
9 * @license   OMS License 2.0
10 * @version   1.0.0
11 * @link      https://jingga.app
12 */
13declare(strict_types=1);
14
15namespace phpOMS\Api\Geocoding;
16
17use phpOMS\Message\Http\HttpRequest;
18use phpOMS\Message\Http\RequestMethod;
19use phpOMS\Message\Http\Rest;
20use phpOMS\Uri\HttpUri;
21
22/**
23 * Check EU VAT.
24 *
25 * @package phpOMS\Api\Geocoding
26 * @license OMS License 2.0
27 * @link    https://jingga.app
28 * @since   1.0.0
29 */
30final class Nominatim
31{
32    private static float $lastRun = 0;
33
34    /**
35     * {@inheritdoc}
36     */
37    public static function geocoding(string $country, string $city, string $address = '') : array
38    {
39        $URL = 'https://nominatim.openstreetmap.org/search.php?format=jsonv2';
40
41        $request = new HttpRequest(
42            new HttpUri(
43                $URL . '&country=' . \urlencode($country) . '&city=' . \urlencode($city) . ($address === '' ? '' : '&street=' . \urlencode($address))
44            )
45        );
46        $request->setMethod(RequestMethod::GET);
47
48        // Required according to the api documentation
49        $request->header->set('User-Agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1');
50
51        // Handling rate limit of the Api
52        $time = \microtime(true);
53        if ($time - self::$lastRun < 1000000) {
54            \usleep((int) (1000000 - ($time - self::$lastRun) + 100));
55        }
56
57        $body           = Rest::request($request)->getBody();
58        $result['body'] = $body;
59
60        /** @var array $json */
61        $json = \json_decode($body, true);
62        if ($json === false) {
63            return [
64                'lat' => 0.0,
65                'lon' => 0.0,
66            ];
67        }
68
69        return [
70            'lat' => (float) ($json[0]['lat'] ?? 0.0),
71            'lon' => (float) ($json[0]['lon'] ?? 0.0),
72        ];
73    }
74}