Completed
Push — master ( 8f5bc0...179bc9 )
by WEBEWEB
03:06
created

LuhnAlgorithmHelper::check()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 9.424
c 0
b 0
f 0
cc 4
nc 5
nop 1
1
<?php
2
3
/**
4
 * This file is part of the core-library package.
5
 *
6
 * (c) 2018 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Library\Core\Algorithm;
13
14
/**
15
 * Luhn algorithm helper.
16
 *
17
 * @author webeweb <https://github.com/webeweb/>
18
 * @package WBW\Library\Core\Algorithm
19
 */
20
class LuhnAlgorithmHelper {
21
22
    /**
23
     * Check.
24
     *
25
     * @param string $str The string.
26
     * @return boolean Returns true in case of success, false otherwise.
27
     */
28
    public static function check($str) {
29
30
        // Initialize.
31
        $sum    = 0;
32
        $length = strlen($str);
33
        $parity = $length % 2;
34
35
        // Get the sum.
36
        $sum += substr($str, $length - 1);
37
38
        // Handle each character.
39
        for ($i = $length - 2; 0 <= $i; --$i) {
40
41
            // Get the digit.
42
            $digit = intval(substr($str, $i, 1));
43
44
            // Check the parity.
45
            if ($parity === $i % 2) {
46
                $digit *= 2;
47
            }
48
            if (9 < $digit) {
49
                $digit -= 9;
50
            }
51
52
            // Add the digit.
53
            $sum += $digit;
54
        }
55
56
        // Return.
57
        return 0 === $sum % 10;
58
    }
59
60
}
61