1 | <?php |
||
9 | class GoogleCalendarFactory |
||
10 | { |
||
11 | public static function createForCalendarId(string $calendarId): GoogleCalendar |
||
12 | { |
||
13 | $config = config('google-calendar'); |
||
14 | |||
15 | $client = self::createAuthenticatedGoogleClient($config); |
||
16 | |||
17 | $service = new Google_Service_Calendar($client); |
||
18 | |||
19 | return self::createCalendarClient($service, $calendarId); |
||
20 | } |
||
21 | |||
22 | public static function createAuthenticatedGoogleClient(array $config): Google_Client |
||
23 | { |
||
24 | $authProfile = $config['default_auth_profile']; |
||
25 | |||
26 | if ($authProfile === 'service_account') { |
||
27 | return self::createServiceAccountClient($config['auth_profiles']['service_account']); |
||
28 | } |
||
29 | if ($authProfile === 'oauth') { |
||
30 | return self::createOAuthClient($config['auth_profiles']['oauth']); |
||
31 | } |
||
32 | |||
33 | throw InvalidConfiguration::invalidAuthenticationProfile($authProfile); |
||
34 | } |
||
35 | |||
36 | protected static function createServiceAccountClient(array $authProfile): Google_Client |
||
37 | { |
||
38 | $client = new Google_Client; |
||
39 | |||
40 | $client->setScopes([ |
||
41 | Google_Service_Calendar::CALENDAR, |
||
42 | ]); |
||
43 | |||
44 | $client->setAuthConfig($authProfile['credentials_json']); |
||
45 | |||
46 | return $client; |
||
47 | } |
||
48 | |||
49 | protected static function createOAuthClient(array $authProfile): Google_Client |
||
50 | { |
||
51 | $client = new Google_Client; |
||
52 | |||
53 | $client->setScopes([ |
||
54 | Google_Service_Calendar::CALENDAR, |
||
55 | ]); |
||
56 | |||
57 | $client->setAuthConfig($authProfile['credentials_json']); |
||
58 | |||
59 | $client->setAccessToken(file_get_contents($authProfile['token_json'])); |
||
60 | |||
61 | return $client; |
||
62 | } |
||
63 | |||
64 | protected static function createCalendarClient(Google_Service_Calendar $service, string $calendarId): GoogleCalendar |
||
68 | } |
||
69 |