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

AfmValidator::validate()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

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