Test Failed
Push — master ( 40c64c...4518ff )
by Dimas
09:34
created

client   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 252
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 94
dl 0
loc 252
rs 9.0399
c 0
b 0
f 0
wmc 42

16 Methods

Rating   Name   Duplication   Size   Complexity  
A get_token_folder() 0 3 1
A setCredentials() 0 10 1
A set_token_folder() 0 7 2
A set_scope() 0 15 4
C auto_login() 0 36 12
A fetch_user() 0 8 1
A userdata() 0 3 2
A is_url() 0 3 1
A __construct() 0 12 2
A login_data() 0 3 2
A getOrigin() 0 3 3
A set_offline() 0 10 2
A revoke() 0 5 1
A is_login() 0 3 3
A check_subscriber() 0 26 3
A isValid() 0 3 2

How to fix   Complexity   

Complex Class

Complex classes like client often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use client, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace GoogleExt;
4
5
use Filemanager\file;
6
//use Google_Client;
7
use Google\Client as Google_Client;
8
9
class client extends Google_Client
10
{
11
  /**
12
   * Google Client Instances.
13
   *
14
   * @var \Google_Client
0 ignored issues
show
Bug introduced by
The type Google_Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
   */
16
  private $Client;
0 ignored issues
show
introduced by
The private property $Client is not used, and could be removed.
Loading history...
17
  /**
18
   * Filemanager instance.
19
   *
20
   * @var \Filemanager\file
21
   */
22
  private $filemanager;
23
  private $token_folder;
24
  private $configuration;
25
26
  public function __construct(array $config = ['token' => ['folder' => __DIR__ . '/token']])
27
  {
28
    parent::__construct($config);
29
    $this->filemanager = new \Filemanager\file();
30
    if (isset($config['token']['folder'])) {
31
      $token_folder = $config['token']['folder'];
32
      $this->token_folder = $token_folder;
33
      file::folder($token_folder, null, null, true);
0 ignored issues
show
Unused Code introduced by
The call to Filemanager\file::folder() has too many arguments starting with null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

33
      file::/** @scrutinizer ignore-call */ 
34
            folder($token_folder, null, null, true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
34
      file::file($token_folder . '/.htaccess', 'deny from all');
0 ignored issues
show
Bug introduced by
'deny from all' of type string is incompatible with the type boolean expected by parameter $create of Filemanager\file::file(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

34
      file::file($token_folder . '/.htaccess', /** @scrutinizer ignore-type */ 'deny from all');
Loading history...
35
      file::file($token_folder . '/.gitignore', "*\n!.gitignore\n!.htaccess");
36
    }
37
    $this->configuration = $config;
38
  }
39
40
  /**
41
   * Check user google is login.
42
   *
43
   * @return bool
44
   */
45
  public function is_login()
46
  {
47
    return isset($_SESSION['google']['login']) && !empty($_SESSION['google']['login']) && isset($_SESSION['google']['login']['email']);
48
  }
49
50
  /**
51
   * Revoke token.
52
   *
53
   * @return $this
54
   */
55
  public function revoke()
56
  {
57
    $this->revokeToken();
58
59
    $this;
60
  }
61
62
  /**
63
   * Get current origin url.
64
   *
65
   * @return string
66
   */
67
  public function getOrigin(string $path = null)
68
  {
69
    return (isset($_SERVER['HTTPS']) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$path";
70
  }
71
72
  public function get_token_folder()
73
  {
74
    return $this->token_folder;
75
  }
76
77
  public function set_token_folder(string $path)
78
  {
79
    if ($path = realpath($path)) {
80
      $this->token_folder = $path;
81
    }
82
83
    return $this;
84
  }
85
86
  public function set_scope($scopes)
87
  {
88
    if (is_string($scopes)) {
89
      if ($this->is_url($scopes)) {
90
        $this->addScope($scopes);
91
      } else {
92
        throw new \MVC\Exception('Scope is URL format', 1);
93
94
        return null;
0 ignored issues
show
Unused Code introduced by
return null is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
95
      }
96
    } elseif (is_array($scopes)) {
97
      $this->setScopes($scopes);
98
    }
99
100
    return $this;
101
  }
102
103
  /**
104
   * Set access token offline.
105
   *
106
   * @param bool $offline
107
   *
108
   * @return client
109
   */
110
  public function set_offline($offline = true)
111
  {
112
    if ($offline) {
113
      $this->setAccessType('offline');
114
      $this->setApprovalPrompt('force');
115
    } else {
116
      $this->setApprovalPrompt('auto');
117
    }
118
119
    return $this;
120
  }
121
122
  /**
123
   * Set default credentials.
124
   *
125
   * @return client
126
   */
127
  public function setCredentials(string $client, string $secret, string $key)
128
  {
129
    $this->setApplicationName('Login to ' . $_SERVER['HTTP_HOST']);
130
    $this->setDeveloperKey($key);
131
    $this->setClientId($client);
132
    $this->setClientSecret($secret);
133
    $this->addScope('https://www.googleapis.com/auth/userinfo.email');
134
    $this->addScope('https://www.googleapis.com/auth/userinfo.profile');
135
136
    return $this;
137
  }
138
139
  /**
140
   * Check if current instance is valid.
141
   *
142
   * @return bool
143
   */
144
  public function isValid()
145
  {
146
    return $this->getAccessToken() && !$this->isAccessTokenExpired();
147
  }
148
149
  public function is_url($string)
150
  {
151
    return filter_var($string, FILTER_VALIDATE_URL);
152
  }
153
154
  /**
155
   * Check user has subscribed to youtube channel.
156
   *
157
   * @param string $cid          channel id
158
   * @param bool   $only_get_url = return URL channel
159
   */
160
  public function check_subscriber(string $cid = 'UCGNaoefvJRfd15fo-LQ0zvg', bool $only_get_url = false)
161
  {
162
    if (!$only_get_url) {
163
      $service = new \Google_Service_YouTube($this);
164
      $response = $service->subscriptions->listSubscriptions(
165
        'snippet,contentDetails',
166
        array_filter(['forChannelId' => $cid, 'mine' => true])
167
      );
168
169
      $result = count($response['items']);
170
      $output = [];
171
      if ($result > 0) {
172
        $output['success'] = true;
173
        $output['data'] = $response['items'];
174
        $_SESSION['subscribed'] = 1;
175
      } else {
176
        $output['error'] = true;
177
        $output['data'] = 'Belum Subscribe';
178
        $output['msg'] = 'Belum Subscribe';
179
        $_SESSION['subscribed'] = 0;
180
      }
181
    } else {
182
      $output = 'https://www.youtube.com/channel/' . $cid;
183
    }
184
185
    return $output;
186
  }
187
188
  public function auto_login()
189
  {
190
    $config = $this->configuration;
191
    if (isset($_GET['code'])) {
192
      $token = $this->fetchAccessTokenWithAuthCode($_GET['code']);
193
      /*$this->authenticate($_GET['code']);
194
      $access_token = $this->getAccessToken();
195
      e($access_token, $token);*/
196
      if (!empty($token)) {
197
        if (isset($token['error'])) {
198
          e($token);
199
        }
200
        //$this->setAccessToken($token);
201
      }
202
      if (isset($config['token']['folder']) && $this->getAccessToken()) {
203
        $user = $this->fetch_user();
204
        $_SESSION['google']['login'] = $user;
205
        file::file($config['token']['folder'] . '/' . $user['email'] . '.json', $token, true);
206
      }
207
    } else {
208
      if (isset($this->login_data()['email'])) {
209
        $email = $this->login_data()['email'];
210
        $tokenpath = $config['token']['folder'] . '/' . $email . '.json';
211
        if (file_exists($tokenpath)) {
212
          $token = json_decode(file_get_contents($tokenpath), true);
213
          $this->setAccessToken($token);
214
        }
215
      }
216
    }
217
218
    if (isset($_SESSION['google']['login'])) {
219
      $user = $_SESSION['google']['login'];
220
      // auto refresh token
221
      if ($this->isAccessTokenExpired() && isset($user['email']) && $this->getAccessToken()) {
222
        $this->fetchAccessTokenWithRefreshToken($this->getRefreshToken());
223
        file::file($config['token']['folder'] . '/' . $user['email'] . '.json', json_encode($this->getAccessToken()), true);
0 ignored issues
show
Bug introduced by
json_encode($this->getAccessToken()) of type string is incompatible with the type boolean expected by parameter $create of Filemanager\file::file(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

223
        file::file($config['token']['folder'] . '/' . $user['email'] . '.json', /** @scrutinizer ignore-type */ json_encode($this->getAccessToken()), true);
Loading history...
224
      }
225
    }
226
  }
227
228
  /**
229
   * Get current user login ($_SESSION['login']).
230
   *
231
   * @return array
232
   */
233
  public function login_data()
234
  {
235
    return isset($_SESSION['login']) ? \ArrayHelper\helper::unset($_SESSION['login'], ['password']) : [];
236
  }
237
238
  /**
239
   * Get current google user data.
240
   *
241
   * @return void
242
   */
243
  public function userdata()
244
  {
245
    return isset($_SESSION['google']['login']) ? \ArrayHelper\helper::unset($_SESSION['google']['login'], ['password']) : [];
0 ignored issues
show
Bug Best Practice introduced by
The expression return IssetNode ? Array...('password')) : array() also could return the type array which is incompatible with the documented return type void.
Loading history...
246
  }
247
248
  /**
249
   * Fetch user information from google.
250
   *
251
   * @return array
252
   */
253
  public function fetch_user()
254
  {
255
    $service = new \Google_Service_Oauth2($this);
256
    $this->addScope(\Google_Service_Oauth2::USERINFO_EMAIL);
257
    $this->addScope(\Google_Service_Oauth2::USERINFO_PROFILE);
258
    $this->authenticate($_GET['code']);
0 ignored issues
show
Deprecated Code introduced by
The function Google\Client::authenticate() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

258
    /** @scrutinizer ignore-deprecated */ $this->authenticate($_GET['code']);
Loading history...
259
260
    return (array) $service->userinfo->get();
261
  }
262
}
263