|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of Respect/Validation. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Respect\Validation\Rules; |
|
13
|
|
|
|
|
14
|
|
|
use DateTime; |
|
15
|
|
|
use Respect\Validation\Exceptions\ComponentException; |
|
16
|
|
|
|
|
17
|
|
|
class Age extends AllOf |
|
18
|
|
|
{ |
|
19
|
|
|
public $minAge; |
|
20
|
|
|
public $maxAge; |
|
21
|
|
|
|
|
22
|
26 |
|
public function __construct($minAge = null, $maxAge = null) |
|
23
|
|
|
{ |
|
24
|
26 |
|
if (null === $minAge && null === $maxAge) { |
|
25
|
1 |
|
throw new ComponentException('An age interval must be provided'); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
25 |
|
if (null !== $minAge && null !== $maxAge && $maxAge <= $minAge) { |
|
29
|
2 |
|
throw new ComponentException(sprintf('%d cannot be greater than or equals to %d', $minAge, $maxAge)); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
23 |
|
$this->setMinAge($minAge); |
|
33
|
23 |
|
$this->setMaxAge($maxAge); |
|
34
|
23 |
|
} |
|
35
|
|
|
|
|
36
|
23 |
|
private function createDateTimeFromAge($age) |
|
37
|
|
|
{ |
|
38
|
23 |
|
$interval = sprintf('-%d years', $age); |
|
39
|
|
|
|
|
40
|
23 |
|
return new DateTime($interval); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
23 |
|
private function setMaxAge($maxAge) |
|
44
|
|
|
{ |
|
45
|
23 |
|
$this->maxAge = $maxAge; |
|
46
|
|
|
|
|
47
|
23 |
|
if (null === $maxAge) { |
|
48
|
7 |
|
return; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
16 |
|
$minDate = $this->createDateTimeFromAge($maxAge); |
|
52
|
16 |
|
$minDate->setTime(0, 0, 0); |
|
53
|
|
|
|
|
54
|
16 |
|
$minRule = new Min($minDate, true); |
|
55
|
|
|
|
|
56
|
16 |
|
$this->addRule($minRule); |
|
57
|
16 |
|
} |
|
58
|
|
|
|
|
59
|
23 |
|
private function setMinAge($minAge) |
|
60
|
|
|
{ |
|
61
|
23 |
|
$this->minAge = $minAge; |
|
62
|
|
|
|
|
63
|
23 |
|
if (null === $minAge) { |
|
64
|
7 |
|
return; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
16 |
|
$maxDate = $this->createDateTimeFromAge($minAge); |
|
68
|
16 |
|
$maxDate->setTime(23, 59, 59); |
|
69
|
|
|
|
|
70
|
16 |
|
$maxRule = new Max($maxDate, true); |
|
71
|
|
|
|
|
72
|
16 |
|
$this->addRule($maxRule); |
|
73
|
16 |
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|