Skip to content

Commit

Permalink
Merge pull request #30 from hmlb/better_yahoo_error_handling
Browse files Browse the repository at this point in the history
Better error management in YahooFinanceRatioProvider
  • Loading branch information
Philippe Le Van (@plv) committed May 19, 2015
2 parents 3707cf8 + e4344df commit 4a51f9a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
35 changes: 33 additions & 2 deletions Pair/RatioProvider/YahooFinanceRatioProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
{
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
],
"require": {
"php": ">=5.3.2",
"ext-curl" : "*",
"symfony/framework-bundle": "~2.1",
"mathiasverraes/money": "1.2.*",
"symfony/form": "~2.1",
Expand Down

0 comments on commit 4a51f9a

Please sign in to comment.