|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Drupal\controller_annotations\Request\ParamConverter; |
|
4
|
|
|
|
|
5
|
|
|
use Drupal\controller_annotations\Configuration\ParamConverter; |
|
6
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
7
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
|
8
|
|
|
use DateTime; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Convert DateTime instances from request attribute variable. |
|
12
|
|
|
* |
|
13
|
|
|
* @author Benjamin Eberlei <[email protected]> |
|
14
|
|
|
*/ |
|
15
|
|
|
class DateTimeParamConverter implements ParamConverterInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* {@inheritdoc} |
|
19
|
|
|
* |
|
20
|
|
|
* @throws NotFoundHttpException When invalid date given |
|
21
|
|
|
*/ |
|
22
|
|
|
public function apply(Request $request, ParamConverter $configuration) |
|
23
|
|
|
{ |
|
24
|
|
|
$param = $configuration->getName(); |
|
25
|
|
|
|
|
26
|
|
|
if (!$request->attributes->has($param)) { |
|
27
|
|
|
return false; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
$options = $configuration->getOptions(); |
|
31
|
|
|
$value = $request->attributes->get($param); |
|
32
|
|
|
|
|
33
|
|
|
if (!$value && $configuration->isOptional()) { |
|
34
|
|
|
return false; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
if (isset($options['format'])) { |
|
38
|
|
|
$date = DateTime::createFromFormat($options['format'], $value); |
|
39
|
|
|
|
|
40
|
|
|
if (!$date) { |
|
41
|
|
|
throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".', $param)); |
|
42
|
|
|
} |
|
43
|
|
|
} else { |
|
44
|
|
|
if (false === strtotime($value)) { |
|
45
|
|
|
throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".', $param)); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
$date = new DateTime($value); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
$request->attributes->set($param, $date); |
|
52
|
|
|
|
|
53
|
|
|
return true; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* {@inheritdoc} |
|
58
|
|
|
*/ |
|
59
|
|
|
public function supports(ParamConverter $configuration) |
|
60
|
|
|
{ |
|
61
|
|
|
if (null === $configuration->getClass()) { |
|
62
|
|
|
return false; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return 'DateTime' === $configuration->getClass(); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|