Completed
Push — master ( 1ebd5f...de33d4 )
by Siim
10:15
created

SerializerTrait::createSerializer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: siim
5
 * Date: 11.02.19
6
 * Time: 9:56
7
 */
8
9
namespace Sf4\Api\Utils\Traits;
10
11
use Symfony\Component\Serializer\Encoder\JsonEncoder;
12
use Symfony\Component\Serializer\Exception\ExceptionInterface;
13
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
14
use Symfony\Component\Serializer\Serializer;
15
16
trait SerializerTrait
17
{
18
19
    /**
20
     * @param array|object|null $data
21
     */
22
    public function populate(array $data): void
23
    {
24
        if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
25
            $json = json_encode($data);
26
            $class = get_class($this);
27
            $this->createSerializer()->deserialize($json, $class, 'json', [
28
                'object_to_populate' => $this
29
            ]);
30
        }
31
    }
32
33
    /**
34
     * @return array
35
     */
36
    public function toArray(): array
37
    {
38
        return $this->objectToArray();
39
    }
40
41
    /**
42
     * @param null $object
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $object is correct as it would always require null to be passed?
Loading history...
43
     * @param array $ignoredAttributes
44
     * @return array
45
     */
46
    public function objectToArray($object = null, $ignoredAttributes = ['id', 'uuid']): array
47
    {
48
        if (null === $object) {
0 ignored issues
show
introduced by
The condition null === $object is always true.
Loading history...
49
            $object = $this;
50
        } elseif (is_scalar($object)) {
51
            $object = [$object];
52
        }
53
54
        if (is_array($object)) {
0 ignored issues
show
introduced by
The condition is_array($object) is always false.
Loading history...
55
            return $object;
56
        }
57
58
        try {
59
            $response = $this->createSerializer()->normalize($object, null, [
60
                ObjectNormalizer::ENABLE_MAX_DEPTH => true,
61
                ObjectNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes
62
            ]);
63
        } catch (ExceptionInterface $e) {
64
            $response = [];
65
        }
66
67
        return $response;
68
    }
69
70
    private function createSerializer(): Serializer
71
    {
72
        $encoders = [new JsonEncoder()];
73
        $normalizers = [new ObjectNormalizer()];
74
        return new Serializer($normalizers, $encoders);
75
    }
76
}
77