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

DateTimeParamConverter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 95.24%

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 4
dl 0
loc 53
ccs 20
cts 21
cp 0.9524
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C apply() 0 33 7
A supports() 0 8 2
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