AnalyticsClientFactory::configureCache()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
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 Illuminate\Support\Facades\Cache;
9
use Symfony\Component\Cache\Adapter\Psr16Adapter;
10
11
class AnalyticsClientFactory
12
{
13
    public static function createForConfig(array $analyticsConfig): AnalyticsClient
14
    {
15
        $authenticatedClient = self::createAuthenticatedGoogleClient($analyticsConfig);
16
17
        $googleService = new Google_Service_Analytics($authenticatedClient);
18
19
        return self::createAnalyticsClient($analyticsConfig, $googleService);
20
    }
21
22
    public static function createAuthenticatedGoogleClient(array $config): Google_Client
23
    {
24
        $client = new Google_Client();
25
26
        $client->setScopes([
27
            Google_Service_Analytics::ANALYTICS_READONLY,
28
        ]);
29
30
        $client->setAuthConfig($config['service_account_credentials_json']);
31
32
        self::configureCache($client, $config['cache']);
33
34
        return $client;
35
    }
36
37
    protected static function configureCache(Google_Client $client, $config)
38
    {
39
        $config = collect($config);
40
41
        $store = Cache::store($config->get('store'));
42
43
        $cache = new Psr16Adapter($store);
44
45
        $client->setCache($cache);
46
47
        $client->setCacheConfig(
48
            $config->except('store')->toArray()
49
        );
50
    }
51
52
    protected static function createAnalyticsClient(array $analyticsConfig, Google_Service_Analytics $googleService): AnalyticsClient
53
    {
54
        $client = new AnalyticsClient($googleService, app(Repository::class));
55
56
        $client->setCacheLifeTimeInMinutes($analyticsConfig['cache_lifetime_in_minutes']);
57
58
        return $client;
59
    }
60
}
61