Completed
Push — master ( fd983c...6ef91a )
by Maxime
04:57
created

Nominatim::__construct()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 35
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7.3329

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 35
rs 8.439
ccs 16
cts 24
cp 0.6667
cc 6
eloc 23
nc 6
nop 2
crap 7.3329
1
<?php
2
/**
3
 * Class Nominatim
4
 *
5
 * @package      maxh\nominatim
6
 * @author       Maxime Hélias <[email protected]>
7
 */
8
9
namespace maxh\Nominatim;
10
11
use GuzzleHttp\Client;
12
use GuzzleHttp\Psr7\Request;
13
use Psr\Http\Message\ResponseInterface;
14
15
use maxh\Nominatim\Exceptions\InvalidParameterException;
16
use maxh\Nominatim\Exceptions\NominatimException;
17
18
/**
19
 *  Wrapper to manage exchanges with OSM Nominatim API
20
 *
21
 */
22
class Nominatim
23
{
24
25
    /**
26
     * Contain url of the current application
27
     * @var string
28
     */
29
    private $application_url = null;
30
31
    /**
32
     * Contain http client connection
33
     * @var Client
34
     */
35
    private $http_client = null;
36
37
    /**
38
     * The search object which serves as a template for new ones created
39
     * by 'newSearch()' method.
40
     *
41
     * @var Search
42
     */
43
    private $baseSearch;
44
45
    /**
46
     * Template for new ones created by 'newReverser()' method.
47
     * @var Reverse
48
     */
49
    private $baseReverse;
50
51
    /**
52
     * Template for new ones created by 'newLookup()' method.
53
     * @var Lookup
54
     */
55
    private $baseLookup;
56
57
    /**
58
     * Constructor
59
     * @param string                $application_url Contain url of the current application
60
     * @param Guzzle\Client|null    $http_client     Client object from Guzzle
61
     */
62 5
    public function __construct(
63
        $application_url,
64
        Client $http_client = null
65 1
    ) {
66
67 5
        if (!isset($application_url)) {
68
            throw new InvalidParameterException("Application url parameter is empty");
69
        }
70
71 5
        if (!isset($http_client)) {
72 5
            $http_client = new Client([
73 5
                'base_uri'           => $application_url,
74 5
                'timeout'            => 30,
75 5
                'connection_timeout' => 5,
76 5
            ]);
77 5
        } elseif ($http_client instanceof Client) {
78
            $application_url_client = $http_client->getConfig('base_uri');
79
80
            if (!isset($application_url_client)) {
81
                $http_client->setDefaultOption('base_uri', $application_url);
82
            } elseif ($application_url_client != $application_url) {
83
                throw new InvalidParameterException("http_client parameter hasn't the same url application.");
84
            }
85
        } else {
86
            throw new InvalidParameterException("http_client parameter must be a GuzzleHttp\Client object or empty");
87
        }
88
89 5
        $this->application_url = $application_url;
90 5
        $this->http_client = $http_client;
91
92
        //Create base
93 5
        $this->baseSearch = new Search();
94 5
        $this->baseReverse = new Reverse();
95 5
        $this->baseLookup = new Lookup();
96 5
    }
97
98
    /**
99
     * Returns a new search object based on the base search.
100
     *
101
     * @return Search
102
     */
103 3
    public function newSearch()
104
    {
105 3
        return clone $this->baseSearch;
106
    }
107
108
    /**
109
     * Returns a new search object based on the base reverse.
110
     *
111
     * @return Reverse
112
     */
113 2
    public function newReverse()
114
    {
115 2
        return clone $this->baseReverse;
116
    }
117
118
    /**
119
     * Returns a new search object based on the base lookup.
120
     *
121
     * @return Lookup
122
     */
123 2
    public function newLookup()
124
    {
125 2
        return clone $this->baseLookup;
126
    }
127
128
    /**
129
     * Decode the data returned from the request
130
     *
131
     * @param  string   $format   json or xml
132
     * @param  Request  $request  Request object from Guzzle
133
     * @param  ResponseInterface $response Interface response object from Guzzle
134
     *
135
     * @return array|\SimpleXMLElement
136
     * @throws maxh\Nominatim\Exceptions\NominatimException if no format for decode
137
     */
138
    private function decodeResponse($format, Request $request, ResponseInterface $response)
139
    {
140
        if ($format == 'json') {
141
            return json_decode($response->getBody(), true);
142
        }
143
144
        if ($format == 'xml') {
145
            return new \SimpleXMLElement($response->getBody());
146
        }
147
148
        throw new NominatimException("Format is undefined or not supported for decode response", $request, $response);
149
    }
150
151
    /**
152
     * Runs the query and returns the result set from Nominatim.
153
     * @param  QueryInterface $nRequest  The object request to send
154
     *
155
     * @return array                                        The decoded data returned from Nominatim
156
     * @throws \GuzzleHttp\Exception\ClientException        if http request is an error
157
     */
158
    public function find(QueryInterface $nRequest)
159
    {
160
        $url = $this->application_url . '/' . $nRequest->getPath() . '?';
161
        $request = new Request('GET', $url);
162
163
        //Convert the query array to string with space replace to +
164
        $query = \GuzzleHttp\Psr7\build_query($nRequest->getQuery(), PHP_QUERY_RFC1738);
165
166
        $url = $request->getUri()->withQuery($query);
167
        $request = $request->withUri($url);
168
169
        return $this->decodeResponse(
170
            $nRequest->getFormat(),
171
            $request,
172
            $this->http_client->send($request)
173
        );
174
    }
175
176
    /**
177
     * Return the client using by instance
178
     * @return GuzzleHttp\Client
179
     */
180 1
    public function getClient()
181
    {
182 1
        return $this->http_client;
183
    }
184
}
185