Passed
Pull Request — main (#3)
by Daryl
02:28
created

Api::getMachine()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Clubdeuce\Tessitura\Helpers;
4
5
use Clubdeuce\Tessitura\Base\Base;
6
use Clubdeuce\Tessitura\Interfaces\ApiInterface;
7
use Clubdeuce\Tessitura\Interfaces\LoggerAwareInterface;
8
use Exception;
9
use GuzzleHttp\Client;
10
use GuzzleHttp\ClientInterface;
11
use GuzzleHttp\Exception\GuzzleException;
12
use GuzzleHttp\Psr7\Response;
13
use GuzzleHttp\Psr7\Stream;
14
use Psr\Log\LoggerInterface;
15
16
/**
17
 * Class API
18
 * @package Clubdeuce\Tessitura\Helpers
19
 */
20
class Api extends Base implements 
21
    ApiInterface,
22
    LoggerAwareInterface
23
{
24
25
    const CACHE_EXPIRATION_DEFAULT = 10 * 60; // 10 minutes
26
27
    /**
28
     * @var string The base path to the Tessitura API
29
     */
30
    protected string $_base_route = '';
31
32
    /**
33
     * @var string The machine name required for authentication.
34
     */
35
    protected string $_machine;
36
37
    /**
38
     * @var string The password required for authentication.
39
     */
40
    protected string $_password;
41
42
    /**
43
     * @var string The username required for authentication.
44
     */
45
    protected string $_username;
46
47
    /**
48
     * @var string The usergroup required for authentication
49
     */
50
    protected string $_usergroup;
51
52
    /**
53
     * @var string The Tessitura API version to use with this library
54
     */
55
    protected string $_version = '15';
56
57
    /**
58
     * @var ClientInterface GuzzleHttp client
59
     */
60
    protected ClientInterface $_client;
61
62
    /**
63
     * @var LoggerInterface|null
64
     */
65
    protected ?LoggerInterface $_logger = null;
66
67
    /**
68
     * API constructor.
69
     *
70
     * @param mixed[] $args {
71
     * @type string   $base_route
72
     * @type string   $location
73
     * @type string   $password
74
     * @type string   $usergroup
75
     * @type string   $username
76
     * @type string   $version
77
     * }
78
     * @param ClientInterface|null $client The HTTP client to use for API requests
79
     * @param LoggerInterface|null $logger The logger to use for logging
80
     */
81 14
    public function __construct(
82
        array $args = [],
83
        ?ClientInterface $client = null,
84
        ?LoggerInterface $logger = null
85
    ) {
86 14
        $args = $this->parseArgs($args, array(
87 14
            'baseRoute' => '',
88 14
            'machine' => '',
89 14
            'password' => '',
90 14
            'usergroup' => '',
91 14
            'username' => '',
92 14
            'version' => '16',
93 14
        ));
94
95 14
        if ($logger) {
96
            $this->setLogger($logger);
97
        }
98
99 14
        if (!$client && !empty($args['baseRoute'])) {
100 1
            $client = new Client([
101 1
                'base_uri' => $args['baseRoute'],
102 1
                'timeout' => 10.0,
103 1
            ]);
104
        }
105
106 14
        $args['client'] = $client;
107
108 14
        parent::__construct($args);
109
110
    }
111
112
    /**
113
     * @param string $resource
114
     * @param mixed[] $args
115
     * @return mixed
116
     * @throws Exception
117
     */
118 2
    public function get(string $resource, array $args = array()): mixed
119
    {
120 2
        $args = array_merge($args, array(
121 2
            'method' => 'GET',
122 2
        ));
123
124 2
        return $this->makeRequest($resource, $args);
125
    }
126
127
    /**
128
     * @param string  $endpoint
129
     * @param mixed[] $args
130
     * @return mixed
131
     * @throws Exception|GuzzleException
132
     */
133 2
    protected function makeRequest(string $endpoint, array $args): array
134
    {
135
        /**
136
         * @var Response $response
137
         */
138 2
        $response = $this->_client->get($this->getUri($endpoint), $args);
139
140 1
        if (200 === $response->getStatusCode()) {
141 1
            return json_decode($response->getBody(), true);
142
        }
143
144
        // We have successfully gotten a response from the API, but not a 200 status code.
145
        /**
146
         * @var Stream $body
147
         */
148
        $body = $response->getBody();
149
150
        throw new Exception(
151
            $body->getContents(),
152
            $response->getStatusCode()
153
        );
154
    }
155
156 1
    public function getVersion(): string
157
    {
158 1
        return $this->_version;
159
    }
160
161
    /**
162
     * @param mixed[] $args
163
     *
164
     * @return mixed[] {
165
     * @type int $cache_expiration
166
     * @type int $timeout
167
     * @type array $headers
168
     * }
169
     */
170 1
    protected function getRequestArgs(array $args = []): array
171
    {
172
173 1
        $args = $this->parseArgs($args, array(
174 1
            'cache_expiration' => self::CACHE_EXPIRATION_DEFAULT,
175 1
            'headers'          => [],
176 1
            'body'             => '',
177 1
            'timeout'          => 10.0,
178 1
        ));
179
180 1
        if (is_array($args['body'])) {
181
            if (empty($args['body'])) {
182
                $args['body'] = null;
183
            } else {
184
                $args['body'] = json_encode($args['body']);
185
            }
186
        }
187
188 1
        $parsedUrl = parse_url($this->baseRoute());
189 1
        $args['headers'] = $this->parseArgs($args['headers'], array(
190 1
            'Authorization' => $this->getAuthorizationHeaderValue(),
191 1
            'Content-Type'   => 'application/json',
192 1
            'Content-Length' => strlen($args['body']),
193 1
            'Accept'         => 'application/json',
194 1
            'Host'           => $parsedUrl['host'] ?? $this->baseRoute(),
195 1
        ));
196
197 1
        return array_filter($args);
198
199
    }
200
201
    /**
202
     * @return string
203
     */
204 2
    protected function getAuthorizationHeaderValue(): string
205
    {
206
207 2
        $auth_key = sprintf('%1$s:%2$s:%3$s:%4$s', $this->getUsername(), $this->getUsergroup(), $this->getMachine(), $this->getPassword());
208
209 2
        return sprintf('Basic %1$s', base64_encode($auth_key));
210
211
    }
212
213
    /**
214
     * @param string $endpoint
215
     *
216
     * @return string
217
     */
218 3
    protected function getUri(string $endpoint): string
219
    {
220
221 3
        return "{$this->baseRoute()}/{$endpoint}";
222
223
    }
224
225
    /**
226
     * @param string $endpoint
227
     * @param mixed[] $args
228
     * @return Exception|mixed[]
229
     * @throws GuzzleException
230
     */
231
    public function post(string $endpoint, array $args = []): array|Exception
232
    {
233
234
        $args = array_merge($args, array(
235
            'method' => 'POST',
236
        ));
237
238
        return $this->makeRequest($endpoint, $args);
239
240
    }
241
242
    /**
243
     * @param string $message
244
     * @param mixed[] $args {
245
     * @type string $file
246
     * @type string $line
247
     * @type string $function
248
     * @type array $trace
249
     * @type mixed[] $extra
250
     * }
251
     */
252
    protected function logEvent(string $message, array $args = []): void
253
    {
254
255
        $args = $this->parseArgs($args, array(
256
            'log' => 'tessitura',
257
        ));
258
259
        $message = 'Tessitura API: ' . $message;
260
261
        if ($this->getLogger()) {
262
            $this->getLogger()->info($message, $args);
263
        }
264
265
    }
266
267
    /**
268
     * Sets a logger instance on the object.
269
     *
270
     * @param LoggerInterface $logger The logger instance to use.
271
     * @return void
272
     */
273 1
    public function setLogger(LoggerInterface $logger): void
274
    {
275 1
        $this->_logger = $logger;
276
    }
277
278
    /**
279
     * Gets the logger instance.
280
     *
281
     * @return LoggerInterface|null The logger instance or null if none is set.
282
     */
283 1
    public function getLogger(): ?LoggerInterface
284
    {
285 1
        return $this->_logger;
286
    }
287
288
    public function logger(): ?LoggerInterface
289
    {
290
        return $this->getLogger();
291
    }
292
293
    public function setClient(ClientInterface $client): void
294
    {
295
        $this->_client = $client;
296
    }
297
298 1
    public function getClient(): ClientInterface
299
    {
300 1
        return $this->_client;
301
    }
302
303 4
    public function baseRoute(): string
304
    {
305 4
        return $this->_base_route;
306
    }
307
308 1
    public function setBaseRoute(string $baseRoute): void
309
    {
310 1
        $this->_base_route = $baseRoute;
311
    }
312
313 1
    public function setMachine(string $machine): void
314
    {
315 1
        $this->_machine = $machine;
316
    }
317
318 1
    public function setPassword(string $password): void
319
    {
320 1
        $this->_password = $password;
321
    }
322
323 1
    public function setUsername(string $username): void
324
    {
325 1
        $this->_username = $username;
326
    }
327
328 1
    public function setUsergroup(string $usergroup): void
329
    {
330 1
        $this->_usergroup = $usergroup;
331
    }
332
333 1
    public function setVersion(string $version): void
334
    {
335 1
        $this->_version = $version;
336
    }
337
338 1
    public function getBaseRoute(): string
339
    {
340 1
        return $this->_base_route;
341
    }
342
343 3
    public function getMachine(): string
344
    {
345 3
        return $this->_machine;
346
    }
347
348 3
    public function getPassword(): string
349
    {
350 3
        return $this->_password;
351
    }
352
353 4
    public function getUsergroup(): string
354
    {
355 4
        return $this->_usergroup;
356
    }
357
358 3
    public function getUsername(): string
359
    {
360 3
        return $this->_username;
361
    }
362
}
363