Completed
Pull Request — master (#5)
by Ruben
03:27
created

AbstractCoreApiClient::makeRequest()   A

Complexity

Conditions 3
Paths 11

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 12
cts 12
cp 1
rs 9.0856
c 0
b 0
f 0
cc 3
eloc 12
nc 11
nop 3
crap 3
1
<?php
2
3
namespace MovingImage\Client\VMPro\ApiClient;
4
5
use GuzzleHttp\ClientInterface;
6
use JMS\Serializer\Serializer;
7
use MovingImage\Client\VMPro\Exception;
8
use MovingImage\Util\Logging\Traits\LoggerAwareTrait;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Log\LoggerAwareInterface;
11
12
/**
13
 * Class AbstractCoreApiClient.
14
 *
15
 * @author Ruben Knol <[email protected]>
16
 */
17
abstract class AbstractCoreApiClient implements LoggerAwareInterface
18
{
19
    use LoggerAwareTrait;
20
21
    /**
22
     * @const string
23
     */
24
    const OPT_VIDEO_MANAGER_ID = 'videoManagerId';
25
26
    /**
27
     * @var ClientInterface The Guzzle HTTP client
28
     */
29
    protected $httpClient;
30
31
    /**
32
     * @var Serializer The JMS Serializer instance
33
     */
34
    protected $serializer;
35
36
    /**
37
     * ApiClient constructor.
38
     *
39
     * @param ClientInterface $httpClient
40
     * @param Serializer      $serializer
41
     */
42 90
    public function __construct(
43
        ClientInterface $httpClient,
44 5
        Serializer $serializer
45
    ) {
46 90
        $this->httpClient = $httpClient;
47 90
        $this->serializer = $serializer;
48 90
    }
49
50
    /**
51
     * Perform the actual request in the implementation classes.
52
     *
53
     * @param string $method
54
     * @param string $uri
55
     * @param array  $options
56
     *
57
     * @return mixed
58
     */
59
    abstract protected function _doRequest($method, $uri, $options);
60
61
    /**
62
     * Make a request to the API and serialize the result according to our
63
     * serialization strategy.
64
     *
65
     * @param string $method
66
     * @param string $uri
67
     * @param array  $options
68
     *
69
     * @return object|ResponseInterface
70
     */
71 48
    protected function makeRequest($method, $uri, $options)
72
    {
73 48
        $logger = $this->getLogger();
74
75
        try {
76
            // Automagically pre-pend videoManagerId if the option is present in the
77
            // options for sending the request
78 48
            if (isset($options[self::OPT_VIDEO_MANAGER_ID])) {
79 48
                $uri = sprintf('%d/%s', $options[self::OPT_VIDEO_MANAGER_ID], $uri);
80 40
            }
81
82 48
            $logger->info(sprintf('Making API %s request to %s', $method, $uri), [$uri]);
83
84 48
            $response = $this->_doRequest($method, $uri, $options);
85
86 36
            $logger->debug('Response from HTTP call was status code:', [$response->getStatusCode()]);
87 36
            $logger->debug('Response JSON was:', [$response->getBody()]);
88
89 36
            return $response;
90 12
        } catch (\Exception $e) {
91 12
            throw $e; // Just rethrow for now
92
        }
93
    }
94
95
    /**
96
     * Deserialize a response into an instance of it's associated class.
97
     *
98
     * @param string $data
99
     * @param string $serialisationClass
100
     *
101
     * @return object
102
     */
103 12
    protected function deserialize($data, $serialisationClass)
104
    {
105 12
        return $this->serializer->deserialize($data, $serialisationClass, 'json');
106
    }
107
108
    /**
109
     * Helper method to build the JSON data array for making a request
110
     * with ::makeRequest(). Optional parameters with empty or null value will be
111
     * omitted from the return value.
112
     *
113
     * Examples:
114
     *
115
     * $this->buildJsonParameters(['title' => 'test'], ['description' => '', 'bla' => 'test'])
116
     *
117
     * Would result in:
118
     *
119
     * [
120
     *     'title' => 'test',
121
     *     'bla' => 'test',
122
     * ]
123
     *
124
     * @param array $required
125
     * @param array $optional
126
     *
127
     * @return array
128
     */
129 48
    protected function buildJsonParameters(array $required, array $optional)
130
    {
131 48
        foreach ($required as $key => $value) {
132 48
            if (empty($value)) {
133 18
                throw new Exception(sprintf('Required parameter \'%s\' is missing..', $key));
134
            }
135 30
        }
136
137 36
        $json = $required;
138
139 36
        foreach ($optional as $key => $value) {
140 30
            if (!empty($value) || $value === false) {
141 20
                $json[$key] = $value;
142 15
            }
143 30
        }
144
145 36
        return $json;
146
    }
147
}
148