Completed
Push — master ( ea26bd...83b769 )
by Ronan
01:18
created

Luhn::check()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 27
rs 6.7272
cc 7
eloc 18
nc 12
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
        if (0 === (int) $luhn) {
31
            return false;
32
        }
33
        $check = 0;
34
35
        for ($i = 0; $i < $length; $i += 2) {
36
            if ($length % 2 == 0) {
37
                $check += 3 * (int) substr($luhn, $i, 1);
38
                $check += (int) substr($luhn, $i + 1, 1);
39
            } else {
40
                $check += (int) substr($luhn, $i, 1);
41
                $check += 3 * (int) substr($luhn, $i + 1, 1);
42
            }
43
        }
44
45
        return $check % 10 == 0;
46
    }
47
48
    /**
49
     * @param string $luhn
50
     * @param array  $hyphens
51
     *
52
     * @return string
53
     */
54
    public static function unDecorate($luhn, $hyphens = [])
55
    {
56
        $hyphensLength = count($hyphens);
57
        // removing hyphens
58
        for ($i = 0; $i < $hyphensLength; ++$i) {
59
            $luhn = str_replace($hyphens[$i], '', $luhn);
60
        }
61
62
        return $luhn;
63
    }
64
}
65