Passed
Pull Request — master (#14)
by
unknown
02:33
created

CurrencyConverterHelper::getRateToUse()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 24
nc 8
nop 2
dl 0
loc 38
rs 8.4444
c 0
b 0
f 0
1
<?php
2
namespace CurrencyConverter\View\Helper;
3
4
use Cake\View\Helper;
5
use Cake\ORM\TableRegistry;
6
use Cake\I18n\Time;
7
8
/**
9
 * @property \Cake\View\Helper\HtmlHelper $Html
10
 * @property \Cake\View\Helper\FormHelper $Form
11
 * @property \Cake\View\Helper\NumberHelper $Number
12
 */
13
class CurrencyConverterHelper extends Helper
14
{
15
    /**
16
     * Using database
17
     *
18
     * @var bool
19
     */
20
    public $database;
21
22
    /**
23
     * Time interval for refreshing database
24
     *
25
     * @var int
26
     */
27
    public $refresh;
28
29
    /**
30
     * Number of decimal to use for formatting converted price
31
     *
32
     * @var int
33
     */
34
    public $decimal;
35
36
    /**
37
     * CurrencyratesTable Class
38
     * @var \Cake\ORM\Table
39
     */
40
    private $_currencyratesTable;
41
42
    /**
43
     * Default settings
44
     *
45
     * @var array
46
     */
47
    protected $_defaultConfig = [
48
        'database' => 2, // Use database to store rate
49
        'refresh' => 24, // Time interval for refreshing rate in database
50
        'decimal' => 2, // Number of decimal to use for convert number
51
    ];
52
53
    /**
54
     * @param array $config
55
     * @return void
56
     */
57
    public function initialize(array $config = []) {
58
59
        $config = $this->getConfig();
60
61
        $this->database = $config['database'];
62
        $this->refresh = $config['refresh'];
63
        $this->decimal = $config['decimal'];
64
65
        $this->_currencyratesTable = TableRegistry::get('CurrencyConverter.Currencyrates');
0 ignored issues
show
Deprecated Code introduced by
The function Cake\ORM\TableRegistry::get() has been deprecated: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

65
        $this->_currencyratesTable = /** @scrutinizer ignore-deprecated */ TableRegistry::get('CurrencyConverter.Currencyrates');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
66
    }
67
68
    /**
69
     * Convert method take an amount as first parameter and convert it using $from currency and $to currency.
70
     *
71
     * @param float|string $amount the amount to convert.
72
     * @param string $from currency to convert from
73
     * @param string $to currency to convert to
74
     * @return float $amount converted
75
     */
76
    public function convert($amount, $from, $to)
77
    {
78
        $amount = floatval($amount);
79
        $rate = $this->getRateToUse($from, $to);
80
81
        return $convert = $this->_formatConvert($rate * $amount);
0 ignored issues
show
Unused Code introduced by
The assignment to $convert is dead and can be removed.
Loading history...
82
    }
83
84
    /**
85
     * Rate method return the rate of two currencies
86
     *
87
     * @param string $from currency to get the rate from
88
     * @param string $to currency to get the rate to
89
     * @return float|null $rate
90
     */
91
    public function rate($from, $to)
92
    {
93
        return $this->getRateToUse($from, $to);
94
    }
95
96
    /**
97
     * getRateToUse return rate to use
98
     * Using $from and $to parameters representing currency to deal with and the configuration settings
99
     * This method save or update currencyrates Table if necesseray too.
100
     *
101
     * @param string $from currency to get the rate from
102
     * @param string $to currency to get the rate to
103
     * @return float|null $rate
104
     */
105
    public function getRateToUse($from, $to)
106
    {
107
        if ($from == $to) {
108
            return 1;
109
        } else {
110
            if ($this->database) {
111
                // Get a currency rate from table
112
                $result = $this->_currencyratesTable->find('all')->where(['from_currency' => $from, 'to_currency' => $to])->first();
113
                if ($result) {
114
                    // If currency rate is in table and it doesn't have to be updated
115
                    if ($result->get('modified')->wasWithinLast($this->refresh . ' hours')) {
116
                        return $rate = $result->get('rate');
0 ignored issues
show
Unused Code introduced by
The assignment to $rate is dead and can be removed.
Loading history...
117
                    } else {
118
                        $rate = $this->_getRateFromAPI($from, $to);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $rate is correct as $this->_getRateFromAPI($from, $to) targeting CurrencyConverter\View\H...lper::_getRateFromAPI() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
119
                        if ($rate) {
0 ignored issues
show
introduced by
$rate is of type null, thus it always evaluated to false.
Loading history...
120
                            $result->rate = $rate;
121
                            $this->_currencyratesTable->save($result);
122
                        }
123
                        return $rate;
124
                    }
125
                }
126
                // If currency rate isn't in table
127
                if (!$result) {
128
                    $rate = $this->_getRateFromAPI($from, $to);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $rate is correct as $this->_getRateFromAPI($from, $to) targeting CurrencyConverter\View\H...lper::_getRateFromAPI() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
129
                    if ($rate) {
0 ignored issues
show
introduced by
$rate is of type null, thus it always evaluated to false.
Loading history...
130
                        $entity = $this->_currencyratesTable->newEntity([
131
                            'from_currency' => $from,
132
                            'to_currency' => $to,
133
                            'rate' => $rate
134
                        ]);
135
                        $this->_currencyratesTable->save($entity);
136
                    }
137
                    return $rate;
138
                }
139
            }
140
        }
141
        
142
        return $this->_getRateFromAPI($from, $to);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->_getRateFromAPI($from, $to) targeting CurrencyConverter\View\H...lper::_getRateFromAPI() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
143
    }
144
145
    /**
146
     * Format number using configuration
147
     *
148
     * @param float price to format
0 ignored issues
show
Bug introduced by
The type CurrencyConverter\View\Helper\price was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
149
     * @return float
150
     */
151
    private function _formatConvert($number)
152
    {
153
        return floatval(number_format($number, $this->decimal));
154
    }
155
156
    /**
157
     * Call free.currencyconverterapi.com API to get a rate for one currency to an other one currency
158
     *
159
     * @param string $from the currency
160
     * @param string $to the currency
161
     * @return int|null $rate
162
     */
163
    private function _getRateFromAPI($from, $to)
164
    {
165
        $rate = null;
166
167
        $url = 'https://free.currencyconverterapi.com/api/v5/convert?q=' . $from . '_' . $to . '&compact=ultra';
168
        $request = @fopen($url, 'r');
169
170
        if ($request) {
0 ignored issues
show
introduced by
$request is of type false|resource, thus it always evaluated to false.
Loading history...
171
            $response = fgets($request, 4096);
172
            fclose($request);
173
174
            $response = json_decode($response, true);
175
            if (isset($response[$from . '_' . $to])) {
176
                $rate = $response[$from . '_' . $to];
177
            }
178
        }
179
        
180
        return $rate;
181
    }
182
}
183