ComradeDeserializer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace ComradeReader\Service;
4
5
use ComradeReader\Exception\Deserializer\DeserializerException;
6
use ComradeReader\Model\Entity\PaginatedResults;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * Deserializer
11
 * ============
12
 *   Decodes a JSON string into single object or into
13
 *   multiple objects. Supports paginated responses.
14
 *
15
 * @package ComradeReader\Service
16
 */
17
class ComradeDeserializer
18
{
19
    /** @var ResponseInterface $response */
20
    private $response;
21
22
    /** @var Symfony\Component\Serializer\SerializerInterface|\JMS\Serializer\SerializerInterface $serializer */
23
    protected $serializer;
24
25
    /**
26
     * @param ResponseInterface $response
27
     * @param object            $serializer
28
     */
29
    public function __construct(ResponseInterface $response, $serializer)
30
    {
31
        $this->response   = $response;
32
        $this->serializer = $serializer;
33
    }
34
35
    /**
36
     * @return string
37
     */
38
    public function getPlainResponse()
39
    {
40
        return $this->response->getBody()->getContents();
41
    }
42
43
    /**
44
     * @throws DeserializerException
45
     * @return array|mixed
46
     */
47
    public function getDecodedResponse()
48
    {
49
        $response = json_decode($this->getPlainResponse(), true);
50
51
        if (!is_array($response)) {
52
            throw new DeserializerException(
53
                'Response is not a valid json, decode error: ' . json_last_error_msg(),
54
                $this->getPlainResponse()
55
            );
56
        }
57
58
        return $response;
59
    }
60
61
    /**
62
     * @return ResponseInterface
63
     */
64
    public function getResponse(): ResponseInterface
65
    {
66
        return $this->response;
67
    }
68
69
    /**
70
     * @return array|mixed
71
     */
72
    public function getData()
73
    {
74
        $decoded = $this->getDecodedResponse();
75
76
        if (isset($decoded['success'])
77
            && $decoded['success']
78
            && isset($decoded['data'])
79
            && is_array($decoded['data']))
80
        {
81
            return $decoded['data'];
82
        }
83
84
        return $decoded;
85
    }
86
87
    /**
88
     * @param string $targetEntity
89
     * @return object
90
     */
91
    public function decodeIntoObject($targetEntity)
92
    {
93
        $response = $this->_convertNaming(
94
            $this->getData()
95
        );
96
        return $this->serializer->deserialize(json_encode($response), $targetEntity, 'json');
97
    }
98
99
    /**
100
     * Decodes a response into array of objects or into a PaginatedResults
101
     *
102
     * @param string $targetEntity
103
     * @return object[]|PaginatedResults
104
     */
105
    public function decodeIntoMultipleObjects($targetEntity)
106
    {
107
        $responseDecoded = $this->getData();
108
109
        // paginator
110
        $responseObjects = isset($responseDecoded['results']) ? $responseDecoded['results'] : $responseDecoded;
111
        $responseObjects = array_map(
112
113
            function ($item) use ($targetEntity)
114
            {
115
                $item = $this->_convertNaming($item);
116
                return $this->serializer->deserialize(json_encode($item), $targetEntity, 'json');
117
            },
118
119
            $responseObjects
120
        );
121
122
        if (isset($responseDecoded['results'])) {
123
            return new PaginatedResults(
124
                $responseObjects,
125
                $responseDecoded['current_page'],
126
                $responseDecoded['max_pages']
127
            );
128
        }
129
130
        return $responseObjects;
131
    }
132
133
    /**
134
     * @param array $array
135
     * @return array
136
     */
137
    private function _convertNaming($array)
138
    {
139
        $result = [];
140
141
        foreach ($array as $key => $value) {
142
            $key = lcfirst(implode('', array_map('ucfirst', explode('_', $key))));
143
            $result[$key] = $value;
144
        }
145
146
        return $result;
147
    }
148
}