EnumNormalizer::denormalize()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 4
dl 0
loc 7
rs 10
1
<?php
2
3
namespace W2w\Lib\ApieBenSampoEnumPlugin\Normalizers;
4
5
use BenSampo\Enum\Enum;
6
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
7
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
8
use W2w\Lib\Apie\Exceptions\InvalidValueForValueObjectException;
9
10
class EnumNormalizer implements NormalizerInterface, DenormalizerInterface
11
{
12
    public function denormalize($data, $class, $format = null, array $context = [])
13
    {
14
        $result = $class::coerce($data);
15
        if (!$result) {
16
            throw new InvalidValueForValueObjectException($data, $class);
17
        }
18
        return $result;
19
    }
20
21
    public function supportsDenormalization($data, $type, $format = null)
22
    {
23
        return is_a($type, Enum::class, true);
24
    }
25
26
    public function normalize($object, $format = null, array $context = [])
27
    {
28
        /** @var Enum $object */
29
        return $object->value;
30
    }
31
32
    public function supportsNormalization($data, $format = null)
33
    {
34
        return $data instanceof Enum;
35
    }
36
}
37