Completed
Push — master ( 62c9f8...42303c )
by Peter
01:50
created

ErrorDetector::detect()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 27
ccs 14
cts 14
cp 1
rs 8.439
cc 6
eloc 14
nc 5
nop 1
crap 6
1
<?php
2
3
/**
4
 * AnimeDb package.
5
 *
6
 * @author    Peter Gribanov <[email protected]>
7
 * @copyright Copyright (c) 2011, Peter Gribanov
8
 * @license   http://opensource.org/licenses/GPL-3.0 GPL v3
9
 */
10
11
namespace AnimeDb\Bundle\ShikimoriBrowserBundle\Service;
12
13
use AnimeDb\Bundle\ShikimoriBrowserBundle\Exception\ErrorException;
14
use AnimeDb\Bundle\ShikimoriBrowserBundle\Exception\NotFoundException;
15
use Psr\Http\Message\ResponseInterface;
16
17
class ErrorDetector
18
{
19
    /**
20
     * @param ResponseInterface $response
21
     *
22
     * @return array
23
     */
24 6
    public function detect(ResponseInterface $response)
25
    {
26 6
        if ($response->getStatusCode() == 404) {
27 1
            throw NotFoundException::page();
28
        }
29
30 5
        $content = $response->getBody()->getContents();
31
32 5
        if ($content == '') {
33 1
            return [];
34
        }
35
36 4
        $data = json_decode($content, true);
37
38 4
        if (json_last_error() !== JSON_ERROR_NONE) {
39 1
            throw ErrorException::invalidResponse(json_last_error_msg(), json_last_error());
40
        }
41
42 3
        if (!empty($data['code'])) {
43 2
            throw ErrorException::failed(
44 2
                isset($data['message']) ? $data['message'] : '',
45 2
                $data['code']
46
            );
47
        }
48
49 1
        return (array) $data;
50
    }
51
}
52