Passed
Push — master ( 1a40fa...3e41fe )
by Francis
01:04
created

GMail::watch()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 21
rs 9.4888
cc 5
nc 8
nop 4
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/users/';
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 . "$user/profile",
98
      ["Authorization: Bearer $this->token"]
99
    );
100
    if ($response !== false) return $this->process_response($code, $response);
101
    return null;
102
  }
103
  /**
104
   * [watch Causes push notifications to be sent on events which occur in the
105
   * user's mailbox. Requires Google Cloud PubSub.
106
   * see https://developers.google.com/gmail/api/v1/reference/users/watch]
107
   * @param  string $topic             Topic to push events to.
108
   * @param  string $userId            The ID/Email address of the user whose
109
   *                                   mailbox event, are being listened to.
110
   * @param  mixed  $labelIds          Narrow down labels in the mailbox, whose
111
   *      [string|int]                 events are to be listened to.
112
   * @param  string $labelFilterAction [description]
113
   * @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...
114
   */
115
  public function watch(string $topic, string $userId='me', mixed $labelIds=null, string $labelFilterAction='include'):?array {
0 ignored issues
show
Bug introduced by
The type mixed 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...
116
    $body = [
117
      'topicName'         => $topic,
118
      'labelFilterAction' => $labelFilterAction
119
    ];
120
121
    if ($labelIds != null) {
122
      if (is_scalar($labelIds)) {
0 ignored issues
show
introduced by
The condition is_scalar($labelIds) is always false.
Loading history...
123
        $body['labelIds'] = [$labelIds];
124
      } elseif (is_array($labelIds)) {
0 ignored issues
show
introduced by
The condition is_array($labelIds) is always false.
Loading history...
125
        $body['labelIds'] = $labelIds;
126
      }
127
    }
128
129
    list($code, $response) = (new GMailCURL(GMailCURL::POST))(
130
      self::API . "$userId/watch",
131
      ["Authorization: Bearer $this->token"],
132
      $body
133
    );
134
    if ($response !== false)$this->process_response($code, $response);
135
    return null;
136
  }
137
  /**
138
   * [process_response description]
139
   * @param  int    $code   [description]
140
   * @param  string $response [description]
141
   * @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...
142
   */
143
  private function process_response(int $code, string $response) {
144
    $response = json_decode($response, true);
145
    $response[self::HTTP_CODE] = $code;
146
    return $response;
147
  }
148
}
149
?>
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...
150