Passed
Push — master ( 1faf78...54b905 )
by Thanos
03:17
created

AfmValidator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 91.3%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 3
dl 0
loc 44
ccs 21
cts 23
cp 0.913
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
C validate() 0 29 7
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
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
        $first = (int) array_shift($reverseAfm);
24 7
        $sum = 0;
25
26 7
        foreach ($reverseAfm as $index => $value) {
27 7
            $sum += $value * pow(2, ++$index);
28
        }
29
30 7
        $mod = $sum % 11;
31 7
        if ((10 === $mod && $first === 0) || ($mod === $first)) {
32 6
            return true;
33
        }
34
35 1
        $this->buildViolation($value, $constraint);
36
37 1
        return false;
38
    }
39
40
    private function isOdd($index)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
41
    {
42
        return $index % 2 === 1;
43
    }
44
45 2
    private function buildViolation($value, $constraint)
46
    {
47 2
        $this->context->buildViolation($constraint->message)
48 2
            ->setParameter('{{ string }}', $value)
49 2
            ->addViolation();
50
    }
51
}