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

BillChargesSumValidator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 5
dl 0
loc 42
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 6 1
A validateAttribute() 0 9 3
A clientValidateAttribute() 0 18 1
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