Gtin   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 87.5%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 50
ccs 7
cts 8
cp 0.875
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fillParameters() 0 7 2
B check() 0 23 7
1
<?php
2
3
/**
4
 * This file is part of Dimtrovich/Validation.
5
 *
6
 * (c) 2023 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Dimtrovich\Validation\Rules;
13
14
use Rakit\Validation\Rule;
15
16
class Gtin extends Ean
17
{
18
    /**
19
     * {@inheritDoc}
20
     */
21
    public function fillParameters(array $params): Rule
22
    {
23
        if (empty($params)) {
24 2
            $params = [8, 12, 13, 14];
25
        }
26
27 2
        return parent::fillParameters($params);
28
    }
29
30
    /**
31
     * Check if the current value is a valid Global Trade Item Number.
32
     *
33
     * Value must be either GTIN-13 or GTIN-8, which is checked as EAN by parent class.
34
     * Or value must be GTIN-14 or GTIN-12 which will be handled like this:
35
     *
36
     * - GTIN-14 will be checked as EAN-13 after cropping first char
37
     * - GTIN-12 will be checked as EAN-13 after adding leading zero
38
     *
39
     * @credit <a href="https://github.com/Intervention/validation">Intervention/validation - \Intervention\Validation\Rules\Gtin</a>
40
     *
41
     * @param mixed $value
42
     */
43
    public function check($value): bool
44
    {
45
        if (! is_numeric($value)) {
46 2
            return false;
47
        }
48
49
        if (! $this->hasAllowedLength($value)) {
50 2
            return false;
51
        }
52
53
        switch (strlen($value)) {
54
            case 8:
55
            case 13:
56 2
                return parent::check($value);
57
58
            case 14:
59 2
                return parent::checksumMatches(substr($value, 1));
60
61
            case 12:
62 2
                return parent::checksumMatches('0' . $value);
63
        }
64
65
        return false;
66
    }
67
}
68