Passed
Branch v4 (ee4d75)
by Benjamin
05:42 queued 01:10
created

Oauth::getToken()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 22
nc 3
nop 1
dl 0
loc 34
rs 8.5806
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link      https://dukt.net/craft/analytics/
4
 * @copyright Copyright (c) 2018, Dukt
5
 * @license   https://dukt.net/craft/analytics/docs/license
6
 */
7
8
namespace dukt\analytics\services;
9
10
use Craft;
11
use yii\base\Component;
12
use League\OAuth2\Client\Token\AccessToken;
13
use Dukt\OAuth2\Client\Provider\Google;
14
use craft\helpers\UrlHelper;
15
use dukt\analytics\Plugin as Analytics;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, dukt\analytics\services\Analytics. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
16
17
class Oauth extends Component
18
{
19
    // Public Methods
20
    // =========================================================================
21
22
    /**
23
     * Save Token
24
     *
25
     * @param AccessToken $token
26
     */
27
    public function saveToken(AccessToken $token)
28
    {
29
        // Save token and token secret in the plugin's settings
30
31
        $plugin = Craft::$app->getPlugins()->getPlugin('analytics');
32
33
        $settings = $plugin->getSettings();
34
35
        $tokenArray = [
36
            'accessToken' => $token->getToken(),
37
            'expires' => $token->getExpires(),
38
            'refreshToken' => $token->getRefreshToken(),
39
            'resourceOwnerId' => $token->getResourceOwnerId(),
40
            'values' => $token->getValues(),
41
        ];
42
43
        $settings->token = $tokenArray;
44
45
        Craft::$app->getPlugins()->savePluginSettings($plugin, $settings->getAttributes());
46
    }
47
48
    /**
49
     * Returns the OAuth Token.
50
     *
51
     * @param bool $refresh
52
     *
53
     * @return AccessToken|null
54
     */
55
    public function getToken($refresh = true)
56
    {
57
        $plugin = Craft::$app->getPlugins()->getPlugin('analytics');
58
        $settings = $plugin->getSettings();
59
60
        if (!$settings->token) {
61
            return null;
62
        }
63
64
        $token = new AccessToken([
65
            'access_token' => $settings->token['accessToken'] ?? null,
66
            'expires' => $settings->token['expires'] ?? null,
67
            'refresh_token' => $settings->token['refreshToken'] ?? null,
68
            'resource_owner_id' => $settings->token['resourceOwnerId'] ?? null,
69
            'values' => $settings->token['values'] ?? null,
70
        ]);
71
72
        if ($refresh && $token->hasExpired()) {
73
            $provider = $this->getOauthProvider();
74
            $grant = new \League\OAuth2\Client\Grant\RefreshToken();
75
            $newToken = $provider->getAccessToken($grant, ['refresh_token' => $token->getRefreshToken()]);
76
77
            $token = new AccessToken([
78
                'access_token' => $newToken->getToken(),
79
                'expires' => $newToken->getExpires(),
80
                'refresh_token' => $settings->token['refreshToken'],
81
                'resource_owner_id' => $newToken->getResourceOwnerId(),
82
                'values' => $newToken->getValues(),
83
            ]);
84
85
            $this->saveToken($token);
86
        }
87
88
        return $token;
89
    }
90
91
    /**
92
     * Delete Token
93
     *
94
     * @return bool
95
     */
96
    public function deleteToken()
97
    {
98
        $plugin = Craft::$app->getPlugins()->getPlugin('analytics');
99
100
        $settings = $plugin->getSettings();
101
        $settings->token = null;
102
        Craft::$app->getPlugins()->savePluginSettings($plugin, $settings->getAttributes());
103
104
        return true;
105
    }
106
107
    /**
108
     * Returns a Twitter provider (server) object.
109
     *
110
     * @return Google
111
     */
112
    public function getOauthProvider()
113
    {
114
        $options = [
115
            'clientId' => Analytics::$plugin->getSettings()->oauthClientId,
116
            'clientSecret' => Analytics::$plugin->getSettings()->oauthClientSecret
117
        ];
118
119
        $options = array_merge($options, Analytics::$plugin->getSettings()->oauthProviderOptions);
120
121
        if (!isset($options['redirectUri'])) {
122
            $options['redirectUri'] = $this->getRedirectUri();
123
        }
124
125
        return new Google($options);
126
    }
127
128
    /**
129
     * Returns the javascript orgin URL.
130
     *
131
     * @return string
132
     * @throws \craft\errors\SiteNotFoundException
133
     */
134
    public function getJavascriptOrigin()
135
    {
136
        return UrlHelper::baseUrl();
137
    }
138
139
    /**
140
     * Returns the redirect URI.
141
     *
142
     * @return string
143
     */
144
    public function getRedirectUri()
145
    {
146
        return UrlHelper::actionUrl('analytics/oauth/callback');
147
    }
148
}
149