OpenExchangeRatesService::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 5
nc 1
nop 3
1
<?php
2
3
/**
4
 * OpenExchangeRates Service
5
 *
6
 * @author Gonzalo Míguez ([email protected])
7
 * @since 2014
8
 */
9
10
namespace Mrzard\OpenExchangeRates\Service;
11
12
use DateTime;
13
use Exception;
14
use GuzzleHttp\ClientInterface;
15
16
/**
17
 * Class OpenExchangeRatesService
18
 *
19
 * This class exposes the OpenExchangeRates API
20
 *
21
 * @package Mrzard\OpenExchangeRatesBundle\Service
22
 */
23
class OpenExchangeRatesService
24
{
25
    /**
26
     * @var string
27
     * 
28
     * the app id
29
     */
30
    protected $appId;
31
32
    /**
33
     * @var string
34
     * 
35
     * the api endpoint
36
     */
37
    protected $endPoint = '://openexchangerates.org/api';
38
39
    /**
40
     * @var string
41
     * 
42
     * base currency
43
     */
44
    protected $baseCurrency = '';
45
46
    /**
47
     * @var ClientInterface
48
     */
49
    protected $client;
50
51
    /**
52
     * @var bool
53
     * 
54
     * https is used
55
     */
56
    protected $https;
57
58
    /**
59
     * Service constructor
60
     *
61
     * @param string $openExchangeRatesAppId the app_id for OpenExchangeRates
62
     * @param array  $apiOptions             Options for the OpenExchangeRatesApi
63
     * @param object $client                 Http client for requests
64
     * @throws \ErrorException
65
     */
66
    public function __construct($openExchangeRatesAppId, $apiOptions, $client)
67
    {
68
        $this->appId = $openExchangeRatesAppId;
69
        $this->https = (bool) $apiOptions['https'];
70
        $this->baseCurrency = (string) $apiOptions['base_currency'];
71
        $this->client = $this->wrapClient($client);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->wrapClient($client) of type object<Mrzard\OpenExchan...ce\HttpClientInterface> is incompatible with the declared type object<GuzzleHttp\ClientInterface> of property $client.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
72
    }
73
74
    /**
75
     * @param $client
76
     * @return HttpClientInterface
77
     * @throws \ErrorException
78
     */
79
    private function wrapClient($client)
80
    {
81
        if ($client instanceof HttpClientInterface) {
82
            return $client;
83
        }
84
        if (!method_exists($client, 'request')) {
85
            throw new \ErrorException('Supplied client doesn\'t have method `request`');
86
        }
87
        
88
	return new HttpClientWrapper($client);
89
    }
90
91
    /**
92
     * @return string
93
     */
94
    public function getEndPoint()
95
    {
96
        $protocol = 'http';
97
        if ($this->useHttps()) {
98
            $protocol .= 's';
99
        }
100
101
        return $protocol.$this->endPoint;
102
    }
103
104
    /**
105
     * Get the appId
106
     *
107
     * @return string
108
     */
109
    public function getAppId()
110
    {
111
        return $this->appId;
112
    }
113
114
    /**
115
     * Get if https is enabled
116
     *
117
     * @return boolean
118
     */
119
    public function useHttps()
120
    {
121
        return $this->https;
122
    }
123
124
    /**
125
     * Sets whether to use https
126
     *
127
     * @param boolean $https
128
     */
129
    public function setHttps($https)
130
    {
131
        $this->https = (bool) $https;
132
    }
133
134
    /**
135
     * Get the base currency
136
     *
137
     * @return string
138
     */
139
    public function getBaseCurrency()
140
    {
141
        return $this->baseCurrency;
142
    }
143
144
    /**
145
     * Set the base currency
146
     *
147
     * @param string $baseCurrency
148
     */
149
    public function setBaseCurrency($baseCurrency)
150
    {
151
        $this->baseCurrency = $baseCurrency;
152
    }
153
154
155
    /**
156
     * Converts $value from currency $symbolFrom to currency $symbolTo
157
     *
158
     * @param float  $value      value to convert
159
     * @param string $symbolFrom symbol to convert from
160
     * @param string $symbolTo   symbol to convert to
161
     *
162
     * @return float
163
     */
164
    public function convertCurrency($value, $symbolFrom, $symbolTo)
165
    {
166
        $query = array('app_id' => $this->getAppId());
167
168
        return $this->getResponse(
169
            'GET',
170
            $this->getEndPoint().'/convert/'.$value.'/'.$symbolFrom.'/'.$symbolTo,
171
            array('query' => $query)
172
        );
173
    }
174
175
    /**
176
     * If base currency is overridden, return $baseCurrency, otherwise
177
     * return the object's base currency
178
     *
179
     * @param $baseCurrency
180
     *
181
     * @return string
182
     */
183
    protected function prepareBaseCurrency($baseCurrency)
184
    {
185
        return null === $baseCurrency ? $this->getBaseCurrency() : $baseCurrency;
186
    }
187
188
    /**
189
     * Given a query and symbols, puts them in the query or not
190
     *
191
     * @param $query
192
     * @param $symbols
193
     *
194
     * @return mixed
195
     */
196
    protected function prepareSymbols($query, $symbols)
197
    {
198
        if (count($symbols)) {
199
            $query['symbols'] = implode(',', $symbols);
200
        }
201
202
        return $query;
203
    }
204
205
    /**
206
     * Get the latest exchange rates
207
     *
208
     * @param array  $symbols array of currency codes to get the rates for.
209
     *                        Default empty (all currencies)
210
     * @param string $base    Base currency, default NULL (gets it from config)
211
     *
212
     * @return array
213
     */
214
    public function getLatest(array $symbols = array(), $base = null)
215
    {
216
        $query = ['app_id' => $this->getAppId()];
217
        if (is_string($base) && strlen($base) === 3) {
218
            $query['base'] = $base;
219
        }
220
221
        return $this->getResponse(
222
            'GET',
223
            $this->getEndPoint().'/latest.json',
224
            array('query' => $this->prepareSymbols($query, $symbols))
225
        );
226
    }
227
228
229
    /**
230
     * Gets a list of all available currencies
231
     */
232
    public function getCurrencies()
233
    {
234
        return $this->getResponse(
235
            'GET',
236
            $this->getEndPoint().'/currencies.json',
237
            array('query' => array('app_id' => $this->getAppId()))
238
        );
239
    }
240
241
242
    /**
243
     * Format response
244
     *
245
     * @param $method  String
246
     * @param $uri     String
247
     * @param $options array
248
     *
249
     * @return array
250
     * @internal param HttpResponseInterface $response
251
     *
252
     */
253
    private function getResponse($method, $uri, $options)
254
    {
255
        try {
256
            $response = new HttpResponseWrapper($this->client->request($method, $uri, $options));
257
            return json_decode($response->getBody()->getContents(), true);
258
        } catch (\Exception $e) {
259
            return array('error' => '-1 Could not run request');
260
        }
261
    }
262
263
264
    /**
265
     * Get historical data
266
     *
267
     * @param \DateTime $date
268
     *
269
     * @param array  $symbols array of currency codes to get the rates for.
270
     *                        Default empty (all currencies)
271
     * @param string $base    Base currency, default NULL (gets it from config)
272
     *
273
     * @return array
274
     */
275
    public function getHistorical(DateTime $date, array $symbols = array(), $base = null)
276
    {
277
        $query = ['app_id' => $this->getAppId()];
278
        if (is_string($base) && strlen($base) === 3) {
279
            $query['base'] = $base;
280
        }
281
282
        return $this->getResponse(
283
            'GET',
284
            $this->getEndPoint().'/historical/'.$date->format('Y-m-d').'.json',
285
            array('query' => $this->prepareSymbols($query, $symbols))
286
        );
287
    }
288
}
289