Passed
Pull Request — 1.x (#16)
by
unknown
02:56
created

ValidNationalCard::passes()   B

Complexity

Conditions 9
Paths 8

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 9
eloc 12
c 1
b 0
f 1
nc 8
nop 2
dl 0
loc 22
rs 8.0555
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
     * @param  string  $attribute
13
     * @param  mixed  $value
14
     * @return bool
15
     */
16
    public function passes($attribute, $value)
17
    {
18
        if (! preg_match('/^\d{10}$/', $value)) {
19
            return false;
20
        }
21
    
22
        for ($i = 0; $i < 10; $i++) {
23
            if (preg_match('/^' . $i . '{10}$/', $value)) {
24
                return false;
25
            }
26
        }
27
    
28
        for ($i = 0, $sum = 0; $i < 9; $i++) {
29
            $sum += ((10 - $i) * intval(substr($value, $i, 1)));
30
            $ret = $sum % 11;
31
            $parity = intval(substr($value, 9, 1));
32
            if (($ret < 2 && $ret == $parity) || ($ret >= 2 && $ret == 11 - $parity)) {
33
                return true;
34
            }
35
        }
36
    
37
        return false;
38
    }
39
40
    /**
41
     * Get the validation error message.
42
     *
43
     * @return string
44
     */
45
    public function message()
46
    {
47
        return __('validate.national-card');
48
    }
49
}
50