1 | <?php declare(strict_types=1); |
||
2 | |||
3 | namespace JustSteveKing\GtinPHP; |
||
4 | |||
5 | class Gtin |
||
6 | { |
||
7 | /** |
||
8 | * Check the length of a GTIN to make sure it is between 8 and 14 characters long |
||
9 | * @param mixed $value |
||
10 | * @return bool |
||
11 | */ |
||
12 | public static function length($value): bool |
||
13 | { |
||
14 | $value = (string) $value; |
||
15 | |||
16 | if (\strlen($value) <= 7 || \strlen($value) >= 15) { |
||
17 | return false; |
||
18 | } |
||
19 | |||
20 | return true; |
||
21 | } |
||
22 | |||
23 | /** |
||
24 | * Check that the GTIN is an integer - simply performs an is_int |
||
25 | * @param mixed $value |
||
26 | * @return bool |
||
27 | */ |
||
28 | public static function integer($value): bool |
||
29 | { |
||
30 | return is_int($value); |
||
31 | } |
||
32 | |||
33 | /** |
||
34 | * Inspects a GTIN to make sure the algorithm matches |
||
35 | * @param mixed $value |
||
36 | * @return bool |
||
37 | */ |
||
38 | public static function inspect($value): bool |
||
39 | { |
||
40 | $gtinString = (string) $value; |
||
41 | |||
42 | $checkDigitArray = []; |
||
43 | $gtinMath = [3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3]; |
||
44 | $modifier = 17 - (\strlen($gtinString) - 1); // First Digit in array |
||
45 | $checkDigit = \substr($gtinString, -1); // Get the check digit |
||
46 | |||
47 | $barcodeArray = \str_split($gtinString); // split gtin into an array |
||
48 | |||
49 | $tempCheckDigit = 0; |
||
0 ignored issues
–
show
Unused Code
introduced
by
![]() |
|||
50 | $tempCheckSum = 0; |
||
51 | |||
52 | // Run through and put digits into multiplication table |
||
53 | for ($i = 0; $i < (\strlen($gtinString) - 1); $i++) { |
||
54 | $checkDigitArray[$modifier + $i] = $barcodeArray[$i]; |
||
55 | } |
||
56 | |||
57 | // Calculate the sum of barcode digits |
||
58 | for ($i = $modifier; $i < 17; $i++) { |
||
59 | $tempCheckSum += ((int) $checkDigitArray[$i] * $gtinMath[$i]); |
||
60 | } |
||
61 | |||
62 | // Difference from rounded up to nearest 10 to final check digit calculation |
||
63 | $tempCheckDigit = (int)(\ceil($tempCheckSum / 10) * 10) - $tempCheckSum; |
||
64 | |||
65 | if ((int) $checkDigit !== $tempCheckDigit) { |
||
66 | return false; |
||
67 | } |
||
68 | |||
69 | return true; |
||
70 | } |
||
71 | |||
72 | /** |
||
73 | * Validates an entire GTIN |
||
74 | * @param mixed $value |
||
75 | * @return bool |
||
76 | */ |
||
77 | public static function validate($value): bool |
||
78 | { |
||
79 | if (! Gtin::length($value)) { |
||
80 | return false; |
||
81 | } |
||
82 | |||
83 | if (! Gtin::integer($value)) { |
||
84 | return false; |
||
85 | } |
||
86 | |||
87 | if (! Gtin::inspect($value)) { |
||
88 | return false; |
||
89 | } |
||
90 | |||
91 | return true; |
||
92 | } |
||
93 | } |
||
94 |