Oauth2ServiceAccountStrategy   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A authenticate() 0 33 4
A getSlug() 0 4 1
1
<?php
2
3
namespace Audiens\DoubleclickClient\authentication;
4
5
use Audiens\DoubleclickClient\CachableTrait;
6
use Audiens\DoubleclickClient\CacheableInterface;
7
use Audiens\DoubleclickClient\entity\BearerToken;
8
use Doctrine\Common\Cache\Cache;
9
use GuzzleHttp\ClientInterface;
10
11
class Oauth2ServiceAccountStrategy implements AuthStrategyInterface, CacheableInterface
12
{
13
14
    use CachableTrait;
15
16
    public const NAME = 'oauth2_service_account';
17
18
    public const BASE_URL = 'https://www.googleapis.com/oauth2/v4/token';
19
20
    public const CACHE_NAMESPACE  = 'oauth2_service_account';
21
    public const CACHE_EXPIRATION = 1800;
22
23
    public const SCOPE = 'https://ddp.googleapis.com/api/ddp/';
24
25
    /** @var Cache */
26
    protected $cache;
27
28
    /** @var JwtFactoryInterface */
29
    protected $jwtFactory;
30
31
    /** @var ClientInterface */
32
    protected $client;
33
34
    public function __construct(ClientInterface $clientInterface, Cache $cache, JwtFactoryInterface $jwtFactory)
35
    {
36
        $this->cache      = $cache;
37
        $this->client     = $clientInterface;
38
        $this->jwtFactory = $jwtFactory;
39
40
        $this->cacheEnabled = $cache instanceof Cache;
41
    }
42
43
    public function authenticate(bool $cache = true): BearerToken
44
    {
45
        $cacheKey = self::CACHE_NAMESPACE.sha1($this->jwtFactory->getHash().self::BASE_URL);
46
47
        if ($cache) {
48
            if ($this->cache->contains($cacheKey)) {
49
                return $this->cache->fetch($cacheKey);
50
            }
51
        }
52
53
        $token = $this->jwtFactory->build();
54
55
        $body = 'grant_type='.urlencode('urn:ietf:params:oauth:grant-type:jwt-bearer').'&assertion='.$token;
56
57
        $response = $this->client->request(
58
            'POST',
59
            self::BASE_URL,
60
            [
61
                'body' => $body,
62
                'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
63
            ]
64
        );
65
66
        $bearerToken = BearerToken::fromArray(json_decode($response->getBody()->getContents(), true));
67
68
        $response->getBody()->rewind();
69
70
        if ($this->isCacheEnabled()) {
71
            $this->cache->save($cacheKey, $bearerToken, self::CACHE_EXPIRATION);
72
        }
73
74
        return $bearerToken;
75
    }
76
77
    public function getSlug(): string
78
    {
79
        return self::NAME;
80
    }
81
}
82