Completed
Push — master ( 06f814...f23c49 )
by Tobias
03:33
created

AnalyticsDataFetcher::getPageViewsAsInteger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 4
crap 2
1
<?php
2
3
namespace Happyr\GoogleAnalyticsBundle\Service;
4
5
use Psr\Cache\CacheItemPoolInterface;
6
7
/**
8
 * This service fetches data from the API.
9
 *
10
 * @author Tobias Nyholm <[email protected]>
11
 */
12
class AnalyticsDataFetcher
13
{
14
    /**
15
     * @var CacheItemPoolInterface cache
16
     */
17
    protected $cache;
18
19
    /**
20
     * @var \Google_Client client
21
     */
22
    protected $client;
23
24
    /**
25
     * @var int profileId
26
     */
27
    protected $viewId;
28
29
    /**
30
     * @var int cacheLifetime
31
     */
32
    protected $cacheLifetime;
33
34
    public function __construct(CacheItemPoolInterface $cache, \Google_Client $client, string $viewId, int $cacheLifetime)
35
    {
36
        $this->cache = $cache;
37
        $this->client = $client;
38
        $this->viewId = $viewId;
0 ignored issues
show
Documentation Bug introduced by
The property $viewId was declared of type integer, but $viewId is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
39
        $this->cacheLifetime = $cacheLifetime;
40
    }
41
42
    /**
43
     * Get page views for the given url.
44
     *
45
     * @return mixed
46
     */
47
    public function getPageViews(string $uri, \DateTimeInterface $startTime = null, \DateTimeInterface $endTime = null, string $regex = '$', array $params = [])
48
    {
49
        if (empty($this->viewId)) {
50
            throw new \LogicException('You need to specify a profile id that we are going to fetch page views from');
51
        }
52
53
        if ($startTime === null) {
54
            // one year ago
55
            $startTime = new \DateTime('-1year');
56
        }
57
58
        if ($endTime === null) {
59
            // today
60
            $endTime = new \DateTime();
61
        }
62
63
        $start = $startTime->format('Y-m-d');
64
        $end = $endTime->format('Y-m-d');
65
66
        //create the cache key
67
        $cacheKey = sha1('v5'.$uri.$regex.$start);
68
        $item = $this->cache->getItem($cacheKey);
69
        if (!$item->isHit()) {
70
            //check if we got a token
71
            if (null === $this->client->getAccessToken()) {
72
                return [];
73
            }
74
75
            $params['filters'] = 'ga:pagePath=~^'.$uri.$regex;
76
            try {
77
                $analytics = new \Google_Service_Analytics($this->client);
78
                $results = $analytics->data_ga->get('ga:'.$this->viewId, $start, $end, 'ga:pageviews', $params);
79
80
                $rows = $results->getRows();
81
            } catch (\Google_Auth_Exception $e) {
0 ignored issues
show
Bug introduced by
The class Google_Auth_Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
82
                $rows = [];
83
            }
84
85
            //save cache item
86
            $item->set($rows)
87
                ->expiresAfter($this->cacheLifetime);
88
            $this->cache->save($item);
89
        }
90
91
        return $item->get();
92
    }
93
94
    public function getPageViewsAsInteger(string $uri, \DateTimeInterface $startTime = null, \DateTimeInterface $endTime = null, string $regex = '$'): int
95
    {
96
        $rows = $this->getPageViews($uri, $startTime, $endTime, $regex);
97
98
        return intval($rows[0][0] ?? 0);
99
    }
100
}
101