Completed
Push — master ( d387da...d21571 )
by Ronan
01:52
created

Luhn::check()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 23
rs 8.5906
cc 6
eloc 16
nc 10
nop 4
1
<?php
2
3
namespace IsoCodes;
4
5
/**
6
 * Abstract Class Luhn.
7
 *
8
 * @link https://en.wikipedia.org/wiki/Luhn_algorithm
9
 */
10
abstract class Luhn
11
{
12
    /**
13
     * @param string $luhn
14
     * @param int    $length
15
     * @param bool   $unDecorate
16
     * @param array  $hyphens
17
     *
18
     * @return bool
19
     */
20
    public static function check($luhn, $length, $unDecorate = true, $hyphens = [])
21
    {
22
        $luhn = $unDecorate ? self::unDecorate($luhn, $hyphens) : $luhn;
23
        if (strlen($luhn) != $length) {
24
            return false;
25
        }
26
        $expr = sprintf('/\\d{%d}/i', $length);
27
        if (!preg_match($expr, $luhn)) {
28
            return false;
29
        }
30
        $check = 0;
31
        for ($i = 0; $i < $length; $i += 2) {
32
            if ($length % 2 == 0) {
33
                $check += 3 * substr($luhn, $i, 1);
34
                $check += (int) substr($luhn, $i + 1, 1);
35
            } else {
36
                $check += (int) substr($luhn, $i, 1);
37
                $check += 3 * substr($luhn, $i + 1, 1);
38
            }
39
        }
40
41
        return $check % 10 == 0;
42
    }
43
44
    /**
45
     * @param string $luhn
46
     * @param array  $hyphens
47
     *
48
     * @return string
49
     */
50
    public static function unDecorate($luhn, $hyphens = [])
51
    {
52
        $hyphensLength = count($hyphens);
53
        // removing hyphens
54
        for ($i = 0; $i < $hyphensLength; ++$i) {
55
            $luhn = str_replace($hyphens[$i], '', $luhn);
56
        }
57
58
        return $luhn;
59
    }
60
}
61