Completed
Push — master ( 77368e...db737a )
by Kevin
04:10
created

Request::locations()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 14
Ratio 100 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 14
loc 14
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 2
crap 3
1
<?php
2
3
namespace Kevintweber\Gauges;
4
5
use Doctrine\Instantiator\Exception\InvalidArgumentException;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\ClientInterface;
8
use GuzzleHttp\HandlerStack;
9
use GuzzleHttp\Middleware;
10
use GuzzleHttp\MessageFormatter;
11
use GuzzleHttp\Psr7\Response;
12
use Psr\Log\LoggerAwareInterface;
13
use Psr\Log\LoggerInterface;
14
use Psr\Log\LogLevel;
15
16
/**
17
 * Used to make Gauges API calls.
18
 */
19
class Request implements LoggerAwareInterface
20
{
21
    const URI = 'https://secure.gaug.es/';
22
23
    /** @var null|ClientInterface */
24
    private $client;
25
26
    /** @var HandlerStack */
27
    private $handlerStack;
28
29
    /** @var null|LoggerInterface */
30
    private $logger;
31
32
    /** @var string */
33
    private $logLevel;
34
35
    /** @var MessageFormatter */
36
    private $messageFormatter;
37
38
    /** @var array */
39
    private $options;
40
41
    /** @var string */
42
    protected $token;
43
44
    /**
45
     * Constructor
46
     *
47
     * @param string $token     Your API token
48
     * @param array  $options   See Guzzle documentation (proxy, etc.)
49
     */
50 26
    public function __construct(string $token, array $options = array())
51
    {
52 26
        $this->client = null;
53 26
        $this->handlerStack = HandlerStack::create();
54 26
        $this->logger = null;
55 26
        $this->logLevel = LogLevel::INFO;
56 26
        $this->messageFormatter = new MessageFormatter();
57 26
        $this->options = array_merge(
58 26
            array('timeout' => 10),
59
            $options
60
        );
61 26
        $this->options['base_uri'] = self::URI;
62 26
        $this->token = $token;
63 26
    }
64
65
    /**
66
     * Getter for the HTTP client.
67
     *
68
     * @return Client
69
     */
70 23
    protected function getHttpClient() : Client
71
    {
72 23
        if ($this->client === null) {
73 23
            if ($this->logger instanceof LoggerInterface) {
74 23
                $this->handlerStack->push(
75 23
                    Middleware::log(
76 23
                        $this->logger,
77 23
                        $this->messageFormatter,
78 23
                        $this->logLevel
79
                    )
80
                );
81
            }
82
83 23
            $this->options['handler'] = $this->handlerStack;
84 23
            $this->client = new Client($this->options);
85
        }
86
87 23
        return $this->client;
88
    }
89
90
    /**
91
     * Setter for the Guzzle HandlerStack
92
     */
93 25
    public function setHandlerStack(HandlerStack $handlerStack)
94
    {
95 25
        $this->handlerStack = $handlerStack;
96 25
    }
97
98 26
    public function setLogger(LoggerInterface $logger)
99
    {
100 26
        $this->logger = $logger;
101 26
    }
102
103 25
    public function setLogLevel(string $logLevel)
104
    {
105 25
        $logLevel = strtolower($logLevel);
106 25
        if ($logLevel !== LogLevel::ALERT &&
107 25
            $logLevel !== LogLevel::CRITICAL &&
108 25
            $logLevel !== LogLevel::DEBUG &&
109 25
            $logLevel !== LogLevel::EMERGENCY &&
110 25
            $logLevel !== LogLevel::ERROR &&
111 25
            $logLevel !== LogLevel::INFO &&
112 25
            $logLevel !== LogLevel::NOTICE &&
113 25
            $logLevel !== LogLevel::WARNING) {
114 1
            throw new \InvalidArgumentException('Invalid log level: ' . $logLevel);
115
        }
116
117 25
        $this->logLevel = $logLevel;
118 25
    }
119
120
    /**
121
     * Setter for the Guzzle MessageFormatter
122
     */
123 26
    public function setMessageFormatter(MessageFormatter $messageFormatter)
124
    {
125 26
        $this->messageFormatter = $messageFormatter;
126 26
    }
127
128
    /**
129
     * Get Your Information
130
     *
131
     * Returns your information.
132
     *
133
     * @return Response
134
     */
135 2
    public function me() : Response
136
    {
137 2
        return $this->makeApiCall('GET', 'me');
138
    }
139
140
    /**
141
     * Update Your Information
142
     *
143
     * Updates and returns your information with the updates applied.
144
     *
145
     * @param string $first_name Your first name. (Optional)
146
     * @param string $last_name  Your last name. (Optional)
147
     *
148
     * @return Response
149
     */
150 1
    public function updateMe(string $first_name = null, string $last_name = null) : Response
151
    {
152 1
        $params = array();
153
154 1
        if (isset($first_name)) {
155 1
            $params['first_name'] = $first_name;
156
        }
157
158 1
        if (isset($last_name)) {
159 1
            $params['last_name'] = $last_name;
160
        }
161
162 1
        return $this->makeApiCall('PUT', 'me', $params);
163
    }
164
165
    /**
166
     * API Client List
167
     *
168
     * Returns an array of your API clients.
169
     *
170
     * @return Response
171
     */
172 1
    public function listClients() : Response
173
    {
174 1
        return $this->makeApiCall('GET', 'clients');
175
    }
176
177
    /**
178
     * Creating an API Client
179
     *
180
     * Creates an API client, which can be used to authenticate against
181
     * the Gaug.es API.
182
     *
183
     * @param string $description Short description for the key (Optional)
184
     *
185
     * @return Response
186
     */
187 1 View Code Duplication
    public function createClient(string $description = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
    {
189 1
        $params = array();
190
191 1
        if (isset($description)) {
192 1
            $params['description'] = $description;
193
        }
194
195 1
        return $this->makeApiCall('POST', 'clients', $params);
196
    }
197
198
    /**
199
     * Delete an API Client
200
     *
201
     * Permanently deletes an API client key.
202
     *
203
     * @param string $id
204
     *
205
     * @return Response
206
     */
207 1
    public function deleteClient(string $id) : Response
208
    {
209 1
        return $this->makeApiCall('DELETE', 'clients/' . $id);
210
    }
211
212
    /**
213
     * Gauges List
214
     *
215
     * Returns an array of your gauges, with recent traffic included.
216
     *
217
     * @param int $page Page number (Optional)
218
     *
219
     * @return Response
220
     */
221 1 View Code Duplication
    public function listGauges(int $page = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
222
    {
223 1
        $params = array();
224
225 1
        if (isset($page)) {
226 1
            $params['page'] = $page;
227
        }
228
229 1
        return $this->makeApiCall('GET', 'gauges', $params);
230
    }
231
232
    /**
233
     * Create a New Gauge
234
     *
235
     * Creates a gauge.
236
     *
237
     * @param string               $title
238
     * @param string|\DateTimeZone $tz
239
     * @param string               $allowedHosts (Optional)
240
     *
241
     * @return Response
242
     */
243 1 View Code Duplication
    public function createGauge(string $title, $tz, string $allowedHosts = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
244
    {
245 1
        if (!$tz instanceof \DateTimeZone) {
246 1
            $tz = new \DateTimeZone($tz);
247
        }
248
249
        $params = array(
250 1
            'title' => $title,
251 1
            'tz' => $tz->getName()
252
        );
253
254 1
        if (isset($allowedHosts)) {
255 1
            $params['allowed_hosts'] = $allowedHosts;
256
        }
257
258 1
        return $this->makeApiCall('POST', 'gauges', $params);
259
    }
260
261
    /**
262
     * Gauge Detail
263
     *
264
     * Gets details for a gauge.
265
     *
266
     * @param string $id
267
     *
268
     * @return Response
269
     */
270 1
    public function gaugeDetail(string $id) : Response
271
    {
272 1
        return $this->makeApiCall('GET', 'gauges/' . $id);
273
    }
274
275
    /**
276
     * Update a Gauge
277
     *
278
     * Updates and returns a gauge with the updates applied.
279
     *
280
     * @param string               $id
281
     * @param string               $title
282
     * @param string|\DateTimeZone $tz
283
     * @param string               $allowedHosts (Optional)
284
     *
285
     * @return Response
286
     */
287 1 View Code Duplication
    public function updateGauge(string $id, string $title, $tz, string $allowedHosts = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
288
    {
289 1
        if (!$tz instanceof \DateTimeZone) {
290 1
            $tz = new \DateTimeZone($tz);
291
        }
292
293
        $params = array(
294 1
            'title' => $title,
295 1
            'tz' => $tz->getName()
296
        );
297
298 1
        if (isset($allowedHosts)) {
299 1
            $params['allowed_hosts'] = $allowedHosts;
300
        }
301
302 1
        return $this->makeApiCall('PUT', 'gauges/' . $id, $params);
303
    }
304
305
    /**
306
     * Delete a Gauge
307
     *
308
     * Permanently deletes a gauge.
309
     *
310
     * @param string $id
311
     *
312
     * @return Response
313
     */
314 1
    public function deleteGauge(string $id) : Response
315
    {
316 1
        return $this->makeApiCall('DELETE', 'gauges/' . $id);
317
    }
318
319
    /**
320
     * List Shares
321
     *
322
     * Lists the people that have access to a Gauge.
323
     *
324
     * @param string $id
325
     *
326
     * @return Response
327
     */
328 1
    public function listShares(string $id) : Response
329
    {
330 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/shares');
331
    }
332
333
    /**
334
     * Share a Gauge
335
     *
336
     * Shares gauge with a person by their email. Any valid email will work
337
     * and will receive an invite even if there is no existing Gauges user
338
     * with that email.
339
     *
340
     * @param string $id
341
     * @param string $email
342
     *
343
     * @return Response
344
     */
345 1
    public function shareGauge(string $id, string $email) : Response
346
    {
347
        $params = array(
348 1
            'email' => $email
349
        );
350
351 1
        return $this->makeApiCall('POST', 'gauges/' . $id . '/shares', $params);
352
    }
353
354
    /**
355
     * Top Content
356
     *
357
     * Gets top content for a gauge, paginated.
358
     *
359
     * @param string           $id
360
     * @param string|\DateTime $date  (Optional) Date in format YYYY-MM-DD
361
     * @param string           $group (Optional) Either "day" or "month".  Default is "day".
362
     * @param int              $page  (Optional)
363
     *
364
     * @return Response
365
     */
366 2
    public function topContent(string $id, $date = null, string $group = null, int $page = null) : Response
367
    {
368 2
        $params = array();
369
370 2
        if (isset($date)) {
371 2
            if (!$date instanceof \DateTime) {
372 2
                $date = new \DateTime($date);
373
            }
374
375 2
            $params['date'] = $date->format('Y-m-d');
376
        }
377
378 2
        if (isset($group)) {
379 2
            $group = strtolower($group);
380 2
            if ($group !== 'month' && $group !== 'day') {
381 1
                throw new \InvalidArgumentException(
382 1
                    'Invalid group parameter for "topContent" call.  Allowed values are "day" or "month".  Actual value is : ' . $group
383
                );
384
            }
385
386 1
            $params['group'] = $group;
387
        }
388
389 1
        if (isset($page)) {
390 1
            $params['page'] = $page;
391
        }
392
393 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/content', $params);
394
    }
395
396
    /**
397
     * Un-share Gauge
398
     *
399
     * @param string $id
400
     * @param string $user_id
401
     *
402
     * @return Response
403
     */
404 1
    public function unshareGauge(string $id, string $user_id) : Response
405
    {
406 1
        return $this->makeApiCall('DELETE', 'gauges/' . $id . '/shares/' . $user_id);
407
    }
408
409
    /**
410
     * Top Referrers
411
     *
412
     * Gets top referrers for a gauge, paginated.
413
     *
414
     * @param string           $id
415
     * @param string|\DateTime $date (Optional) Date in format YYYY-MM-DD
416
     * @param int              $page (Optional)
417
     *
418
     * @return Response
419
     */
420 1 View Code Duplication
    public function topReferrers(string $id, $date = null, int $page = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
421
    {
422 1
        $params = array();
423
424 1
        if (isset($date)) {
425 1
            if (!$date instanceof \DateTime) {
426 1
                $date = new \DateTime($date);
427
            }
428
429 1
            $params['date'] = $date->format('Y-m-d');
430
        }
431
432 1
        if (isset($page)) {
433 1
            $params['page'] = (int) $page;
434
        }
435
436 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/referrers', $params);
437
    }
438
439
    /**
440
     * Traffic
441
     *
442
     * Gets traffic for a gauge.
443
     *
444
     * @param string           $id
445
     * @param string|\DateTime $date (Optional) Date in format YYYY-MM-DD
446
     *
447
     * @return Response
448
     */
449 1 View Code Duplication
    public function traffic(string $id, $date = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
450
    {
451 1
        $params = array();
452
453 1
        if (isset($date)) {
454 1
            if (!$date instanceof \DateTime) {
455 1
                $date = new \DateTime($date);
456
            }
457
458 1
            $params['date'] = $date->format('Y-m-d');
459
        }
460
461 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/traffic', $params);
462
    }
463
464
    /**
465
     * Browser Resolutions
466
     *
467
     * Gets browsers heights, browser widths, and screen widths for a gauge.
468
     *
469
     * @param string $id
470
     * @param string|\DateTime $date (Optional) Date in format YYYY-MM-DD
471
     *
472
     * @return Response
473
     */
474 1 View Code Duplication
    public function browserResolutions(string $id, $date = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
475
    {
476 1
        $params = array();
477
478 1
        if (isset($date)) {
479 1
            if (!$date instanceof \DateTime) {
480 1
                $date = new \DateTime($date);
481
            }
482
483 1
            $params['date'] = $date->format('Y-m-d');
484
        }
485
486 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/resolutions', $params);
487
    }
488
489
    /**
490
     * Technology
491
     *
492
     * Gets browsers and platforms for a gauge.
493
     *
494
     * @param string           $id
495
     * @param string|\DateTime $date (Optional) Date in format YYYY-MM-DD
496
     *
497
     * @return Response
498
     */
499 1 View Code Duplication
    public function technology(string $id, $date = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
500
    {
501 1
        $params = array();
502
503 1
        if (isset($date)) {
504 1
            if (!$date instanceof \DateTime) {
505 1
                $date = new \DateTime($date);
506
            }
507
508 1
            $params['date'] = $date->format('Y-m-d');
509
        }
510
511 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/technology', $params);
512
    }
513
514
    /**
515
     * Search Terms
516
     *
517
     * Gets search terms for a gauge, paginated.
518
     *
519
     * @param string $id
520
     * @param string|\DateTime $date (Optional) Date in format YYYY-MM-DD
521
     * @param int    $page (Optional)
522
     *
523
     * @return Response
524
     */
525 1 View Code Duplication
    public function searchTerms(string $id, $date = null, int $page = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
526
    {
527 1
        $params = array();
528
529 1
        if (isset($date)) {
530 1
            if (!$date instanceof \DateTime) {
531 1
                $date = new \DateTime($date);
532
            }
533
534 1
            $params['date'] = $date->format('Y-m-d');
535
        }
536
537 1
        if (isset($page)) {
538 1
            $params['page'] = $page;
539
        }
540
541 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/terms', $params);
542
    }
543
544
    /**
545
     * Search Engines
546
     *
547
     * Gets search engines for a gauge.
548
     *
549
     * @param string $id
550
     * @param string|\DateTime $date (Optional) Date in format YYYY-MM-DD
551
     *
552
     * @return Response
553
     */
554 1 View Code Duplication
    public function searchEngines(string $id, $date = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
555
    {
556 1
        $params = array();
557
558 1
        if (isset($date)) {
559 1
            if (!$date instanceof \DateTime) {
560 1
                $date = new \DateTime($date);
561
            }
562
563 1
            $params['date'] = $date->format('Y-m-d');
564
        }
565
566 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/engines', $params);
567
    }
568
569
    /**
570
     * Locations
571
     *
572
     * Gets locations for a gauge.
573
     *
574
     * @param string $id
575
     * @param string|\DateTime $date (Optional) Date in format YYYY-MM-DD
576
     *
577
     * @return Response
578
     */
579 1 View Code Duplication
    public function locations(string $id, $date = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
580
    {
581 1
        $params = array();
582
583 1
        if (isset($date)) {
584 1
            if (!$date instanceof \DateTime) {
585 1
                $date = new \DateTime($date);
586
            }
587
588 1
            $params['date'] = $date->format('Y-m-d');
589
        }
590
591 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/locations', $params);
592
    }
593
594
    /**
595
     * Browser stats
596
     *
597
     * Get the browser statistics in a format used with the browserlist module.
598
     * (See https://github.com/ai/browserslist)
599
     *
600
     * @param string $id
601
     * @param string|\DateTime $date (Optional) Date in format YYYY-MM-DD
602
     *
603
     * @return Response
604
     */
605 1 View Code Duplication
    public function browserStats(string $id, $date = null) : Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
606
    {
607 1
        $params = array();
608
609 1
        if (isset($date)) {
610 1
            if (!$date instanceof \DateTime) {
611 1
                $date = new \DateTime($date);
612
            }
613
614 1
            $params['date'] = $date->format('Y-m-d');
615
        }
616
617 1
        return $this->makeApiCall('GET', 'gauges/' . $id . '/browserstats', $params);
618
    }
619
620
    /**
621
     * Make the actual gauges API call.
622
     *
623
     * @param string $method       [GET|POST|PUT|DELETE]
624
     * @param string $path
625
     * @param array  $params
626
     *
627
     * @return Response
628
     */
629 23
    protected function makeApiCall(string $method, string $path, array $params = array()) : Response
630
    {
631
        // Format method.
632 23
        $method = strtoupper($method);
633
634
        // Make API call.
635 23
        return $this->getHttpClient()->request(
636
            $method,
637
            $path,
638
            array(
639 23
                'headers' => array('X-Gauges-Token' => $this->token),
640 23
                'query' => $params
641
            )
642
        );
643
    }
644
}
645