CeiValidator::validateValue()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 10
cts 10
cp 1
rs 9.7333
c 0
b 0
f 0
cc 3
nc 4
nop 1
crap 3
1
<?php
2
3
/**
4
 * @link https://github.com/yiibr/yii2-br-validator
5
 * @license https://github.com/yiibr/yii2-br-validator/blob/master/LICENSE
6
 */
7
8
namespace yiibr\brvalidator;
9
10
use yii\helpers\Json;
11
use Yii;
12
13
/**
14
 * CeiValidator checks if the attribute value is a valid CEI.
15
 *
16
 * @author Guilherme Lessa <[email protected]>
17
 */
18
class CeiValidator extends DocumentValidator
19
{
20
21
    /**
22
     * @inheritdoc
23
     */
24 1
    public function init()
25
    {
26 1
        parent::init();
27 1
        if ($this->message === null) {
28 1
            $this->message = Yii::t('yii', "{attribute} is invalid.");
29
        }
30 1
    }
31
32
    /**
33
     * @inheritdoc
34
     */
35 1
    protected function validateValue($value)
36
    {
37 1
        $cei = preg_replace('/[^0-9_]/', '', $value);
38 1
        $valid  = strlen($cei) == 12;
39
40 1
        if ($valid) {
41 1
            $cei = str_split($cei, 1);
42 1
            $sum = (7 * $cei[0]) + (4 * $cei[1]) + (1 * $cei[2]) + (8 * $cei[3]) + (5 * $cei[4]) + (2 * $cei[5]) +
43 1
                   (1 * $cei[6]) + (6 * $cei[7]) + (3 * $cei[8]) + (7 * $cei[9]) + (4 * $cei[10]);
44
45 1
            $dv = abs(10 - ($sum%10 + $sum/10) % 10);
46 1
            $valid = ($cei[11] == $dv);
47
        }
48
49 1
        return ($valid) ? [] : [$this->message, []];
50
    }
51
52
    /**
53
     * @inheritdoc
54
     */
55 View Code Duplication
    public function clientValidateAttribute($object, $attribute, $view)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
    {
57
        $options = [
58
            'message' => Yii::$app->getI18n()->format($this->message, [
59
                'attribute' => $object->getAttributeLabel($attribute),
60
            ], Yii::$app->language),
61
        ];
62
63
        if ($this->skipOnEmpty) {
64
            $options['skipOnEmpty'] = 1;
65
        }
66
67
        ValidationAsset::register($view);
68
        return 'yiibr.validation.cei(value, messages, ' . Json::encode($options) . ');';
69
    }
70
71
}
72