Passed
Branch master (83eb1b)
by Daniel
02:13
created

Client::setToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 6
rs 10
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 12
    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 12
        if (empty($this->logging)) {
77 12
            $this->logging = 'DEBUG';
78 12
            $this->log = 'inShoreBookwhen.log';
79
        }
80 12
        $this->logger = new Logger('inShore Bookwhen API');
81 12
        $this->logger->pushHandler(new StreamHandler($this->log, Logger::getLevels()[$this->logging]));
82
        
83 12
        $this->validator = new Validator();
84
        
85 12
        $this->include = [];
86
        
87 12
        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 12
            if ($this->validator->validToken($token)) {
95 12
                self::$token = $token;
96 12
                $this->instanceToken = self::$token;
97
            }
98
        }
99
        
100 12
        $this->apiBaseUri = 'https://api.bookwhen.com/';    
101 12
        $this->apiQuery = [];
102 12
        $this->apiVersion = 'v2';
103
        
104 12
        $this->guzzleClient = new GuzzleClient([
105 12
            'base_uri' => $this->apiBaseUri
106
        ]);
107
        
108 12
        $this->logger->info('Client class successfully instantiated');
109 12
        $this->logger->debug(var_export($this, true));
110 12
    }
111
    
112
    /**
113
     * {@inheritDoc}
114
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::request()
115
     */
116 10
    protected function request(): ResponseInterface
117
    {
118 10
        $this->logger->debug(__METHOD__ . '()');
119
        try {
120
            // Authorization.
121
            $requestOptions = [
122
                'headers' => [
123 10
                    'Authorization' => 'Basic ' . base64_encode($this->instanceToken . ':')
124
                ]
125
            ];
126
            
127
            // Query.
128 10
            if (!empty($this->apiQuery) && is_array($this->apiQuery)) {
129 1
                $requestOptions['query'] = $this->apiQuery;
130
            }
131
132 10
            $this->logger->debug('request(GET, ' . $this->apiResource . ', ' . var_export($requestOptions, true) . ')');
133 10
            $requestOptions['debug'] = true;
134
            
135 10
            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 1
    public function getClassPass($classPassId)
208
    {
209 1
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
210 1
        $this->apiResource = $this->apiVersion . '/class_passes';
211
    
212 1
        if (!$this->validator->validId($classPassId, 'classPass')) {
213
            throw new ValidationException('classPassId', $classPassId);
214
        }
215
216
        try {
217 1
            $Response = $this->request();
218 1
            $body = json_decode($Response->getBody()->getContents());
219 1
            $classPass = $body->data;
220 1
            $return = $classPass;
221 1
            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 1
    public function getClassPasses(
234
        $title = null, 
235
        $detail = null, 
236
        $usageType = null,
237
        $cost = null, 
238
        $usageAllowance = null, 
239
        $useRestrictedForDays = null): array
240
    {   
241
        
242 1
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
243
        
244 1
        if (!is_null($title) && !$this->validator->validTitle($title)) {
245
            throw new ValidationException('title', $title);
246
        }
247
248 1
        $this->apiResource = $this->apiVersion . '/class_passes';
249
250 1
        $return = [];
251
        
252
        try {
253 1
            $Response = $this->request();
254 1
            $body = json_decode($Response->getBody()->getContents());
255
            
256 1
            foreach ($body->data as $classPass) {
257 1
                array_push($return, $classPass);
258
            }
259
            
260 1
            return $return;
261
        } catch (Exception $e) {
262
            throw new RestException($e, $this->logger);
263
        }
264
    }
265
    
266
    /**
267
     *
268
     * {@inheritDoc}
269
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getEvent()
270
     */
271 1
    public function getEvent($eventId)
272
    {
273 1
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
274
        
275 1
        if (!$this->validator->validId($eventId, 'event')) {
276
            throw new ValidationException('eventId', $eventId);
277
        }
278 1
        $this->apiResource = $this->apiVersion . '/events' . '/' . $eventId;
279
    
280
        try {
281 1
            $Response = $this->request();
282 1
            $body = json_decode($Response->getBody()->getContents());
283 1
            $event = $body->data;
284 1
            $event->soldOut = (bool) ($event->attributes->attendee_count >= $event->attributes->attendee_limit);
285 1
            $return = $event;
286 1
            return $return;
287
        } catch (Exception $e) {
288
            throw new RestException($e, $this->logger);
289
        }
290
    }
291
    
292
    /**
293
     *
294
     * {@inheritDoc}
295
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getEvents()
296
     */
297 1
    public function getEvents(
298
        $calendar = false,
299
        $entry = false,
300
        $location = [],
301
        $tags = [],
302
        $title = [],
303
        $detail = [],
304
        $from = null,
305
        $to = null,
306
        $includeLocation = false,
307
        $includeAttachments = false,
308
        $includeTickets = false,
309
        $includeTicketsEvents = false,
310
        $includeTicketsClassPasses = false): array
311
    {   
312
        
313 1
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
314
        
315
        // Validate $tags.
316 1
        if (!empty($tags)) {
317
            if (!is_array($tags)) {
318
                throw new ValidationException('tags', implode(' ', $tags));
319
            } else {
320
                $tags = array_unique($tags);
321
                foreach ($tags as $tag) {
322
                    if (!empty($tag) && !$this->validator->validTag($tag)) {
323
                        throw new ValidationException('tag', $tag);
324
                    }
325
                }
326
            }
327
            $this->apiQuery['filter[tag]'] = implode(',', $tags);
328
        }
329
        
330
        // Validate $from;
331 1
        if (!empty($from)) {
332
            if (!$this->validator->validFrom($from, $to)) {
333
                throw new ValidationException('from', $from . '-' . $to);
334
            } else {
335
                $this->apiQuery['filter[from]'] = $from;
336
            }
337
        }
338
        
339
        // Validate $to;
340 1
        if (!empty($to)) {
341
            if (!$this->validator->validTo($to, $from)) {
342
                throw new ValidationException('to', $to . '-' . $from);
343
            } else {
344
                $this->apiQuery['filter[to]'] = $to;
345
            }
346
        }
347
        
348
        // API resource.
349 1
        $this->apiResource = $this->apiVersion . '/events';
350
        
351
        
352 1
        $include = [];
353
        // Validate $includeLocation;
354
355 1
        if (!empty($includeLocation)) {
356
            if (!$this->validator->validInclude($includeLocation)) {
357
                throw new ValidationException('include', $includeLocation);
358
            } else if ($includeLocation) {
359
                $include[] = 'location';
360
            }
361
        }
362
363
        // Validate $includeAttachments;
364 1
        if (!empty($includeAttachments)) {
365
            if (!$this->validator->validInclude($includeAttachments)) {
366
                throw new ValidationException('include', $includeAttachments);
367
            } else if ($includeAttachments) {
368
                $include[] = 'attachments';
369
            }
370
        }
371
        
372
        // Validate $includeTickets
373 1
        if (!empty($includeTickets)) {
374
            if (!$this->validator->validInclude($includeTickets)) {
375
                throw new ValidationException('include', $includeTickets);
376
            } else if ($includeTickets) {
377
                $include[] = 'tickets';
378
            }
379
        }
380
        
381
        // Validate $includeTicketsEvents;
382 1
        if (!empty($includeTicketsEvents)) {
383
            if (!$this->validator->validInclude($includeTicketsEvents)) {
384
                throw new ValidationException('include', $includeTicketsEvents);
385
            } else if ($includeTicketsEvents) {
386
                $include[] = 'tickets.events';
387
            }
388
        }
389
390
        // Validate $includeTicketsEvents;
391 1
        if (!empty($includeTicketsClassPasses)) {
392
            if (!$this->validator->validInclude($includeTicketsClassPasses)) {
393
                throw new ValidationException('include', $includeTicketsClassPasses);
394
            } else if ($includeTicketsClassPasses) {
395
                $include[] = 'tickets.class_passes';
396
            }
397
        }
398
399 1
        if (count($include) > 0) {
400
            $this->apiQuery['include'] = implode(',', $include);
401
402
        }
403
  
404
        try {
405 1
            $Response = $this->request();
406
            
407 1
            $body = json_decode($Response->getBody()->getContents());
408
            
409
            // Prepocess response onto nice model objects.
410
            // @todo abstract.
411 1
            $return = [];
412
            
413 1
            foreach ($body->data as $event) {
414
                // Add additional properties here.
415 1
                $event->soldOut = (bool) ($event->attributes->attendee_count >= $event->attributes->attendee_limit);
416 1
                array_push($return, $event);
417
            }
418
            
419 1
            return $return;
420
        } catch (Exception $e) {
421
            throw new RestException($e, $this->logger);
422
        }
423
    }
424
    
425
    /**
426
     *
427
     * {@inheritDoc}
428
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getLocation()
429
     */
430 1
    public function getLocation($locationId)
431
    {
432 1
        $this->apiResource = $this->apiVersion . '/locations';
433 1
        if (!$this->validator->validId($locationId, 'location')) {
434
            throw new ValidationException('locationId', $locationId);
435
        }
436
        
437
        try {
438 1
            $Response = $this->request();
439 1
            $body = json_decode($Response->getBody()->getContents());
440 1
            $location = $body->data;
441 1
            $return = $location;
442 1
            return $return;
443
        } catch (Exception $e) {
444
            throw new RestException($e->getMessage(), $this->logger);
445
        }
446
447
    }
448
    
449
    /**
450
     *
451
     * {@inheritDoc}
452
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getLocations()
453
     * @todo validate params.
454
     */
455 1
    public function getLocations($addressText = null, $additionalInfo = null): array
456
    {
457 1
        $this->apiResource = $this->apiVersion . '/locations';
458
459 1
        $return = [];
460
        
461
        try {
462 1
            $Response = $this->request();
463 1
            $body = json_decode($Response->getBody()->getContents());
464
            
465 1
            foreach ($body->data as $location) {
466 1
                array_push($return, $location);
467
            }
468
            
469 1
            return $return;
470
        } catch (Exception $e) {
471
            throw new RestException($e, $this->logger);
472
        }
473
    } 
474
    
475
    /**
476
     *
477
     * {@inheritDoc}
478
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getTicket()
479
     */
480 1
    public function getTicket($ticketId)
481
    {
482 1
        if (!$this->validator->validId($ticketId, 'ticket')) {
483
            throw new ValidationException('ticketId', $ticketId);
484
        }
485
486 1
        $this->apiResource = $this->apiVersion . '/tickets';
487
488
        
489
        try {
490 1
            $Response = $this->request();
491 1
            $body = json_decode($Response->getBody()->getContents());
492 1
            $ticket = $body->data[0];
493 1
            $return = $ticket;
494 1
            return $return;
495
        } catch (Exception $e) {
496
            throw new RestException($e, $this->logger);
497
        }
498
    }
499
    
500
    /**
501
     * 
502
     * {@inheritDoc}
503
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getTickets()
504
     */
505 2
    public function getTickets($eventId): array
506
    {
507 2
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
508 2
        if (!$this->validator->validId($eventId, 'event')) {
509 1
            throw new ValidationException('eventId', $eventId);
510
        }
511
512 1
        $this->apiQuery = ['event' => $eventId];
513
        
514 1
        $this->apiResource = $this->apiVersion . '/tickets';
515
                
516
        try {
517 1
            $return = [];
518
            
519 1
            $Response = $this->request();
520 1
            $body = json_decode($Response->getBody()->getContents());
521
            
522 1
            foreach ($body->data as $ticket) {
523 1
                array_push($return, $ticket);
524
            }
525 1
            $this->logger->debug(var_export($return, true));
526 1
            return $return;
527
        } catch (GuzzleHttp\Exception\ClientException $e) {
528
            throw new RestException($e, $this->logger);
529
        }
530
    }
531
    
532
    /**
533
     * Set Debug.
534
     */
535
    public function setLogging($level)
536
    {
537
        $this->logging = $level;
538
    } 
539
    
540
    /**
541
     * Set Guzzle Client
542
     */
543
    public function setGuzzleClient($guzzleClient)
544
    {
545
        $this->guzzleClient = $guzzleClient;
546
    } 
547
    
548
    /**
549
     * Sets the token for all future new instances
550
     * @param $token string The API access token, as obtained on diffbot.com/dev.
551
     */
552
    public static function setToken($token)
553
    {
554
        $validator = new Validator();
555
        if (!$validator->validToken($token)) {
556
            throw new \InvalidArgumentException('Invalid Token.');
557
        }
558
        self::$token = $token;
559
    } 
560
}
561
562
// EOF!
563