Completed
Push — master ( 62d2ea...1993b9 )
by Andrii
11:09
created

BillForm   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 262
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 4
dl 0
loc 262
rs 10
c 0
b 0
f 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
A createFromBill() 0 15 1
A createMultipleFromBills() 0 9 2
A load() 0 7 1
A getCharges() 0 8 2
A newCharge() 0 4 1
A rules() 0 18 1
A attributeLabels() 0 12 1
A getIsNewRecord() 0 4 1
A getChargesAsArray() 0 11 2
A fields() 0 16 1
A loadCharges() 0 16 3
A getPrimaryKey() 0 4 1
A primaryKey() 0 4 1
A batchQuery() 0 10 2
A getOldAttribute() 0 4 1
A setOldAttribute() 0 4 1
A setOldAttributes() 0 4 1
A afterSave() 0 4 1
1
<?php
2
3
namespace hipanel\modules\finance\forms;
4
5
use hipanel\modules\finance\models\Bill;
6
use hipanel\modules\finance\models\Charge;
7
use hipanel\modules\finance\validation\BillChargesSumValidator;
8
use Yii;
9
use yii\base\Model;
10
11
class BillForm extends Model
12
{
13
    const SCENARIO_CREATE = 'create';
14
    const SCENARIO_UPDATE = 'update';
15
16
    /**
17
     * @var integer
18
     */
19
    public $id;
20
21
    /**
22
     * @var integer
23
     */
24
    public $client_id;
25
26
    /**
27
     * @var string
28
     */
29
    public $currency;
30
31
    /**
32
     * @var float
33
     */
34
    public $sum;
35
36
    /**
37
     * @var string
38
     */
39
    public $time;
40
41
    /**
42
     * @var string
43
     */
44
    public $type;
45
46
    /**
47
     * @var string
48
     */
49
    public $gtype;
50
51
    /**
52
     * @var float
53
     */
54
    public $quantity;
55
56
    /**
57
     * @var string
58
     */
59
    public $label;
60
61
    /**
62
     * @var Charge[]
63
     */
64
    public $charges = [];
65
66
    /**
67
     * Creates [[BillForm]] from [[Bill]]
68
     *
69
     * @param Bill $bill
70
     * @param string $scenario
71
     * @return BillForm
72
     */
73
    public static function createFromBill($bill, $scenario)
74
    {
75
        $attributes = $bill->getAttributes(['id', 'client_id', 'currency', 'type', 'gtype', 'sum', 'time', 'quantity', 'label']);
76
77
        $form = new self(['scenario' => $scenario]);
78
        $form->setAttributes($attributes, false);
79
80
        $form->charges = array_map(function ($model) use ($scenario) {
81
            $model->scenario = $scenario;
82
83
            return $model;
84
        }, $bill->charges);
0 ignored issues
show
Documentation introduced by
The property charges does not exist on object<hipanel\modules\finance\models\Bill>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
85
86
        return $form;
87
    }
88
89
    /**
90
     * @param Bill[] $bills
91
     * @param string $scenario
92
     * @return BillForm[]
93
     */
94
    public static function createMultipleFromBills($bills, $scenario)
95
    {
96
        $result = [];
97
        foreach ($bills as $bill) {
98
            $result[$bill->id] = self::createFromBill($bill, $scenario);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\finance\models\Bill>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
99
        }
100
101
        return $result;
102
    }
103
104
    /**
105
     * @inheritdoc
106
     */
107
    public function load($data, $formName = null)
108
    {
109
        $this->setAttributes($data);
110
        $this->loadCharges($data['charges']);
111
112
        return true;
113
    }
114
115
    /**
116
     * @return Charge[]
117
     */
118
    public function getCharges()
119
    {
120
        if (!empty($this->charges)) {
121
            return $this->charges;
122
        }
123
124
        return [$this->newCharge()];
125
    }
126
127
    /**
128
     * Creates new charge
129
     *
130
     * @return Charge
131
     */
132
    public function newCharge()
133
    {
134
        return (new Charge(['scenario' => Charge::SCENARIO_CREATE]));
135
    }
136
137
    /**
138
     * @return array
139
     */
140
    public function rules()
141
    {
142
        return [
143
            [['id'], 'integer', 'on' => [self::SCENARIO_UPDATE]],
144
            [['sum', 'quantity'], 'number', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_UPDATE]],
145
            [['time'], 'date', 'format' => 'php:d.m.Y H:i:s'],
146
            [['label', 'currency', 'type'], 'safe', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_UPDATE]],
147
            [['sum'], BillChargesSumValidator::class],
148
149
            [['id'], 'required', 'on' => [self::SCENARIO_UPDATE]],
150
            [
151
                ['client_id', 'sum', 'quantity', 'time', 'currency', 'type'],
152
                'required',
153
                'on' => [self::SCENARIO_CREATE, self::SCENARIO_UPDATE],
154
            ],
155
            [['!charges'], 'safe', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_UPDATE]],
156
        ];
157
    }
158
159
    public function attributeLabels()
160
    {
161
        return [
162
            'client_id' => Yii::t('hipanel', 'Client'),
163
            'time' => Yii::t('hipanel', 'Time'),
164
            'currency' => Yii::t('hipanel', 'Currency'),
165
            'sum' => Yii::t('hipanel:finance', 'Sum'),
166
            'label' => Yii::t('hipanel', 'Description'),
167
            'type' => Yii::t('hipanel', 'Type'),
168
            'quantity' => Yii::t('hipanel', 'Quantity'),
169
        ];
170
    }
171
172
    public function getIsNewRecord()
173
    {
174
        return $this->id === null;
175
    }
176
177
    private function getChargesAsArray()
178
    {
179
        return array_filter(array_map(function ($model) {
180
            /** @var Charge $model */
181
            if ($model->validate()) {
182
                return $model->toArray();
183
            }
184
185
            return null;
186
        }, $this->charges));
187
    }
188
189
    public function fields()
190
    {
191
        return [
192
            'id',
193
            'client_id',
194
            'currency',
195
            'sum',
196
            'time',
197
            'type',
198
            'quantity',
199
            'label',
200
            'charges' => function () {
201
                return $this->getChargesAsArray();
202
            },
203
        ];
204
    }
205
206
    public function loadCharges($data)
207
    {
208
        $charges = [];
209
210
        foreach ((array)$data as $datum) {
211
            $charge = $this->newCharge();
212
            if ($charge->load($datum, '')) {
213
                $charge->markAsNotNew();
214
                $charges[] = $charge;
215
            }
216
        }
217
218
        $this->charges = $charges;
219
220
        return true;
221
    }
222
223
224
    public function getPrimaryKey()
225
    {
226
        return $this->id;
227
    }
228
229
    public static function primaryKey()
230
    {
231
        return ['id'];
232
    }
233
234
    /**
235
     * For compatibility with [[hiqdev\hiart\Collection]]
236
     *
237
     * @param $defaultScenario
238
     * @param array $data
239
     * @param array $options
240
     * @return mixed
241
     */
242
    public function batchQuery($defaultScenario, $data = [], array $options = [])
243
    {
244
        $map = [
245
            'create' => 'create-with-charges',
246
            'update' => 'update-with-charges',
247
        ];
248
        $scenario = isset($map[$defaultScenario]) ? $map[$defaultScenario] : $defaultScenario;
249
250
        return (new Bill)->batchQuery($scenario, $data, $options);
251
    }
252
253
    public function getOldAttribute($attribute)
254
    {
255
        return $this->$attribute;
256
    }
257
258
    public function setOldAttribute($attribute, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $attribute 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...
Unused Code introduced by
The parameter $value 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...
259
    {
260
        return true;
261
    }
262
263
    public function setOldAttributes($values)
0 ignored issues
show
Unused Code introduced by
The parameter $values 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...
264
    {
265
        return true;
266
    }
267
268
    public function afterSave()
269
    {
270
        return true;
271
    }
272
}
273