Passed
Push — scrutinizer ( 8846f8...d0c472 )
by
unknown
05:44
created

Client::getEvents()   F

Complexity

Conditions 28
Paths > 20000

Size

Total Lines 125
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 236.3273

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 28
eloc 59
c 5
b 0
f 0
nc 24304
nop 13
dl 0
loc 125
ccs 20
cts 56
cp 0.357
crap 236.3273
rs 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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