Completed
Push — 8.x-1.x ( 082f3b...0421f5 )
by
unknown
28:58 queued 09:33
created

DateTimeParamConverter::apply()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 33
ccs 0
cts 17
cp 0
rs 6.7272
cc 7
eloc 18
nc 6
nop 2
crap 56
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