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

AfmValidator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 3
dl 0
loc 50
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B validate() 0 25 4
A checkModAgainstLastDigit() 0 4 3
A calculateChecksum() 0 9 2
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
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
}