Completed
Push — 8.x-1.x ( 0d95ba...2c0805 )
by
unknown
26:58
created

DateTimeParamConverter::apply()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 17
ccs 10
cts 10
cp 1
rs 9.2
cc 4
eloc 10
nc 3
nop 2
crap 4
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