Completed
Pull Request — master (#266)
by Alexander
02:53
created

AnalyticsClient::performQuery()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 45
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 24
nc 2
nop 5
1
<?php
2
3
namespace Spatie\Analytics;
4
5
use DateTime;
6
use Google_Service_Analytics;
7
use Illuminate\Contracts\Cache\Repository;
8
use Psr\Log\LoggerInterface;
9
10
class AnalyticsClient
11
{
12
    /** @var \Google_Service_Analytics */
13
    protected $service;
14
15
    /** @var \Illuminate\Contracts\Cache\Repository */
16
    protected $cache;
17
18
    /** @var LoggerInterface */
19
    protected $log;
20
21
    /** @var int */
22
    protected $cacheLifeTimeInMinutes = 0;
23
24
    public function __construct(Google_Service_Analytics $service, Repository $cache, LoggerInterface $log)
25
    {
26
        $this->service = $service;
27
28
        $this->cache = $cache;
29
30
        $this->log = $log;
31
    }
32
33
    /**
34
     * Set the cache time.
35
     *
36
     * @param int $cacheLifeTimeInMinutes
37
     *
38
     * @return self
39
     */
40
    public function setCacheLifeTimeInMinutes(int $cacheLifeTimeInMinutes)
41
    {
42
        $this->cacheLifeTimeInMinutes = $cacheLifeTimeInMinutes;
43
44
        return $this;
45
    }
46
47
    /**
48
     * Query the Google Analytics Service with given parameters.
49
     *
50
     * @param string    $viewId
51
     * @param \DateTime $startDate
52
     * @param \DateTime $endDate
53
     * @param string    $metrics
54
     * @param array     $others
55
     *
56
     * @return array|null
57
     */
58
    public function performQuery(string $viewId, DateTime $startDate, DateTime $endDate, string $metrics, array $others = [])
59
    {
60
        $cacheName = $this->determineCacheName(func_get_args());
61
62
        if ($this->cacheLifeTimeInMinutes == 0) {
63
            $this->cache->forget($cacheName);
64
        }
65
66
        return $this->cache->remember($cacheName, $this->cacheLifeTimeInMinutes, function () use ($viewId, $startDate, $endDate, $metrics, $others) {
67
            $this->log->notice('[AnalyticsClient.performQuery] Fetching - first page');
68
            $result = $this->service->data_ga->get(
69
                "ga:{$viewId}",
70
                $startDate->format('Y-m-d'),
71
                $endDate->format('Y-m-d'),
72
                $metrics,
73
                $others
74
            );
75
76
            $nextLink = $result->getNextLink();
77
78
            while ($nextLink) {
79
                $options = [];
80
                /**
81
                 * @source https://stackoverflow.com/a/33526740
82
                 */
83
                parse_str(substr($nextLink, strpos($nextLink, '?') + 1), $options);
84
85
                $percentage = $options['start-index'] * 100 / $result->getTotalResults();
86
                $this->log->notice(sprintf('[AnalyticsClient.performQuery] Fetching - paging active %.2f%% of %d [%s]',
87
                    $percentage, $result->getTotalResults(), $nextLink)
88
                );
89
90
                $data = $this->service->data_ga->call('get', [$options], "Google_Service_Analytics_GaData");
91
92
                if ($data->rows) {
93
                    $result->rows = array_merge($result->rows, $data->rows);
94
                }
95
96
                $nextLink = $data->getNextLink();
97
98
            }
99
100
            return $result;
101
        });
102
    }
103
104
    public function getAnalyticsService(): Google_Service_Analytics
105
    {
106
        return $this->service;
107
    }
108
109
    /*
110
     * Determine the cache name for the set of query properties given.
111
     */
112
    protected function determineCacheName(array $properties): string
113
    {
114
        return 'spatie.laravel-analytics.'.md5(serialize($properties));
115
    }
116
}
117