Test Setup Failed
Push — main ( abdcb9...2e5f68 )
by Slawomir
04:37
created

SerializationTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 40
rs 10
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A responseObject() 0 4 1
A getSerializer() 0 3 1
A responseObjects() 0 9 2
A convert() 0 3 1
A json() 0 3 1
A object() 0 3 1
1
<?php
2
3
namespace App\Tests\TestUtils;
4
5
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
6
use Symfony\Component\Serializer\Encoder\JsonEncoder;
7
use Symfony\Component\Serializer\Encoder\XmlEncoder;
8
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
9
use Symfony\Component\Serializer\Normalizer\UidNormalizer;
10
use Symfony\Component\Serializer\Serializer;
11
use Symfony\Component\Serializer\SerializerInterface;
12
13
trait SerializationTrait
14
{
15
    private ?SerializerInterface $serializer = null;
16
17
    protected function json(mixed $obj): string
18
    {
19
        return $this->getSerializer()->serialize($obj, 'json');
20
    }
21
22
    protected function object(string $json, string $class): mixed
23
    {
24
        return $this->getSerializer()->deserialize($json, $class, 'json');
25
    }
26
27
    protected function convert(array $data, string $class): mixed
28
    {
29
        return $this->getSerializer()->deserialize(json_encode($data), $class, 'json');
30
    }
31
32
    protected function responseObject(KernelBrowser $client, string $class): mixed
33
    {
34
        $content = $client->getResponse()->getContent();
35
        return $this->object($content, $class);
36
    }
37
38
    protected function responseObjects(KernelBrowser $client, string $class): array
39
    {
40
        $content = $client->getResponse()->getContent();
41
        $array = json_decode($content, true);
42
        $result = [];
43
        foreach ($array as $item) {
44
            array_push($result, $this->convert($item, $class));
45
        }
46
        return $result;
47
48
    }
49
50
    private function getSerializer(): SerializerInterface
51
    {
52
        return self::getContainer()->get('serializer');
53
    }
54
}