Completed
Push — master ( d4acb4...642459 )
by Hannes
20s
created

Modulo10Gtin::isValid()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace byrokrat\checkdigit;
6
7
/**
8
 * Modulo10 calculator, variant used for GTIN (EAN, UPC, ISBN-13, JAN and ITF) barcodes
9
 */
10
class Modulo10Gtin implements Calculator
11
{
12
    /**
13
     * Check if the last digit of number is a valid modulo 10 check digit
14
     */
15 4
    public function isValid(string $number): bool
16
    {
17 4
        return substr($number, -1) === $this->calculateCheckDigit(substr($number, 0, -1) ?: '');
18
    }
19
20
    /**
21
     * Calculate the modulo 10 check digit for number
22
     *
23
     * @throws InvalidStructureException If $number is not numerical
24
     */
25 8
    public function calculateCheckDigit(string $number): string
26
    {
27 8
        if (!ctype_digit($number)) {
28 6
            throw new InvalidStructureException(
29 6
                "Number can only contain numerical characters, found <$number>"
30
            );
31
        }
32
33 2
        $weight = 3;
34 2
        $sum = 0;
35
36 2 View Code Duplication
        foreach (array_reverse(str_split($number)) as $pos => $digit) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
37 2
            $sum += $digit * ($pos % 2 ? 1 : $weight);
38
        }
39
40 2
        $ceil = $sum;
41
42 2
        while ($ceil % 10 != 0) {
43 2
            $ceil++;
44
        }
45
46 2
        return (string)($ceil-$sum);
47
    }
48
}
49