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