AbstractResponse::getData()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebServCo\Api;
6
7
use WebServCo\Framework\Http\Response;
8
9
abstract class AbstractResponse
10
{
11
    protected string $endpoint;
12
13
    protected mixed $data;
14
15
    protected string $method;
16
17
    protected Response $response;
18
19
    protected int $status;
20
21
    public function __construct(string $endpoint, string $method, Response $response)
22
    {
23
        $this->endpoint = $endpoint;
24
        $this->method = $method;
25
        $this->response = $response;
26
        $this->status = $this->response->getStatus();
27
        // In some situations there is no content to process
28
        if (\in_array($this->status, [204, 205], true)) {
29
            return;
30
        }
31
        $this->data = $this->processResponseData();
32
    }
33
34
    public function getData(): mixed
35
    {
36
        return $this->data;
37
    }
38
39
    public function getEndpoint(): string
40
    {
41
        return $this->endpoint;
42
    }
43
44
    public function getMethod(): string
45
    {
46
        return $this->method;
47
    }
48
49
    public function getStatus(): int
50
    {
51
        return $this->status;
52
    }
53
54
    protected function processResponseData(): mixed
55
    {
56
        $responseContent = $this->response->getContent();
57
        $contentType = $this->response->getHeaderLine('content-type');
58
        $parts = \explode(';', $contentType);
59
60
        switch ($parts[0]) {
61
            case 'application/json':
62
            case 'text/json':
63
                return \json_decode($responseContent, true);
64
            case 'application/x-www-form-urlencoded':
65
                if (false === \strpos($responseContent, '=')) {
66
                    /* Sometimes Discogs returns text/plain with this content type ... */
67
                    return $responseContent;
68
                }
69
                $data = [];
70
                \parse_str($responseContent, $data);
71
                return $data;
72
            case 'text/plain':
73
            case 'text/html':
74
                return $responseContent;
75
            default:
76
                throw new \WebServCo\Framework\Exceptions\UnsupportedMediaTypeException(
77
                    \sprintf('Api returned unsupported content type: %s.', (string) $contentType),
78
                );
79
        }
80
    }
81
}
82