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

Modulo10Gtin   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 7.69 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 1
dl 3
loc 39
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 4 2
A calculateCheckDigit() 3 23 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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