Passed
Pull Request — master (#2)
by Andreas
01:40
created

RestClient::getMessageFactory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Larium\Pay\Client;
6
7
use Http\Discovery\Psr17FactoryDiscovery;
8
use Http\Message\Authentication\BasicAuth;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
12
class RestClient extends AbstractClient
13
{
14
    private string $username;
15
16
    private string $pass;
17
18
    private array $headerAuthentication = [];
19
20 2
    public function __construct(
21
        private readonly string $baseUri,
22
        private readonly string $resource,
23
        private array $headers = [],
24
        array $options = []
25
    ) {
26 2
        $this->options = $options;
27
    }
28
29
    public function addHeader(string $name, string $value): void
30
    {
31
        $this->headers[$name] = $value;
32
    }
33
34
    public function get(string $id = null, string|array $payload = ''): array
35
    {
36
        $uri = $this->getUri($id);
37
        if ($query = $this->normalizePayload($payload)) {
38
            $uri = $uri . '?' . ltrim($query, '?');
39
        }
40
41
        return $this->request($uri, 'GET');
42
    }
43
44
    public function post(string|array $payload): array
45
    {
46
        return $this->request($this->getUri(), 'POST', $payload);
47
    }
48
49
    public function put(string $id, string|array $payload = ''): array
50
    {
51
        $uri = $this->getUri($id);
52
53
        return $this->request($uri, 'PUT', $payload);
54
    }
55
56
    private function request(
57
        string $uri,
58
        string $method,
59
        string|array $payload = ''
60
    ): array {
61
        $factory = Psr17FactoryDiscovery::findRequestFactory();
62
        $request = $factory->createRequest(
63
            $method,
64
            $uri
65
        );
66
67
        foreach ($this->headers as $name => $value) {
68
            $request = $request->withHeader($name, $value);
69
        }
70
71
        if (is_array($payload)) {
72
            $payload = $this->normalizePayload($payload);
73
        }
74
75
        if (!empty($payload)) {
76
            $stream = Psr17FactoryDiscovery::findStreamFactory()->createStream($payload);
77
            $request = $request->withBody($stream);
78
        }
79
80
        $request = $this->authenticate($request);
81
82
        return $this->resolveResponse($this->sendRequest($request));
83
    }
84
85
    public function delete(string $id): array
86
    {
87
        $uri = $this->getUri($id);
88
89
        return $this->request($uri, 'DELETE');
90
    }
91
92 2
    public function getUri(string $id = null): string
93
    {
94 2
        $uri = $this->resource
95 2
            ? sprintf('%s/%s', $this->baseUri, $this->resource)
96
            : $this->baseUri;
97
98 2
        if ($id) {
99 1
            $uri = sprintf($uri, $id);
100
        }
101
102 2
        return $uri;
103
    }
104
105
    public function setBasicAuthentication(
106
        string $username,
107
        string $password
108
    ): void {
109
        $this->username = $username;
110
        $this->pass = $password;
111
    }
112
113
    public function setHeaderAuthentication(string $name, string $value): void
114
    {
115
        $this->headerAuthentication = ['name' => $name, 'value' => $value];
116
    }
117
118
    protected function authenticate(RequestInterface $request): RequestInterface
119
    {
120
        if ($this->username || $this->pass) {
121
            $authentication = new BasicAuth($this->username, $this->pass);
122
123
            return $authentication->authenticate($request);
124
        }
125
126
        if (!empty($this->headerAuthentication)) {
127
            $request = $request->withHeader(
128
                $this->headerAuthentication['name'],
129
                $this->headerAuthentication['value']
130
            );
131
132
            return $request;
133
        }
134
135
        return $request;
136
    }
137
138
    private function normalizePayload(string|array $payload): string
139
    {
140
        if (is_string($payload)) {
0 ignored issues
show
introduced by
The condition is_string($payload) is always false.
Loading history...
141
            return $payload;
142
        }
143
144
        return http_build_query($payload);
145
    }
146
147
    /**
148
     * Resolve the response from client.
149
     *
150
     * @param ResponseInterface $response
151
     * @return array An array with following values:
152
     *              'status': The Http status of response
153
     *              'headers': An array of response headers
154
     *              'body': The json decoded body response. (Since we are in
155
     *              RestClient)
156
     *              'raw_response': The raw body response for logging purposes.
157
     *              'raw_request': The raw body request for logging purposes.
158
     */
159
    protected function resolveResponse(ResponseInterface $response): array
160
    {
161
        $body = $response->getBody()->__toString();
162
        $responseBody = json_decode($body, true) ?: [];
163
164
        return [
165
            'status' => $response->getStatusCode(),
166
            'headers' => $response->getHeaders(),
167
            'body' => $responseBody,
168
            'raw_response' => $body,
169
            'raw_request' => $this->rawRequest,
170
        ];
171
    }
172
}
173