Completed
Push — 8.x-1.x ( 0421f5...0df7dc )
by
unknown
25:14
created

DateTimeParamConverter::apply()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7.0099

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 16
cts 17
cp 0.9412
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 18
nc 6
nop 2
crap 7.0099
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 4
    public function apply(Request $request, ParamConverter $configuration)
23
    {
24 4
        $param = $configuration->getName();
25
26 4
        if (!$request->attributes->has($param)) {
27
            return false;
28
        }
29
30 4
        $options = $configuration->getOptions();
31 4
        $value = $request->attributes->get($param);
32
33 4
        if (!$value && $configuration->isOptional()) {
34 1
            return false;
35
        }
36
37 3
        if (isset($options['format'])) {
38 1
            $date = DateTime::createFromFormat($options['format'], $value);
39
40 1
            if (!$date) {
41 1
                throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".', $param));
42
            }
43
        } else {
44 2
            if (false === strtotime($value)) {
45 1
                throw new NotFoundHttpException(sprintf('Invalid date given for parameter "%s".', $param));
46
            }
47
48 1
            $date = new DateTime($value);
49
        }
50
51 1
        $request->attributes->set($param, $date);
52
53 1
        return true;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 1
    public function supports(ParamConverter $configuration)
60
    {
61 1
        if (null === $configuration->getClass()) {
62 1
            return false;
63
        }
64
65 1
        return 'DateTime' === $configuration->getClass();
66
    }
67
}
68