ValidCreditCard::message()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 3
rs 10
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
    public function passes($attribute, $value): bool
13
    {
14
        $value = preg_replace('/\D/', '', $value);
15
16
        $numLength = strlen($value);
17
        $sum = 0;
18
        $reverse = strrev($value);
19
20
        for ($i = 0; $i < $numLength; $i++) {
21
            $currentNum = intval($reverse[$i]);
22
            if ($i % 2 == 1) {
23
                $currentNum *= 2;
24
                if ($currentNum > 9) {
25
                    $currentNum -= 9;
26
                }
27
            }
28
            $sum += $currentNum;
29
        }
30
31
        return $sum % 10 == 0;
32
    }
33
34
    /**
35
     * Get the validation error message.
36
     */
37
    public function message(): string
38
    {
39
        return __('validate.credit-card');
40
    }
41
}
42