ValidNationalCard   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 13
c 2
b 0
f 0
dl 0
loc 33
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A message() 0 3 1
B passes() 0 20 8
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