Passed
Branch main (4cb13d)
by Mr.
04:54 queued 02:43
created

JsonHttpSerializer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 50
ccs 13
cts 14
cp 0.9286
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A deserialize() 0 11 3
A serialize() 0 3 1
A getResponseHeaders() 0 3 1
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LibraryCatalog\Transformer;
6
7
use LibraryCatalog\Exception\HttpBadRequestException;
8
use LibraryCatalog\Transformer\Encoder\EncoderInterface;
9
10
class JsonHttpSerializer implements HttpSerializerInterface
11
{
12
    /** @var EncoderInterface */
13
    protected $encoder;
14
15
    /**
16
     * Serializer constructor.
17
     * @param EncoderInterface $encoder
18
     */
19 2
    public function __construct(EncoderInterface $encoder)
20
    {
21 2
        $this->encoder = $encoder;
22 2
    }
23
24
    /**
25
     * @param $data
26
     * @return string
27
     * @throws Encoder\Exception
28
     */
29 17
    public function serialize($data): string
30
    {
31 17
        return $this->encoder->encode($data);
32
    }
33
34
    /**
35
     * Should deserialize HTTP RAW data to array.
36
     *
37
     * @param string $data
38
     * @return array
39
     * @throws HttpBadRequestException
40
     */
41 7
    public function deserialize(string $data): array
42
    {
43
        try {
44 7
            $res = $this->encoder->decode($data);
45 1
        } catch (\Exception $e) {
46 1
            throw new HttpBadRequestException('Bad request, can not json-decode input data');
47
        }
48 6
        if (!is_array($res)) {
49
            throw new HttpBadRequestException('Bad request, can not json-decode input data');
50
        }
51 6
        return $res;
52
    }
53
54
    /**
55
     * @return array
56
     */
57 1
    public function getResponseHeaders(): array
58
    {
59 1
        return ['Content-Type' => 'application/json'];
60
    }
61
}
62