Completed
Push — master ( d94b80...c79c6c )
by Pieter
02:26
created

CarbonNormalizer::supportsDenormalization()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 1
c 1
b 0
f 1
nc 3
nop 3
dl 0
loc 3
rs 10
1
<?php
2
3
4
namespace W2w\Lib\Apie\Normalizers;
5
6
use Carbon\Carbon;
7
use Carbon\CarbonImmutable;
8
use Carbon\CarbonInterface;
9
use DateTime;
10
use DateTimeImmutable;
11
use DateTimeInterface;
12
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
13
14
/**
15
 * Extension on DateTimeNormalizer to use Carbon over the regular DateTime class instances.
16
 */
17
class CarbonNormalizer extends DateTimeNormalizer
18
{
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public function denormalize($data, $type, $format = null, array $context = [])
23
    {
24
        $internalType = $type;
25
        if ($type === CarbonInterface::class) {
26
            $internalType = DateTimeInterface::class;
27
        }
28
        if ($type === Carbon::class) {
29
            $internalType = DateTime::class;
30
        }
31
        if ($type === CarbonImmutable::class) {
32
            $internalType = DateTimeImmutable::class;
33
        }
34
        $result = parent::denormalize($data, $internalType, $format, $context);
35
        switch($type) {
36
            case Carbon::class:
37
            case DateTime::class:
38
                return Carbon::make($result);
39
            case DateTimeInterface::class:
40
            case CarbonInterface::class:
41
                if (class_exists(CarbonImmutable::class)) {
42
                    return CarbonImmutable::make($result);
43
                }
44
                return Carbon::make($result);
45
            case CarbonImmutable::class:
46
            case DateTimeImmutable::class:
47
                if (class_exists(CarbonImmutable::class)) {
48
                    return CarbonImmutable::make($result);
49
                }
50
                return $result;
51
        }
52
        return $result;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function supportsDenormalization($data, $type, $format = null)
59
    {
60
        return $type === Carbon::class || $type === CarbonImmutable::class || parent::supportsDenormalization($data, $type, $format);
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function hasCacheableSupportsMethod(): bool
67
    {
68
        return true;
69
    }
70
}
71