GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 9fb71b...daa624 )
by Ivan
12:22
created

Currency   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 297
Duplicated Lines 16.16 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 29
c 1
b 0
f 0
lcom 1
cbo 9
dl 48
loc 297
rs 10

13 Methods

Rating   Name   Duplication   Size   Complexity  
A tableName() 0 4 1
A rules() 0 8 1
A attributeLabels() 0 21 1
A behaviors() 0 8 1
B findById() 24 24 4
B getMainCurrency() 0 28 4
A getRateProvider() 0 4 1
B getSelection() 0 29 3
B search() 24 24 2
A getFormatter() 0 16 2
A format() 0 9 2
B getByName() 0 33 5
A getIsoCodes() 0 14 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace app\modules\shop\models;
4
5
use app\modules\shop\models\CurrencyRateProvider;
6
use app\modules\shop\components\SpecialPriceProductInterface;
7
use devgroup\TagDependencyHelper\ActiveRecordHelper;
8
use Yii;
9
use yii\base\InvalidConfigException;
10
use yii\caching\TagDependency;
11
use yii\helpers\ArrayHelper;
12
use yii\data\ActiveDataProvider;
13
14
/**
15
 * This is the model class Multi-currency
16
 *
17
 * @property integer $id
18
 * @property string $name
19
 * @property string $iso_code
20
 * @property integer $is_main
21
 * @property double $convert_nominal
22
 * @property double $convert_rate
23
 * @property integer $sort_order
24
 * @property integer $intl_formatting
25
 * @property integer $min_fraction_digits
26
 * @property integer $max_fraction_digits
27
 * @property string $dec_point
28
 * @property string $thousands_sep
29
 * @property string $format_string
30
 * @property double $additional_rate
31
 * @property double $additional_nominal
32
 * @property integer $currency_rate_provider_id
33
 */
34
class Currency extends \yii\db\ActiveRecord
35
{
36
    private static $mainCurrency = null;
37
    private static $selection = null;
38
    private static $identity_map = [];
39
    private $formatter = null;
40
41
    /**
42
     * @inheritdoc
43
     */
44
    public static function tableName()
45
    {
46
        return '{{%currency}}';
47
    }
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public function rules()
53
    {
54
        return [
55
            [['is_main', 'sort_order', 'intl_formatting', 'min_fraction_digits', 'max_fraction_digits', 'currency_rate_provider_id'], 'integer'],
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 145 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
56
            [['convert_nominal', 'convert_rate', 'additional_rate', 'additional_nominal'], 'number'],
57
            [['name', 'iso_code', 'dec_point', 'thousands_sep', 'format_string'], 'string', 'max' => 255]
58
        ];
59
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64
    public function attributeLabels()
65
    {
66
        return [
67
            'id' => Yii::t('app', 'ID'),
68
            'name' => Yii::t('app', 'Name'),
69
            'iso_code' => Yii::t('app', 'ISO-4217 code'),
70
            'is_main' => Yii::t('app', 'Is main currency'),
71
            'convert_nominal' => Yii::t('app', 'Convert nominal'),
72
            'convert_rate' => Yii::t('app', 'Convert rate'),
73
            'sort_order' => Yii::t('app', 'Sort Order'),
74
            'intl_formatting' => Yii::t('app', 'Intl formatting with ICU'),
75
            'min_fraction_digits' => Yii::t('app', 'Min fraction digits'),
76
            'max_fraction_digits' => Yii::t('app', 'Max fraction digits'),
77
            'dec_point' => Yii::t('app', 'Decimal point'),
78
            'thousands_sep' => Yii::t('app', 'Thousands separator'),
79
            'format_string' => Yii::t('app', 'Format string'),
80
            'additional_rate' => Yii::t('app', 'Additional rate'),
81
            'additional_nominal' => Yii::t('app', 'Additional nominal'),
82
            'currency_rate_provider_id' => Yii::t('app', 'Currency rate provider'),
83
        ];
84
    }
85
86
    /**
87
     * @inheritdoc
88
     */
89
    public function behaviors()
90
    {
91
        return [
92
            [
93
                'class' => \devgroup\TagDependencyHelper\ActiveRecordHelper::className(),
94
            ],
95
        ];
96
    }
97
98
    /**
99
     * Returns model instance by ID using IdentityMap
100
     * @param integer $id
101
     * @return Currency
102
     */
103 View Code Duplication
    public static function findById($id)
104
    {
105
        if (!isset(static::$identity_map[$id])) {
106
            static::$identity_map[$id] = Yii::$app->cache->get('Currency: ' . $id);
107
            if (static::$identity_map[$id] === false) {
108
                static::$identity_map[$id] = Currency::findOne($id);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
109
                if (is_object(static::$identity_map[$id])) {
110
                    Yii::$app->cache->set(
111
                        'Currency: ' . $id,
112
                        static::$identity_map[$id],
113
                        86400,
114
                        new TagDependency(
115
                            [
116
                                'tags' => [
117
                                    \devgroup\TagDependencyHelper\ActiveRecordHelper::getObjectTag(Currency::className(), $id),
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
118
                                ],
119
                            ]
120
                        )
121
                    );
122
                }
123
            }
124
        }
125
        return static::$identity_map[$id];
126
    }
127
128
129
    /**
130
     * Returns main currency object for this shop with static-cache
131
     *
132
     * @return Currency Main currency object
133
     */
134
    public static function getMainCurrency()
135
    {
136
        if (static::$mainCurrency === null) {
137
            static::$mainCurrency = Yii::$app->cache->get("MainCurrency");
138
            if (static::$mainCurrency === false) {
139
                static::$mainCurrency = Currency::find()
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
140
                    ->where(['is_main' => 1])
141
                    ->one();
142
                if (static::$mainCurrency !== null) {
143
                    static::$identity_map[static::$mainCurrency->id] = static::$mainCurrency;
144
                }
145
                Yii::$app->cache->set(
146
                    "MainCurrency",
147
                    static::$mainCurrency,
148
                    604800,
149
                    new TagDependency(
150
                        [
151
                            'tags' => [
152
                                \devgroup\TagDependencyHelper\ActiveRecordHelper::getObjectTag(static::className(), static::$mainCurrency->id),
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 143 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
153
                            ],
154
                        ]
155
                    )
156
                );
157
            }
158
        }
159
160
        return static::$mainCurrency;
161
    }
162
163
    /**
164
     * Relation to CurrencyRateProvider model
165
     * @return \yii\db\ActiveQuery
166
     */
167
    public function getRateProvider()
168
    {
169
        return $this->hasOne(CurrencyRateProvider::className(), ['id' => 'currency_rate_provider_id']);
170
    }
171
172
    /**
173
     * Returns array(id=>name) of currencies for dropdown list
174
     * @return array
175
     * @throws InvalidConfigException
176
     */
177
    public static function getSelection()
178
    {
179
        if (static::$selection === null) {
180
            static::$selection = Yii::$app->cache->get('AllCurrenciesSelection');
181
            if (static::$selection === false) {
182
183
                $rows = Currency::find()
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
184
                    ->select(['id', 'name'])
185
                    ->orderBy(['is_main'=>SORT_DESC, 'sort_order' => SORT_ASC])
186
                    ->asArray()
187
                    ->all();
188
                static::$selection = ArrayHelper::map($rows, 'id', 'name');
189
190
                Yii::$app->cache->set(
191
                    "AllCurrenciesSelection",
192
                    static::$selection,
193
                    604800,
194
                    new TagDependency(
195
                        [
196
                            'tags' => [
197
                                \devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(static::className()),
198
                            ],
199
                        ]
200
                    )
201
                );
202
            }
203
        }
204
        return static::$selection;
205
    }
206
207
    /**
208
     * Search tasks
209
     * @param $params
210
     * @return ActiveDataProvider
211
     */
212 View Code Duplication
    public function search($params)
213
    {
214
        /* @var $query \yii\db\ActiveQuery */
215
        $query = self::find();
216
        $dataProvider = new ActiveDataProvider(
217
            [
218
                'query' => $query,
219
                'pagination' => [
220
                    'pageSize' => 10,
221
                ],
222
            ]
223
        );
224
        if (!($this->load($params))) {
225
            return $dataProvider;
226
        }
227
        $query->andFilterWhere(['id' => $this->id]);
228
        $query->andFilterWhere(['like', 'name', $this->name]);
229
        $query->andFilterWhere(['like', 'iso_code', $this->iso_code]);
230
        $query->andFilterWhere(['is_main' => $this->is_main]);
231
        $query->andFilterWhere(['currency_rate_provider_id' => $this->currency_rate_provider_id]);
232
233
234
        return $dataProvider;
235
    }
236
237
    /**
238
     * Returns \yii\i18n\Formatter instance for current Currency instance
239
     * @return \yii\i18n\Formatter
240
     * @throws InvalidConfigException
241
     */
242
    private function getFormatter()
243
    {
244
        if ($this->formatter === null) {
245
            $this->formatter = Yii::createObject([
246
                'class' => '\yii\i18n\Formatter',
247
                'currencyCode' => $this->iso_code,
248
                'decimalSeparator' => $this->dec_point,
249
                'thousandSeparator' => $this->thousands_sep,
250
                'numberFormatterOptions' => [
251
                    7 => $this->min_fraction_digits, // min
252
                    6 => $this->max_fraction_digits, // max
253
                ]
254
            ]);
255
        }
256
        return $this->formatter;
257
    }
258
259
    /**
260
     * Formats price with current currency settings
261
     * @param $price
262
     * @return string
263
     */
264
    public function format($price)
265
    {
266
        if ($this->intl_formatting === 1) {
267
            return $this->getFormatter()->asCurrency($price);
268
        } else {
269
            $number_value = $this->getFormatter()->asDecimal($price);
270
            return strtr($this->format_string, ['#'=>$number_value]);
271
        }
272
    }
273
274
    /**
275
     * Returns Currency instance by name
276
     * @param $name
277
     * @return array|mixed|null|\yii\db\ActiveRecord
278
     */
279
    public static function getByName($name)
280
    {
281
        // first search in identity map
282
        foreach (static::$identity_map as $id => $currency) {
283
            if ($currency->name === $name) {
284
                return $currency;
285
            }
286
        }
287
        // if not - find in db
288
        $currency = Yii::$app->cache->get('Currency:name:'.$name);
289
        if ($currency === false) {
290
            $currency = Currency::find()
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
291
                ->where(['name' => $name])
292
                ->one();
293
            Yii::$app->cache->set(
294
                'Currency:name:'.$name,
295
                $currency,
296
                86400,
297
                new TagDependency(
298
                    [
299
                        'tags' => [
300
                            \devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag(static::className()),
301
                        ],
302
                    ]
303
                )
304
            );
305
        }
306
        if ($currency !== null) {
307
            // put to identity map
308
            static::$identity_map[$currency->id] = $currency;
309
        }
310
        return $currency;
311
    }
312
313
    /**
314
     * @return array all ISO codes from DB
315
     */
316
    public static function getIsoCodes()
317
    {
318
        $column = Yii::$app->cache->get('ISO:column');
319
        if ($column === false) {
320
            $column = array_column(static::find()->select(['iso_code'])->asArray()->all(), 'iso_code');
321
            Yii::$app->cache->set(
322
                'ISO:column',
323
                $column,
324
                86400,
325
                new TagDependency(['tags' => [ActiveRecordHelper::getCommonTag(static::className())]])
326
            );
327
        }
328
        return $column;
329
    }
330
}
331