Passed
Push — master ( feb24d...02877d )
by Dominik
03:23
created

DateTimeFieldNormalizer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Normalizer;
6
7
final class DateTimeFieldNormalizer implements FieldNormalizerInterface
8
{
9
    /**
10
     * @var FieldNormalizerInterface
11
     */
12
    private $fieldNormalizer;
13
14
    /**
15
     * @var string
16
     */
17
    private $format;
18
19
    /**
20
     * @param FieldNormalizerInterface $fieldNormalizer
21
     * @param string                   $format
22
     */
23 4
    public function __construct(FieldNormalizerInterface $fieldNormalizer, string $format = 'c')
24
    {
25 4
        $this->fieldNormalizer = $fieldNormalizer;
26 4
        $this->format = $format;
27 4
    }
28
29
    /**
30
     * @param string                     $path
31
     * @param object                     $object
32
     * @param NormalizerContextInterface $context
33
     * @param NormalizerInterface|null   $normalizer
34
     *
35
     * @return mixed
36
     */
37 4
    public function normalizeField(
38
        string $path,
39
        $object,
40
        NormalizerContextInterface $context,
41
        NormalizerInterface $normalizer = null
42
    ) {
43 4
        $value = $this->fieldNormalizer->normalizeField($path, $object, $context, $normalizer);
44
45 4
        if (is_string($value)) {
46
            try {
47 2
                $value = new \DateTime($value);
48 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...
49
            }
50
        }
51
52 4
        if (!$value instanceof \DateTimeInterface) {
53 2
            return $value;
54
        }
55
56 2
        return $value->format($this->format);
57
    }
58
}
59