Passed
Push — master ( 54b905...f751d8 )
by Thanos
05:52
created

AmkaValidator::validate()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 11
cts 11
cp 1
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 11
nc 4
nop 2
crap 5
1
<?php
2
3
namespace SymfonyGreekValidation;
4
5
use Symfony\Component\Validator\Constraint;
6
use Symfony\Component\Validator\ConstraintValidator;
7
8
class AmkaValidator extends ConstraintValidator
9
{
10 21
    public function validate($value, Constraint $constraint)
11
    {
12 21
        if (empty($value)) {
13 2
            return true;
14
        }
15
16 19
        if (!preg_match('/^[0-9]{11}$/', $value) || $value === '00000000000') {
17 3
            $this->buildViolation($value, $constraint);
18
19 3
            return false;
20
        }
21
22 16
        $checksum = $this->calculateChecksum($value);
23
24 16
        if ($checksum % 10 !== 0) {
25 2
            $this->buildViolation($value, $constraint);
26
27 2
            return false;
28
        }
29
30 14
        return true;
31
    }
32
33 16
    private function calculateChecksum(string $amka): int
34
    {
35 16
        $sum = 0;
36 16
        foreach(str_split($amka) as $index => $char) {
37 16
            $tempDigit = intval($char);
38 16
            if ($this->isOdd($index)) {
39 16
                $tempDigit *= 2;
40 16
                if ($tempDigit > 9) {
41 15
                    $tempDigit -= 9;
42
                }
43
            }
44
45 16
            $sum += $tempDigit;
46
        }
47
48 16
        return $sum;
49
    }
50
51 16
    private function isOdd($index): bool
52
    {
53 16
        return $index % 2 === 1;
54
    }
55
56 5
    private function buildViolation($value, $constraint): void
57
    {
58 5
        $this->context->buildViolation($constraint->message)
59 5
            ->setParameter('{{ string }}', $value)
60 5
            ->addViolation();
61
    }
62
}