This repository has been archived by the owner on Apr 3, 2023. It is now read-only.
/
DateRangeValidator.php
74 lines (63 loc) · 2 KB
/
DateRangeValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace Mero\Bundle\BaseBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @author Rafael Mello <merorafael@gmail.com>
*
* @api
*/
class DateRangeValidator extends ConstraintValidator
{
/**
* {@inheritDoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof DateRange) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\DateRange');
}
if (null === $value) {
return;
}
if (!($value instanceof \DateTime)) {
$this->context->addViolation($constraint->invalidMessage, [
'{{ value }}' => $value,
]);
return;
}
if (null !== $constraint->max && $value > $constraint->max) {
$this->context->addViolation($constraint->maxMessage, [
'{{ value }}' => $value,
'{{ limit }}' => $this->formatDate($constraint->max),
]);
}
if (null !== $constraint->min && $value < $constraint->min) {
$this->context->addViolation($constraint->minMessage, [
'{{ value }}' => $value,
'{{ limit }}' => $this->formatDate($constraint->min),
]);
}
}
protected function formatDate($date)
{
$formatter = new \IntlDateFormatter(
null,
\IntlDateFormatter::SHORT,
\IntlDateFormatter::NONE,
date_default_timezone_get(),
\IntlDateFormatter::GREGORIAN
);
return $this->processDate($formatter, $date);
}
/**
* @param \IntlDateFormatter $formatter
* @param \Datetime $date
* @return string
*/
protected function processDate(\IntlDateFormatter $formatter, \Datetime $date)
{
return $formatter->format((int) $date->format('U'));
}
}