Completed
Push — develop ( 97a737...3a270c )
by Fabian
29s queued 18s
created

JsonResponseHelper::isResponsible()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cakasim\Payone\Sdk\Api\Client\ResponseHelper;
6
7
use Cakasim\Payone\Sdk\Api\Client\ClientException;
8
use Cakasim\Payone\Sdk\Api\Message\JsonResponseInterface;
9
use Cakasim\Payone\Sdk\Api\Message\ResponseInterface;
10
use Psr\Http\Message\RequestInterface as HttpRequestInterface;
11
use Psr\Http\Message\ResponseInterface as HttpResponseInterface;
12
13
/**
14
 * @author Fabian Böttcher <[email protected]>
15
 * @since 0.1.0
16
 */
17
class JsonResponseHelper implements ResponseHelperInterface
18
{
19
    /**
20
     * @inheritDoc
21
     */
22
    public function isResponsible(ResponseInterface $response): bool
23
    {
24
        return $response instanceof JsonResponseInterface;
25
    }
26
27
    /**
28
     * @inheritDoc
29
     */
30
    public function modifyHttpRequest(HttpRequestInterface $request): HttpRequestInterface
31
    {
32
        return $request->withHeader('Accept', 'application/json');
33
    }
34
35
    /**
36
     * @inheritDoc
37
     */
38
    public function makeResponseData(HttpResponseInterface $response)
39
    {
40
        // Ensure application/json content type which indicates a JSON response.
41
        if (stristr($response->getHeaderLine('Content-Type'), 'application/json') === false) {
42
            throw new ClientException("Cannot read JSON response. The 'Content-Type' response header is not 'application/json'.");
43
        }
44
45
        // Get whole body contents of the response.
46
        $bodyContents = $response->getBody()->getContents();
47
48
        // Expect a non-empty response body.
49
        if (empty($bodyContents)) {
50
            throw new ClientException("Cannot read JSON response. The response body is empty.");
51
        }
52
53
        return $bodyContents;
54
    }
55
}
56