Passed
Push — master ( 7bcc6f...9b4044 )
by Thanos
01:49
created

AmkaValidator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 96.67%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 4
dl 0
loc 55
ccs 29
cts 30
cp 0.9667
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B validate() 0 22 6
A calculateChecksum() 0 17 4
A isOdd() 0 4 1
A buildViolation() 0 6 1
1
<?php
2
3
namespace SymfonyGreekValidation;
4
5
use Symfony\Component\Validator\Constraint;
6
use Symfony\Component\Validator\ConstraintValidator;
7
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
8
9
class AmkaValidator extends ConstraintValidator
10
{
11 21
    public function validate($value, Constraint $constraint)
12
    {
13 21
        if (!$constraint instanceof Amka) {
14
            throw new UnexpectedTypeException($constraint, Amka::class);
15
        }
16
17 21
        if (empty($value)) {
18 2
            return;
19
        }
20
21 19
        if (!preg_match('/^[0-9]{11}$/', $value) || $value === '00000000000') {
22 3
            $this->buildViolation($value, $constraint);
23 3
            return;
24
        }
25
26 16
        $checksum = $this->calculateChecksum($value);
27
28 16
        if ($checksum % 10 !== 0) {
29 2
            $this->buildViolation($value, $constraint);
30 2
            return;
31
        }
32 14
    }
33
34 16
    private function calculateChecksum(string $amka): int
35
    {
36 16
        $sum = 0;
37 16
        foreach (str_split($amka) as $index => $char) {
38 16
            $tempDigit = intval($char);
39 16
            if ($this->isOdd($index)) {
40 16
                $tempDigit *= 2;
41 16
                if ($tempDigit > 9) {
42 15
                    $tempDigit -= 9;
43
                }
44
            }
45
46 16
            $sum += $tempDigit;
47
        }
48
49 16
        return $sum;
50
    }
51
52 16
    private function isOdd($index): bool
53
    {
54 16
        return $index % 2 === 1;
55
    }
56
57 5
    private function buildViolation($value, $constraint): void
58
    {
59 5
        $this->context->buildViolation($constraint->message)
60 5
            ->setParameter('{{ string }}', $value)
61 5
            ->addViolation();
62
    }
63
}