diff --git a/Pair/RatioProvider/YahooFinanceRatioProvider.php b/Pair/RatioProvider/YahooFinanceRatioProvider.php index 131bbc88..e6fb2e8f 100644 --- a/Pair/RatioProvider/YahooFinanceRatioProvider.php +++ b/Pair/RatioProvider/YahooFinanceRatioProvider.php @@ -35,13 +35,38 @@ public function fetchRatio($referenceCurrencyCode, $currencyCode) ); } - $endpoint = $this->getEndpoint($baseCurrency, $currency); - $responseContent = file_get_contents($endpoint); + $responseContent = $this->executeQuery($this->getEndpoint($baseCurrency, $currency)); $ratio = $this->getRatioFromResponse($responseContent); return $ratio; } + /** + * Executes the query to the API endpoint. + * + * @param string $endpoint Endpoint's URI + * + * @return string The response content + * + * @throws MoneyException if the query has failed or the response status is not 200 + */ + protected function executeQuery($endpoint) + { + $ch = curl_init($endpoint); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + $responseContent = curl_exec($ch); + $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + if ($responseContent === false || $httpStatus != 200) { + throw new MoneyException('Could not execute YahooFinanceRatioProvider query to endpoint '.$endpoint); + } + + curl_close($ch); + + return $responseContent; + } + /** * @param Currency $referenceCurrency * @param Currency $currency @@ -61,6 +86,8 @@ protected function getEndpoint(Currency $referenceCurrency, Currency $currency) * @param string $response The json response of the YahooFinance Api * * @return float The current exchange rate between currencies + * + * @throws MoneyException If no rate can be extracted from the response */ protected function getRatioFromResponse($response) { @@ -70,6 +97,10 @@ protected function getRatioFromResponse($response) ->results ->rate ->Rate; + if ($rate == 'N/A') { + $pair = $content->query->results->rate->id; + throw new MoneyException('YahooFinanceApi does not have an exchange rate for '.$pair); + } $ratio = (float) $rate; return $ratio; diff --git a/composer.json b/composer.json index 45f072ba..6c3d2c88 100644 --- a/composer.json +++ b/composer.json @@ -16,6 +16,7 @@ ], "require": { "php": ">=5.3.2", + "ext-curl" : "*", "symfony/framework-bundle": "~2.1", "mathiasverraes/money": "1.2.*", "symfony/form": "~2.1",