Passed
Push — 1.x ( fb82a9...cd6c0f )
by Milwad
01:16 queued 12s
created

ValidCreditCard::passes()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
eloc 12
c 1
b 0
f 1
nc 4
nop 2
dl 0
loc 20
rs 9.8666
1
<?php
2
3
namespace Milwad\LaravelValidate\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
7
class ValidCreditCard implements Rule
8
{
9
    /**
10
     * Check if the credit card number is valid using the Luhn algorithm.
11
     *
12
     * @param  string  $attribute
13
     * @param  mixed  $value
14
     * @return bool
15
     */
16
    public function passes($attribute, $value)
17
    {
18
        $value = preg_replace('/\D/', '', $value);
19
20
        $numLength = strlen($value);
21
        $sum = 0;
22
        $reverse = strrev($value);
23
24
        for ($i = 0; $i < $numLength; $i++) {
25
            $currentNum = intval($reverse[$i]);
26
            if ($i % 2 == 1) {
27
                $currentNum *= 2;
28
                if ($currentNum > 9) {
29
                    $currentNum -= 9;
30
                }
31
            }
32
            $sum += $currentNum;
33
        }
34
35
        return $sum % 10 == 0;
36
    }
37
38
    /**
39
     * Get the validation error message.
40
     *
41
     * @return string
42
     */
43
    public function message()
44
    {
45
        return __('validate.credit-card');
46
    }
47
}
48