Completed
Pull Request — master (#430)
by Anton
04:30
created

CreditCardRule::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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