CreditCardRule::validate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
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