Failed Conditions
Push — issue#666 ( 82e9d5...91903a )
by Guilherme
08:00
created

AgeValidator::validate()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 8.0069

Importance

Changes 0
Metric Value
cc 8
eloc 21
nc 11
nop 2
dl 0
loc 32
ccs 20
cts 21
cp 0.9524
crap 8.0069
rs 5.3846
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\ValidationBundle\Validator\Constraints;
12
13
use Symfony\Component\Validator\Constraint;
14
use Symfony\Component\Validator\ConstraintValidator;
15
16
class AgeValidator extends ConstraintValidator
17
{
18 3
    public function validate($value, Constraint $constraint)
19
    {
20 3
        if (!$value instanceof \DateTime || !$constraint instanceof Age) {
21
            return;
22
        }
23
24 3
        $now = new \DateTime();
25 3
        $minAgeDate = new \DateTime("-{$constraint->min} years");
26 3
        $maxAgeDate = new \DateTime("-{$constraint->max} years");
27
28 3
        $error = false;
29 3
        $limit = 0;
30
31 3
        if ($value > $now) {
32 1
            $error = $constraint->futureError;
33
        } else {
34 2
            if ($constraint->min > 0 && $value > $minAgeDate) {
35 1
                $error = $constraint->minError;
36 1
                $limit = $constraint->min;
37
            }
38
39 2
            if ($value < $maxAgeDate) {
40 1
                $error = $constraint->maxError;
41 1
                $limit = $constraint->max;
42
            }
43
        }
44
45 3
        if ($error) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $error of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
46 3
            $this->context
47 3
                ->buildViolation($error)
48 3
                ->setParameter('{{ limit }}', $limit)
49 3
                ->addViolation();
50
        }
51 3
    }
52
}
53