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

JsonHttpSerializer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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