1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Analytics; |
4
|
|
|
|
5
|
|
|
use Google_Client; |
6
|
|
|
use Google_Service_Analytics; |
7
|
|
|
use Illuminate\Contracts\Cache\Repository; |
8
|
|
|
use Madewithlove\IlluminatePsrCacheBridge\Laravel\CacheItemPool; |
9
|
|
|
|
10
|
|
|
class AnalyticsClientFactory |
11
|
|
|
{ |
12
|
|
|
public static function createForConfig(array $analyticsConfig): AnalyticsClient |
13
|
|
|
{ |
14
|
|
|
$authenticatedClient = self::createAuthenticatedGoogleClient($analyticsConfig); |
15
|
|
|
|
16
|
|
|
$googleService = new Google_Service_Analytics($authenticatedClient); |
17
|
|
|
|
18
|
|
|
return self::createAnalyticsClient($analyticsConfig, $googleService); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public static function createAuthenticatedGoogleClient(array $config): Google_Client |
22
|
|
|
{ |
23
|
|
|
$client = new Google_Client(); |
24
|
|
|
|
25
|
|
|
$client->setScopes([ |
26
|
|
|
Google_Service_Analytics::ANALYTICS_READONLY, |
27
|
|
|
]); |
28
|
|
|
|
29
|
|
|
$client->setAuthConfig($config['service_account_credentials_json']); |
30
|
|
|
|
31
|
|
|
self::configureCache($client, $config['cache']); |
32
|
|
|
|
33
|
|
|
return $client; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
protected static function configureCache(Google_Client $client, $config) |
37
|
|
|
{ |
38
|
|
|
$config = collect($config); |
39
|
|
|
|
40
|
|
|
$store = \Cache::store($config->get('store')); |
41
|
|
|
|
42
|
|
|
$cache = new CacheItemPool($store); |
43
|
|
|
|
44
|
|
|
$client->setCache($cache); |
45
|
|
|
|
46
|
|
|
$client->setCacheConfig( |
47
|
|
|
$config->except('store')->toArray() |
48
|
|
|
); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
protected static function createAnalyticsClient(array $analyticsConfig, Google_Service_Analytics $googleService): AnalyticsClient |
52
|
|
|
{ |
53
|
|
|
$client = new AnalyticsClient($googleService, app(Repository::class)); |
54
|
|
|
|
55
|
|
|
$client->setCacheLifeTimeInMinutes($analyticsConfig['cache_lifetime_in_minutes']); |
56
|
|
|
|
57
|
|
|
return $client; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|