Completed
Push — master ( 18149d...ca977e )
by Oleg
02:39
created
lib/WebMarketingROI/OptimizelyPHP/OptimizelyApiClient.php 1 patch
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -50,13 +50,13 @@  discard block
 block discarded – undo
50 50
      * @param array $authCredentials Auth credentials.
51 51
      * @param string $apiVersion Optional. Currently supported 'v2' only.     
52 52
      */
53
-    public function __construct($authCredentials, $apiVersion='v2')
53
+    public function __construct($authCredentials, $apiVersion = 'v2')
54 54
     {
55 55
         if (!is_array($authCredentials)) {
56 56
             throw new Exception('Auth credentials must be an array');            
57 57
         }
58 58
         
59
-        if ($apiVersion!='v2') {
59
+        if ($apiVersion != 'v2') {
60 60
             throw new Exception('Invalid API version passed');
61 61
         }
62 62
         
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
      */
86 86
     public function setApiVersion($apiVersion)
87 87
     {
88
-        if ($apiVersion!='v2') {
88
+        if ($apiVersion != 'v2') {
89 89
             throw new Exception('Invalid API version passed');
90 90
         }
91 91
         
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
      */
108 108
     public function setAuthCredentials($authCredentials)
109 109
     {
110
-        if (!is_array($authCredentials) || count($authCredentials)==0) {
110
+        if (!is_array($authCredentials) || count($authCredentials) == 0) {
111 111
             throw new Exception('Auth credentials must be an non-empty array');            
112 112
         }
113 113
         
@@ -166,16 +166,16 @@  discard block
 block discarded – undo
166 166
      * @return array Optimizely response in form of array.
167 167
      * @throws Exception
168 168
      */
169
-    public function sendApiRequest($url, $queryParams = array(), $method='GET', 
169
+    public function sendApiRequest($url, $queryParams = array(), $method = 'GET', 
170 170
             $postData = array())
171 171
     {
172 172
         // If access token has expired, try to get another one with refresh token.
173
-        if ($this->isAccessTokenExpired() && $this->getRefreshToken()!=null) {
173
+        if ($this->isAccessTokenExpired() && $this->getRefreshToken() != null) {
174 174
             $this->getAccessTokenByRefreshToken();
175 175
         }
176 176
         
177 177
         // Produce absolute URL
178
-        $url = 'https://api.optimizely.com/' . $this->apiVersion . $url;
178
+        $url = 'https://api.optimizely.com/'.$this->apiVersion.$url;
179 179
         
180 180
         $result = $this->sendHttpRequest($url, $queryParams, $method, $postData);
181 181
         
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
      * @return array Optimizely response in form of array.
192 192
      * @throws Exception
193 193
      */
194
-    private function sendHttpRequest($url, $queryParams = array(), $method='GET', 
194
+    private function sendHttpRequest($url, $queryParams = array(), $method = 'GET', 
195 195
             $postData = array())
196 196
     {
197 197
         // Reset diagnostics info.
@@ -199,36 +199,36 @@  discard block
 block discarded – undo
199 199
         
200 200
         // Check if CURL is initialized (it should have been initialized in 
201 201
         // constructor).
202
-        if ($this->curlHandle==false) {
202
+        if ($this->curlHandle == false) {
203 203
             throw new Exception('CURL is not initialized', 
204 204
                     Exception::CODE_CURL_ERROR);
205 205
         }
206 206
         
207
-        if ($method!='GET' && $method!='POST' && $method!='PUT' && 
208
-            $method!='PATCH' && $method!='DELETE') {
209
-            throw new Exception('Invalid HTTP method passed: ' . $method);
207
+        if ($method != 'GET' && $method != 'POST' && $method != 'PUT' && 
208
+            $method != 'PATCH' && $method != 'DELETE') {
209
+            throw new Exception('Invalid HTTP method passed: '.$method);
210 210
         }
211 211
         
212 212
         if (!isset($this->authCredentials['access_token'])) {
213
-            throw new Exception('OAuth access token is not set. You should pass ' . 
213
+            throw new Exception('OAuth access token is not set. You should pass '. 
214 214
                     'it to the class constructor when initializing the Optimizely client.');
215 215
         }
216 216
                 
217 217
         // Append query parameters to URL.
218
-        if (count($queryParams)!=0) {            
218
+        if (count($queryParams) != 0) {            
219 219
             $query = http_build_query($queryParams);
220
-            $url .= '?' . $query;
220
+            $url .= '?'.$query;
221 221
         }
222 222
         
223 223
         $headers = array(
224
-            "Authorization: Bearer " . $this->authCredentials['access_token'],
224
+            "Authorization: Bearer ".$this->authCredentials['access_token'],
225 225
             "Content-Type: application/json"
226 226
             );
227 227
         $content = '';
228
-        if (count($postData)!=0) {
228
+        if (count($postData) != 0) {
229 229
             $content = json_encode($postData, JSON_NUMERIC_CHECK);            
230 230
         }
231
-        $headers[] = "Content-length:" . strlen($content);            
231
+        $headers[] = "Content-length:".strlen($content);            
232 232
         
233 233
         // Reset CURL state.
234 234
         if (!function_exists('curl_reset')) {
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
         // Set HTTP options.
242 242
         curl_setopt($this->curlHandle, CURLOPT_URL, $url);
243 243
         curl_setopt($this->curlHandle, CURLOPT_CUSTOMREQUEST, $method);        
244
-        if (count($postData)!=0) {
244
+        if (count($postData) != 0) {
245 245
             curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, $content);            
246 246
         }
247 247
         curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
         if ($result === false) {
261 261
             $code = curl_errno($this->curlHandle);
262 262
             $error = curl_error($this->curlHandle);
263
-            throw new Exception("Failed to send HTTP request $method '$url', " . 
263
+            throw new Exception("Failed to send HTTP request $method '$url', ". 
264 264
                     "the error code was $code, error message was: '$error'", 
265 265
                     Exception::CODE_CURL_ERROR, $code, $error);
266 266
         }        
@@ -274,12 +274,12 @@  discard block
 block discarded – undo
274 274
         $headers = explode("\n", $headers);
275 275
         $parsedHeaders = array();
276 276
         foreach ($headers as $i=>$header) {
277
-            if ($i==0)
277
+            if ($i == 0)
278 278
                 continue; // Skip first line (http code).
279 279
             $pos = strpos($header, ':');
280
-            if ($pos!=false) {
280
+            if ($pos != false) {
281 281
                 $headerName = trim(strtolower(substr($header, 0, $pos)));
282
-                $headerValue = trim(substr($header, $pos+1));
282
+                $headerValue = trim(substr($header, $pos + 1));
283 283
                 $parsedHeaders[$headerName] = $headerValue;
284 284
             }
285 285
         }
@@ -311,20 +311,20 @@  discard block
 block discarded – undo
311 311
         
312 312
         // JSON-decode payload.
313 313
         $decodedPayload = json_decode($body, true);
314
-        if ($decodedPayload===false) {
315
-            throw new Exception('Could not JSON-decode the Optimizely API response. Request was ' . 
316
-                    $method . ' "' . $url . '". The response was: "' . $body . '"',
314
+        if ($decodedPayload === false) {
315
+            throw new Exception('Could not JSON-decode the Optimizely API response. Request was '. 
316
+                    $method.' "'.$url.'". The response was: "'.$body.'"',
317 317
                     Exception::CODE_API_ERROR, array('http_code'=>$httpCode));
318 318
         }
319 319
         
320 320
         // Check HTTP response code.
321
-        if ($httpCode<200 || $httpCode>299) {
321
+        if ($httpCode < 200 || $httpCode > 299) {
322 322
             
323 323
             if (!isset($decodedPayload['message']) || 
324 324
                 !isset($decodedPayload['code']) ||
325 325
                 !isset($decodedPayload['uuid'])) {
326
-                throw new Exception('Optimizely API responded with error code ' . $httpCode . 
327
-                    '. Request was ' . $method . ' "' . $url . '". Response was "' . $body . '"',
326
+                throw new Exception('Optimizely API responded with error code '.$httpCode. 
327
+                    '. Request was '.$method.' "'.$url.'". Response was "'.$body.'"',
328 328
                     Exception::CODE_API_ERROR, array(
329 329
                         'http_code' => $httpCode,
330 330
                         'rate_limit' => $rateLimit,
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
             $matched = preg_match_all('/<(.+)>;\s+rel=(\w+)(,|\z)/U', 
359 359
                     $parsedHeaders['link'], $matches, PREG_SET_ORDER);
360 360
             if (!$matched) {
361
-                throw new Exception('Error parsing LINK header: ' . 
361
+                throw new Exception('Error parsing LINK header: '. 
362 362
                         $parsedHeaders['link'], Exception::CODE_API_ERROR, $httpCode);
363 363
             }
364 364
             
@@ -368,22 +368,22 @@  discard block
 block discarded – undo
368 368
                 $rel = $match[2];
369 369
                 
370 370
                 $matched = preg_match('/page=(\d+)/U', $url, $pageMatches);
371
-                if (!$matched || count($pageMatches)!=2) {
372
-                    throw new Exception('Error extracting page argument while parsing LINK header: ' . 
371
+                if (!$matched || count($pageMatches) != 2) {
372
+                    throw new Exception('Error extracting page argument while parsing LINK header: '. 
373 373
                             $parsedHeaders['link'], Exception::CODE_API_ERROR, 
374 374
                             array('http_code'=>$httpCode));
375 375
                 }
376 376
                 
377 377
                 $pageNumber = $pageMatches[1];
378 378
                 
379
-                if ($rel=='prev') {
379
+                if ($rel == 'prev') {
380 380
                     $result->setPrevPage($pageNumber);
381
-                } else if ($rel=='next') {
381
+                } else if ($rel == 'next') {
382 382
                     $result->setNextPage($pageNumber);
383
-                } else if ($rel=='last') {
383
+                } else if ($rel == 'last') {
384 384
                     $result->setLastPage($pageNumber);
385 385
                 } else {
386
-                    throw new Exception('Unexpected rel argument while parsing LINK header: ' . 
386
+                    throw new Exception('Unexpected rel argument while parsing LINK header: '. 
387 387
                             $parsedHeaders['link'], Exception::CODE_API_ERROR, 
388 388
                             array('http_code'=>$httpCode));
389 389
                 }
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
      */
402 402
     private function isAccessTokenExpired() 
403 403
     {
404
-        if(!isset($this->authCredentials['access_token'])) {
404
+        if (!isset($this->authCredentials['access_token'])) {
405 405
             return true; // We do not have access token.
406 406
         }
407 407
         
@@ -442,15 +442,15 @@  discard block
 block discarded – undo
442 442
         $clientSecret = $this->authCredentials['client_secret'];
443 443
         $refreshToken = $this->authCredentials['refresh_token'];
444 444
         
445
-        $url = "https://app.optimizely.com/oauth2/token?refresh_token=$refreshToken" . 
445
+        $url = "https://app.optimizely.com/oauth2/token?refresh_token=$refreshToken". 
446 446
                 "&client_id=$clientId&client_secret=$clientSecret&grant_type=refresh_token";
447 447
         
448 448
         $response = $this->sendHttpRequest($url, array(), 'POST');
449 449
         $decodedJsonData = $response->getDecodedJsonData();
450 450
         
451 451
         if (!isset($decodedJsonData['access_token'])) {
452
-            throw new Exception('Not found access token in response. Request URL was "' . 
453
-                    $url. '". Response was "' . print_r(json_encode($decodedJsonData), true). '"',
452
+            throw new Exception('Not found access token in response. Request URL was "'. 
453
+                    $url.'". Response was "'.print_r(json_encode($decodedJsonData), true).'"',
454 454
                     Exception::CODE_API_ERROR, $response->getHttpCode());
455 455
         }
456 456
         
Please login to merge, or discard this patch.