Cancelled
Push — develop ( 5a5c91...8665a3 )
by Florian
33s queued 10s
created

GoogleOAuthService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Service;
4
5
use App\Entity\User;
6
use App\Exception\GoogleApiException;
7
use DateTime;
8
use Doctrine\ORM\EntityManagerInterface;
9
use Google_Client;
10
11
class GoogleOAuthService
12
{
13
    private Google_Client $googleClient;
14
    private EntityManagerInterface $em;
15
16
    /**
17
     * @param Google_Client          $googleClient
18
     * @param EntityManagerInterface $em
19
     */
20
    public function __construct(Google_Client $googleClient, EntityManagerInterface $em)
21
    {
22
        $this->googleClient = $googleClient;
23
        $this->em = $em;
24
    }
25
26
    /**
27
     * @param User $user
28
     */
29
    public function refreshAccessTokenIfExpired(User $user): void
30
    {
31
        if (!$user->hasAccessTokenExpired()) {
32
            return;
33
        }
34
35
        $data = $this->googleClient->refreshToken($user->getRefreshToken());
36
        $user
37
            ->setAccessToken($data['access_token'])
38
            ->setAccessTokenExpiresAt(new DateTime(sprintf('+%d seconds', $data['expires_in'])));
39
        $this->em->flush();
40
    }
41
42
    /**
43
     * @param User $user
44
     *
45
     * @throws GoogleApiException
46
     */
47
    public function revoke(User $user): void
48
    {
49
        $revoked = $this->googleClient->revokeToken($user->getRefreshToken());
50
51
        if (!$revoked) {
52
            throw new GoogleApiException('User access revoking failed');
53
        }
54
55
        $user->setRevoked(true);
56
        $this->em->flush();
57
    }
58
}
59