SerializationTrait::convert()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
1
<?php
2
3
namespace App\Tests\TestUtils;
4
5
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
6
use Symfony\Component\Serializer\SerializerInterface;
7
8
trait SerializationTrait
9
{
10
    private ?SerializerInterface $serializer = null;
11
12
    protected function json(mixed $obj): string
13
    {
14
        return $this->getSerializer()->serialize($obj, 'json');
15
    }
16
17
    protected function object(string $json, string $class): mixed
18
    {
19
        return $this->getSerializer()->deserialize($json, $class, 'json');
20
    }
21
22
    protected function convert(array $data, string $class): mixed
23
    {
24
        return $this->getSerializer()->deserialize(json_encode($data), $class, 'json');
25
    }
26
27
    protected function responseObject(KernelBrowser $client, string $class): mixed
28
    {
29
        $content = $client->getResponse()->getContent();
30
        return $this->object($content, $class);
31
    }
32
33
    protected function responseObjects(KernelBrowser $client, string $class): array
34
    {
35
        $content = $client->getResponse()->getContent();
36
        $array = json_decode($content, true);
37
        $result = [];
38
        foreach ($array as $item) {
39
            array_push($result, $this->convert($item, $class));
40
        }
41
        return $result;
42
43
    }
44
45
    private function getSerializer(): SerializerInterface
46
    {
47
        return self::getContainer()->get('serializer');
48
    }
49
}