Completed
Push — master ( 585147...baa0c9 )
by Robert
04:07
created

ResponseModel::dataToArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
ccs 9
cts 9
cp 1
rs 9.4285
cc 3
eloc 7
nc 3
nop 0
crap 3
1
<?php
2
3
namespace MediaMonks\RestApiBundle\Model;
4
5
use MediaMonks\RestApiBundle\Exception\AbstractValidationException;
6
use MediaMonks\RestApiBundle\Exception\ExceptionInterface;
7
use MediaMonks\RestApiBundle\Response\Error;
8
use MediaMonks\RestApiBundle\Response\PaginatedResponseInterface;
9
use MediaMonks\RestApiBundle\Util\StringUtil;
10
use Symfony\Component\HttpFoundation\RedirectResponse;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\HttpKernel\Exception\HttpException;
13
14
class ResponseModel
15
{
16
    const EXCEPTION_GENERAL = 'Exception';
17
    const EXCEPTION_HTTP = 'HttpException';
18
19
    /**
20
     * @var int
21
     */
22
    protected $statusCode = Response::HTTP_OK;
23
24
    /**
25
     * @var bool
26
     */
27
    protected $returnStatusCode = false;
28
29
    /**
30
     * @var mixed
31
     */
32
    protected $data;
33
34
    /**
35
     * @var Response
36
     */
37
    protected $response;
38
39
    /**
40
     * @var \Exception
41
     */
42
    protected $exception;
43
44
    /**
45
     * @var PaginatedResponseInterface
46
     */
47
    protected $pagination;
48
49
    /**
50
     * @return int
51
     */
52 19
    public function getStatusCode()
53
    {
54 19
        if (isset($this->response)) {
55 4
            return $this->response->getStatusCode();
56
        }
57 15
        if (isset($this->exception)) {
58 4
            return $this->getExceptionStatusCode();
59
        }
60 11
        if ($this->isEmpty()) {
61 2
            return Response::HTTP_NO_CONTENT;
62
        }
63
64 9
        return $this->statusCode;
65
    }
66
67
    /**
68
     * @return int
69
     */
70 4
    protected function getExceptionStatusCode()
71
    {
72 4
        if ($this->exception instanceof HttpException) {
73 1
            return $this->exception->getStatusCode();
74 3
        } elseif ($this->exception instanceof AbstractValidationException) {
75 1
            return Response::HTTP_BAD_REQUEST;
76 2
        } elseif ($this->isValidHttpStatusCode($this->exception->getCode())) {
77 1
            return $this->exception->getCode();
78
        }
79 1
        return Response::HTTP_INTERNAL_SERVER_ERROR;
80
    }
81
82
    /**
83
     * @param int $code
84
     * @return bool
85
     */
86 2
    protected function isValidHttpStatusCode($code)
87
    {
88 2
        return array_key_exists($code, Response::$statusTexts) && $code >= Response::HTTP_BAD_REQUEST;
89
    }
90
91
    /**
92
     * @param int $statusCode
93
     * @return $this
94
     */
95 7
    public function setStatusCode($statusCode)
96
    {
97 7
        $this->statusCode = $statusCode;
98
99 7
        return $this;
100
    }
101
102
    /**
103
     * @return bool
104
     */
105 13
    public function getReturnStatusCode()
106
    {
107 13
        return $this->returnStatusCode;
108
    }
109
110
    /**
111
     * @param bool $returnStatusCode
112
     * @return $this
113
     */
114 2
    public function setReturnStatusCode($returnStatusCode)
115
    {
116 2
        $this->returnStatusCode = $returnStatusCode;
117
118 2
        return $this;
119
    }
120
121
    /**
122
     * @return mixed
123
     */
124 10
    public function getData()
125
    {
126 10
        return $this->data;
127
    }
128
129
    /**
130
     * @param mixed $data
131
     * @return $this
132
     */
133 20
    public function setData($data)
134
    {
135 20
        $this->data = $data;
136
137 20
        return $this;
138
    }
139
140
    /**
141
     * @return \Exception
142
     */
143 11
    public function getException()
144
    {
145 11
        return $this->exception;
146
    }
147
148
    /**
149
     * @param \Exception $exception
150
     * @return $this
151
     */
152 6
    public function setException(\Exception $exception)
153
    {
154 6
        $this->exception = $exception;
155
156 6
        return $this;
157
    }
158
159
    /**
160
     * @return array
161
     */
162 11
    public function getPagination()
163
    {
164 11
        return $this->pagination;
165
    }
166
167
    /**
168
     * @param PaginatedResponseInterface $pagination
169
     * @return $this
170
     */
171 2
    public function setPagination(PaginatedResponseInterface $pagination)
172
    {
173 2
        $this->pagination = $pagination;
174 2
        $this->setData($pagination->getData());
175
176 2
        return $this;
177
    }
178
179
    /**
180
     * @return Response
181
     */
182 11
    public function getResponse()
183
    {
184 11
        return $this->response;
185
    }
186
187
    /**
188
     * @param Response $response
189
     * @return ResponseModel
190
     */
191 5
    public function setResponse(Response $response)
192
    {
193 5
        $this->response = $response;
194 5
        $this->setStatusCode($response->getStatusCode());
195 5
        $this->setData($response->getContent());
196
197 5
        return $this;
198
    }
199
200
    /**
201
     * @return array
202
     */
203 12
    public function toArray()
204
    {
205 12
        $return = [];
206 12
        if ($this->getReturnStatusCode()) {
207 1
            $return['statusCode'] = $this->getStatusCode();
208 1
        }
209 12
        if (isset($this->exception)) {
210 3
            $return['error'] = $this->exceptionToArray();
211 12
        } elseif (isset($this->response) && $this->response instanceof RedirectResponse) {
212 1
            $return['location'] = $this->response->headers->get('Location');
213 1
        } else {
214 8
            $return += $this->dataToArray();
215
        }
216 12
        return $return;
217
    }
218
219
    /**
220
     * @return array
221
     */
222 8
    protected function dataToArray()
223
    {
224 8
        $return = [];
225 8
        if (isset($this->data)) {
226 7
            $return['data'] = $this->data;
227 7
            if (isset($this->pagination)) {
228 1
                $return['pagination'] = $this->pagination->toArray();
229 1
            }
230 7
        }
231 8
        return $return;
232
    }
233
234
    /**
235
     * @return array
236
     */
237 3
    protected function exceptionToArray()
238
    {
239 3
        if ($this->exception instanceof ExceptionInterface) {
240 1
            return $this->exception->toArray();
241 2
        } elseif ($this->exception instanceof HttpException) {
242 1
            return $this->httpExceptionToArray();
243
        }
244
245 1
        return $this->generalExceptionToArray();
246
    }
247
248
    /**
249
     * @return array
250
     */
251 1
    protected function httpExceptionToArray()
252
    {
253
        return [
254 1
            'code'    => $this->getExceptionErrorCode(Error::CODE_HTTP, self::EXCEPTION_HTTP),
255 1
            'message' => $this->exception->getMessage()
256 1
        ];
257
    }
258
259
    /**
260
     * @return array
261
     */
262 1
    protected function generalExceptionToArray()
263
    {
264
        return [
265 1
            'code'    => trim($this->getExceptionErrorCode(Error::CODE_GENERAL, self::EXCEPTION_GENERAL), '.'),
266 1
            'message' => $this->exception->getMessage()
267 1
        ];
268
    }
269
270
    /**
271
     * @param string $errorCode
272
     * @param string $trim
273
     * @return string
274
     */
275 2
    protected function getExceptionErrorCode($errorCode, $trim = null)
276
    {
277 2
        return sprintf($errorCode, StringUtil::classToSnakeCase($this->exception, $trim));
278
    }
279
280
    /**
281
     * @return bool
282
     */
283 17
    public function isEmpty()
284
    {
285
        return (
286 17
            !isset($this->exception)
287 17
            && is_null($this->data)
288 17
            && !isset($this->pagination)
289 17
            && (!isset($this->response) || $this->response->isEmpty())
290 17
        );
291
    }
292
293
    // @codeCoverageIgnoreStart
294
    /**
295
     * This is called when an exception is thrown during the response transformation
296
     *
297
     * @return string
298
     */
299
    public function __toString()
300
    {
301
        $data                  = $this->toArray();
302
        $data['error']['code'] = Error::CODE_REST_API_BUNDLE;
303
304
        return json_encode($data);
305
    }
306
    // @codeCoverageIgnoreEnd
307
}
308