CreditCardRule   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 51
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A verifyMod10() 0 19 4
A validate() 0 9 2
1
<?php
2
3
/**
4
 * Bluz Framework Component
5
 *
6
 * @copyright Bluz PHP Team
7
 * @link      https://github.com/bluzphp/framework
8
 */
9
10
declare(strict_types=1);
11
12
namespace Bluz\Validator\Rule;
13
14
/**
15
 * Check credit card number by Mod10 algorithm
16
 *
17
 * @package Bluz\Validator\Rule
18
 * @link    https://en.wikipedia.org/wiki/Luhn_algorithm
19
 */
20
class CreditCardRule extends AbstractRule
21
{
22
    /**
23
     * @var string error template
24
     */
25
    protected $description = 'must be a valid Credit Card number';
26
27
    /**
28
     * Check input data
29
     *
30
     * @param  string $input
31
     *
32
     * @return bool
33
     */
34 11
    public function validate($input): bool
35
    {
36 11
        $input = preg_replace('([ \.-])', '', (string) $input);
37
38 11
        if (!is_numeric($input)) {
39 4
            return false;
40
        }
41
42 7
        return $this->verifyMod10($input);
43
    }
44
45
    /**
46
     * Verify by Mod10
47
     *
48
     * @param string $input
49
     *
50
     * @return bool
51
     */
52 7
    private function verifyMod10(string $input): bool
53
    {
54 7
        $sum = 0;
55 7
        $input = strrev($input);
56 7
        $inputLen = \strlen($input);
57 7
        for ($i = 0; $i < $inputLen; $i++) {
58 7
            $current = $input[$i];
59 7
            if ($i % 2 === 1) {
60 7
                $current *= 2;
61 7
                if ($current > 9) {
62 5
                    $firstDigit = $current % 10;
63 5
                    $secondDigit = ($current - $firstDigit) / 10;
64 5
                    $current = $firstDigit + $secondDigit;
65
                }
66
            }
67 7
            $sum += $current;
68
        }
69
70 7
        return ($sum % 10 === 0);
71
    }
72
}
73