Completed
Push — master ( 60d97c...40284d )
by Ronan
06:47
created

Gtin::unDecorate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
3
namespace IsoCodes;
4
5
/**
6
 * Abstract Class Gtin Global Trade Item Numbers.
7
 *
8
 * @link http://www.gs1.org/how-calculate-check-digit-manually
9
 */
10
abstract class Gtin
11
{
12
    /**
13
     * @param string $gtin
14
     * @param int    $length
15
     *
16
     * @return bool
17
     */
18
    public static function check($gtin, $length)
19
    {
20
        $gtin = self::unDecorate($gtin);
21
        if (strlen($gtin) != $length) {
22
            return false;
23
        }
24
        $expr = sprintf('/\\d{%d}/i', $length);
25
        if (!preg_match($expr, $gtin)) {
26
            return false;
27
        }
28
        $check = 0;
29
        for ($i = 0; $i < $length; $i += 2) {
30
            if ($length % 2 == 0) {
31
                $check += 3 * substr($gtin, $i, 1);
32
                $check += (int) substr($gtin, $i + 1, 1);
33
            } else {
34
                $check += (int) substr($gtin, $i, 1);
35
                $check += 3 * substr($gtin, $i + 1, 1);
36
            }
37
        }
38
39
        return $check % 10 == 0;
40
    }
41
42
    /**
43
     * @param string $gtin
44
     *
45
     * @return string
46
     */
47
    public static function unDecorate($gtin)
48
    {
49
        // removing hyphens
50
        $gtin = str_replace(' ', '', $gtin);
51
        $gtin = str_replace('-', '', $gtin); // this is a dash
52
        $gtin = str_replace('‐', '', $gtin); // this is an authentic hyphen
53
54
        return $gtin;
55
    }
56
}
57