GigyaGrant::getToken()   A
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 14
c 1
b 0
f 0
nc 8
nop 0
dl 0
loc 22
ccs 15
cts 15
cp 1
crap 6
rs 9.2222
1
<?php
2
/**
3
 * This file is part of graze/gigya-client
4
 *
5
 * Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/gigya-client/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/gigya-client
12
 */
13
14
namespace Graze\Gigya\Auth\OAuth2;
15
16
use DateInterval;
17
use DateTime;
18
use Graze\Gigya\Gigya;
19
use Graze\Gigya\Response\ErrorCode;
20
21
class GigyaGrant implements GrantInterface
22
{
23
    /** @var AccessToken|null */
24
    private $token;
25
    /** @var Gigya */
26
    private $gigya;
27
28
    /**
29
     * GigyaGrant constructor.
30
     *
31
     * @param Gigya $gigya
32
     */
33 6
    public function __construct(Gigya $gigya)
34
    {
35 6
        $this->gigya = $gigya;
36 6
        $this->token = null;
37 6
    }
38
39
    /**
40
     * @return AccessToken|null
41
     */
42 4
    public function getToken()
43
    {
44 4
        if (!is_null($this->token) && $this->token->isExpired()) {
45 1
            $this->token = null;
46
        }
47
48 4
        if (is_null($this->token)) {
49 4
            $response = $this->gigya->socialize()->getToken([
50 4
                'grant_type' => 'none',
51 4
            ], ['auth' => 'credentials']);
52 4
            if ($response->getErrorCode() == ErrorCode::OK) {
53 3
                $data = $response->getData();
54 3
                $token = $data->get('access_token');
55 3
                $expires = null;
56 3
                if ($data->has('expires_in')) {
57 2
                    $expires = (new DateTime())->add(new DateInterval(sprintf('PT%dS', $data->get('expires_in', 0))));
58
                }
59 3
                $this->token = new AccessToken($token, $expires);
60
            }
61
        }
62
63 4
        return $this->token;
64
    }
65
}
66