Completed
Push — master ( 38deb0...7544ac )
by Anton
11s
created

CreditCardRule   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 52
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 6
lcom 0
cbo 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 10 2
A verifyMod10() 0 19 4
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