Passed
Pull Request — develop (#48)
by
unknown
25:40 queued 10:41
created

Client::request()   A

Complexity

Conditions 4
Paths 7

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 9
dl 0
loc 21
c 2
b 0
f 0
rs 9.9666
cc 4
nc 7
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace InShore\BookWhen;
6
7
use GuzzleHttp\Client as GuzzleClient;
8
use GuzzleHttp\Psr7\Request;
9
use InShore\BookWhen\Exceptions\ConfigurationException;
10
use InShore\BookWhen\Exceptions\RestException;
11
use InShore\BookWhen\Exceptions\ValidationException;
12
use InShore\BookWhen\Interfaces\ClientInterface;
13
use InShore\BookWhen\Validator;
14
use Psr\Http\Message\ResponseInterface;
15
16
/**
17
 * Class Client
18
 *
19
 * The main class for API consumption
20
 *
21
 * @package inshore-packages\bookwhen
22
 * @todo comments
23
 * @todo externalise config
24
 * @todo fix token
25
 */
26
class Client implements ClientInterface
27
{
28
    
29
    /** @var string The API access token */
30
    private static $token = null;
31
    
32
    /** @var string The instance token, settable once per new instance */
33
    private $instanceToken;
34
    
35
    private $apiBaseUri;
36
    
37
    private $apiQuery;
38
   
39
    private $apiResource;
40
    
41
    private $apiVersion;
42
    
43
    private $validator;
44
    
45
    private $guzzleClient;
46
    
47
    /**
48
     * @param string|null $token The API access token, as obtained on diffbot.com/dev
49
     * @throws DiffbotException When no token is provided
50
     */
51
    public function __construct($token = null)
52
    {
53
        
54
        $this->apiBaseUri = 'https://api.bookwhen.com/';
55
            
56
        $this->apiQuery = [];
57
        
58
        $this->apiVersion = 'v2';
59
        
60
        $this->validator = new Validator();
61
        
62
        $this->guzzleClient = new GuzzleClient([
63
            'base_uri' => $this->apiBaseUri
64
        ]);
65
        
66
        if ($token === null) {
67
            if (self::$token === null) {
0 ignored issues
show
introduced by
The condition self::token === null is always false.
Loading history...
68
                $msg = 'No token provided, and none is globally set. ';
69
                $msg .= 'Use Diffbot::setToken, or instantiate the Diffbot class with a $token parameter.';
70
                throw new ConfigurationException($msg);
71
            }
72
        } else {
73
            if ($this->validator->validToken($token)) {
74
                self::$token = $token;
75
                $this->instanceToken = self::$token;
76
            }
77
        }
78
    }
79
    
80
    /**
81
     * @todo debug flag
82
     */
83
    protected function request(): ResponseInterface
84
    {
85
        try {
86
            // Authorization.
87
            $requestOptions = [
88
                'headers' => [
89
                    'Authorization' => 'Basic ' . base64_encode($this->instanceToken . ':')
90
                ]
91
            ];
92
            
93
            // Query.
94
            if (!empty($this->apiQuery) && is_array($this->apiQuery)) {
95
                $requestOptions['query'] = $this->apiQuery;
96
            }
97
   
98
            //$requestOptions['debug'] = true;
99
            
100
            return $this->guzzleClient->request('GET', $this->apiResource, $requestOptions);
101
           
102
        } catch (Exception $e) {
103
            throw new RestException($e);
104
        }
105
    }
106
    
107
    /**
108
     * @todo
109
     */
110
    public function getAttachment($attachmentId)
111
    {
112
        if (!empty($attachmentId && !$this->validator->validId($attachmentId, 'attachment'))) {
113
            throw new ValidationException('Supplied attachmentId ' . $attachmentId . ' is invalid.');
114
        }
115
        $this->apiResource = $this->apiVersion . '/attachments' . '/' . $attachmentId;
116
     
117
        try {
118
            $Response = $this->request();
119
            $body = json_decode($Response->getBody()->getContents());
120
            $attachment = $body->data[0];
121
            $return = $attachment;
122
            return $return;
123
        } catch (Exception $e) {
124
            throw new RestException($e->getMessage());
125
        }
126
    }
127
    
128
    /**
129
     *
130
     * {@inheritDoc}
131
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getAttachments()
132
     * @todo validate params.
133
     */
134
    public function getAttachments($title = null, $fileName = null, $fileType = null): array
135
    {    
136
        
137
        $this->apiResource = $this->apiVersion . '/attachments';
138
        
139
        try {
140
            $return = [];
141
            $Response = $this->request();
142
            $body = json_decode($Response->getBody()->getContents());
143
            
144
            foreach ($body->data as $attachment) {
145
                array_push($return, $attachment);
146
            }
147
            
148
            return $return;
149
        } catch (Exception $e) {
150
            throw new RestException($e->getMessage());
151
        }
152
    }
153
    
154
    /**
155
     *
156
     * {@inheritDoc}
157
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getClassPass()
158
     */
159
    public function getClassPass($classPassId)
160
    {
161
        $this->apiResource = $this->apiVersion . '/class_passes';
162
       
163
        if (!empty($classPassId && !$this->validator->validId($classPassId, 'classPass'))) {
164
            throw ValidationException::class;
165
        }
166
     
167
        try {
168
            $Response = $this->request();
169
            $body = json_decode($Response->getBody()->getContents());
170
            $classPass = $body->data[0];
171
            $return = $classPass;
172
            return $return;
173
        } catch (Exception $e) {
174
            throw new RestException($e->getMessage());;
175
        }
176
    }
177
    
178
    /**
179
     *
180
     * {@inheritDoc}
181
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getClassPasses()
182
     */
183
    public function getClassPasses($title = null, $detail = null, $usageType, $cost = null, $usageAllowance = null, $useRestrictedForDays = null): array
184
    {   
185
        $this->apiResource = $this->apiVersion . '/???';
186
        
187
        // @todo prepocess response onto nice model objects.
188
        $Response = $this->request();
189
        return json_decode($Response->getBody()->getContents());
190
    }
191
    
192
    /**
193
     *
194
     * {@inheritDoc}
195
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getEvent()
196
     */
197
    public function getEvent($eventId)
198
    {
199
        if (!empty($eventId && !$this->validator->validId($eventId, 'event'))) {
200
            throw new ValidationException();
201
        }
202
        $this->apiResource = $this->apiVersion . '/events' . '/' . $eventId;
203
     
204
        try {
205
            $Response = $this->request();
206
            $body = json_decode($Response->getBody()->getContents());
207
            $event = $body->data;
208
            $event->soldOut = (bool) ($event->attributes->attendee_count >= $event->attributes->attendee_limit);
209
            $return = $event;
210
            return $return;
211
        } catch (Exception $e) {
212
            throw new RestException($e->getMessage());
213
        }
214
    }
215
    
216
    /**
217
     *
218
     * {@inheritDoc}
219
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getEvents()
220
     */
221
    public function getEvents(
222
        $calendar = false,
223
        $entry = false,
224
        $location = [],
225
        $tags = [],
226
        $title = [],
227
        $detail = [],
228
        $from = null,
229
        $to = null,
230
        $includeLocation = false,
231
        $includeAttachments = false,
232
        $includeTickets = false,
233
        $includeTicketsEvents = false,
234
        $includeTicketsClassPasses = false): array
235
    {    
236
        // Validate $tags.
237
        if (!empty($tags)) {
238
            if (!is_array($tags)) {
239
                throw new ValidationException();
240
            } else {
241
                $tags = array_unique($tags);
242
                foreach ($tags as $tag) {
243
                    if (!empty($tag) && !$this->validator->validTag($tag)) {
244
                        throw new ValidationException();
245
                    }
246
                }
247
            }
248
            $this->apiQuery['filter[tag]'] = implode(',', $tags);
249
        }
250
        
251
        // Validate $from;
252
        if (!empty($from)) {
253
            if (!$this->validator->validFrom($from, $to)) {
254
                throw new ValidationException();
255
            } else {
256
                $this->apiQuery['filter[from]'] = $from;
257
            }
258
        }
259
        
260
        // Validate $to;
261
        if (!empty($to)) {
262
            if (!$this->validator->validTo($to, $from)) {
263
                throw ValidationException::class;
264
            } else {
265
                $this->apiQuery['filter[to]'] = $to;
266
            }
267
        }
268
        
269
        // API resource.
270
        $this->apiResource = $this->apiVersion . '/events';
271
        
272
        
273
        
274
        // Validate $includeLocation;
275
        
276
        // Validate $includeTickets;
277
  
278
        try {
279
            $Response = $this->request();
280
            
281
            $body = json_decode($Response->getBody()->getContents());
282
            
283
            // Prepocess response onto nice model objects.
284
            // @todo abstract.
285
            $return = [];
286
            
287
            foreach ($body->data as $event) {
288
                // Add additional properties here.
289
                $event->soldOut = (bool) ($event->attributes->attendee_count >= $event->attributes->attendee_limit);
290
                array_push($return, $event);
291
            }
292
            
293
            return $return;
294
        } catch (Exception $e) {
295
            throw new RestException($e->getMessage());
296
        }
297
    }
298
    
299
    /**
300
     *
301
     * {@inheritDoc}
302
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getLocation()
303
     */
304
    public function getLocation($locationId)
305
    {
306
        $this->apiResource = $this->apiVersion . '/locations';
307
        if(!empty($locationId && !$this->Valdator->validId($locationId, 'location'))) {
0 ignored issues
show
Bug Best Practice introduced by
The property Valdator does not exist on InShore\BookWhen\Client. Did you maybe forget to declare it?
Loading history...
308
            throw new ValidationException();
309
        }
310
        
311
        try {
312
            $Response = $this->request();
313
            $body = json_decode($Response->getBody()->getContents());
314
            $location = $body->data[0];
315
            $return = $location;
316
            return $return;
317
        } catch (Exception $e) {
318
            throw new RestException($e->getMessage());
319
        }
320
321
    }
322
    
323
    /**
324
     *
325
     * {@inheritDoc}
326
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getLocations()
327
     * @todo validate params.
328
     */
329
    public function getLocations($addressText = null, $additionalInfo = null): array
330
    {
331
        $this->apiResource = $this->apiVersion . '/locations';
332
333
        $return = [];
334
        
335
        try {
336
            $Response = $this->request();
337
            $body = json_decode($Response->getBody()->getContents());
338
            
339
            foreach ($body->data as $location) {
340
                array_push($return, $location);
341
            }
342
            
343
            return $return;
344
        } catch (Exception $e) {
345
            throw new RestException($e->getMessage());
346
        }
347
    } 
348
    
349
    /**
350
     *
351
     * {@inheritDoc}
352
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getTicket()
353
     */
354
    public function getTicket($ticketId)
355
    {        
356
        if (!empty($ticketId && !$this->validator->validId($ticketId, 'ticket'))) {
357
           // throw new ValidationException();
358
        }
359
360
        $this->apiResource = $this->apiVersion . '/tickets';
361
362
        
363
        try {
364
            $Response = $this->request();
365
            $body = json_decode($Response->getBody()->getContents());
366
            $ticket = $body->data[0];
367
            $return = $ticket;
368
            return $return;
369
        } catch (Exception $e) {
370
            throw new RestException($e->getMessage());
371
        }
372
    }
373
    
374
    /**
375
     * 
376
     * {@inheritDoc}
377
     * @see \InShore\BookWhen\Interfaces\ClientInterface::getTickets()
378
     */
379
    public function getTickets($eventId): array
380
    {
381
        if (!$this->validator->validId($eventId, 'event')) {
382
            throw new ValidationException();
383
        }
384
385
        $this->apiQuery = ['event' => $eventId];
386
        
387
        $this->apiResource = $this->apiVersion . '/tickets';
388
                
389
        try {
390
            $return = [];
391
            
392
            $Response = $this->request();
393
            $body = json_decode($Response->getBody()->getContents());
394
            
395
            foreach ($body->data as $ticket) {
396
                array_push($return, $ticket);
397
            }
398
            
399
            return $return;
400
        } catch (Exception $e) {
401
            throw new RestException($e->getMessage());
402
        }
403
    }
404
    
405
    /**
406
     * Set Guzzle Client
407
     */
408
    public function setGuzzleClient($guzzleClient)
409
    {
410
        $this->guzzleClient = $guzzleClient;
411
    } 
412
    
413
    /**
414
     * Sets the token for all future new instances
415
     * @param $token string The API access token, as obtained on diffbot.com/dev.
416
     */
417
    public static function setToken($token)
418
    {
419
        $validator = new Validator();
420
        if (!$validator->validToken($token)) {
421
            throw new \InvalidArgumentException('Invalid Token.');
422
        }
423
        self::$token = $token;
424
    } 
425
}
426
427
// EOF!
428