Completed
Push — 8.x-1.x ( 99c4c7...dece3c )
by
unknown
29:31
created

DateTimeParamConverter::apply()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 17
Ratio 100 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 17
loc 17
ccs 9
cts 10
cp 0.9
rs 9.2
cc 4
eloc 10
nc 3
nop 2
crap 4.016
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 View Code Duplication
    public function apply(Request $request, ParamConverter $configuration)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
23
    {
24 4
        $param = $configuration->getName();
25 4
        if (!$request->attributes->has($param)) {
26
            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