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

AmkaValidator::validate()   C

Complexity

Conditions 8
Paths 10

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 8

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 18
cts 18
cp 1
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 18
nc 10
nop 2
crap 8
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
        $sum = 0;
23 16
        foreach(str_split($value) as $index => $char) {
24 16
            $tempDigit = intval($char);
25 16
            if ($this->isOdd($index)) {
26 16
                $tempDigit *= 2;
27 16
                if ($tempDigit > 9) {
28 15
                    $tempDigit -= 9;
29
                }
30
            }
31
32 16
            $sum += $tempDigit;
33
        }
34
35 16
        if ($sum % 10 !== 0) {
36 2
            $this->buildViolation($value, $constraint);
37
38 2
            return false;
39
        }
40
41 14
        return true;
42
    }
43
44 16
    private function isOdd($index)
45
    {
46 16
        return $index % 2 === 1;
47
    }
48
49 5
    private function buildViolation($value, $constraint)
50
    {
51 5
        $this->context->buildViolation($constraint->message)
52 5
            ->setParameter('{{ string }}', $value)
53 5
            ->addViolation();
54
    }
55
}