Completed
Push — master ( 39e8d7...c6707f )
by WEBEWEB
01:36
created

LuhnAlgorithm::check()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 31
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 13
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\Checksum;
13
14
/**
15
 * Luhn algorithm.
16
 *
17
 * @author webeweb <https://github.com/webeweb/>
18
 * @package WBW\Library\Core\Algorithm\Checksum
19
 * @final
20
 */
21
final class LuhnAlgorithm {
22
23
    /**
24
     * Check.
25
     *
26
     * @param string $str The string.
27
     * @return boolean Returns true in case of success, false otherwise.
28
     */
29
    public static function check($str) {
30
31
        // Initialize.
32
        $sum    = 0;
33
        $length = strlen($str);
34
        $parity = $length % 2;
35
36
        // Get the sum.
37
        $sum += substr($str, $length - 1);
38
39
        // Handle each character.
40
        for ($i = $length - 2; 0 <= $i; --$i) {
41
42
            // Get the digit.
43
            $digit = intval(substr($str, $i, 1));
44
45
            // Check the parity.
46
            if ($parity === $i % 2) {
47
                $digit *= 2;
48
            }
49
            if (9 < $digit) {
50
                $digit -= 9;
51
            }
52
53
            // Add the digit.
54
            $sum += $digit;
55
        }
56
57
        // Return.
58
        return 0 === $sum % 10;
59
    }
60
61
}
62