TituloValidator   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 44
c 1
b 0
f 0
dl 0
loc 80
rs 10
wmc 20

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 5 2
C validateValue() 0 53 16
A clientValidateAttribute() 0 14 2
1
<?php
2
3
namespace dynamikaweb\validators;
4
5
use Yii;
6
use yii\helpers\Json;
7
8
class TituloValidator extends DocumentValidator
9
{
10
11
    public function init() 
12
    {
13
        parent::init();
14
        if ($this->message === null) {
15
            $this->message = Yii::t('yii', "{attribute} is invalid.");
16
        }
17
    }
18
    
19
    protected function validateValue($value)
20
    {
21
        $valid = true;
22
        $input = preg_replace('/[^\d]/', '', $value);
23
24
        $uf = substr($input, -4, 2);
25
        
26
        if (
27
            ((mb_strlen($input) < 5) || (mb_strlen($input) > 13)) ||
28
            (str_repeat($input[1], mb_strlen($input)) == $input) ||
29
            ($uf < 1 || $uf > 28)
30
        ) {
31
            $valid = false;
32
        }
33
34
        if ($valid) {
35
            $dv = substr($input, -2);
36
            $sequencia = substr($input, 0, -4);
37
            $base = 2;
38
39
            for ($i = 0; $i < 2; $i++) {
40
                $fator = 9;
41
                $soma = 0;
42
43
                for ($j = (mb_strlen($sequencia) - 1); $j > -1; $j--) {
44
                    $soma += $sequencia[$j] * $fator;
45
46
                    if ($fator == $base) {
47
                        $fator = 10;
48
                    }
49
50
                    $fator--;
51
                }
52
53
                $digito = $soma % 11;
54
                if (($digito == 0) and ($uf < 3)) {
55
                    $digito = 1;
56
                } elseif ($digito == 10) {
57
                    $digito = 0;
58
                }
59
60
                if ($dv[$i] != $digito) {
61
                    $valid = false;
62
                }
63
64
                switch ($i) {
65
                    case '0':
66
                        $sequencia = $uf . $digito;
67
                        break;
68
                }
69
            }
70
        }
71
        return ($valid) ? [] : [$this->message, []];
72
    }
73
74
    public function clientValidateAttribute($object, $attribute, $view)
75
    {
76
        $options = [
77
            'message' => Yii::$app->getI18n()->format($this->message, [
78
                'attribute' => $object->getAttributeLabel($attribute),
79
            ], Yii::$app->language)
80
        ];
81
82
        if ($this->skipOnEmpty) {
83
            $options['skipOnEmpty'] = 1;
84
        }
85
86
        ValidationAsset::register($view);
87
        return 'dynamikaweb.validation.titulo(value, messages, ' . Json::encode($options) . ');';
88
    }
89
    
90
}