Skip to content

Commit

Permalink
Restructuring Rate response object to return a more standardized data…
Browse files Browse the repository at this point in the history
… format for all providers. Added more testing including some live API testing.
  • Loading branch information
danielme85 committed Aug 25, 2018
1 parent b848555 commit a94272f
Show file tree
Hide file tree
Showing 14 changed files with 166 additions and 132 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,6 @@ Temporary Items

# Created by .ignore support plugin (hsz.mobi)
.idea
vendor
vendor
.env
.env.testing
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,13 @@ https://github.com/gerardojbaez/money
### Supported functions per API
Default API is: The European Central Bank

| Config var | API | HTTPS | Historical | Time Series | Sign-up required |
| ----------------- | -------------------------- |:------------: | :---------: | :---------: | :--------------: |
|eurocentralbank | The European Central Bank | yes | yes | no | no |
|openexchange | https://openexchangerates.org | non-free | non-free | non-free | yes |
|yahoo | Yahoo Finance | yes | no | no | no |
|currencylayer | https://currencylayer.com/ | non-free | yes | non-free | yes |
|fixer | http://fixer.io/ | yes | yes | no | yes |
| Config var | API | HTTPS | Historical | Sign-up required |
| ----------------- | -------------------------- |:------------: | :---------: | :--------------: |
|eurocentralbank | The European Central Bank | yes | yes | no |
|openexchange | https://openexchangerates.org | non-free | non-free | yes |
|yahoo | Yahoo Finance | yes | no | no |
|currencylayer | https://currencylayer.com/ | non-free | yes | yes |
|fixer | http://fixer.io/ | yes | yes | yes |

### Disclaimer
Please take note of the Terms of Use for the different data sources.
Expand Down
File renamed without changes.
6 changes: 6 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,10 @@
</exclude>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
</php>
</phpunit>
2 changes: 1 addition & 1 deletion src/CConverterServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class CConverterServiceProvider extends ServiceProvider {
*/
public function boot()
{
$this->mergeConfigFrom(__DIR__.'/../config/CConverter.php', 'CConverter');
$this->mergeConfigFrom(__DIR__.'/../config/currencyConverter.php', 'currencyConverter');
$this->publishes([
__DIR__ . '/../config/CConverter.php' => config_path('CConverter.php')
]);
Expand Down
4 changes: 2 additions & 2 deletions src/Currency.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ class Currency
*
*/
public function __construct($api = null, $https = null, $useCache = null, $cacheMin = null, $runastest = false) {
if (!$settings = Config::get('CConverter')) {
Log::info('The CConverter.php config file was not found.');
if (!$settings = Config::get('currencyConverter')) {
Log::info('The currencyConverter.php config file was not found.');
}
//Override config/settings with constructor variables if present.
if (isset($api)) {
Expand Down
35 changes: 9 additions & 26 deletions src/Providers/BaseProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
namespace danielme85\CConverter\Providers;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class BaseProvider
{
public $api;
public $logEnabled;

protected $date;
protected $currency;
protected $baseRates;
protected $baseRateSeries;

protected $runastest;
protected $settings;
Expand All @@ -40,20 +40,18 @@ public function __construct($settings)
* @param string $url
* @param array $headers
*
* @return \Psr\Http\Message\StreamInterface
* @return string
*/
protected function connect($url, $headers = null)
{
if (!empty($headers)) {
$client = new Client(['headers' => $headers]);

}
else {
$client = new Client();

}
$request = $client->get($url);
$response = $request->getBody();
$response = $request->getBody()->getContents();

return $response;
}
Expand Down Expand Up @@ -84,12 +82,15 @@ protected function setBaseRates(Rates $rates) : bool
* Get rates
*
* @param string $currency
* @param $date
* @param string $date
*
* @return Rates|null
*/
protected function getBaseRates(string $currency, $date)
protected function getBaseRates(string $currency, string $date)
{
$this->currency = $currency;
$this->date = $date;

if (isset($this->baseRates[strtoupper($currency)][$date])) {

return $this->baseRates[strtoupper($currency)][$date];
Expand All @@ -98,22 +99,4 @@ protected function getBaseRates(string $currency, $date)
return null;
}

/**
* Get rate series
*
* @param string $currency
* @param $date
*
* @return Rates|null
*/
protected function getBaseRateSeries(string $currency)
{
if (isset($this->baseRates[strtoupper($currency)])) {

return $this->baseRates[strtoupper($currency)];
}

return null;
}

}
43 changes: 26 additions & 17 deletions src/Providers/CurrencyLayer.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,15 @@ public function rates(string $currency, string $date = null) : Rates
{
$rates = $this->getBaseRates($currency, $date);
if (empty($rates)) {
$rates = $this->convert($this->download($currency, $date));
$this->setBaseRates($rates);
$rates = $this->convert($this->download($date));

if ($currency !== 'USD') {
$rates = $rates->convertBaseRateToCurrency($currency);
$this->setBaseRates($rates);
}
else {
$this->setBaseRates($rates);
}
}

return $rates;
Expand All @@ -34,26 +41,28 @@ public function rates(string $currency, string $date = null) : Rates
*
* @return array
*/
private function download($currency, $fromDate = null, $toDate = null) {
private function download($fromDate = null, $toDate = null) {
//use test data if running as test
if ($this->runastest) {
$response = file_get_contents(dirname(__FILE__). '/../../tests/currencyLayerTestData.json');
}
else {
if ($this->settings['use-ssl']) {
$base = 'USD';

if ($this->settings['use-https']) {
$url = 'https';
} else {
$url = 'http';
}

if (!empty($fromDate) and !empty($toDate)) {
$url .= '://apilayer.net/api/timeframe?access_key='.$this->settings['currencylayer-access-key'].'&source='.$currency.'&start_date='.$fromDate.'&end_date='.$toDate;
$url .= '://apilayer.net/api/timeframe?access_key='.$this->settings['currencylayer-access-key'].'&source='.$base.'&start_date='.$fromDate.'&end_date='.$toDate;
}
else if (!empty($fromDate)) {
$url .= '://apilayer.net/api/historical?access_key=' . $this->settings['currencylayer-access-key'] . '&date=' . $fromDate . '&source=' . $currency;
$url .= '://apilayer.net/api/historical?access_key=' . $this->settings['currencylayer-access-key'] . '&date=' . $fromDate . '&source=' . $base;

} else {
$url .= '://apilayer.net/api/live?access_key=' . $this->settings['currencylayer-access-key'] . '&source=' . $currency;
$url .= '://apilayer.net/api/live?access_key=' . $this->settings['currencylayer-access-key'] . '&source=' . $base;
}

$response = $this->connect($url);
Expand All @@ -72,33 +81,33 @@ private function download($currency, $fromDate = null, $toDate = null) {
private function convert($input): Rates
{
$rates = new Rates();
$rates->timestamp = time();
$rates->date = $this->date;
$rates->base = 'USD';
$rates->rates = [];

$data = json_decode($input, true);

if (!empty($data)) {
if (isset($data['success'])) {
if ($data['success']) {
$time = $data['timestamp'];

$rates->timestamp = time();
$rates->date = date('Y-m-d', $time);
$rates->datetime = date('Y-m-d H:i:s', $time);
$rates->base = strtoupper($data['source']);
$rates->extra = [];
$rates->rates = [];
$rates->extra['cl_timestamp'] = $data['timestamp'] ?? null;
$newrates = [];

if (isset($data['quotes']) and is_array($data['quotes'])) {
foreach ($data['quotes'] as $key => $row) {
if ($key === "$rates->base$rates->base") {
$key = $rates->base;
} else {
$key = str_replace($rates->base, '', $key);
}
$newrates[$key] = $row;
$newrates[$key] = round($row, 5);
}
}
}
}
if (isset($data['error'])) {
$rates->extra['cl_error'] = $data['error'] ?? null;
}
}
if (!empty($newrates)) {
$rates->rates = $newrates;
Expand Down
74 changes: 39 additions & 35 deletions src/Providers/EuropeanCentralBank.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ private function download($date = null)
]);
}



return $response;
}

Expand All @@ -85,56 +87,58 @@ private function download($date = null)
*/
private function convert($input) : Rates
{
$data = json_decode($input, true);
$series = end($data['dataSets']);
$structure = $data['structure']['dimensions']['series'];

$time = strtotime($series['validFrom']);

$rates = new Rates();
$rates->timestamp = time();
$rates->date = date('Y-m-d', $time);
$rates->datetime = date('Y-m-d H:i:s', $time);
$rates->date = $this->date;
$rates->base = 'EUR';
$rates->extra = ['european_central_bank_valid_from' => $series['validFrom']];
$rates->rates = [];

$newrates = [];
if (!empty($input)) {
$data = json_decode($input, true);
if (!empty($data)) {
$series = end($data['dataSets']) ?? null;
$structure = $data['structure']['dimensions']['series'] ?? null;

$rates->extra['european_central_bank_valid_from'] = $series['validFrom'] ?? null;

$newrates = [];

if (!empty($structure)) {
foreach ($structure as $struc) {
if ($struc['id'] === 'CURRENCY') {
if (!empty($struc['values'])) {
foreach ($struc['values'] as $label) {
$labels[] = $label['id'];
if (!empty($structure)) {
foreach ($structure as $struc) {
if ($struc['id'] === 'CURRENCY') {
if (!empty($struc['values'])) {
foreach ($struc['values'] as $label) {
$labels[] = $label['id'];
}
}
}
}
}
}
}

if (!empty($series['series'])) {
foreach ($series['series'] as $row) {
$avg = 0;
$counter = 0;
foreach ($row as $subrow) {
if (!empty($subrow)) {
foreach ($subrow as $value) {
$avg += $value[0];
$counter++;
if (!empty($series['series'])) {
foreach ($series['series'] as $row) {
$avg = 0;
$counter = 0;
foreach ($row as $subrow) {
if (!empty($subrow)) {
foreach ($subrow as $value) {
$avg += $value[0];
$counter++;
}
}
}
$newrates[] = $avg / $counter;
}
}
$newrates[] = $avg/$counter;
}
}

if (!empty($labels) and !empty($newrates)) {
foreach ($labels as $i => $label) {
$rates->rates[$label] = $newrates[$i];
if (!empty($labels) and !empty($newrates)) {
foreach ($labels as $i => $label) {
$rates->rates[$label] = $newrates[$i];
}
//add 1:1 conversion rate from base for testing
$rates->rates['EUR'] = 1;
}
}
//add 1:1 conversion rate from base for testing
$rates->rates['EUR'] = 1;
}

return $rates;
Expand Down
19 changes: 9 additions & 10 deletions src/Providers/Fixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ class Fixer extends BaseProvider implements ProviderInterface
*/
public function rates(string $currency, string $date = null) : Rates
{
$results = [];
$rates = $this->getBaseRates($currency, $date);
if (empty($rates)) {
if ($this->settings['fixer-use-real-base']) {
Expand Down Expand Up @@ -83,22 +82,22 @@ public function download(string $currency, string $date = null) {
/**
* Convert data from fixer.io to standardized format.
*
* @param array $data
* @return array
* @param string $input
* @return Rates
*/
private function convert($input) {
$data = json_decode($input, true);

$time = strtotime($data['date']);

private function convert($input) : Rates
{
$rates = new Rates();
$rates->timestamp = time();
$rates->date = date('Y-m-d', $time);
$rates->datetime = date('Y-m-d H:i:s', $time);
$rates->date = $this->date;
$rates->base = 'EUR';
$rates->rates = [];

$data = json_decode($input, true);

if (!empty($data)) {
if (!empty($data['rates'])) {
$rates->extra['fixer_date'] = $data['date'] ?? null;
foreach ($data['rates'] as $key => $row) {
$newrates[$key] = $row;
}
Expand Down
Loading

0 comments on commit a94272f

Please sign in to comment.