Completed
Pull Request — master (#430)
by Anton
04:09 queued 58s
created

CreditCardRule::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
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
    public function validate($input): bool
34
    {
35
        $input = preg_replace('([ \.-])', '', $input);
36
37
        if (!is_numeric($input)) {
38
            return false;
39
        }
40
41
        return $this->verifyMod10($input);
42
    }
43
44
    /**
45
     * Verify by Mod10
46
     *
47
     * @param  string $input
48
     *
49
     * @return bool
50
     */
51
    private function verifyMod10($input)
52
    {
53
        $sum = 0;
54
        $input = strrev($input);
55
        for ($i = 0; $i < strlen($input); $i++) {
56
            $current = substr($input, $i, 1);
57
            if ($i % 2 == 1) {
58
                $current *= 2;
59
                if ($current > 9) {
60
                    $firstDigit = $current % 10;
61
                    $secondDigit = ($current - $firstDigit) / 10;
62
                    $current = $firstDigit + $secondDigit;
63
                }
64
            }
65
            $sum += $current;
66
        }
67
68
        return ($sum % 10 == 0);
69
    }
70
}
71