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

DateTimeFieldNormalizer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 52
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A normalizeField() 0 21 4
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