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

AfmValidator::validate()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 16
cts 16
cp 1
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 16
nc 6
nop 2
crap 7
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
}