ValidNationalCard::passes()   B
last analyzed

Complexity

Conditions 8
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 11
nc 5
nop 2
dl 0
loc 20
rs 8.4444
c 2
b 0
f 0
1
<?php
2
3
namespace Milwad\LaravelValidate\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
7
class ValidNationalCard implements Rule
8
{
9
    /**
10
     * Check national card is valid.
11
     */
12
    public function passes($attribute, $value): bool
13
    {
14
        if (! preg_match('/^\d{10}$/', $value)) {
15
            return false;
16
        }
17
18
        if (preg_match('/^(.)\1*$/u', $value)) {
19
            return false;
20
        }
21
22
        for ($i = 0, $sum = 0; $i < 9; $i++) {
23
            $sum += ((10 - $i) * intval(substr($value, $i, 1)));
24
            $ret = $sum % 11;
25
            $parity = intval(substr($value, 9, 1));
26
            if (($ret < 2 && $ret == $parity) || ($ret >= 2 && $ret == 11 - $parity)) {
27
                return true;
28
            }
29
        }
30
31
        return false;
32
    }
33
34
    /**
35
     * Get the validation error message.
36
     */
37
    public function message(): string
38
    {
39
        return __('validate.national-card');
40
    }
41
}
42