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

BillChargesSumValidator::validateAttribute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 2
1
<?php
2
3
namespace hipanel\modules\finance\validation;
4
5
use hipanel\modules\finance\forms\BillForm;
6
use Yii;
7
use yii\helpers\ArrayHelper;
8
use yii\helpers\Json;
9
use yii\validators\Validator;
10
11
class BillChargesSumValidator extends Validator
12
{
13
    public function init()
14
    {
15
        parent::init();
16
17
        $this->message = Yii::t('hipanel:finance', 'Bill sum must match resources sum');
18
    }
19
20
    /**
21
     * @param BillForm $model
22
     * @param string $attribute
23
     */
24
    public function validateAttribute($model, $attribute)
25
    {
26
        if (count($model->charges) > 0) {
27
            $chargesSum = array_sum(ArrayHelper::getColumn($model->charges, 'sum'));
28
            if (abs($chargesSum) !== abs($model->sum)) {
29
                $model->addError($attribute, $this->message . ': ' . $chargesSum);
30
            }
31
        }
32
    }
33
34
    public function clientValidateAttribute($model, $attribute, $view)
35
    {
36
        $message = Json::encode($this->message);
37
38
        return <<<JS
39
    var sum = 0,
40
        inputs = $(this.input).closest('.bill-item').find('input[data-attribute="sum"]');
41
42
    if (inputs.length > 0) {
43
        inputs.map(function () {
44
            sum += $(this).val() * 100;
45
        });
46
        if (Math.abs(sum) !== Math.abs(value * 100)) {
47
            messages.push($message + ': ' + (sum / 100));
48
        }
49
    }
50
JS;
51
    }
52
}
53