Completed
Push — master ( f26ca7...1a40fa )
by Francis
01:19
created

GMail::process_response()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 2
1
<?php
2
declare(strict_types=1);
3
defined('BASEPATH') OR exit('No direct script access allowed');
4
5
require_once('GMailScopes.php');
6
require_once('GMailUtil.php');
7
8
class GMail {
9
10
  const AUTH_URL  = 'https://accounts.google.com/o/oauth2/auth';
11
  const TOKEN_URL = 'https://accounts.google.com/o/oauth2/token';
12
  const API       = 'https://www.googleapis.com/gmail/v1/';
13
  const HTTP_CODE = 'http_code';
14
  private $clientId;
15
  private $clientSecret;
16
  private $redirectUri = 'urn:ietf:wg:oauth:2.0:oob';
17
  private $token;
18
19
  function __construct($params=null) {
20
    get_instance()->load->splint('francis94c/ci-gmail', '%curl');
0 ignored issues
show
Bug introduced by
The function get_instance was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

20
    /** @scrutinizer ignore-call */ 
21
    get_instance()->load->splint('francis94c/ci-gmail', '%curl');
Loading history...
21
    if ($params != null) $this->init($params);
22
  }
23
24
  /**
25
   * [init Initialize library with cofigs. Can be called multiple times to set
26
   *       config items]
27
   * @param array $config Associative Config Array.
28
   */
29
  public function init(array $config):void {
30
    $this->clientId = $config['client_id'] ?? $this->clientId;
31
    $this->clientSecret = $config['client_secret'] ?? $this->clientSecret;
32
    $this->redirectUri = $config['redirect_uri'] ?? $this->redirectUri;
33
  }
34
  /**
35
   * [setAuthorizationToken description]
36
   * @param string $token [description]
37
   */
38
  public function setAuthorizationToken(string $token):void {
39
    $this->token = $token;
40
  }
41
  /**
42
   * [getClientId Get Client ID.]
43
   * @return null|string Client ID.
44
   */
45
  public function getClientId():?string {
46
    return $this->clientId;
47
  }
48
  /**
49
   * [getAuthorizeUrl Gets/composes the authorize url to direct users to so they
50
   *                  can give your application access to their GMail accounts
51
   *                  based on the given scopes.]
52
   * @param  string $scope        Access Scope.
53
   * @param  string $redirectUri  URL to redirect to after access is granted.
54
   * @param  string $responseType Response type. 'code' by default.
55
   * @param  bool   $prompt       Add the prompt=consent query to the URL.
56
   * @return string               Authorize URL
57
   */
58
  public function getAuthorizeUrl(string $scope, string $redirectUri=null, string $responseType='code', string $accessType='offline', bool $prompt=false):string {
59
    $redirectUri = $redirectUri ?? $this->redirectUri;
60
    if ($scope == null) throw new Exception("GMail scope cannot be null");
61
    $params = [
62
      'client_id'     => $this->clientId,
63
      'redirect_uri'  => $redirectUri,
64
      'scope'         => $scope,
65
      'response_type' => $responseType,
66
      'access_type'   => $accessType
67
    ];
68
    if ($prompt) $params['prompt'] = 'consent';
69
    return self::AUTH_URL . build_url_query($params, false);
70
  }
71
  /**
72
   * [getToken description]
73
   * @param  string $code [description]
74
   * @return [type]       [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
75
   */
76
  public function getToken(string $code, string $redirectUri=null):?array {
77
    $redirectUri = $redirectUri ?? $this->redirectUri;
78
    list($code, $response) = (new GMailCURL(GMailCURL::POST))(
79
      self::TOKEN_URL . build_url_query([
80
        'code'          => $code,
81
        'client_id'     => $this->clientId,
82
        'client_secret' => $this->clientSecret,
83
        'redirect_uri'  => $redirectUri,
84
        'grant_type'    => 'authorization_code'
85
      ], false)
86
    );
87
    if ($response !== false)$this->process_response($code, $response);
88
    return null;
89
  }
90
  /**
91
   * [getProfile description]
92
   * @param  string $user [description]
93
   * @return [type]       [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
94
   */
95
  public function getProfile(string $user='me'):?array {
96
    list($code, $response) = (new GMailCURL(GMailCURL::GET))(
97
      self::API . "users/$user/profile",
98
      ["Authorization: Bearer $this->token"]
99
    );
100
    if ($response !== false) return $this->process_response($code, $response);
101
    return null;
102
  }
103
  /**
104
   * [process_response description]
105
   * @param  int    $code   [description]
106
   * @param  string $response [description]
107
   * @return [type]         [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
108
   */
109
  private function process_response(int $code, string $response) {
110
    $response = json_decode($response, true);
111
    $response[self::HTTP_CODE] = $code;
112
    return $response;
113
  }
114
}
115
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
116