Completed
Pull Request — master (#10)
by Omid
03:54
created

AbstractCoreApiClient::makeRequest()   B

Complexity

Conditions 3
Paths 11

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 12
cts 12
cp 1
rs 8.9713
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 30
    public function __construct(
43
        ClientInterface $httpClient,
44 2
        Serializer $serializer
45
    ) {
46 30
        $this->httpClient = $httpClient;
47 30
        $this->serializer = $serializer;
48 30
    }
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 16
    protected function makeRequest($method, $uri, $options)
72
    {
73 16
        $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 16
            if (isset($options[self::OPT_VIDEO_MANAGER_ID])) {
79 16
                $uri = sprintf('%d/%s', $options[self::OPT_VIDEO_MANAGER_ID], $uri);
80 16
            }
81
82 16
            $logger->info(sprintf('Making API %s request to %s', $method, $uri), [$uri]);
83
84
            /** @var ResponseInterface $response */
85 16
            $response = $this->_doRequest($method, $uri, $options);
86
87 12
            $logger->debug('Response from HTTP call was status code:', [$response->getStatusCode()]);
88 12
            $logger->debug('Response JSON was:', [$response->getBody()]);
89
90 12
            return $response;
91 4
        } catch (\Exception $e) {
92 4
            throw $e; // Just rethrow for now
93
        }
94
    }
95
96
    /**
97
     * Deserialize a response into an instance of it's associated class.
98
     *
99
     * @param string $data
100
     * @param string $serialisationClass
101
     *
102
     * @return object
103
     */
104 4
    protected function deserialize($data, $serialisationClass)
105
    {
106 4
        return $this->serializer->deserialize($data, $serialisationClass, 'json');
107
    }
108
109
    /**
110
     * Helper method to build the JSON data array for making a request
111
     * with ::makeRequest(). Optional parameters with empty or null value will be
112
     * omitted from the return value.
113
     *
114
     * Examples:
115
     *
116
     * $this->buildJsonParameters(['title' => 'test'], ['description' => '', 'bla' => 'test'])
117
     *
118
     * Would result in:
119
     *
120
     * [
121
     *     'title' => 'test',
122
     *     'bla' => 'test',
123
     * ]
124
     *
125
     * @param array $required
126
     * @param array $optional
127
     *
128
     * @return array
129
     */
130 16
    protected function buildJsonParameters(array $required, array $optional)
131
    {
132 16
        foreach ($required as $key => $value) {
133 16
            if (empty($value)) {
134 4
                throw new Exception(sprintf('Required parameter \'%s\' is missing..', $key));
135
            }
136 12
        }
137
138 12
        $json = $required;
139
140 12
        foreach ($optional as $key => $value) {
141 10
            if (!empty($value) || $value === false) {
142 6
                $json[$key] = $value;
143 6
            }
144 12
        }
145
146 12
        return $json;
147
    }
148
}
149