Completed
Push — master ( 19a19a...cc44b4 )
by Dmitry
13:35
created

Price::isShared()   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
namespace hipanel\modules\finance\models;
4
5
use Yii;
6
use yii\helpers\Inflector;
7
use yii\helpers\StringHelper;
8
use hipanel\models\Ref;
9
use hipanel\modules\finance\models\factories\PriceModelFactory;
10
11
/**
12
 * Class Price
13
 *
14
 * @property int $id
15
 * @property int $plan_id
16
 * @property string|int $object_id
17
 * @property string|float $price
18
 * @property string $currency
19
 * @property string|int $main_object_id
20
 * @property string $main_object_name
21
 * @property string $unit
22
 * @property string $type
23
 * @property string $quantity
24
 * @property string $formula
25
 *
26
 * @property TargetObject $object
27
 * @property Plan $plan
28
 *
29
 * @author Dmytro Naumenko <[email protected]>
30
 */
31
class Price extends \hipanel\base\Model
32
{
33
    use \hipanel\base\ModelTrait;
34
35
    const SCENARIO_CREATE = 'create';
36
    const SCENARIO_UPDATE = 'update';
37
    const SCENARIO_DELETE = 'delete';
38
39
    public function rules()
40
    {
41
        return array_merge(parent::rules(), [
42
            [['id', 'parent_id', 'plan_id', 'object_id', 'type_id', 'unit_id', 'currency_id', 'main_object_id'], 'integer'],
43
            [['type', 'plan_name', 'unit', 'currency', 'note', 'data', 'main_object_name'], 'string'],
44
            [['quantity', 'price'], 'number'],
45
            [['class'], 'string'], // todo: probably, refactor is needed
46
47
            [['plan_id', 'type', 'price', 'currency'], 'required', 'on' => ['create', 'update']],
48
            [['id'], 'required', 'on' => ['update', 'set-note', 'delete']],
49
            [['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...
50
                return (new \ReflectionClass($this))->getShortName();
51
            }],
52
            [['class'], 'string'],
53
            [['formula'], 'string', 'on' => ['create', 'update']] // TODO syn check
54
        ]);
55
    }
56
57
    public function attributeLabels()
58
    {
59
        return [
60
            'plan_id' => Yii::t('hipanel:finance', 'Tariff plan'),
61
            'plan' => Yii::t('hipanel:finance', 'Tariff plan'),
62
            'quantity' => Yii::t('hipanel:finance', 'Prepaid'),
63
            'unit' => Yii::t('hipanel:finance', 'Unit'),
64
            'price' => Yii::t('hipanel:finance', 'Price'),
65
            'formula' => Yii::t('hipanel.finance.price', 'Formula'),
66
            'note' => Yii::t('hipanel', 'Note'),
67
            'type' => Yii::t('hipanel', 'Type'),
68
        ];
69
    }
70
71
    public function getTypeOptions()
72
    {
73
        return Ref::getList('type,bill', null, [
74
            'select' => 'name',
75
            'pnames' => 'monthly,overuse',
76
            'with_recursive' => 1,
77
        ]);
78
    }
79
80
    /**
81
     * Returns array of unit option, that are available for this price
82
     * depending on price type.
83
     *
84
     * @return array
85
     */
86
    public function getUnitOptions()
87
    {
88
        $unitGroup = [
89
            'speed' => ['bps', 'kbps', 'mbps', 'gbps', 'tbps'],
90
            'size' => ['mb', 'mb10', 'mb100', 'gb', 'tb'],
91
        ];
92
93
        $availableUnitsByPriceType = [
94
            'overuse,ip_num' => ['items'],
95
            'overuse,support_time' => ['hour'],
96
            'overuse,backup_du' => $unitGroup['size'],
97
            'overuse,server_traf_max' => $unitGroup['size'],
98
            'overuse,server_traf95_max' => $unitGroup['speed'],
99
            'overuse,server_du' => $unitGroup['size'],
100
            'overuse,server_ssd' => $unitGroup['size'],
101
            'overuse,server_sata' => $unitGroup['size'],
102
            'overuse,backup_traf' => $unitGroup['size'],
103
            'overuse,domain_traf' => $unitGroup['size'],
104
            'overuse,domain_num' => ['items'],
105
            'overuse,ip_traf_max' => $unitGroup['size'],
106
            'overuse,account_traf' => $unitGroup['size'],
107
            'overuse,account_du' => $unitGroup['size'],
108
            'overuse,mail_num' => ['items'],
109
            'overuse,mail_du' => $unitGroup['size'],
110
            'overuse,db_num' => ['items'],
111
        ];
112
113
        $units = Ref::getList('type,unit', 'hipanel.finance.units', [
114
            'with_recursive' => 1,
115
            'select' => 'oname_label',
116
            'mapOptions' => ['from' => 'oname'],
117
        ]);
118
119
        $possibleTypes = $availableUnitsByPriceType[$this->type] ?? [];
120
121
        return array_intersect_key($units, array_combine($possibleTypes, $possibleTypes));
122
    }
123
124
    /**
125
     * Method checks, whether current price quantity is predefined and is not a result
126
     * of sophisticated calculation on server side.
127
     * @return bool
128
     */
129
    public function isQuantityPredefined(): bool
130
    {
131
        if (!$this->isOveruse()
132
            && ($this->isShared() || $this->getSubtype() === 'rack_unit')
133
        ) {
134
            return false;
135
        }
136
137
        return true;
138
    }
139
140
    /**
141
     * @return bool Whether this price is shared
142
     */
143
    public function isShared(): bool
144
    {
145
        return $this->object_id === null;
146
    }
147
148
    public function getUnitLabel()
149
    {
150
        return $this->getUnitOptions()[$this->unit] ?? null;
151
    }
152
153
    public function getCurrencyOptions()
154
    {
155
        return Ref::getList('type,currency');
156
    }
157
158
    public function getObject()
159
    {
160
        return $this->hasOne(TargetObject::class, ['id' => 'id']);
161
    }
162
163
    public function getPlan()
164
    {
165
        return $this->hasOne(Plan::class, ['id' => 'plan_id']);
166
    }
167
168
    public static function tableName()
169
    {
170
        return Inflector::camel2id(StringHelper::basename(__CLASS__), '-');
171
    }
172
173
    public function isOveruse()
174
    {
175
        return strpos($this->type, 'overuse,') === 0;
176
    }
177
178
    public function getSubtype()
179
    {
180
        [, $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...
181
        return $subtype;
182
    }
183
184
    /**
185
     * {@inheritdoc}
186
     */
187
    public static function instantiate($row)
188
    {
189
        /** @var PriceModelFactory $factory */
190
        $factory = Yii::$container->get(PriceModelFactory::class);
191
        return $factory->build($row['class'] ?? 'SinglePrice', $row['type']);
192
    }
193
194
    public function formulaLines(): array
195
    {
196
        if (strlen($this->formula) === 0) {
197
            return [];
198
        }
199
200
        return explode("\n", $this->formula);
201
    }
202
}
203