Passed
Push — scrutinizer ( f052ee...4395d0 )
by
unknown
06:54
created

Client::getTicket()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.1825

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 5
nop 1
dl 0
loc 17
ccs 8
cts 11
cp 0.7272
crap 3.1825
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace InShore\Bookwhen;
6
7
use GuzzleHttp;
8
use GuzzleHttp\Client as GuzzleClient;
9
use GuzzleHttp\Psr7\Request;
10
use InShore\Bookwhen\Exceptions\ConfigurationException;
11
use InShore\Bookwhen\Exceptions\RestException;
12
use InShore\Bookwhen\Exceptions\ValidationException;
13
use InShore\Bookwhen\Interfaces\ClientInterface;
14
use InShore\Bookwhen\Validator;
15
use Monolog\Logger;
16
use Monolog\Handler\StreamHandler;
17
use Psr\Http\Message\ResponseInterface;
18
19
/**
20
 * Class Client
21
 *
22
 * The main class for API consumption
23
 *
24
 * @package inshore\bookwhen
25
 * @todo comments
26
 * @todo externalise config
27
 * @todo fix token
28
 */
29
class Client implements ClientInterface
30
{
31
    
32
    /** @var string The API access token */
33
    private static $token = null;
34
    
35
    /** @var string The instance token, settable once per new instance */
36
    private $instanceToken;
37
    
38
    private $apiBaseUri;
39
    
40
    private $apiQuery;
41
   
42
    private $apiResource;
43
    
44
    private $apiVersion;
45
46
    private $include;
47
    
48
    /** @var string The path to the log file */
49
    private $log;
50
    
51
    /** @var object loging object. */
52
    private $logger;
53
    
54
    /** @var string the logging level. */
55
    private $logging;
56
    
57
    private $validator;
58
    
59
    private $guzzleClient;
60
    
61
    /**
62
     * {@inheritDoc}
63
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::__construct()
64
     */
65 8
    public function __construct($token = null, $debug = 'DEBUG')
66
    {
67
        // Logging.
68
        // 'DEBUG',
69
        // 'INFO',
70
        // 'NOTICE',
71
        // 'WARNING',
72
        // 'ERROR',
73
        // 'CRITICAL',
74
        // 'ALERT',
75
        // 'EMERGENCY',
76 8
        if (empty($this->logging)) {
77 8
            $this->logging = 'DEBUG';
78 8
            $this->log = 'inShoreBookwhen.log';
79
        }
80 8
        $this->logger = new Logger('inShore Bookwhen API');
81 8
        $this->logger->pushHandler(new StreamHandler($this->log, Logger::getLevels()[$this->logging]));
82
        
83 8
        $this->validator = new Validator();
84
        
85 8
        $this->include = [];
86
        
87 8
        if ($token === null) {
88
            //             if (self::$token === null) {
89
            //                 $msg = 'No token provided, and none is globally set. ';
90
            //                 $msg .= 'Use Diffbot::setToken, or instantiate the Diffbot class with a $token parameter.';
91
            //                 throw new ConfigurationException($msg);
92
            //             }
93
        } else {
94 8
            if ($this->validator->validToken($token)) {
95 8
                self::$token = $token;
96 8
                $this->instanceToken = self::$token;
97
            }
98
        }
99
        
100 8
        $this->apiBaseUri = 'https://api.bookwhen.com/';    
101 8
        $this->apiQuery = [];
102 8
        $this->apiVersion = 'v2';
103
        
104 8
        $this->guzzleClient = new GuzzleClient([
105 8
            'base_uri' => $this->apiBaseUri
106
        ]);
107
        
108 8
        $this->logger->info('Client class successfully instantiated');
109 8
        $this->logger->debug(var_export($this, true));
110 8
    }
111
    
112
    /**
113
     * {@inheritDoc}
114
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::request()
115
     */
116 6
    protected function request(): ResponseInterface
117
    {
118 6
        $this->logger->debug(__METHOD__ . '()');
119
        try {
120
            // Authorization.
121
            $requestOptions = [
122
                'headers' => [
123 6
                    'Authorization' => 'Basic ' . base64_encode($this->instanceToken . ':')
124
                ]
125
            ];
126
            
127
            // Query.
128 6
            if (!empty($this->apiQuery) && is_array($this->apiQuery)) {
129 1
                $requestOptions['query'] = $this->apiQuery;
130
            }
131
   
132 6
            $this->logger->debug('request(GET, ' . $this->apiResource . ', ' . var_export($requestOptions, true) . ')');
133 6
            $requestOptions['debug'] = true;
134
            
135 6
            return $this->guzzleClient->request('GET', $this->apiResource, $requestOptions);
136
           
137
        } catch (Exception $e) {
138
            throw new RestException($e, $this->logger);
139
        }
140
    }
141
    
142
    /**
143
     * {@inheritDoc}
144
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getAttachment()
145
     */
146 2
    public function getAttachment($attachmentId)
147
    {
148 2
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
149 2
        if (!$this->validator->validId($attachmentId, 'attachment')) {
150 1
            throw new ValidationException('attachmentId', $attachmentId);
151
        }
152 1
        $this->apiResource = $this->apiVersion . '/attachments' . '/' . $attachmentId;
153
     
154
        try {
155 1
            $Response = $this->request();
156 1
            $body = json_decode($Response->getBody()->getContents());
157 1
            $attachment = $body->data[0];
158 1
            $return = $attachment;
159 1
            return $return;
160
        } catch (Exception $e) {
161
            throw new RestException($e, $this->logger);
162
        }
163
    }
164
    
165
    /**
166
     *
167
     * {@inheritDoc}
168
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getAttachments()
169
     */
170 1
    public function getAttachments($title = null, $fileName = null, $fileType = null): array
171
    {    
172 1
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
173 1
        if (!is_null($title) && !$this->validator->validTitle($title)) {
174
            throw new ValidationException('title', $title);
175
        }
176
177 1
        if (!is_null($fileName) && !$this->validator->validFileName($fileName)) {
178
            throw new ValidationException('file name', $fileName);
179
        }
180
        
181 1
        if (!is_null($fileType) && !$this->validator->validFileType($fileType)) {
182
            throw new ValidationException('file type', $fileType);
183
        }
184
        
185 1
        $this->apiResource = $this->apiVersion . '/attachments';
186
        
187
        try {
188 1
            $return = [];
189 1
            $Response = $this->request();
190 1
            $body = json_decode($Response->getBody()->getContents());
191
            
192 1
            foreach ($body->data as $attachment) {
193 1
                array_push($return, $attachment);
194
            }
195
            
196 1
            return $return;
197
        } catch (Exception $e) {
198
            throw new RestException($e, $this->logger);
199
        }
200
    }
201
    
202
    /**
203
     *
204
     * {@inheritDoc}
205
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getClassPass()
206
     */
207
    public function getClassPass($classPassId)
208
    {
209
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
210
        $this->apiResource = $this->apiVersion . '/class_passes';
211
       
212
        if (!$this->validator->validId($classPassId, 'classPass')) {
213
            throw new ValidationException('classPassId', $classPassId);
214
        }
215
     
216
        try {
217
            $Response = $this->request();
218
            $body = json_decode($Response->getBody()->getContents());
219
            $classPass = $body->data[0];
220
            $return = $classPass;
221
            return $return;
222
        } catch (Exception $e) {
223
            throw new RestException($e->getMessage(), $this->logger);
224
        }
225
    }
226
    
227
    /**
228
     *
229
     * {@inheritDoc}
230
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getClassPasses()
231
     * @todo break params on to multiplper lines..
232
     */
233
    public function getClassPasses(
234
        $title = null, 
235
        $detail = null, 
236
        $usageType, 
237
        $cost = null, 
238
        $usageAllowance = null, 
239
        $useRestrictedForDays = null): array
240
    {   
241
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
242
        
243
        if (!is_null($title) && !$this->validator->validTitle($title)) {
244
            throw new ValidationException('title', $title);
245
        }
246
       
247
        $this->apiResource = $this->apiVersion . '/???';
248
        
249
        // @todo prepocess response onto nice model objects.
250
        $Response = $this->request();
251
        return json_decode($Response->getBody()->getContents());
252
    }
253
    
254
    /**
255
     *
256
     * {@inheritDoc}
257
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getEvent()
258
     */
259 1
    public function getEvent($eventId)
260
    {
261 1
        if (!$this->validator->validId($eventId, 'event')) {
262
            throw new ValidationException('eventId', $eventId);
263
        }
264 1
        $this->apiResource = $this->apiVersion . '/events' . '/' . $eventId;
265
     
266
        try {
267 1
            $Response = $this->request();
268 1
            $body = json_decode($Response->getBody()->getContents());
269 1
            $event = $body->data;
270 1
            $event->soldOut = (bool) ($event->attributes->attendee_count >= $event->attributes->attendee_limit);
271 1
            $return = $event;
272 1
            return $return;
273
        } catch (Exception $e) {
274
            throw new RestException($e, $this->logger);
275
        }
276
    }
277
    
278
    /**
279
     *
280
     * {@inheritDoc}
281
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getEvents()
282
     */
283 1
    public function getEvents(
284
        $calendar = false,
285
        $entry = false,
286
        $location = [],
287
        $tags = [],
288
        $title = [],
289
        $detail = [],
290
        $from = null,
291
        $to = null,
292
        $includeLocation = false,
293
        $includeAttachments = false,
294
        $includeTickets = false,
295
        $includeTicketsEvents = false,
296
        $includeTicketsClassPasses = false): array
297
    {    
298 1
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
299
        
300
        // Validate $tags.
301 1
        if (!empty($tags)) {
302
            if (!is_array($tags)) {
303
                throw new ValidationException('tags', implode(' ', $tags));
304
            } else {
305
                $tags = array_unique($tags);
306
                foreach ($tags as $tag) {
307
                    if (!empty($tag) && !$this->validator->validTag($tag)) {
308
                        throw new ValidationException('tag', $tag);
309
                    }
310
                }
311
            }
312
            $this->apiQuery['filter[tag]'] = implode(',', $tags);
313
        }
314
        
315
        // Validate $from;
316 1
        if (!empty($from)) {
317
            if (!$this->validator->validFrom($from, $to)) {
318
                throw new ValidationException('from', $from . '-' . $to);
319
            } else {
320
                $this->apiQuery['filter[from]'] = $from;
321
            }
322
        }
323
        
324
        // Validate $to;
325 1
        if (!empty($to)) {
326
            if (!$this->validator->validTo($to, $from)) {
327
                throw new ValidationException('to', $to . '-' . $from);
328
            } else {
329
                $this->apiQuery['filter[to]'] = $to;
330
            }
331
        }
332
        
333
        // API resource.
334 1
        $this->apiResource = $this->apiVersion . '/events';
335
        
336
        
337 1
        $include = [];
338
        // Validate $includeLocation;
339
340 1
        if (!empty($includeLocation)) {
341
            if (!$this->validator->validInclude($includeLocation)) {
342
                throw new ValidationException('include', $includeLocation);
343
            } else if ($includeLocation) {
344
                $include[] = 'location';
345
            }
346
        }
347
348
        // Validate $includeAttachments;
349 1
        if (!empty($includeAttachments)) {
350
            if (!$this->validator->validInclude($includeAttachments)) {
351
                throw new ValidationException('include', $includeAttachments);
352
            } else if ($includeAttachments) {
353
                $include[] = 'attachments';
354
            }
355
        }
356
        
357
        // Validate $includeTickets
358 1
        if (!empty($includeTickets)) {
359
            if (!$this->validator->validInclude($includeTickets)) {
360
                throw new ValidationException('include', $includeTickets);
361
            } else if ($includeTickets) {
362
                $include[] = 'tickets';
363
            }
364
        }
365
        
366
        // Validate $includeTicketsEvents;
367 1
        if (!empty($includeTicketsEvents)) {
368
            if (!$this->validator->validInclude($includeTicketsEvents)) {
369
                throw new ValidationException('include', $includeTicketsEvents);
370
            } else if ($includeTicketsEvents) {
371
                $include[] = 'tickets.events';
372
            }
373
        }
374
375
        // Validate $includeTicketsEvents;
376 1
        if (!empty($includeTicketsClassPasses)) {
377
            if (!$this->validator->validInclude($includeTicketsClassPasses)) {
378
                throw new ValidationException('include', $includeTicketsClassPasses);
379
            } else if ($includeTicketsClassPasses) {
380
                $include[] = 'tickets.class_passes';
381
            }
382
        }
383
384 1
        if (count($include) > 0) {
385
            $this->apiQuery['include'] = implode(',', $include);
386
387
        }
388
  
389
        try {
390 1
            $Response = $this->request();
391
            
392 1
            $body = json_decode($Response->getBody()->getContents());
393
            
394
            // Prepocess response onto nice model objects.
395
            // @todo abstract.
396 1
            $return = [];
397
            
398 1
            foreach ($body->data as $event) {
399
                // Add additional properties here.
400 1
                $event->soldOut = (bool) ($event->attributes->attendee_count >= $event->attributes->attendee_limit);
401 1
                array_push($return, $event);
402
            }
403
            
404 1
            return $return;
405
        } catch (Exception $e) {
406
            throw new RestException($e, $this->logger);
407
        }
408
    }
409
    
410
    /**
411
     *
412
     * {@inheritDoc}
413
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getLocation()
414
     */
415
    public function getLocation($locationId)
416
    {
417
        $this->apiResource = $this->apiVersion . '/locations';
418
        if (!$this->validator->validId($locationId, 'location')) {
419
            throw new ValidationException('locationId', $locationId);
420
        }
421
        
422
        try {
423
            $Response = $this->request();
424
            $body = json_decode($Response->getBody()->getContents());
425
            $location = $body->data[0];
426
            $return = $location;
427
            return $return;
428
        } catch (Exception $e) {
429
            throw new RestException($e->getMessage(), $this->logger);
430
        }
431
432
    }
433
    
434
    /**
435
     *
436
     * {@inheritDoc}
437
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getLocations()
438
     * @todo validate params.
439
     */
440
    public function getLocations($addressText = null, $additionalInfo = null): array
441
    {
442
        $this->apiResource = $this->apiVersion . '/locations';
443
444
        $return = [];
445
        
446
        try {
447
            $Response = $this->request();
448
            $body = json_decode($Response->getBody()->getContents());
449
            
450
            foreach ($body->data as $location) {
451
                array_push($return, $location);
452
            }
453
            
454
            return $return;
455
        } catch (Exception $e) {
456
            throw new RestException($e, $this->logger);
457
        }
458
    } 
459
    
460
    /**
461
     *
462
     * {@inheritDoc}
463
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getTicket()
464
     */
465 1
    public function getTicket($ticketId)
466
    {
467 1
        if (!$this->validator->validId($ticketId, 'ticket')) {
468
            throw new ValidationException('ticketId', $ticketId);
469
        }
470
471 1
        $this->apiResource = $this->apiVersion . '/tickets';
472
473
        
474
        try {
475 1
            $Response = $this->request();
476 1
            $body = json_decode($Response->getBody()->getContents());
477 1
            $ticket = $body->data[0];
478 1
            $return = $ticket;
479 1
            return $return;
480
        } catch (Exception $e) {
481
            throw new RestException($e, $this->logger);
482
        }
483
    }
484
    
485
    /**
486
     * 
487
     * {@inheritDoc}
488
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getTickets()
489
     */
490 2
    public function getTickets($eventId): array
491
    {
492 2
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
493 2
        if (!$this->validator->validId($eventId, 'event')) {
494 1
            throw new ValidationException('eventId', $eventId);
495
        }
496
497 1
        $this->apiQuery = ['event' => $eventId];
498
        
499 1
        $this->apiResource = $this->apiVersion . '/tickets';
500
                
501
        try {
502 1
            $return = [];
503
            
504 1
            $Response = $this->request();
505 1
            $body = json_decode($Response->getBody()->getContents());
506
            
507 1
            foreach ($body->data as $ticket) {
508 1
                array_push($return, $ticket);
509
            }
510 1
            $this->logger->debug(var_export($return, true));
511 1
            return $return;
512
        } catch (GuzzleHttp\Exception\ClientException $e) {
513
            throw new RestException($e, $this->logger);
514
        }
515
    }
516
    
517
    /**
518
     * Set Debug.
519
     */
520
    public function setLogging($level)
521
    {
522
        $this->logging = $level;
523
    } 
524
    
525
    /**
526
     * Set Guzzle Client
527
     */
528
    public function setGuzzleClient($guzzleClient)
529
    {
530
        $this->guzzleClient = $guzzleClient;
531
    } 
532
    
533
    /**
534
     * Sets the token for all future new instances
535
     * @param $token string The API access token, as obtained on diffbot.com/dev.
536
     */
537
    public static function setToken($token)
538
    {
539
        $validator = new Validator();
540
        if (!$validator->validToken($token)) {
541
            throw new \InvalidArgumentException('Invalid Token.');
542
        }
543
        self::$token = $token;
544
    } 
545
}
546
547
// EOF!
548