BillChargesSumValidator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 5
dl 0
loc 45
ccs 0
cts 26
cp 0
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 21 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 charges 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 ($model->sum != -$chargesSum) {
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 += Number($(this).val()) * 100;
45
            });
46
            if (isNaN(sum)) {
47
                return;
48
            }
49
            if (value * 100 != -sum) {
50
                messages.push($message + ': ' + (-(sum / 100)));
51
            }
52
        }
53
JS;
54
    }
55
}
56