Gtin::check()   B
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 7.2269

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 13
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 23
ccs 5
cts 6
cp 0.8333
crap 7.2269
rs 8.8333
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