Test Failed
Pull Request — master (#14)
by
unknown
02:40
created

CurrencyConverterHelper::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace CurrencyConverter\View\Helper;
4
5
use Cake\View\Helper;
6
use Cake\ORM\TableRegistry;
7
use Cake\I18n\Time;
8
9
/**
10
 * @property \Cake\View\Helper\HtmlHelper $Html
11
 * @property \Cake\View\Helper\FormHelper $Form
12
 * @property \Cake\View\Helper\NumberHelper $Number
13
 */
14
class CurrencyConverterHelper extends Helper
15
{
16
    /**
17
     * CurrencyratesTable Object
18
     * @var \Cake\ORM\Table
19
     */
20
    private $_currencyratesTable;
21
22
    /**
23
     * Default settings
24
     *
25
     * @var array
26
     */
27
    protected $_defaultConfig = [
28
        'database' => 2, // Use database to store rate
29
        'refresh' => 24, // Time interval for refreshing rate in database
30
        'decimal' => 2, // Number of decimal to use for convert number
31
    ];
32
33
    /**
34
     * @param array $config
35
     * @return void
36
     */
37
    public function initialize(array $config = []) {
38
39
        $config = $this->getConfig();
40
41
        $this->database = $config['database'];
0 ignored issues
show
Bug Best Practice introduced by
The property database does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
42
        $this->refresh = $config['refresh'];
0 ignored issues
show
Bug Best Practice introduced by
The property refresh does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
43
        $this->decimal = $config['decimal'];
0 ignored issues
show
Bug Best Practice introduced by
The property decimal does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
44
45
        $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

45
        $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...
46
    }
47
48
    /**
49
     * Convert method take an amount as first parameter and convert it using $from currency and $to currency.
50
     *
51
     * @param float|string $amount the amount to convert.
52
     * @param string $from currency to convert from
53
     * @param string $to currency to convert to
54
     * @return float $amount converted
55
     */
56
    public function convert($amount, $from, $to)
57
    {
58
        $amount = floatval($amount);
59
        $rate = $this->getRateToUse($from, $to);
60
61
        return $convert = $this->_formatConvert($rate * $amount);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $convert = $this-...onvert($rate * $amount) returns the type CurrencyConverter\View\Helper\floatval which is incompatible with the documented return type double.
Loading history...
Unused Code introduced by
The assignment to $convert is dead and can be removed.
Loading history...
62
    }
63
64
    /**
65
     * Rate method return the rate of two currencies
66
     *
67
     * @param string $from currency to get the rate from
68
     * @param string $to currency to get the rate to
69
     * @return float|null $rate
70
     */
71
    public function rate($from, $to)
72
    {
73
        return $this->getRateToUse($from, $to);
74
    }
75
76
    /**
77
     * getRateToUse return rate to use
78
     * Using $from and $to parameters representing currency to deal with and the configuration settings
79
     * This method save or update currencyrates Table if necesseray too.
80
     *
81
     * @param string $from currency to get the rate from
82
     * @param string $to currency to get the rate to
83
     * @return float|null $rate
84
     */
85
    public function getRateToUse($from, $to)
86
    {
87
        if ($from == $to) return 1;
88
        if ($this->database) {
89
            // Get a currency rate from table
90
            $result = $this->_currencyratesTable->find('all')->where(['from_currency' => $from, 'to_currency' => $to])->first();
91
            // If currency rate is in table and it doesn't have to be updated
92
            if ($result && $result->modified->wasWithinLast($this->refresh . ' hours')) return $rate = $result->rate;
0 ignored issues
show
Bug introduced by
Accessing rate on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
Accessing modified on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Unused Code introduced by
The assignment to $rate is dead and can be removed.
Loading history...
93
            // If currency rate is in table and it have to be updated
94
            if ($result && !$result->modified->wasWithinLast($this->refresh . ' hours')) {
95
                if ($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...
96
                    $result->rate = $rate;
97
                    $this->_currencyratesTable->save($result);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type array; however, parameter $entity of Cake\ORM\Table::save() does only seem to accept Cake\Datasource\EntityInterface, maybe add an additional type check? ( Ignorable by Annotation )

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

97
                    $this->_currencyratesTable->save(/** @scrutinizer ignore-type */ $result);
Loading history...
98
                }
99
                return $rate;
100
            }
101
            // If currency rate isn't in table
102
            if (!$result) {
103
                if ($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...
104
                    $entity = $this->_currencyratesTable->newEntity([
105
                        'from_currency' => $from,
106
                        'to_currency' => $to,
107
                        'rate' => $rate
108
                    ]);
109
                    $this->_currencyratesTable->save($entity);
110
                }
111
                return $rate;
112
            }
113
        }
114
115
        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...
116
    }
117
118
    /**
119
     * Format float number using configuration
120
     *
121
     * @return floatval
0 ignored issues
show
Bug introduced by
The type CurrencyConverter\View\Helper\floatval 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...
122
     */
123
    private function _formatConvert($number)
124
    {
125
        return number_format($number, $this->decimal);
0 ignored issues
show
Bug Best Practice introduced by
The expression return number_format($number, $this->decimal) returns the type string which is incompatible with the documented return type CurrencyConverter\View\Helper\floatval.
Loading history...
126
    }
127
128
    /**
129
     * Call free.currencyconverterapi.com API to get a rate for one currency to an other one currency
130
     *
131
     * @param string $from the currency
132
     * @param string $to the currency
133
     * @return int|null $rate
134
     */
135
    private function _getRateFromAPI($from, $to)
136
    {
137
        $rate = null;
138
139
        $url = 'https://free.currencyconverterapi.com/api/v5/convert?q=' . $from . '_' . $to . '&compact=ultra';
140
        $request = @fopen($url, 'r');
141
142
        if ($request) {
0 ignored issues
show
introduced by
$request is of type false|resource, thus it always evaluated to false.
Loading history...
143
            $response = fgets($request, 4096);
144
            fclose($request);
145
146
            $response = json_decode($response, true);
147
            if (isset($response[$from . '_' . $to])) {
148
                $rate = $response[$from . '_' . $to];
149
            }
150
        }
151
        
152
        return $rate;
153
    }
154
}