Completed
Push — master ( b14a13...f7bdb9 )
by Andrii
26:35 queued 11:41
created

Price::isServer95Traf()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Finance module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-finance
6
 * @package   hipanel-module-finance
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\finance\models;
12
13
use hipanel\base\Model;
14
use hipanel\base\ModelTrait;
15
use hipanel\models\Ref;
16
use hipanel\modules\finance\models\factories\PriceModelFactory;
17
use Money\Money;
18
use Money\MoneyParser;
19
use Yii;
20
use yii\helpers\Inflector;
21
use yii\helpers\StringHelper;
22
23
/**
24
 * Class Price.
25
 *
26
 * @property int $id
27
 * @property int $plan_id
28
 * @property string|int $object_id
29
 * @property string|float $price
30
 * @property string $currency
31
 * @property string|int $main_object_id
32
 * @property string $main_object_name
33
 * @property string $unit
34
 * @property string $type
35
 * @property string $quantity
36
 * @property string $formula
37
 * @property int|null parent_id
38
 *
39
 * @property TargetObject $object
40
 * @property Plan $plan
41
 *
42
 * @author Dmytro Naumenko <[email protected]>
43
 */
44
class Price extends Model
45
{
46
    use ModelTrait;
47
48
    const SCENARIO_CREATE = 'create';
49
    const SCENARIO_UPDATE = 'update';
50
    const SCENARIO_DELETE = 'delete';
51
52
    public function rules()
53
    {
54
        return array_merge(parent::rules(), [
55
            [['id', 'parent_id', 'plan_id', 'object_id', 'type_id', 'unit_id', 'currency_id', 'main_object_id'], 'integer'],
56
            [['type', 'type_label', 'plan_name', 'unit', 'currency', 'note', 'data', 'main_object_name'], 'string'],
57
            [['quantity', 'price'], 'number'],
58
            [['class'], 'string'], // todo: probably, refactor is needed
59
60
            [['plan_id', 'type', 'price', 'currency'], 'required', 'on' => ['create', 'update']],
61
            [['id'], 'required', 'on' => ['update', 'set-note', 'delete']],
62
            [['class'], 'default', 'value' => function ($model) {
0 ignored issues
show
Unused Code introduced by
The parameter $model is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
63
                return (new \ReflectionClass($this))->getShortName();
64
            }],
65
            [['class'], 'string'],
66
            [['formula'], 'string', 'on' => ['create', 'update']], // TODO syn check
67
        ]);
68
    }
69
70
    public function attributeLabels()
71
    {
72
        return [
73
            'plan_id' => Yii::t('hipanel:finance', 'Tariff plan'),
74
            'plan' => Yii::t('hipanel:finance', 'Tariff plan'),
75
            'quantity' => Yii::t('hipanel:finance', 'Prepaid'),
76
            'unit' => Yii::t('hipanel:finance', 'Unit'),
77
            'price' => Yii::t('hipanel:finance', 'Price'),
78
            'formula' => Yii::t('hipanel.finance.price', 'Formula'),
79
            'note' => Yii::t('hipanel', 'Note'),
80
            'type' => Yii::t('hipanel', 'Type'),
81
        ];
82
    }
83
84
    public function getTypeOptions()
85
    {
86
        return Ref::getList('type,bill', null, [
87
            'select' => 'name',
88
            'pnames' => 'monthly,overuse',
89
            'with_recursive' => 1,
90
        ]);
91
    }
92
93
    /**
94
     * Returns array of unit option, that are available for this price
95
     * depending on price type.
96
     *
97
     * @return array
98
     */
99
    public function getUnitOptions()
100
    {
101
        $unitGroup = [
102
            'hour'  => ['hour'],
103
            'items' => ['items'],
104
            'speed' => ['bps', 'kbps', 'mbps', 'gbps', 'tbps'],
105
            'size'  => ['mb', 'mb10', 'mb100', 'gb', 'tb'],
106
        ];
107
108
        $type2group = [
109
            'overuse,ip_num'            => 'items',
110
            'overuse,support_time'      => 'hour',
111
            'overuse,backup_du'         => 'size',
112
            'overuse,server_traf_max'   => 'size',
113
            'overuse,server_traf95_max' => 'speed',
114
            'overuse,cdn_traf_max'      => 'size',
115
            'overuse,cdn_traf95_max'    => 'speed',
116
            'overuse,cdn_cache'         => 'size',
117
            'overuse,storage_du'        => 'size',
118
            'overuse,server_du'         => 'size',
119
            'overuse,server_ssd'        => 'size',
120
            'overuse,server_sata'       => 'size',
121
            'overuse,backup_traf'       => 'size',
122
            'overuse,domain_traf'       => 'size',
123
            'overuse,domain_num'        => 'items',
124
            'overuse,ip_traf_max'       => 'size',
125
            'overuse,account_traf'      => 'size',
126
            'overuse,account_du'        => 'size',
127
            'overuse,mail_num'          => 'items',
128
            'overuse,mail_du'           => 'size',
129
            'overuse,db_num'            => 'items',
130
        ];
131
132
        foreach ($type2group as $type => $group) {
133
            $availableUnitsByPriceType[$type] = $unitGroup[$group];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$availableUnitsByPriceType was never initialized. Although not strictly required by PHP, it is generally a good practice to add $availableUnitsByPriceType = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
134
        }
135
136
        $units = Ref::getList('type,unit', 'hipanel.finance.units', [
137
            'with_recursive' => 1,
138
            'select' => 'oname_label',
139
            'mapOptions' => ['from' => 'oname'],
140
        ]);
141
142
        $possibleTypes = $availableUnitsByPriceType[$this->type] ?? [];
143
144
        return array_intersect_key($units, array_combine($possibleTypes, $possibleTypes));
145
    }
146
147
    /**
148
     * Method checks, whether current price quantity is predefined and is not a result
149
     * of sophisticated calculation on server side.
150
     * @return bool
151
     */
152
    public function isQuantityPredefined(): bool
153
    {
154
        if (!$this->isOveruse()
155
            && ($this->isShared() || $this->getSubtype() === 'rack_unit')
156
        ) {
157
            return false;
158
        }
159
160
        return true;
161
    }
162
163
    /**
164
     * @return bool Whether this price is shared
165
     */
166
    public function isShared(): bool
167
    {
168
        return $this->object_id === null;
169
    }
170
171
    public function getUnitLabel()
172
    {
173
        return $this->getUnitOptions()[$this->unit] ?? null;
174
    }
175
176
    public function getCurrencyOptions()
177
    {
178
        return Ref::getList('type,currency');
179
    }
180
181
    public function getObject()
182
    {
183
        return $this->hasOne(TargetObject::class, ['id' => 'id']);
184
    }
185
186
    public function getPlan()
187
    {
188
        return $this->hasOne(Plan::class, ['id' => 'plan_id']);
189
    }
190
191
    public static function tableName()
192
    {
193
        return Inflector::camel2id(StringHelper::basename(__CLASS__), '-');
194
    }
195
196
    public function isOveruse()
197
    {
198
        return strpos($this->type, 'overuse,') === 0;
199
    }
200
201
    public function isServer95Traf()
202
    {
203
        return false;
204
    }
205
206
    public function getSubtype()
207
    {
208
        [, $subtype] = explode(',', $this->type);
0 ignored issues
show
Bug introduced by
The variable $subtype does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
209
210
        return $subtype;
211
    }
212
213
    /**
214
     * {@inheritdoc}
215
     */
216
    public static function instantiate($row)
217
    {
218
        /** @var PriceModelFactory $factory */
219
        $factory = Yii::$container->get(PriceModelFactory::class);
220
221
        return $factory->build($row['class'] ?? 'SinglePrice', $row['type']);
222
    }
223
224
    public function formulaLines(): array
225
    {
226
        if (strlen($this->formula) === 0) {
227
            return [];
228
        }
229
230
        return explode("\n", $this->formula);
231
    }
232
233
    public function getMoney(): Money
234
    {
235
        // TODO: decide how to get MoneyParser correctly
236
        return Yii::$container->get(MoneyParser::class)
237
            ->parse((string)$this->price, strtoupper($this->currency));
238
    }
239
}
240