CreditCard   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 34
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 24 3
1
<?php
2
3
namespace Mbright\Validation\Rule\Validate;
4
5
class CreditCard implements ValidateRuleInterface
6
{
7
    /**
8
     * Validates the value as a credit card number.
9
     *
10
     * @param object $subject The subject to be filtered.
11
     * @param string $field The subject field name.
12
     *
13
     * @return bool True if valid, false if not.
14
     */
15 33
    public function __invoke($subject, string $field): bool
16
    {
17
        // get the value; remove spaces, dashes, and dots
18 33
        $value = str_replace([' ', '-', '.'], '', (string) $subject->$field);
19
20
        // is it composed only of digits?
21 33
        if (!ctype_digit($value)) {
22 12
            return false;
23
        }
24
25
        // luhn mod-10 algorithm: https://gist.github.com/1287893
26
        $sumTable = [
27 21
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
28
            [0, 2, 4, 6, 8, 1, 3, 5, 7, 9],
29
        ];
30
31 21
        $sum = 0;
32 21
        $flip = 0;
33
34 21
        for ($i = strlen($value) - 1; $i >= 0; $i--) {
35 21
            $sum += $sumTable[$flip++ & 0x1][$value[$i]];
36
        }
37
38 21
        return $sum % 10 === 0;
39
    }
40
}
41