Completed
Pull Request — master (#163)
by
unknown
01:10
created

GoogleCalendarFactory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 61
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A createForCalendarId() 0 10 1
A createAuthenticatedGoogleClient() 0 13 3
A createServiceAccountClient() 0 12 1
A createOAuthClient() 0 14 1
A createCalendarClient() 0 4 1
1
<?php
2
3
namespace Spatie\GoogleCalendar;
4
5
use Google_Client;
6
use Google_Service_Calendar;
7
8
class GoogleCalendarFactory
9
{
10
    public static function createForCalendarId(string $calendarId): GoogleCalendar
11
    {
12
        $config = config('google-calendar');
13
14
        $client = self::createAuthenticatedGoogleClient($config);
15
16
        $service = new Google_Service_Calendar($client);
17
18
        return self::createCalendarClient($service, $calendarId);
19
    }
20
21
    public static function createAuthenticatedGoogleClient(array $config): Google_Client
22
    {
23
        $authProfile = $config['default_auth_profile'];
24
25
        switch ($authProfile) {
26
            case 'service_account':
27
                return self::createServiceAccountClient($config['auth_profiles']['service_account']);
28
            case 'oauth':
29
                return self::createOAuthClient($config['auth_profiles']['oauth']);
30
        }
31
32
        throw new \InvalidArgumentException("Unsupported authentication profile [{$authProfile}].");
33
    }
34
35
    protected static function createServiceAccountClient(array $authProfile): Google_Client
36
    {
37
        $client = new Google_Client;
38
39
        $client->setScopes([
40
            Google_Service_Calendar::CALENDAR,
41
        ]);
42
43
        $client->setAuthConfig($authProfile['credentials_json']);
44
45
        return $client;
46
    }
47
48
    protected static function createOAuthClient(array $authProfile): Google_Client
49
    {
50
        $client = new Google_Client;
51
52
        $client->setScopes([
53
            Google_Service_Calendar::CALENDAR,
54
        ]);
55
56
        $client->setAuthConfig($authProfile['credentials_json']);
57
58
        $client->setAccessToken(file_get_contents($authProfile['token_json']));
59
60
        return $client;
61
    }
62
63
64
    protected static function createCalendarClient(Google_Service_Calendar $service, string $calendarId): GoogleCalendar
65
    {
66
        return new GoogleCalendar($service, $calendarId);
67
    }
68
}
69