Skip to content

Commit

Permalink
Merge pull request #13 from imanilchaudhari/update
Browse files Browse the repository at this point in the history
enh: code refactured
  • Loading branch information
imanilchaudhari authored Apr 6, 2024
2 parents 9e2a560 + 6218799 commit 5050de9
Show file tree
Hide file tree
Showing 16 changed files with 164 additions and 147 deletions.
105 changes: 47 additions & 58 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,17 @@
[![Total Downloads](https://poser.pugx.org/imanilchaudhari/yii2-currency-converter/downloads)](https://packagist.org/packages/imanilchaudhari/yii2-currency-converter)
[![Build Status](https://travis-ci.org/imanilchaudhari/yii2-currency-converter.svg?branch=master)](https://travis-ci.org/imanilchaudhari/yii2-currency-converter)
[![Code Coverage](https://codecov.io/gh/imanilchaudhari/yii2-currency-converter/branch/master/graph/badge.svg)](https://codecov.io/gh/imanilchaudhari/yii2-currency-converter)
[![Mutation testing badge](https://img.shields.io/endpoint?style=flat&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fyiisoft%2F_____%2Fmaster)](https://dashboard.stryker-mutator.io/reports/github.com/imanilchaudhari/yii2-currency-converter/master)
[![type-coverage](https://shepherd.dev/github/imanilchaudhari/yii2-currency-converter/coverage.svg)](https://shepherd.dev/github/imanilchaudhari/yii2-currency-converter)
[![psalm-level](https://shepherd.dev/github/imanilchaudhari/yii2-currency-converter/level.svg)](https://shepherd.dev/github/imanilchaudhari/yii2-currency-converter)

This extension will help to find out current currency conversion rate. This extension uses Yahoo's currency conversion API.
This extension will help to find out current currency conversion rate using various providers.

Why Use It
-----------
* Reliable Rate. Uses Yahoo API, Open Exchange Rates API.
* Conversion without curreny code (from country code).
* Caching of rate, to avoid connecting to Yahoo again and again.

Important Notice
----------------
As of recent changes on Yahoo Terms of Service. As such, the service is being discontinued. I highly recommend you to use [Open Exchange Rates API](http://openexchangerates.org/). As suggested by [chaimleich](https://github.com/chaimleich) on this [pull request](https://github.com/imanilchaudhari/yii2-currency-converter/pull/3). You can find Open Exchnage Rates working example below.
Documentation is at [docs/README.md](docs/README.md).

Requirements
-----------
* PHP version 7.4 or later
* Curl Extension (Optional)



Installation
------------

Expand All @@ -41,13 +29,13 @@ The preferred way to install this extension is through [composer](http://getcomp
Either run

```
php composer.phar require --prefer-dist imanilchaudhari/yii2-currency-converter "2.0"
php composer.phar require --prefer-dist imanilchaudhari/yii2-currency-converter "3.0"
```

or add

```
"imanilchaudhari/yii2-currency-converter": "2.0"
"imanilchaudhari/yii2-currency-converter": "3.0"
```

to the require section of your `composer.json` file.
Expand All @@ -57,63 +45,64 @@ Usage
-----

Once the extension is installed, simply use it in your code by :
```php
'components' => [
'currencyConverter' => [
'class' => 'imanilchaudhari\CurrencyConverter\CurrencyConverter',
'provider' => [
'class' => 'imanilchaudhari\CurrencyConverter\Provider\ExchangeRatesApi',
],
],
...
],

$converter = Yii::$app->currencyConverter;
$rate = $converter->convert('USD', 'NPR');

```

***OR***

```php
use Yii;
use imanilchaudhari\CurrencyConverter\CurrencyConverter;
use imanilchaudhari\CurrencyConverter\Provider\OpenExchangeRatesApi;

$converter = new CurrencyConverter();
$converter = new CurrencyConverter([
'provider' => [
'class' => OpenExchangeRatesApi::class,
'appId' => Yii::$app->params['openExchangeRate']['appId'],
],
]);
$rate = $converter->convert('USD', 'NPR');

print_r($rate); // it will print current Nepalese currency (NPR) rate according to USD


```

Available Currency Codes
Exchange Rate Providers
-----------------------
```php
$currencies = [
'AF' => 'AFA',
'AL' => 'ALL',
'DZ' => 'DZD',
'AS' => 'USD',
'AD' => 'EUR',
...
];
- [ApiForexApi](./src/Provider/ApiForexApi.php) - Get exchange rates from https://api.forex/
- [CurrencyApi](./src/Provider/CurrencyApi.php) - Get exchange rates from https://currencyapi.com/
- [CurrencyFreaksApi](./src/Provider/CurrencyFreaksApi.php) - Get exchange rates from https://currencyfreaks.com/
- [CurrencylayerApi](./src/Provider/CurrencylayerApi.php) - Get exchange rates from https://currencylayer.com/
- [ExchangeRatesApi](./src/Provider/ExchangeRatesApi.php) - Get exchange rates from https://www.exchangerate-api.com/
- [FixerApi](./src/Provider/FixerApi.php) - Get exchange rates from https://fixer.io/
- [OpenExchangeRatesApi](./src/Provider/OpenExchangeRatesApi.php) - Get exchange rates from https://openexchangerates.org/

```

Note: to view all the applicable currencies [click here](https://github.com/imanilchaudhari/yii2-currency-converter/blob/1.1/CountryToCurrency.php).
## Testing

Contributors
-------
* [Robot72](https://github.com/Robot72 "Robot72")
* [chaimleich](https://github.com/chaimleich "chaimleich")
### Unit testing

Open Exchange Rates APi Integration
-----------------------------------
Here is a code snippets suggested by [chaimleich](https://github.com/chaimleich) on [this pull request](https://github.com/imanilchaudhari/yii2-currency-converter/pull/3).
```php
The package is tested with [PHPUnit](https://phpunit.de/). To run tests:

use Yii;
use imanilchaudhari\CurrencyConverter\Provider\OpenExchangeRatesApi;

class CurrencyConverter extends \imanilchaudhari\CurrencyConverter\CurrencyConverter
{
/**
* @inheritdoc
*/
public function getRateProvider()
{
if (!$this->rateProvider) {
$this->setRateProvider(new OpenExchangeRatesApi([
'appId' => Yii::$app->params['openExchangeRate']['appId'],
]));
}

return $this->rateProvider;
}
}
```shell
./vendor/bin/phpunit
```

## License

The Yii2 Currency Converter is free software. It is released under the terms of the MIT License. Please see [`LICENSE`](./LICENSE.md) for more information.


[![Powered by](https://img.shields.io/badge/Powered_by-Yii_Framework-green.svg?style=flat)](https://www.yiiframework.com/)
7 changes: 1 addition & 6 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,8 @@
"yiisoft/yii2-httpclient": "^2.0"
},
"require-dev": {
"maglnet/composer-require-checker": "^3.8",
"phpunit/phpunit": "^8.5",
"rector/rector": "^1.0",
"spatie/phpunit-watcher": "^1.23",
"vimeo/psalm": "^4.30"
"rector/rector": "^1.0"
},
"autoload": {
"psr-4": {
Expand All @@ -47,8 +44,6 @@
"config": {
"sort-packages": true,
"allow-plugins": {
"infection/extension-installer": true,
"composer/package-versions-deprecated": true,
"yiisoft/yii2-composer": true
}
},
Expand Down
56 changes: 48 additions & 8 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,51 @@

This package provides the most famous currency rates providers' implementations. The package was originally built on Yahoo API, but there was a discontinuation of it. It is therefore highly recommended that you make use of only active providers, such as the ones listed below.

### Active Provider
- [ApiForex API](ApiForexApi.md)
- [Currency API](CurrencyApi.md)
- [CurrencyFreaks API](CurrencyFreaksApi.md)
- [Currency Layer API](CurrencylayerApi.md)
- [Exchange Rates API](ExchangeRatesApi.md)
- [Fixer API](FixerApi.md)
- [Open Exchange Rates API](OpenExchangeRatesApi.md)
Usage
-----

Once the extension is installed, simply use it in your code by :
```php
'components' => [
'currencyConverter' => [
'class' => 'imanilchaudhari\CurrencyConverter\CurrencyConverter',
'provider' => [
'class' => 'imanilchaudhari\CurrencyConverter\Provider\ExchangeRatesApi',
],
],
...
],

$converter = Yii::$app->currencyConverter;
$rate = $converter->convert('USD', 'NPR');

```

***OR***

```php
use imanilchaudhari\CurrencyConverter\CurrencyConverter;
use imanilchaudhari\CurrencyConverter\Provider\OpenExchangeRatesApi;

$converter = new CurrencyConverter([
'provider' => [
'class' => OpenExchangeRatesApi::class,
'appId' => Yii::$app->params['openExchangeRate']['appId'],
],
]);
$rate = $converter->convert('USD', 'NPR');

print_r($rate); // it will print current Nepalese currency (NPR) rate according to USD

```

Active Providers
-----------------------
- [ApiForex API](ApiForexApi.md) - Get exchange rates from https://api.forex/
- [Currency API](CurrencyApi.md) - Get exchange rates from https://currencyapi.com/
- [CurrencyFreaks API](CurrencyFreaksApi.md) - Get exchange rates from https://currencyfreaks.com/
- [Currency Layer API](CurrencylayerApi.md) - Get exchange rates from https://currencylayer.com/
- [Exchange Rates API](ExchangeRatesApi.md) - Get exchange rates from https://www.exchangerate-api.com/
- [Fixer API](FixerApi.md) - Get exchange rates from https://fixer.io/
- [Open Exchange Rates API](OpenExchangeRatesApi.md) - Get exchange rates from https://openexchangerates.org/

36 changes: 13 additions & 23 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,28 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheDirectory=".phpunit.cache"
requireCoverageMetadata="false"
beStrictAboutCoverageMetadata="true"
beStrictAboutOutputDuringTests="true"
executionOrder="random"
failOnRisky="true"
failOnWarning="true"
stopOnFailure="false"
colors="true"
>
<php>
<ini name="error_reporting" value="-1"/>
</php>
<phpunit bootstrap="./tests/bootstrap.php"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
<testsuites>
<testsuite name="Test Suite">
<directory>./tests</directory>
</testsuite>
</testsuites>

<testsuites>
<testsuite name="Yii2 Currency Converter Tests">
<directory>./tests</directory>
</testsuite>
</testsuites>

<source>
<source>
<include>
<directory suffix=".php">./src</directory>
</include>
Expand Down
19 changes: 0 additions & 19 deletions psalm.xml

This file was deleted.

File renamed without changes.
38 changes: 16 additions & 22 deletions src/CurrencyConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,13 @@ class CurrencyConverter extends Component implements RateConverterInterface
{
/**
* Cache duration
*
* @var int $duration
*/
public $duration = 3600;

/**
* @var array request object configuration.
* @var array object configuration.
*/
public $provider = [
'class' => 'imanilchaudhari\CurrencyConverter\Provider\ExchangeRatesApi'
Expand All @@ -62,8 +64,8 @@ public function convert($source, $target, $amount = 1)
{
$cache = Yii::$app->cache;

$sourceCurrency = $this->parseCurrencyArgument($source);
$targetCurrency = $this->parseCurrencyArgument($target);
$sourceCurrency = is_array($source) ? $this->parseCurrencyArgument($source) : $source;
$targetCurrency = is_array($source) ? $this->parseCurrencyArgument($target) : $target;

if ($cache) {
if ($rate = $cache->get($sourceCurrency . '_ ' . $targetCurrency . '_cache')) {
Expand All @@ -89,11 +91,10 @@ public function convert($source, $target, $amount = 1)
*/
public function getRateProvider()
{
if (!is_object($this->_provider)) {
$this->setRateProvider($this->provider);
if ($this->_provider instanceof RateProviderInterface) {
return $this->_provider;
}

return $this->_provider;
return $this->setRateProvider($this->provider);
}

/**
Expand All @@ -104,31 +105,24 @@ public function getRateProvider()
*/
protected function setRateProvider($config)
{
$this->_provider = Yii::createObject($config);
return $this;
return $this->_provider = Yii::createObject($config);
}

/**
* Parses the Currency Arguments
*
* @param string|array $data
* @param array $data
* @return string
* @throws InvalidArgumentException
*/
protected function parseCurrencyArgument($data)
{
if (is_string($data)) {
$currency = $data;
} elseif (is_array($data)) {
if (isset($data['country'])) {
$currency = $this->getCurrencyCode($data['country']);
} elseif (isset($data['currency'])) {
$currency = $data['currency'];
} else {
throw new InvalidArgumentException('Please provide country or currency!');
}
if (isset($data['country'])) {
$currency = $this->getCurrencyCode($data['country']);
} elseif (isset($data['currency'])) {
$currency = $data['currency'];
} else {
throw new InvalidArgumentException('Invalid currency provided. String or array expected.');
throw new InvalidArgumentException('Please provide country or currency!');
}

return $currency;
Expand All @@ -143,7 +137,7 @@ protected function parseCurrencyArgument($data)
*/
protected function getCurrencyCode($countryCode)
{
$currencies = Json::decode([file_get_contents(__DIR__ . '/resource/codes.json')], true);
$currencies = Json::decode(file_get_contents(__DIR__ . '/resources/codes.json'), true);
if (!array_key_exists($countryCode, $currencies)) {
throw new InvalidArgumentException(sprintf('Unsupported country code, %s', $countryCode));
}
Expand Down
2 changes: 1 addition & 1 deletion src/Interface/RateConverterInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ interface RateConverterInterface
*
* @param array|string $source
* @param array|string $target
* @param float optional $amount
* @param int|float $amount
*
* @return float
*/
Expand Down
Loading

0 comments on commit 5050de9

Please sign in to comment.