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
|
5 |
|
public function apply(Request $request, ParamConverter $configuration) |
23
|
|
|
{ |
24
|
5 |
|
$param = $configuration->getName(); |
25
|
5 |
|
if (!$request->attributes->has($param)) { |
26
|
1 |
|
return false; |
27
|
|
|
} |
28
|
|
|
|
29
|
4 |
|
$value = $request->attributes->get($param); |
30
|
4 |
|
if (!$value && $configuration->isOptional()) { |
31
|
1 |
|
return false; |
32
|
|
|
} |
33
|
|
|
|
34
|
3 |
|
$request->attributes->set($param, |
35
|
3 |
|
$this->getDateTime($configuration, $value, $param)); |
36
|
|
|
|
37
|
1 |
|
return true; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param ParamConverter $configuration |
42
|
|
|
* @param string $value |
43
|
|
|
* @param string $param |
44
|
|
|
* |
45
|
|
|
* @return \DateTime |
46
|
|
|
*/ |
47
|
3 |
|
protected function getDateTime(ParamConverter $configuration, $value, $param) |
48
|
|
|
{ |
49
|
3 |
|
$options = $configuration->getOptions(); |
50
|
|
|
|
51
|
3 |
|
if (isset($options['format'])) { |
52
|
1 |
|
$date = DateTime::createFromFormat($options['format'], $value); |
53
|
2 |
|
} elseif(false !== strtotime($value)) { |
54
|
1 |
|
$date = new DateTime($value); |
55
|
|
|
} |
56
|
|
|
|
57
|
3 |
|
if (empty($date)) { |
58
|
2 |
|
throw new NotFoundHttpException( |
59
|
2 |
|
sprintf('Invalid date given for parameter "%s".', $param)); |
60
|
|
|
} |
61
|
|
|
|
62
|
1 |
|
return $date; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* {@inheritdoc} |
67
|
|
|
*/ |
68
|
1 |
|
public function supports(ParamConverter $configuration) |
69
|
|
|
{ |
70
|
1 |
|
return \DateTime::class === $configuration->getClass(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|