1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://github.com/yiibr/yii2-br-validator |
4
|
|
|
* @license https://github.com/yiibr/yii2-br-validator/blob/master/LICENSE |
5
|
|
|
*/ |
6
|
|
|
namespace yiibr\brvalidator; |
7
|
|
|
|
8
|
|
|
use yii\helpers\Json; |
9
|
|
|
use Yii; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* CnpjValidator checks if the attribute value is a valid CNPJ. |
13
|
|
|
* |
14
|
|
|
* @author Leandro Gehlen <[email protected]> |
15
|
|
|
*/ |
16
|
|
|
class CnpjValidator extends DocumentValidator |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @inheritdoc |
21
|
|
|
*/ |
22
|
2 |
|
public function init() |
23
|
|
|
{ |
24
|
2 |
|
parent::init(); |
25
|
2 |
|
if ($this->message === null) { |
26
|
2 |
|
$this->message = Yii::t('yii', "{attribute} is invalid."); |
27
|
|
|
} |
28
|
2 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @inheritdoc |
32
|
|
|
*/ |
33
|
2 |
|
protected function validateValue($value) |
34
|
|
|
{ |
35
|
2 |
|
$valid = true; |
36
|
2 |
|
$cnpj = preg_replace('/[^0-9_]/', '', $value); |
37
|
|
|
|
38
|
2 |
View Code Duplication |
for ($x=0; $x<10; $x++) { |
|
|
|
|
39
|
2 |
|
if ( $cnpj == str_repeat($x, 14) ) { |
40
|
1 |
|
$valid = false; |
41
|
|
|
} |
42
|
|
|
} |
43
|
2 |
|
if ($valid) { |
44
|
2 |
|
if (strlen($cnpj) != 14) { |
45
|
2 |
|
$valid = false; |
46
|
|
|
} else { |
47
|
1 |
|
for ($t = 12; $t < 14; $t ++) { |
48
|
1 |
|
$d = 0; |
49
|
1 |
|
$c = 0; |
50
|
1 |
View Code Duplication |
for ($m = $t - 7; $m >= 2; $m --, $c ++) { |
|
|
|
|
51
|
1 |
|
$d += $cnpj[$c] * $m; |
52
|
|
|
} |
53
|
1 |
View Code Duplication |
for ($m = 9; $m >= 2; $m --, $c ++) { |
|
|
|
|
54
|
1 |
|
$d += $cnpj[$c] * $m; |
55
|
|
|
} |
56
|
1 |
|
$d = ((10 * $d) % 11) % 10; |
57
|
1 |
|
if ($cnpj[$c] != $d) { |
58
|
1 |
|
$valid = false; |
59
|
1 |
|
break; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
2 |
|
return ($valid) ? [] : [$this->message, []]; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
View Code Duplication |
public function clientValidateAttribute($object, $attribute, $view) |
|
|
|
|
68
|
|
|
{ |
69
|
|
|
$options = [ |
70
|
|
|
'message' => Yii::$app->getI18n()->format($this->message, [ |
71
|
|
|
'attribute' => $object->getAttributeLabel($attribute), |
72
|
|
|
], Yii::$app->language) |
73
|
|
|
]; |
74
|
|
|
|
75
|
|
|
if ($this->skipOnEmpty) { |
76
|
|
|
$options['skipOnEmpty'] = 1; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
ValidationAsset::register($view); |
80
|
|
|
return 'yiibr.validation.cnpj(value, messages, ' . Json::encode($options) . ');'; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
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.