Completed
Push — issue#736 ( 78f04a )
by Guilherme
19:20
created

AgeValidator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 40
rs 10
wmc 9
lcom 1
cbo 5

1 Method

Rating   Name   Duplication   Size   Complexity  
D validate() 0 37 9
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
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
16
17
class AgeValidator extends ConstraintValidator
18
{
19
    public function validate($value, Constraint $constraint)
20
    {
21
        if (!$constraint instanceof Age) {
22
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Age');
23
        }
24
        if (!$value instanceof \DateTime || !$constraint instanceof Age) {
25
            throw new UnexpectedTypeException($value, '\DateTime');
26
        }
27
28
        $now = new \DateTime();
29
        $minAgeDate = new \DateTime("-{$constraint->min} years");
30
        $maxAgeDate = new \DateTime("-{$constraint->max} years");
31
32
        $error = false;
33
        $limit = 0;
34
35
        if ($value > $now) {
36
            $error = $constraint->futureError;
37
        } else {
38
            if ($constraint->min > 0 && $value > $minAgeDate) {
39
                $error = $constraint->minError;
40
                $limit = $constraint->min;
41
            }
42
43
            if ($value < $maxAgeDate) {
44
                $error = $constraint->maxError;
45
                $limit = $constraint->max;
46
            }
47
        }
48
49
        if ($error) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $error of type string|false 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...
50
            $this->context
51
                ->buildViolation($error)
52
                ->setParameter('{{ limit }}', $limit)
53
                ->addViolation();
54
        }
55
    }
56
}
57