Completed
Push — develop ( f2bd12...f57c6e )
by Seth
06:57
created

UserAPIToken::getToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 3
b 0
f 0
nc 2
nop 0
dl 0
loc 6
rs 9.4285
1
<?php
2
	
3
/**
4
 * Represents a user who either has or is in the process of acquiring an API
5
 * access token via OAuth
6
 *
7
 * @auther Seth Battis <[email protected]>
8
 **/
9
class UserAPIToken {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
10
11
	const USER_TOKENS_TABLE = 'user_tokens';
12
	
13
	/**
14
	 * @var string $consumerKey The unique ID of the tool consumer from whence the user is making requests to the LTI
15
	 **/	
16
	private $consumerKey;
17
	
18
	/**
19
	 * @var string $id The unique ID (within the context of a particular Tool Consumer) of a particular user
20
	 **/
21
	private $id;
22
	
23
	/**
24
	 * @var mysqli $sql A MySQL connection
25
	 **/
26
	private $sql;
27
	
28
	/**
29
	 * @var string|null $token This user's API access token (if acquired) or NULL if not yet acquired
30
	 **/
31
	private $token = null;
32
	
33
	/**
34
	 * @var string|null $apiUrl The URL of the API for which this user's token is valid, NULL if no token
35
	 **/
36
	private $apiUrl = null;
37
38
	/**
39
	 * Create a new UserAPIToken to either register a new user in the
40
	 * USER_TOKENS_TABLE or	look up an existing user.
41
	 *
42
	 * @param string $consumerKey The unique ID of the Tool Consumer from whence the user is making requests to the LTI
43
	 * @param string $userId The unique ID of the user within that Tool Consumer
44
	 * @param mysqli $mysqli An active MySQL database connection to update USER_TOKEN_TABLE
45
	 *
46
	 * @throws UserAPIToken_Exception CONSUMER_KEY_REQUIRED If no consumer key is provided
47
	 * @throws UserAPIToken_Exception USER_ID_REQUIRED If no user ID is provided
48
	 * @throws UserAPIToken_Exception MYSQLI_REQUIRED If no MySQL database connection is provided
49
	 * @throws UserAPIToken_Excpetion MYSQLI_ERROR If the user cannot be found or inserted in USER_TOKEN_TABLE
50
	 **/
51
	public function __construct($consumerKey, $userId, $mysqli) {
52
		
53
		if (empty((string) $consumerKey)) {
54
			throw new UserAPIToken_Exception(
55
				'A consumer key is required',
56
				UserAPIToken_Exception::CONSUMER_KEY_REQUIRED
57
			);
58
		}
59
		
60
		if (empty((string) $userId)) {
61
			throw new UserAPIToken_Exception(
62
				'A user ID is required',
63
				UserAPIToken_Exception::USER_ID_REQUIRED
64
			);
65
		}
66
		
67
		if (!($mysqli instanceof mysqli)) {
68
			throw new UserAPIToken_Exception(
69
				'A valid mysqli object is required',
70
				UserAPIToken_Exception::MYSQLI_REQUIRED
71
			);
72
		}
73
		
74
		$this->sql = $mysqli;
75
		$this->consumerKey = $this->sql->real_escape_string($consumerKey);
76
		$this->id = $this->sql->real_escape_string($userId);
77
				
78
		$result = $this->sql->query("SELECT * FROM `" . self::USER_TOKENS_TABLE . "` WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'");
79
		$row = $result->fetch_assoc();
80
		if ($row) {
81
			$this->token = $row['token'];
82
			$this->apiUrl = $row['api_url'];
83
		} else {
84
			if (!$this->sql->query("INSERT INTO `" . self::USER_TOKENS_TABLE . "` (`consumer_key`, `id`) VALUES ('{$this->consumerKey}', '{$this->id}')")) {
85
				throw new UserAPIToken_Exception(
86
					"Error inserting a new user: {$this->sql->error}",
87
					UserAPIToken_Exception::MYSQLI_ERROR
88
				);
89
			}
90
		}
91
	}
92
	
93
	/**
94
	 * @return string|boolean The API access token for this user, or FALSE if no token has been acquired
95
	 **/
96
	public function getToken() {
97
		if ($this->token) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->token of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
98
			return $this->token;
99
		}
100
		return false;
101
	}
102
	
103
	/**
104
	 * Stores a new API Token into USER_TOKEN_TABLE for this user
105
	 *
106
	 * @param string $token A new API access token for this user
107
	 *
108
	 * @return boolean Returns TRUE if the token is successfully stored in USER_TOKEN_TABLE, FALSE otherwise
109
	 *
110
	 * @throws UserAPIToken_Exception TOKEN_REQUIRED If no token is provided
111
	 **/
112 View Code Duplication
	public function setToken($token) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
113
		if (empty($token)) {
114
			throw new UserAPIToken_Exception(
115
				'A token is required',
116
				UserAPIToken_Exception::TOKEN_REQUIRED
117
			);
118
		}
119
		if($this->consumerKey && $this->id && $this->sql) {
120
			$_token = $this->sql->real_escape_string($token);
121
			if (!$this->sql->query("UPDATE `" . self::USER_TOKENS_TABLE . "` set `token` = '$_token' WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'")) {
122
				throw new UserAPIToken_Exception(
123
					"Error updating token: {$this->sql->error}",
124
					UserAPIToken_Exception::MYSQLI_ERROR
125
				);
126
			}
127
			$this->token = $token;
128
			
129
			return true;
130
		}
131
		
132
		return false;
133
	}
134
	
135
	/**
136
	 * @return string|boolean The URL of the API for which the user's API token is valid, or FALSE if no token has been acquired
137
	 **/
138
	function getAPIUrl() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
139
		if ($this->apiUrl) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->apiUrl of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
140
			return $this->apiUrl;
141
		}
142
		return false;
143
	}
144
	
145
	/**
146
	 * Stores a new URL for the API URL for which the user's API access token is valid in USER_TOKEN_TABLE
147
	 *
148
	 * @param string $apiUrl The URL of the API
149
	 *
150
	 * @return boolean TRUE if the URL of the API is stored in USER_TOKEN_TABLE, FALSE otherwise
151
	 *
152
	 * @throws UserAPITokenException API_URL_REQUIRED If no URL is provided
153
	 **/
154 View Code Duplication
	public function setAPIUrl($apiUrl) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
155
		if (empty($apiUrl)) {
156
			throw new UserAPIToken_Exception(
157
				'API URL is required',
158
				UserAPIToken_Exception::API_URL_REQUIRED
159
			);
160
		}
161
		
162
		if ($this->consumerKey && $this->id && $this->sql) {
163
			$_apiUrl = $this->sql->real_escape_string($apiUrl);
164
			if (!$this->sql->query("UPDATE `" . self::USER_TOKENS_TABLE . "` set `api_url` = '$_apiUrl' WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'")) {
165
				throw new UserAPIToken_Exception(
166
					"Error updating API URL for user token: {$this->sql->error}",
167
					UserAPIToken_Exception::MYSQLI_ERROR
168
				);
169
			}
170
			$this->apiUrl = $apiUrl;
171
			return true;
172
		}
173
		return false;
174
	}
175
}
176
177
/**
178
 * Exceptions thrown by the UserAPIToken
179
 *
180
 * @author Seth Battis <[email protected]>
181
 **/
182
class UserAPIToken_Exception extends CanvasAPIviaLTI_Exception {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
183
	const CONSUMER_KEY_REQUIRED = 1;
184
	const USER_ID_REQUIRED = 2;
185
	const MYSQLI_REQUIRED = 3;
186
	const MYSQLI_ERROR = 4;
187
	const TOKEN_REQUIRED = 5;
188
	const API_URL_REQUIRED = 6;
189
}
190
191
?>
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...