Completed
Push — develop ( dc6195...07f4b7 )
by Daniel
19s queued 10s
created

Client::setLogging()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
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
            $event->availability = (integer) ($event->attributes->attendee_count >= $event->attributes->attendee_limit);
286 1
            $return = $event;
287 1
            return $return;
288
        } catch (Exception $e) {
289
            throw new RestException($e, $this->logger);
290
        }
291
    }
292
    
293
    /**
294
     *
295
     * {@inheritDoc}
296
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getEvents()
297
     */
298 1
    public function getEvents(
299
        $calendar = false,
300
        $entry = false,
301
        $location = [],
302
        $tags = [],
303
        $title = [],
304
        $detail = [],
305
        $from = null,
306
        $to = null,
307
        $includeLocation = false,
308
        $includeAttachments = false,
309
        $includeTickets = false,
310
        $includeTicketsEvents = false,
311
        $includeTicketsClassPasses = false): array
312
    {   
313
        
314 1
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
315
        
316
        // Validate $tags.
317 1
        if (!empty($tags)) {
318
            if (!is_array($tags)) {
319
                throw new ValidationException('tags', implode(' ', $tags));
320
            } else {
321
                $tags = array_unique($tags);
322
                foreach ($tags as $tag) {
323
                    if (!empty($tag) && !$this->validator->validTag($tag)) {
324
                        throw new ValidationException('tag', $tag);
325
                    }
326
                }
327
            }
328
            $this->apiQuery['filter[tag]'] = implode(',', $tags);
329
        }
330
        
331
        // Validate $from;
332 1
        if (!empty($from)) {
333
            if (!$this->validator->validFrom($from, $to)) {
334
                throw new ValidationException('from', $from . '-' . $to);
335
            } else {
336
                $this->apiQuery['filter[from]'] = $from;
337
            }
338
        }
339
        
340
        // Validate $to;
341 1
        if (!empty($to)) {
342
            if (!$this->validator->validTo($to, $from)) {
343
                throw new ValidationException('to', $to . '-' . $from);
344
            } else {
345
                $this->apiQuery['filter[to]'] = $to;
346
            }
347
        }
348
        
349
        // API resource.
350 1
        $this->apiResource = $this->apiVersion . '/events';
351
        
352
        
353 1
        $include = [];
354
        // Validate $includeLocation;
355
356 1
        if (!empty($includeLocation)) {
357
            if (!$this->validator->validInclude($includeLocation)) {
358
                throw new ValidationException('include', $includeLocation);
359
            } else if ($includeLocation) {
360
                $include[] = 'location';
361
            }
362
        }
363
364
        // Validate $includeAttachments;
365 1
        if (!empty($includeAttachments)) {
366
            if (!$this->validator->validInclude($includeAttachments)) {
367
                throw new ValidationException('include', $includeAttachments);
368
            } else if ($includeAttachments) {
369
                $include[] = 'attachments';
370
            }
371
        }
372
        
373
        // Validate $includeTickets
374 1
        if (!empty($includeTickets)) {
375
            if (!$this->validator->validInclude($includeTickets)) {
376
                throw new ValidationException('include', $includeTickets);
377
            } else if ($includeTickets) {
378
                $include[] = 'tickets';
379
            }
380
        }
381
        
382
        // Validate $includeTicketsEvents;
383 1
        if (!empty($includeTicketsEvents)) {
384
            if (!$this->validator->validInclude($includeTicketsEvents)) {
385
                throw new ValidationException('include', $includeTicketsEvents);
386
            } else if ($includeTicketsEvents) {
387
                $include[] = 'tickets.events';
388
            }
389
        }
390
391
        // Validate $includeTicketsEvents;
392 1
        if (!empty($includeTicketsClassPasses)) {
393
            if (!$this->validator->validInclude($includeTicketsClassPasses)) {
394
                throw new ValidationException('include', $includeTicketsClassPasses);
395
            } else if ($includeTicketsClassPasses) {
396
                $include[] = 'tickets.class_passes';
397
            }
398
        }
399
400 1
        if (count($include) > 0) {
401
            $this->apiQuery['include'] = implode(',', $include);
402
403
        }
404
  
405
        try {
406 1
            $Response = $this->request();
407
            
408 1
            $body = json_decode($Response->getBody()->getContents());
409
            
410
            // Prepocess response onto nice model objects.
411
            // @todo abstract.
412 1
            $return = [];
413
            
414 1
            foreach ($body->data as $event) {
415
                // Add additional properties here.
416 1
                $event->availability = (int) ($event->attributes->attendee_limit - $event->attributes->attendee_count);
417 1
                $event->soldOut = (bool) ($event->attributes->attendee_count >= $event->attributes->attendee_limit);
418 1
                array_push($return, $event);
419
            }
420
            
421 1
            return $return;
422
        } catch (Exception $e) {
423
            throw new RestException($e, $this->logger);
424
        }
425
    }
426
    
427
    /**
428
     *
429
     * {@inheritDoc}
430
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getLocation()
431
     */
432 1
    public function getLocation($locationId)
433
    {
434 1
        $this->apiResource = $this->apiVersion . '/locations';
435 1
        if (!$this->validator->validId($locationId, 'location')) {
436
            throw new ValidationException('locationId', $locationId);
437
        }
438
        
439
        try {
440 1
            $Response = $this->request();
441 1
            $body = json_decode($Response->getBody()->getContents());
442 1
            $location = $body->data;
443 1
            $return = $location;
444 1
            return $return;
445
        } catch (Exception $e) {
446
            throw new RestException($e->getMessage(), $this->logger);
447
        }
448
449
    }
450
    
451
    /**
452
     *
453
     * {@inheritDoc}
454
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getLocations()
455
     * @todo validate params.
456
     */
457 1
    public function getLocations($addressText = null, $additionalInfo = null): array
458
    {
459 1
        $this->apiResource = $this->apiVersion . '/locations';
460
461 1
        $return = [];
462
        
463
        try {
464 1
            $Response = $this->request();
465 1
            $body = json_decode($Response->getBody()->getContents());
466
            
467 1
            foreach ($body->data as $location) {
468 1
                array_push($return, $location);
469
            }
470
            
471 1
            return $return;
472
        } catch (Exception $e) {
473
            throw new RestException($e, $this->logger);
474
        }
475
    } 
476
    
477
    /**
478
     *
479
     * {@inheritDoc}
480
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getTicket()
481
     */
482 1
    public function getTicket($ticketId)
483
    {
484 1
        if (!$this->validator->validId($ticketId, 'ticket')) {
485
            throw new ValidationException('ticketId', $ticketId);
486
        }
487
488 1
        $this->apiResource = $this->apiVersion . '/tickets';
489
490
        
491
        try {
492 1
            $Response = $this->request();
493 1
            $body = json_decode($Response->getBody()->getContents());
494 1
            $ticket = $body->data[0];
495 1
            $return = $ticket;
496 1
            return $return;
497
        } catch (Exception $e) {
498
            throw new RestException($e, $this->logger);
499
        }
500
    }
501
    
502
    /**
503
     * 
504
     * {@inheritDoc}
505
     * @see \InShore\Bookwhen\Interfaces\ClientInterface::getTickets()
506
     */
507 2
    public function getTickets($eventId): array
508
    {
509 2
        $this->logger->debug(__METHOD__ . '(' . var_export(func_get_args(), true) . ')');
510 2
        if (!$this->validator->validId($eventId, 'event')) {
511 1
            throw new ValidationException('eventId', $eventId);
512
        }
513
514 1
        $this->apiQuery = ['event' => $eventId];
515
        
516 1
        $this->apiResource = $this->apiVersion . '/tickets';
517
                
518
        try {
519 1
            $return = [];
520
            
521 1
            $Response = $this->request();
522 1
            $body = json_decode($Response->getBody()->getContents());
523
            
524 1
            foreach ($body->data as $ticket) {
525 1
                array_push($return, $ticket);
526
            }
527 1
            $this->logger->debug(var_export($return, true));
528 1
            return $return;
529
        } catch (GuzzleHttp\Exception\ClientException $e) {
530
            throw new RestException($e, $this->logger);
531
        }
532
    }
533
    
534
    /**
535
     * Set Debug.
536
     */
537
    public function setLogging($level)
538
    {
539
        $this->logging = $level;
540
    } 
541
    
542
    /**
543
     * Set Guzzle Client
544
     */
545
    public function setGuzzleClient($guzzleClient)
546
    {
547
        $this->guzzleClient = $guzzleClient;
548
    } 
549
    
550
    /**
551
     * Sets the token for all future new instances
552
     * @param $token string The API access token, as obtained on diffbot.com/dev.
553
     */
554
    public static function setToken($token)
555
    {
556
        $validator = new Validator();
557
        if (!$validator->validToken($token)) {
558
            throw new \InvalidArgumentException('Invalid Token.');
559
        }
560
        self::$token = $token;
561
    } 
562
}
563
564
// EOF!
565