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
|
|
|
|