Test Setup Failed
Push — master ( 9d8f9a...f6d0c4 )
by
unknown
25:07
created

AbstractCoreApiClient::makeRequest()   A

Complexity

Conditions 5
Paths 37

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 9.0008
c 0
b 0
f 0
cc 5
nc 37
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MovingImage\Client\VMPro\ApiClient;
6
7
use GuzzleHttp\ClientInterface;
8
use JMS\Serializer\Serializer;
9
use MovingImage\Client\VMPro\Exception;
10
use MovingImage\Client\VMPro\Util\Logging\Traits\LoggerAwareTrait;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Log\LoggerAwareInterface;
13
14
abstract class AbstractCoreApiClient implements LoggerAwareInterface
15
{
16
    use LoggerAwareTrait;
17
18
    protected const OPT_VIDEO_MANAGER_ID = 'videoManagerId';
19
20
    protected ClientInterface $httpClient;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
21
22
    protected Serializer $serializer;
23
24
    public function __construct(
25
        ClientInterface $httpClient,
26
        Serializer $serializer
27
    ) {
28
        $this->httpClient = $httpClient;
29
        $this->serializer = $serializer;
30
    }
31
32
    /**
33
     * Make a request to the API and serialize the result according to our
34
     * serialization strategy.
35
     *
36
     * @return object|ResponseInterface
37
     * @throws \Exception
38
     */
39
    protected function makeRequest(string $method, string $uri, array $options)
40
    {
41
        $logger = $this->getLogger();
42
43
        try {
44
            // Automagically pre-pend videoManagerId if the option is present in the
45
            // options for sending the request
46
            if (isset($options[self::OPT_VIDEO_MANAGER_ID])) {
47
                $uri = sprintf('%d/%s', $options[self::OPT_VIDEO_MANAGER_ID], $uri);
48
            }
49
50
            $logger->info(sprintf('Making API %s request to %s', $method, $uri), [$uri]);
51
52
            /** @var ResponseInterface $response */
53
            $response = $this->_doRequest($method, $uri, $options);
54
55
            $logger->debug('Response from HTTP call was status code:', [$response->getStatusCode()]);
56
            $logger->debug('Response JSON was:', [$response->getBody()]);
57
58
            $response->getBody()->rewind();
59
60
            return $response;
61
        } catch (\Exception $e) {
62
            throw $e; // Just rethrow for now
63
        }
64
    }
65
66
    /**
67
     * Perform the actual request in the implementation classes.
68
     *
69
     * @return mixed
70
     */
71
    abstract protected function _doRequest(string $method, string $uri, array $options);
72
73
    /**
74
     * Deserialize a response into an instance of it's associated class.
75
     *
76
     * @return object
77
     */
78
    protected function deserialize(string $data, string $serialisationClass)
79
    {
80
        return $this->serializer->deserialize($data, $serialisationClass, 'json');
81
    }
82
83
    /**
84
     * Helper method to build the JSON data array for making a request
85
     * with ::makeRequest(). Optional parameters with empty or null value will be
86
     * omitted from the return value.
87
     *
88
     * Examples:
89
     *
90
     * $this->buildJsonParameters(['title' => 'test'], ['description' => '', 'bla' => 'test'])
91
     *
92
     * Would result in:
93
     *
94
     * [
95
     *     'title' => 'test',
96
     *     'bla' => 'test',
97
     * ]
98
     *
99
     * @throws Exception
100
     */
101
    protected function buildJsonParameters(array $required, array $optional): array
102
    {
103
        foreach ($required as $key => $value) {
104
            if (empty($value)) {
105
                throw new Exception(sprintf('Required parameter \'%s\' is missing..', $key));
106
            }
107
        }
108
109
        $json = $required;
110
111
        foreach ($optional as $key => $value) {
112
            if (!empty($value) || false === $value) {
113
                $json[$key] = $value;
114
            }
115
        }
116
117
        return $json;
118
    }
119
120
    /**
121
     * Serializes the provided response to a string, suitable for caching.
122
     * The type of the $response argument varies depending on the guzzle version.
123
     *
124
     * @param  mixed  $response
125
     *
126
     * @return string
127
     */
128
    abstract protected function serializeResponse($response);
129
130
    /**
131
     * Unserializes the serialized response into a response object.
132
     * The return type varies depending on the guzzle version.
133
     *
134
     * @param  string  $serialized
135
     *
136
     * @return mixed
137
     *
138
     * @throws Exception
139
     */
140
    abstract protected function unserializeResponse($serialized);
141
}
142