Test Failed
Push — master ( 13a00a...ad5f1c )
by Dominik
02:00
created

DateFieldNormalizer::normalizeField()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 8
cts 8
cp 1
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 14
nc 6
nop 5
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Normalizer;
6
7
use Psr\Http\Message\ServerRequestInterface as Request;
8
9
final class DateFieldNormalizer implements FieldNormalizerInterface
10
{
11
    /**
12
     * @var FieldNormalizerInterface
13
     */
14
    private $fieldNormalizer;
15
16
    /**
17
     * @var string
18
     */
19
    private $format;
20
21
    /**
22
     * @param FieldNormalizerInterface $fieldNormalizer
23
     * @param string                   $format
24
     */
25 4
    public function __construct(FieldNormalizerInterface $fieldNormalizer, string $format = 'c')
26
    {
27 4
        $this->fieldNormalizer = $fieldNormalizer;
28 4
        $this->format = $format;
29 4
    }
30
31
    /**
32
     * @param string                     $path
33
     * @param Request                    $request
34
     * @param object                     $object
35
     * @param NormalizerContextInterface $context
36
     * @param NormalizerInterface|null   $normalizer
37
     *
38
     * @return mixed
39
     */
40 4
    public function normalizeField(
41
        string $path,
42
        Request $request,
43
        $object,
44
        NormalizerContextInterface $context,
45
        NormalizerInterface $normalizer = null
46
    ) {
47 4
        $value = $this->fieldNormalizer->normalizeField($path, $request, $object, $context, $normalizer);
48
49 4
        if (is_string($value)) {
50
            try {
51 2
                $value = new \DateTime($value);
52 1
            } catch (\Exception $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
53
            }
54
        }
55
56 4
        if (!$value instanceof \DateTimeInterface) {
57 2
            return $value;
58
        }
59
60 2
        return $value->format($this->format);
61
    }
62
}
63