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

ValidCreditCard   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 14
c 1
b 0
f 1
dl 0
loc 39
rs 10
wmc 5

2 Methods

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