Passed
Push — master ( bd5724...8a312b )
by
unknown
01:47
created
src/Storage/Session.php 2 patches
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -14,117 +14,117 @@
 block discarded – undo
14 14
  */
15 15
 class Session implements StorageInterface
16 16
 {
17
-    /**
18
-     * Namespace
19
-     *
20
-     * @var string
21
-     */
22
-    protected $storeNamespace = 'HYBRIDAUTH::STORAGE';
23
-
24
-    /**
25
-     * Key prefix
26
-     *
27
-     * @var string
28
-     */
29
-    protected $keyPrefix = '';
30
-
31
-    /**
32
-     * Initiate a new session
33
-     *
34
-     * @throws RuntimeException
35
-     */
36
-    public function __construct()
37
-    {
38
-        if (session_id()) {
39
-            return;
40
-        }
41
-
42
-        if (headers_sent()) {
43
-            // phpcs:ignore
44
-            throw new RuntimeException('HTTP headers already sent to browser and Hybridauth won\'t be able to start/resume PHP session. To resolve this, session_start() must be called before outputing any data.');
45
-        }
46
-
47
-        if (!session_start()) {
48
-            throw new RuntimeException('PHP session failed to start.');
49
-        }
50
-    }
51
-
52
-    /**
53
-     * {@inheritdoc}
54
-     */
55
-    public function get($key)
56
-    {
57
-        $key = $this->keyPrefix . strtolower($key);
58
-
59
-        if (isset($_SESSION[$this->storeNamespace], $_SESSION[$this->storeNamespace][$key])) {
60
-            $value = $_SESSION[$this->storeNamespace][$key];
61
-
62
-            if (is_array($value) && array_key_exists('lateObject', $value)) {
63
-                $value = unserialize($value['lateObject']);
64
-            }
65
-
66
-            return $value;
67
-        }
68
-
69
-        return null;
70
-    }
71
-
72
-    /**
73
-     * {@inheritdoc}
74
-     */
75
-    public function set($key, $value)
76
-    {
77
-        $key = $this->keyPrefix . strtolower($key);
78
-
79
-        if (is_object($value)) {
80
-            // We encapsulate as our classes may be defined after session is initialized.
81
-            $value = ['lateObject' => serialize($value)];
82
-        }
83
-
84
-        $_SESSION[$this->storeNamespace][$key] = $value;
85
-    }
86
-
87
-    /**
88
-     * {@inheritdoc}
89
-     */
90
-    public function clear()
91
-    {
92
-        $_SESSION[$this->storeNamespace] = [];
93
-    }
94
-
95
-    /**
96
-     * {@inheritdoc}
97
-     */
98
-    public function delete($key)
99
-    {
100
-        $key = $this->keyPrefix . strtolower($key);
101
-
102
-        if (isset($_SESSION[$this->storeNamespace], $_SESSION[$this->storeNamespace][$key])) {
103
-            $tmp = $_SESSION[$this->storeNamespace];
104
-
105
-            unset($tmp[$key]);
106
-
107
-            $_SESSION[$this->storeNamespace] = $tmp;
108
-        }
109
-    }
110
-
111
-    /**
112
-     * {@inheritdoc}
113
-     */
114
-    public function deleteMatch($key)
115
-    {
116
-        $key = $this->keyPrefix . strtolower($key);
117
-
118
-        if (isset($_SESSION[$this->storeNamespace]) && count($_SESSION[$this->storeNamespace])) {
119
-            $tmp = $_SESSION[$this->storeNamespace];
120
-
121
-            foreach ($tmp as $k => $v) {
122
-                if (strstr($k, $key)) {
123
-                    unset($tmp[$k]);
124
-                }
125
-            }
126
-
127
-            $_SESSION[$this->storeNamespace] = $tmp;
128
-        }
129
-    }
17
+	/**
18
+	 * Namespace
19
+	 *
20
+	 * @var string
21
+	 */
22
+	protected $storeNamespace = 'HYBRIDAUTH::STORAGE';
23
+
24
+	/**
25
+	 * Key prefix
26
+	 *
27
+	 * @var string
28
+	 */
29
+	protected $keyPrefix = '';
30
+
31
+	/**
32
+	 * Initiate a new session
33
+	 *
34
+	 * @throws RuntimeException
35
+	 */
36
+	public function __construct()
37
+	{
38
+		if (session_id()) {
39
+			return;
40
+		}
41
+
42
+		if (headers_sent()) {
43
+			// phpcs:ignore
44
+			throw new RuntimeException('HTTP headers already sent to browser and Hybridauth won\'t be able to start/resume PHP session. To resolve this, session_start() must be called before outputing any data.');
45
+		}
46
+
47
+		if (!session_start()) {
48
+			throw new RuntimeException('PHP session failed to start.');
49
+		}
50
+	}
51
+
52
+	/**
53
+	 * {@inheritdoc}
54
+	 */
55
+	public function get($key)
56
+	{
57
+		$key = $this->keyPrefix . strtolower($key);
58
+
59
+		if (isset($_SESSION[$this->storeNamespace], $_SESSION[$this->storeNamespace][$key])) {
60
+			$value = $_SESSION[$this->storeNamespace][$key];
61
+
62
+			if (is_array($value) && array_key_exists('lateObject', $value)) {
63
+				$value = unserialize($value['lateObject']);
64
+			}
65
+
66
+			return $value;
67
+		}
68
+
69
+		return null;
70
+	}
71
+
72
+	/**
73
+	 * {@inheritdoc}
74
+	 */
75
+	public function set($key, $value)
76
+	{
77
+		$key = $this->keyPrefix . strtolower($key);
78
+
79
+		if (is_object($value)) {
80
+			// We encapsulate as our classes may be defined after session is initialized.
81
+			$value = ['lateObject' => serialize($value)];
82
+		}
83
+
84
+		$_SESSION[$this->storeNamespace][$key] = $value;
85
+	}
86
+
87
+	/**
88
+	 * {@inheritdoc}
89
+	 */
90
+	public function clear()
91
+	{
92
+		$_SESSION[$this->storeNamespace] = [];
93
+	}
94
+
95
+	/**
96
+	 * {@inheritdoc}
97
+	 */
98
+	public function delete($key)
99
+	{
100
+		$key = $this->keyPrefix . strtolower($key);
101
+
102
+		if (isset($_SESSION[$this->storeNamespace], $_SESSION[$this->storeNamespace][$key])) {
103
+			$tmp = $_SESSION[$this->storeNamespace];
104
+
105
+			unset($tmp[$key]);
106
+
107
+			$_SESSION[$this->storeNamespace] = $tmp;
108
+		}
109
+	}
110
+
111
+	/**
112
+	 * {@inheritdoc}
113
+	 */
114
+	public function deleteMatch($key)
115
+	{
116
+		$key = $this->keyPrefix . strtolower($key);
117
+
118
+		if (isset($_SESSION[$this->storeNamespace]) && count($_SESSION[$this->storeNamespace])) {
119
+			$tmp = $_SESSION[$this->storeNamespace];
120
+
121
+			foreach ($tmp as $k => $v) {
122
+				if (strstr($k, $key)) {
123
+					unset($tmp[$k]);
124
+				}
125
+			}
126
+
127
+			$_SESSION[$this->storeNamespace] = $tmp;
128
+		}
129
+	}
130 130
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
             throw new RuntimeException('HTTP headers already sent to browser and Hybridauth won\'t be able to start/resume PHP session. To resolve this, session_start() must be called before outputing any data.');
45 45
         }
46 46
 
47
-        if (!session_start()) {
47
+        if ( ! session_start()) {
48 48
             throw new RuntimeException('PHP session failed to start.');
49 49
         }
50 50
     }
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
      */
55 55
     public function get($key)
56 56
     {
57
-        $key = $this->keyPrefix . strtolower($key);
57
+        $key = $this->keyPrefix.strtolower($key);
58 58
 
59 59
         if (isset($_SESSION[$this->storeNamespace], $_SESSION[$this->storeNamespace][$key])) {
60 60
             $value = $_SESSION[$this->storeNamespace][$key];
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
      */
75 75
     public function set($key, $value)
76 76
     {
77
-        $key = $this->keyPrefix . strtolower($key);
77
+        $key = $this->keyPrefix.strtolower($key);
78 78
 
79 79
         if (is_object($value)) {
80 80
             // We encapsulate as our classes may be defined after session is initialized.
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
      */
98 98
     public function delete($key)
99 99
     {
100
-        $key = $this->keyPrefix . strtolower($key);
100
+        $key = $this->keyPrefix.strtolower($key);
101 101
 
102 102
         if (isset($_SESSION[$this->storeNamespace], $_SESSION[$this->storeNamespace][$key])) {
103 103
             $tmp = $_SESSION[$this->storeNamespace];
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
      */
114 114
     public function deleteMatch($key)
115 115
     {
116
-        $key = $this->keyPrefix . strtolower($key);
116
+        $key = $this->keyPrefix.strtolower($key);
117 117
 
118 118
         if (isset($_SESSION[$this->storeNamespace]) && count($_SESSION[$this->storeNamespace])) {
119 119
             $tmp = $_SESSION[$this->storeNamespace];
Please login to merge, or discard this patch.
src/Provider/Medium.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -17,72 +17,72 @@
 block discarded – undo
17 17
  */
18 18
 class Medium extends OAuth2
19 19
 {
20
-    /**
21
-     * {@inheritdoc}
22
-     */
23
-    protected $scope = 'basicProfile';
20
+	/**
21
+	 * {@inheritdoc}
22
+	 */
23
+	protected $scope = 'basicProfile';
24 24
 
25
-    /**
26
-     * {@inheritdoc}
27
-     */
28
-    protected $apiBaseUrl = 'https://api.medium.com/v1/';
25
+	/**
26
+	 * {@inheritdoc}
27
+	 */
28
+	protected $apiBaseUrl = 'https://api.medium.com/v1/';
29 29
 
30
-    /**
31
-     * {@inheritdoc}
32
-     */
33
-    protected $authorizeUrl = 'https://medium.com/m/oauth/authorize';
30
+	/**
31
+	 * {@inheritdoc}
32
+	 */
33
+	protected $authorizeUrl = 'https://medium.com/m/oauth/authorize';
34 34
 
35
-    /**
36
-     * {@inheritdoc}
37
-     */
38
-    protected $accessTokenUrl = 'https://api.medium.com/v1/tokens';
35
+	/**
36
+	 * {@inheritdoc}
37
+	 */
38
+	protected $accessTokenUrl = 'https://api.medium.com/v1/tokens';
39 39
 
40
-    /**
41
-     * {@inheritdoc}
42
-     */
43
-    protected $apiDocumentation = 'https://github.com/Medium/medium-api-docs';
40
+	/**
41
+	 * {@inheritdoc}
42
+	 */
43
+	protected $apiDocumentation = 'https://github.com/Medium/medium-api-docs';
44 44
 
45
-    /**
46
-     * {@inheritdoc}
47
-     */
48
-    protected function initialize()
49
-    {
50
-        parent::initialize();
45
+	/**
46
+	 * {@inheritdoc}
47
+	 */
48
+	protected function initialize()
49
+	{
50
+		parent::initialize();
51 51
 
52
-        if ($this->isRefreshTokenAvailable()) {
53
-            $this->tokenRefreshParameters += [
54
-                'client_id' => $this->clientId,
55
-                'client_secret' => $this->clientSecret,
56
-            ];
57
-        }
58
-    }
52
+		if ($this->isRefreshTokenAvailable()) {
53
+			$this->tokenRefreshParameters += [
54
+				'client_id' => $this->clientId,
55
+				'client_secret' => $this->clientSecret,
56
+			];
57
+		}
58
+	}
59 59
 
60
-    /**
61
-     * {@inheritdoc}
62
-     *
63
-     * See: https://github.com/Medium/medium-api-docs#getting-the-authenticated-users-details
64
-     */
65
-    public function getUserProfile()
66
-    {
67
-        $response = $this->apiRequest('me');
60
+	/**
61
+	 * {@inheritdoc}
62
+	 *
63
+	 * See: https://github.com/Medium/medium-api-docs#getting-the-authenticated-users-details
64
+	 */
65
+	public function getUserProfile()
66
+	{
67
+		$response = $this->apiRequest('me');
68 68
 
69
-        $data = new Data\Collection($response);
69
+		$data = new Data\Collection($response);
70 70
 
71
-        $userProfile = new User\Profile();
72
-        $data = $data->filter('data');
71
+		$userProfile = new User\Profile();
72
+		$data = $data->filter('data');
73 73
 
74
-        $full_name = explode(' ', $data->get('name'));
75
-        if (count($full_name) < 2) {
76
-            $full_name[1] = '';
77
-        }
74
+		$full_name = explode(' ', $data->get('name'));
75
+		if (count($full_name) < 2) {
76
+			$full_name[1] = '';
77
+		}
78 78
 
79
-        $userProfile->identifier = $data->get('id');
80
-        $userProfile->displayName = $data->get('username');
81
-        $userProfile->profileURL = $data->get('imageUrl');
82
-        $userProfile->firstName = $full_name[0];
83
-        $userProfile->lastName = $full_name[1];
84
-        $userProfile->profileURL = $data->get('url');
79
+		$userProfile->identifier = $data->get('id');
80
+		$userProfile->displayName = $data->get('username');
81
+		$userProfile->profileURL = $data->get('imageUrl');
82
+		$userProfile->firstName = $full_name[0];
83
+		$userProfile->lastName = $full_name[1];
84
+		$userProfile->profileURL = $data->get('url');
85 85
 
86
-        return $userProfile;
87
-    }
86
+		return $userProfile;
87
+	}
88 88
 }
Please login to merge, or discard this patch.
src/Provider/Instagram.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
     {
63 63
         $collection = parent::validateAccessTokenExchange($response);
64 64
 
65
-        if (!$collection->exists('expires_in')) {
65
+        if ( ! $collection->exists('expires_in')) {
66 66
             // Instagram tokens always expire in an hour, but this is implicit not explicit
67 67
 
68 68
             $expires_in = 60 * 60;
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
      */
92 92
     public function maintainToken()
93 93
     {
94
-        if (!$this->isConnected()) {
94
+        if ( ! $this->isConnected()) {
95 95
             return;
96 96
         }
97 97
 
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
         $exchange_by_expiry_days = $this->config->get('exchange_by_expiry_days') ?: 45;
100 100
         if ($exchange_by_expiry_days !== null) {
101 101
             $projected_timestamp = time() + 60 * 60 * 24 * $exchange_by_expiry_days;
102
-            if (!$this->hasAccessTokenExpired() && $this->hasAccessTokenExpired($projected_timestamp)) {
102
+            if ( ! $this->hasAccessTokenExpired() && $this->hasAccessTokenExpired($projected_timestamp)) {
103 103
                 $this->exchangeAccessToken();
104 104
             }
105 105
         }
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
         ]);
145 145
 
146 146
         $data = new Collection($response);
147
-        if (!$data->exists('id')) {
147
+        if ( ! $data->exists('id')) {
148 148
             throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
149 149
         }
150 150
 
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
         $response = $this->apiRequest('me/media', 'GET', $params);
201 201
 
202 202
         $data = new Collection($response);
203
-        if (!$data->exists('data')) {
203
+        if ( ! $data->exists('data')) {
204 204
             throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
205 205
         }
206 206
 
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
         ]);
241 241
 
242 242
         $data = new Collection($response);
243
-        if (!$data->exists('id')) {
243
+        if ( ! $data->exists('id')) {
244 244
             throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
245 245
         }
246 246
 
Please login to merge, or discard this patch.
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -17,240 +17,240 @@
 block discarded – undo
17 17
  */
18 18
 class Instagram extends OAuth2
19 19
 {
20
-    /**
21
-     * {@inheritdoc}
22
-     */
23
-    protected $scope = 'user_profile,user_media';
24
-
25
-    /**
26
-     * {@inheritdoc}
27
-     */
28
-    protected $apiBaseUrl = 'https://graph.instagram.com';
29
-
30
-    /**
31
-     * {@inheritdoc}
32
-     */
33
-    protected $authorizeUrl = 'https://api.instagram.com/oauth/authorize';
34
-
35
-    /**
36
-     * {@inheritdoc}
37
-     */
38
-    protected $accessTokenUrl = 'https://api.instagram.com/oauth/access_token';
39
-
40
-    /**
41
-     * {@inheritdoc}
42
-     */
43
-    protected $apiDocumentation = 'https://developers.facebook.com/docs/instagram-basic-display-api';
44
-
45
-    /**
46
-     * {@inheritdoc}
47
-     */
48
-    protected function initialize()
49
-    {
50
-        parent::initialize();
51
-
52
-        // The Instagram API requires an access_token from authenticated users
53
-        // for each endpoint.
54
-        $accessToken = $this->getStoredData($this->accessTokenName);
55
-        $this->apiRequestParameters[$this->accessTokenName] = $accessToken;
56
-    }
57
-
58
-    /**
59
-     * {@inheritdoc}
60
-     */
61
-    protected function validateAccessTokenExchange($response)
62
-    {
63
-        $collection = parent::validateAccessTokenExchange($response);
64
-
65
-        if (!$collection->exists('expires_in')) {
66
-            // Instagram tokens always expire in an hour, but this is implicit not explicit
67
-
68
-            $expires_in = 60 * 60;
69
-
70
-            $expires_at = time() + $expires_in;
71
-
72
-            $this->storeData('expires_in', $expires_in);
73
-            $this->storeData('expires_at', $expires_at);
74
-        }
75
-
76
-        return $collection;
77
-    }
78
-
79
-    /**
80
-     * {@inheritdoc}
81
-     */
82
-    public function maintainToken()
83
-    {
84
-        if (!$this->isConnected()) {
85
-            return;
86
-        }
87
-
88
-        // Handle token exchange prior to the standard handler for an API request
89
-        $exchange_by_expiry_days = $this->config->get('exchange_by_expiry_days') ?: 45;
90
-        if ($exchange_by_expiry_days !== null) {
91
-            $projected_timestamp = time() + 60 * 60 * 24 * $exchange_by_expiry_days;
92
-            if (!$this->hasAccessTokenExpired() && $this->hasAccessTokenExpired($projected_timestamp)) {
93
-                $this->exchangeAccessToken();
94
-            }
95
-        }
96
-    }
97
-
98
-    /**
99
-     * Exchange the Access Token with one that expires further in the future.
100
-     *
101
-     * @return string Raw Provider API response
102
-     * @throws \Hybridauth\Exception\HttpClientFailureException
103
-     * @throws \Hybridauth\Exception\HttpRequestFailedException
104
-     * @throws InvalidAccessTokenException
105
-     */
106
-    public function exchangeAccessToken()
107
-    {
108
-        if ($this->getStoredData('expires_in') >= 5000000) {
109
-            /*
20
+	/**
21
+	 * {@inheritdoc}
22
+	 */
23
+	protected $scope = 'user_profile,user_media';
24
+
25
+	/**
26
+	 * {@inheritdoc}
27
+	 */
28
+	protected $apiBaseUrl = 'https://graph.instagram.com';
29
+
30
+	/**
31
+	 * {@inheritdoc}
32
+	 */
33
+	protected $authorizeUrl = 'https://api.instagram.com/oauth/authorize';
34
+
35
+	/**
36
+	 * {@inheritdoc}
37
+	 */
38
+	protected $accessTokenUrl = 'https://api.instagram.com/oauth/access_token';
39
+
40
+	/**
41
+	 * {@inheritdoc}
42
+	 */
43
+	protected $apiDocumentation = 'https://developers.facebook.com/docs/instagram-basic-display-api';
44
+
45
+	/**
46
+	 * {@inheritdoc}
47
+	 */
48
+	protected function initialize()
49
+	{
50
+		parent::initialize();
51
+
52
+		// The Instagram API requires an access_token from authenticated users
53
+		// for each endpoint.
54
+		$accessToken = $this->getStoredData($this->accessTokenName);
55
+		$this->apiRequestParameters[$this->accessTokenName] = $accessToken;
56
+	}
57
+
58
+	/**
59
+	 * {@inheritdoc}
60
+	 */
61
+	protected function validateAccessTokenExchange($response)
62
+	{
63
+		$collection = parent::validateAccessTokenExchange($response);
64
+
65
+		if (!$collection->exists('expires_in')) {
66
+			// Instagram tokens always expire in an hour, but this is implicit not explicit
67
+
68
+			$expires_in = 60 * 60;
69
+
70
+			$expires_at = time() + $expires_in;
71
+
72
+			$this->storeData('expires_in', $expires_in);
73
+			$this->storeData('expires_at', $expires_at);
74
+		}
75
+
76
+		return $collection;
77
+	}
78
+
79
+	/**
80
+	 * {@inheritdoc}
81
+	 */
82
+	public function maintainToken()
83
+	{
84
+		if (!$this->isConnected()) {
85
+			return;
86
+		}
87
+
88
+		// Handle token exchange prior to the standard handler for an API request
89
+		$exchange_by_expiry_days = $this->config->get('exchange_by_expiry_days') ?: 45;
90
+		if ($exchange_by_expiry_days !== null) {
91
+			$projected_timestamp = time() + 60 * 60 * 24 * $exchange_by_expiry_days;
92
+			if (!$this->hasAccessTokenExpired() && $this->hasAccessTokenExpired($projected_timestamp)) {
93
+				$this->exchangeAccessToken();
94
+			}
95
+		}
96
+	}
97
+
98
+	/**
99
+	 * Exchange the Access Token with one that expires further in the future.
100
+	 *
101
+	 * @return string Raw Provider API response
102
+	 * @throws \Hybridauth\Exception\HttpClientFailureException
103
+	 * @throws \Hybridauth\Exception\HttpRequestFailedException
104
+	 * @throws InvalidAccessTokenException
105
+	 */
106
+	public function exchangeAccessToken()
107
+	{
108
+		if ($this->getStoredData('expires_in') >= 5000000) {
109
+			/*
110 110
             Refresh a long-lived token (needed on Instagram, but not Facebook).
111 111
             It's not an oAuth style refresh using a refresh token.
112 112
             Actually it's really just another exchange, and invalidates the old token.
113 113
             Facebook/Instagram documentation is not very helpful at explaining that!
114 114
             */
115
-            $exchangeTokenParameters = [
116
-                'grant_type'        => 'ig_refresh_token',
117
-                'client_secret'     => $this->clientSecret,
118
-                'access_token'      => $this->getStoredData('access_token'),
119
-            ];
120
-            $url = 'https://graph.instagram.com/refresh_access_token';
121
-        } else {
122
-            // Exchange short-lived to long-lived
123
-            $exchangeTokenParameters = [
124
-                'grant_type'        => 'ig_exchange_token',
125
-                'client_secret'     => $this->clientSecret,
126
-                'access_token'      => $this->getStoredData('access_token'),
127
-            ];
128
-            $url = 'https://graph.instagram.com/access_token';
129
-        }
130
-
131
-        $response = $this->httpClient->request(
132
-            $url,
133
-            'GET',
134
-            $exchangeTokenParameters
135
-        );
136
-
137
-        $this->validateApiResponse('Unable to exchange the access token');
138
-
139
-        $this->validateAccessTokenExchange($response);
140
-
141
-        return $response;
142
-    }
143
-
144
-    /**
145
-     * {@inheritdoc}
146
-     */
147
-    public function getUserProfile()
148
-    {
149
-        $response = $this->apiRequest('me', 'GET', [
150
-            'fields' => 'id,username,account_type,media_count',
151
-        ]);
152
-
153
-        $data = new Collection($response);
154
-        if (!$data->exists('id')) {
155
-            throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
156
-        }
157
-
158
-        $userProfile = new User\Profile();
159
-        $userProfile->identifier = $data->get('id');
160
-        $userProfile->displayName = $data->get('username');
161
-        $userProfile->profileURL = "https://instagram.com/{$userProfile->displayName}";
162
-        $userProfile->data = [
163
-            'account_type' => $data->get('account_type'),
164
-            'media_count' => $data->get('media_count'),
165
-        ];
166
-
167
-        return $userProfile;
168
-    }
169
-
170
-    /**
171
-     * Fetch user medias.
172
-     *
173
-     * @param int $limit Number of elements per page.
174
-     * @param string $pageId Current pager ID.
175
-     * @param array|null $fields Fields to fetch per media.
176
-     *
177
-     * @return \Hybridauth\Data\Collection
178
-     *
179
-     * @throws \Hybridauth\Exception\HttpClientFailureException
180
-     * @throws \Hybridauth\Exception\HttpRequestFailedException
181
-     * @throws \Hybridauth\Exception\InvalidAccessTokenException
182
-     * @throws \Hybridauth\Exception\UnexpectedApiResponseException
183
-     */
184
-    public function getUserMedia($limit = 12, $pageId = null, array $fields = null)
185
-    {
186
-        if (empty($fields)) {
187
-            $fields = [
188
-                'id',
189
-                'caption',
190
-                'media_type',
191
-                'media_url',
192
-                'thumbnail_url',
193
-                'permalink',
194
-                'timestamp',
195
-                'username',
196
-            ];
197
-        }
198
-
199
-        $params = [
200
-            'fields' => implode(',', $fields),
201
-            'limit' => $limit,
202
-        ];
203
-        if ($pageId !== null) {
204
-            $params['after'] = $pageId;
205
-        }
206
-
207
-        $response = $this->apiRequest('me/media', 'GET', $params);
208
-
209
-        $data = new Collection($response);
210
-        if (!$data->exists('data')) {
211
-            throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
212
-        }
213
-
214
-        return $data;
215
-    }
216
-
217
-    /**
218
-     * Fetches a single user's media.
219
-     *
220
-     * @param string $mediaId Media ID.
221
-     * @param array|null $fields Fields to fetch per media.
222
-     *
223
-     * @return \Hybridauth\Data\Collection
224
-     *
225
-     * @throws \Hybridauth\Exception\HttpClientFailureException
226
-     * @throws \Hybridauth\Exception\HttpRequestFailedException
227
-     * @throws \Hybridauth\Exception\InvalidAccessTokenException
228
-     * @throws \Hybridauth\Exception\UnexpectedApiResponseException
229
-     */
230
-    public function getMedia($mediaId, array $fields = null)
231
-    {
232
-        if (empty($fields)) {
233
-            $fields = [
234
-                'id',
235
-                'caption',
236
-                'media_type',
237
-                'media_url',
238
-                'thumbnail_url',
239
-                'permalink',
240
-                'timestamp',
241
-                'username',
242
-            ];
243
-        }
244
-
245
-        $response = $this->apiRequest($mediaId, 'GET', [
246
-            'fields' => implode(',', $fields),
247
-        ]);
248
-
249
-        $data = new Collection($response);
250
-        if (!$data->exists('id')) {
251
-            throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
252
-        }
253
-
254
-        return $data;
255
-    }
115
+			$exchangeTokenParameters = [
116
+				'grant_type'        => 'ig_refresh_token',
117
+				'client_secret'     => $this->clientSecret,
118
+				'access_token'      => $this->getStoredData('access_token'),
119
+			];
120
+			$url = 'https://graph.instagram.com/refresh_access_token';
121
+		} else {
122
+			// Exchange short-lived to long-lived
123
+			$exchangeTokenParameters = [
124
+				'grant_type'        => 'ig_exchange_token',
125
+				'client_secret'     => $this->clientSecret,
126
+				'access_token'      => $this->getStoredData('access_token'),
127
+			];
128
+			$url = 'https://graph.instagram.com/access_token';
129
+		}
130
+
131
+		$response = $this->httpClient->request(
132
+			$url,
133
+			'GET',
134
+			$exchangeTokenParameters
135
+		);
136
+
137
+		$this->validateApiResponse('Unable to exchange the access token');
138
+
139
+		$this->validateAccessTokenExchange($response);
140
+
141
+		return $response;
142
+	}
143
+
144
+	/**
145
+	 * {@inheritdoc}
146
+	 */
147
+	public function getUserProfile()
148
+	{
149
+		$response = $this->apiRequest('me', 'GET', [
150
+			'fields' => 'id,username,account_type,media_count',
151
+		]);
152
+
153
+		$data = new Collection($response);
154
+		if (!$data->exists('id')) {
155
+			throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
156
+		}
157
+
158
+		$userProfile = new User\Profile();
159
+		$userProfile->identifier = $data->get('id');
160
+		$userProfile->displayName = $data->get('username');
161
+		$userProfile->profileURL = "https://instagram.com/{$userProfile->displayName}";
162
+		$userProfile->data = [
163
+			'account_type' => $data->get('account_type'),
164
+			'media_count' => $data->get('media_count'),
165
+		];
166
+
167
+		return $userProfile;
168
+	}
169
+
170
+	/**
171
+	 * Fetch user medias.
172
+	 *
173
+	 * @param int $limit Number of elements per page.
174
+	 * @param string $pageId Current pager ID.
175
+	 * @param array|null $fields Fields to fetch per media.
176
+	 *
177
+	 * @return \Hybridauth\Data\Collection
178
+	 *
179
+	 * @throws \Hybridauth\Exception\HttpClientFailureException
180
+	 * @throws \Hybridauth\Exception\HttpRequestFailedException
181
+	 * @throws \Hybridauth\Exception\InvalidAccessTokenException
182
+	 * @throws \Hybridauth\Exception\UnexpectedApiResponseException
183
+	 */
184
+	public function getUserMedia($limit = 12, $pageId = null, array $fields = null)
185
+	{
186
+		if (empty($fields)) {
187
+			$fields = [
188
+				'id',
189
+				'caption',
190
+				'media_type',
191
+				'media_url',
192
+				'thumbnail_url',
193
+				'permalink',
194
+				'timestamp',
195
+				'username',
196
+			];
197
+		}
198
+
199
+		$params = [
200
+			'fields' => implode(',', $fields),
201
+			'limit' => $limit,
202
+		];
203
+		if ($pageId !== null) {
204
+			$params['after'] = $pageId;
205
+		}
206
+
207
+		$response = $this->apiRequest('me/media', 'GET', $params);
208
+
209
+		$data = new Collection($response);
210
+		if (!$data->exists('data')) {
211
+			throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
212
+		}
213
+
214
+		return $data;
215
+	}
216
+
217
+	/**
218
+	 * Fetches a single user's media.
219
+	 *
220
+	 * @param string $mediaId Media ID.
221
+	 * @param array|null $fields Fields to fetch per media.
222
+	 *
223
+	 * @return \Hybridauth\Data\Collection
224
+	 *
225
+	 * @throws \Hybridauth\Exception\HttpClientFailureException
226
+	 * @throws \Hybridauth\Exception\HttpRequestFailedException
227
+	 * @throws \Hybridauth\Exception\InvalidAccessTokenException
228
+	 * @throws \Hybridauth\Exception\UnexpectedApiResponseException
229
+	 */
230
+	public function getMedia($mediaId, array $fields = null)
231
+	{
232
+		if (empty($fields)) {
233
+			$fields = [
234
+				'id',
235
+				'caption',
236
+				'media_type',
237
+				'media_url',
238
+				'thumbnail_url',
239
+				'permalink',
240
+				'timestamp',
241
+				'username',
242
+			];
243
+		}
244
+
245
+		$response = $this->apiRequest($mediaId, 'GET', [
246
+			'fields' => implode(',', $fields),
247
+		]);
248
+
249
+		$data = new Collection($response);
250
+		if (!$data->exists('id')) {
251
+			throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
252
+		}
253
+
254
+		return $data;
255
+	}
256 256
 }
Please login to merge, or discard this patch.
src/Adapter/AdapterInterface.php 1 patch
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -16,140 +16,140 @@
 block discarded – undo
16 16
  */
17 17
 interface AdapterInterface
18 18
 {
19
-    /**
20
-     * Initiate the appropriate protocol and process/automate the authentication or authorization flow.
21
-     *
22
-     * @return bool|null
23
-     */
24
-    public function authenticate();
25
-
26
-    /**
27
-     * Returns TRUE if the user is connected
28
-     *
29
-     * @return bool
30
-     */
31
-    public function isConnected();
32
-
33
-    /**
34
-     * Clear all access token in storage
35
-     */
36
-    public function disconnect();
37
-
38
-    /**
39
-     * Retrieve the connected user profile
40
-     *
41
-     * @return \Hybridauth\User\Profile
42
-     */
43
-    public function getUserProfile();
44
-
45
-    /**
46
-     * Retrieve the connected user contacts list
47
-     *
48
-     * @return \Hybridauth\User\Contact[]
49
-     */
50
-    public function getUserContacts();
51
-
52
-    /**
53
-     * Retrieve the connected user pages|companies|groups list
54
-     *
55
-     * @return array
56
-     */
57
-    public function getUserPages();
58
-
59
-    /**
60
-     * Retrieve the user activity stream
61
-     *
62
-     * @param string $stream
63
-     *
64
-     * @return \Hybridauth\User\Activity[]
65
-     */
66
-    public function getUserActivity($stream);
67
-
68
-    /**
69
-     * Post a status on user wall|timeline|blog|website|etc.
70
-     *
71
-     * @param string|array $status
72
-     *
73
-     * @return mixed API response
74
-     */
75
-    public function setUserStatus($status);
76
-
77
-    /**
78
-     * Post a status on page|company|group wall.
79
-     *
80
-     * @param string|array $status
81
-     * @param string $pageId
82
-     *
83
-     * @return mixed API response
84
-     */
85
-    public function setPageStatus($status, $pageId);
86
-
87
-    /**
88
-     * Send a signed request to provider API
89
-     *
90
-     * @param string $url
91
-     * @param string $method
92
-     * @param array $parameters
93
-     * @param array $headers
94
-     * @param bool $multipart
95
-     *
96
-     * @return mixed
97
-     */
98
-    public function apiRequest($url, $method = 'GET', $parameters = [], $headers = [], $multipart = false);
99
-
100
-    /**
101
-     * Do whatever may be necessary to make sure tokens do not expire.
102
-     * Intended to be be called frequently, e.g. via Cron.
103
-     */
104
-    public function maintainToken();
105
-
106
-    /**
107
-     * Return oauth access tokens.
108
-     *
109
-     * @return array
110
-     */
111
-    public function getAccessToken();
112
-
113
-    /**
114
-     * Set oauth access tokens.
115
-     *
116
-     * @param array $tokens
117
-     */
118
-    public function setAccessToken($tokens = []);
119
-
120
-    /**
121
-     * Set http client instance.
122
-     *
123
-     * @param HttpClientInterface $httpClient
124
-     */
125
-    public function setHttpClient(HttpClientInterface $httpClient = null);
126
-
127
-    /**
128
-     * Return http client instance.
129
-     */
130
-    public function getHttpClient();
131
-
132
-    /**
133
-     * Set storage instance.
134
-     *
135
-     * @param StorageInterface $storage
136
-     */
137
-    public function setStorage(StorageInterface $storage = null);
138
-
139
-    /**
140
-     * Return storage instance.
141
-     */
142
-    public function getStorage();
143
-
144
-    /**
145
-     * Set Logger instance.
146
-     *
147
-     * @param LoggerInterface $logger
148
-     */
149
-    public function setLogger(LoggerInterface $logger = null);
150
-
151
-    /**
152
-     * Return logger instance.
153
-     */
154
-    public function getLogger();
19
+	/**
20
+	 * Initiate the appropriate protocol and process/automate the authentication or authorization flow.
21
+	 *
22
+	 * @return bool|null
23
+	 */
24
+	public function authenticate();
25
+
26
+	/**
27
+	 * Returns TRUE if the user is connected
28
+	 *
29
+	 * @return bool
30
+	 */
31
+	public function isConnected();
32
+
33
+	/**
34
+	 * Clear all access token in storage
35
+	 */
36
+	public function disconnect();
37
+
38
+	/**
39
+	 * Retrieve the connected user profile
40
+	 *
41
+	 * @return \Hybridauth\User\Profile
42
+	 */
43
+	public function getUserProfile();
44
+
45
+	/**
46
+	 * Retrieve the connected user contacts list
47
+	 *
48
+	 * @return \Hybridauth\User\Contact[]
49
+	 */
50
+	public function getUserContacts();
51
+
52
+	/**
53
+	 * Retrieve the connected user pages|companies|groups list
54
+	 *
55
+	 * @return array
56
+	 */
57
+	public function getUserPages();
58
+
59
+	/**
60
+	 * Retrieve the user activity stream
61
+	 *
62
+	 * @param string $stream
63
+	 *
64
+	 * @return \Hybridauth\User\Activity[]
65
+	 */
66
+	public function getUserActivity($stream);
67
+
68
+	/**
69
+	 * Post a status on user wall|timeline|blog|website|etc.
70
+	 *
71
+	 * @param string|array $status
72
+	 *
73
+	 * @return mixed API response
74
+	 */
75
+	public function setUserStatus($status);
76
+
77
+	/**
78
+	 * Post a status on page|company|group wall.
79
+	 *
80
+	 * @param string|array $status
81
+	 * @param string $pageId
82
+	 *
83
+	 * @return mixed API response
84
+	 */
85
+	public function setPageStatus($status, $pageId);
86
+
87
+	/**
88
+	 * Send a signed request to provider API
89
+	 *
90
+	 * @param string $url
91
+	 * @param string $method
92
+	 * @param array $parameters
93
+	 * @param array $headers
94
+	 * @param bool $multipart
95
+	 *
96
+	 * @return mixed
97
+	 */
98
+	public function apiRequest($url, $method = 'GET', $parameters = [], $headers = [], $multipart = false);
99
+
100
+	/**
101
+	 * Do whatever may be necessary to make sure tokens do not expire.
102
+	 * Intended to be be called frequently, e.g. via Cron.
103
+	 */
104
+	public function maintainToken();
105
+
106
+	/**
107
+	 * Return oauth access tokens.
108
+	 *
109
+	 * @return array
110
+	 */
111
+	public function getAccessToken();
112
+
113
+	/**
114
+	 * Set oauth access tokens.
115
+	 *
116
+	 * @param array $tokens
117
+	 */
118
+	public function setAccessToken($tokens = []);
119
+
120
+	/**
121
+	 * Set http client instance.
122
+	 *
123
+	 * @param HttpClientInterface $httpClient
124
+	 */
125
+	public function setHttpClient(HttpClientInterface $httpClient = null);
126
+
127
+	/**
128
+	 * Return http client instance.
129
+	 */
130
+	public function getHttpClient();
131
+
132
+	/**
133
+	 * Set storage instance.
134
+	 *
135
+	 * @param StorageInterface $storage
136
+	 */
137
+	public function setStorage(StorageInterface $storage = null);
138
+
139
+	/**
140
+	 * Return storage instance.
141
+	 */
142
+	public function getStorage();
143
+
144
+	/**
145
+	 * Set Logger instance.
146
+	 *
147
+	 * @param LoggerInterface $logger
148
+	 */
149
+	public function setLogger(LoggerInterface $logger = null);
150
+
151
+	/**
152
+	 * Return logger instance.
153
+	 */
154
+	public function getLogger();
155 155
 }
Please login to merge, or discard this patch.
src/Provider/WeChat.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 
116 116
         $data = new Data\Collection($response);
117 117
 
118
-        if (!$data->exists('openid')) {
118
+        if ( ! $data->exists('openid')) {
119 119
             throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
120 120
         }
121 121
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
         $userProfile->region = $data->get('province');
129 129
         $userProfile->country = $data->get('country');
130 130
         $genders = ['', 'male', 'female'];
131
-        $userProfile->gender = $genders[(int)$data->get('sex')];
131
+        $userProfile->gender = $genders[(int) $data->get('sex')];
132 132
 
133 133
         return $userProfile;
134 134
     }
Please login to merge, or discard this patch.
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -17,121 +17,121 @@
 block discarded – undo
17 17
  */
18 18
 class WeChat extends OAuth2
19 19
 {
20
-    /**
21
-     * {@inheritdoc}
22
-     */
23
-    protected $scope = 'snsapi_login,snsapi_userinfo,scope.userInfo';
24
-
25
-    /**
26
-     * {@inheritdoc}
27
-     */
28
-    protected $apiBaseUrl = 'https://api.wechat.com/sns/';
29
-
30
-    /**
31
-     * {@inheritdoc}
32
-     */
33
-    protected $authorizeUrl = 'https://open.weixin.qq.com/connect/qrconnect';
34
-
35
-    /**
36
-     * {@inheritdoc}
37
-     */
38
-    protected $accessTokenUrl = 'https://api.wechat.com/sns/oauth2/access_token';
39
-
40
-    /**
41
-     * Refresh Token Endpoint
42
-     * @var string
43
-     */
44
-    protected $tokenRefreshUrl = 'https://api.wechat.com/sns/oauth2/refresh_token';
45
-
46
-    /**
47
-     * {@ịnheritdoc}
48
-     */
49
-    protected $accessTokenInfoUrl = 'https://api.wechat.com/sns/auth';
50
-
51
-    /**
52
-     * {@inheritdoc}
53
-     */
54
-    protected $tokenExchangeMethod = 'GET';
55
-
56
-    /**
57
-     * {@inheritdoc}
58
-     */
59
-    protected $tokenRefreshMethod = 'GET';
60
-
61
-    /**
62
-     * {@inheritdoc}
63
-     */
64
-    protected $apiDocumentation = ''; // Not available
65
-
66
-    /**
67
-     * {@inheritdoc}
68
-     */
69
-    protected function initialize()
70
-    {
71
-        parent::initialize();
72
-
73
-        $this->AuthorizeUrlParameters += [
74
-            'appid' => $this->clientId
75
-        ];
76
-        unset($this->AuthorizeUrlParameters['client_id']);
77
-
78
-        $this->tokenExchangeParameters += [
79
-            'appid' => $this->clientId,
80
-            'secret' => $this->clientSecret
81
-        ];
82
-        unset($this->tokenExchangeParameters['client_id']);
83
-        unset($this->tokenExchangeParameters['client_secret']);
84
-
85
-        if ($this->isRefreshTokenAvailable()) {
86
-            $this->tokenRefreshParameters += [
87
-                'appid' => $this->clientId,
88
-            ];
89
-        }
90
-
91
-        $this->apiRequestParameters = [
92
-            'appid' => $this->clientId,
93
-            'secret' => $this->clientSecret
94
-        ];
95
-    }
96
-
97
-    /**
98
-     * {@inheritdoc}
99
-     */
100
-    protected function validateAccessTokenExchange($response)
101
-    {
102
-        $collection = parent::validateAccessTokenExchange($response);
103
-
104
-        $this->storeData('openid', $collection->get('openid'));
105
-        $this->storeData('access_token', $collection->get('access_token'));
106
-    }
107
-
108
-    /**
109
-     * {@inheritdoc}
110
-     */
111
-    public function getUserProfile()
112
-    {
113
-        $openid = $this->getStoredData('openid');
114
-        $access_token = $this->getStoredData('access_token');
115
-
116
-        $response = $this->apiRequest('userinfo', 'GET', ['openid' => $openid, 'access_token' => $access_token]);
117
-
118
-        $data = new Data\Collection($response);
119
-
120
-        if (!$data->exists('openid')) {
121
-            throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
122
-        }
123
-
124
-        $userProfile = new User\Profile();
125
-
126
-        $userProfile->identifier = $data->get('openid');
127
-        $userProfile->displayName = $data->get('nickname');
128
-        $userProfile->photoURL = $data->get('headimgurl');
129
-        $userProfile->city = $data->get('city');
130
-        $userProfile->region = $data->get('province');
131
-        $userProfile->country = $data->get('country');
132
-        $genders = ['', 'male', 'female'];
133
-        $userProfile->gender = $genders[(int)$data->get('sex')];
134
-
135
-        return $userProfile;
136
-    }
20
+	/**
21
+	 * {@inheritdoc}
22
+	 */
23
+	protected $scope = 'snsapi_login,snsapi_userinfo,scope.userInfo';
24
+
25
+	/**
26
+	 * {@inheritdoc}
27
+	 */
28
+	protected $apiBaseUrl = 'https://api.wechat.com/sns/';
29
+
30
+	/**
31
+	 * {@inheritdoc}
32
+	 */
33
+	protected $authorizeUrl = 'https://open.weixin.qq.com/connect/qrconnect';
34
+
35
+	/**
36
+	 * {@inheritdoc}
37
+	 */
38
+	protected $accessTokenUrl = 'https://api.wechat.com/sns/oauth2/access_token';
39
+
40
+	/**
41
+	 * Refresh Token Endpoint
42
+	 * @var string
43
+	 */
44
+	protected $tokenRefreshUrl = 'https://api.wechat.com/sns/oauth2/refresh_token';
45
+
46
+	/**
47
+	 * {@ịnheritdoc}
48
+	 */
49
+	protected $accessTokenInfoUrl = 'https://api.wechat.com/sns/auth';
50
+
51
+	/**
52
+	 * {@inheritdoc}
53
+	 */
54
+	protected $tokenExchangeMethod = 'GET';
55
+
56
+	/**
57
+	 * {@inheritdoc}
58
+	 */
59
+	protected $tokenRefreshMethod = 'GET';
60
+
61
+	/**
62
+	 * {@inheritdoc}
63
+	 */
64
+	protected $apiDocumentation = ''; // Not available
65
+
66
+	/**
67
+	 * {@inheritdoc}
68
+	 */
69
+	protected function initialize()
70
+	{
71
+		parent::initialize();
72
+
73
+		$this->AuthorizeUrlParameters += [
74
+			'appid' => $this->clientId
75
+		];
76
+		unset($this->AuthorizeUrlParameters['client_id']);
77
+
78
+		$this->tokenExchangeParameters += [
79
+			'appid' => $this->clientId,
80
+			'secret' => $this->clientSecret
81
+		];
82
+		unset($this->tokenExchangeParameters['client_id']);
83
+		unset($this->tokenExchangeParameters['client_secret']);
84
+
85
+		if ($this->isRefreshTokenAvailable()) {
86
+			$this->tokenRefreshParameters += [
87
+				'appid' => $this->clientId,
88
+			];
89
+		}
90
+
91
+		$this->apiRequestParameters = [
92
+			'appid' => $this->clientId,
93
+			'secret' => $this->clientSecret
94
+		];
95
+	}
96
+
97
+	/**
98
+	 * {@inheritdoc}
99
+	 */
100
+	protected function validateAccessTokenExchange($response)
101
+	{
102
+		$collection = parent::validateAccessTokenExchange($response);
103
+
104
+		$this->storeData('openid', $collection->get('openid'));
105
+		$this->storeData('access_token', $collection->get('access_token'));
106
+	}
107
+
108
+	/**
109
+	 * {@inheritdoc}
110
+	 */
111
+	public function getUserProfile()
112
+	{
113
+		$openid = $this->getStoredData('openid');
114
+		$access_token = $this->getStoredData('access_token');
115
+
116
+		$response = $this->apiRequest('userinfo', 'GET', ['openid' => $openid, 'access_token' => $access_token]);
117
+
118
+		$data = new Data\Collection($response);
119
+
120
+		if (!$data->exists('openid')) {
121
+			throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
122
+		}
123
+
124
+		$userProfile = new User\Profile();
125
+
126
+		$userProfile->identifier = $data->get('openid');
127
+		$userProfile->displayName = $data->get('nickname');
128
+		$userProfile->photoURL = $data->get('headimgurl');
129
+		$userProfile->city = $data->get('city');
130
+		$userProfile->region = $data->get('province');
131
+		$userProfile->country = $data->get('country');
132
+		$genders = ['', 'male', 'female'];
133
+		$userProfile->gender = $genders[(int)$data->get('sex')];
134
+
135
+		return $userProfile;
136
+	}
137 137
 }
Please login to merge, or discard this patch.
src/Provider/Telegram.php 2 patches
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -44,143 +44,143 @@  discard block
 block discarded – undo
44 44
  */
45 45
 class Telegram extends AbstractAdapter implements AdapterInterface
46 46
 {
47
-    protected $botId = '';
48
-
49
-    protected $botSecret = '';
50
-
51
-    protected $callbackUrl = '';
52
-
53
-    /**
54
-     * IPD API Documentation
55
-     *
56
-     * OPTIONAL.
57
-     *
58
-     * @var string
59
-     */
60
-    protected $apiDocumentation = 'https://core.telegram.org/bots';
61
-
62
-    /**
63
-     * {@inheritdoc}
64
-     */
65
-    protected function configure()
66
-    {
67
-        $this->botId = $this->config->filter('keys')->get('id');
68
-        $this->botSecret = $this->config->filter('keys')->get('secret');
69
-        $this->callbackUrl = $this->config->get('callback');
70
-
71
-        if (!$this->botId || !$this->botSecret) {
72
-            throw new InvalidApplicationCredentialsException(
73
-                'Your application id is required in order to connect to ' . $this->providerId
74
-            );
75
-        }
76
-    }
77
-
78
-    /**
79
-     * {@inheritdoc}
80
-     */
81
-    protected function initialize()
82
-    {
83
-    }
84
-
85
-    /**
86
-     * {@inheritdoc}
87
-     */
88
-    public function authenticate()
89
-    {
90
-        $this->logger->info(sprintf('%s::authenticate()', get_class($this)));
91
-        if (!filter_input(INPUT_GET, 'hash')) {
92
-            $this->authenticateBegin();
93
-        } else {
94
-            $this->authenticateCheckError();
95
-            $this->authenticateFinish();
96
-        }
97
-        return null;
98
-    }
99
-
100
-    /**
101
-     * {@inheritdoc}
102
-     */
103
-    public function isConnected()
104
-    {
105
-        $authData = $this->getStoredData('auth_data');
106
-        return !empty($authData);
107
-    }
108
-
109
-    /**
110
-     * {@inheritdoc}
111
-     */
112
-    public function getUserProfile()
113
-    {
114
-        $data = new Collection($this->getStoredData('auth_data'));
115
-
116
-        if (!$data->exists('id')) {
117
-            throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
118
-        }
119
-
120
-        $userProfile = new Profile();
121
-
122
-        $userProfile->identifier = $data->get('id');
123
-        $userProfile->firstName = $data->get('first_name');
124
-        $userProfile->lastName = $data->get('last_name');
125
-        $userProfile->displayName = $data->get('username');
126
-        $userProfile->photoURL = $data->get('photo_url');
127
-        $username = $data->get('username');
128
-        if (!empty($username)) {
129
-            // Only some accounts have usernames.
130
-            $userProfile->profileURL = "https://t.me/{$username}";
131
-        }
132
-
133
-        return $userProfile;
134
-    }
135
-
136
-    /**
137
-     * See: https://telegram.im/widget-login.php
138
-     * See: https://gist.github.com/anonymous/6516521b1fb3b464534fbc30ea3573c2
139
-     */
140
-    protected function authenticateCheckError()
141
-    {
142
-        $auth_data = $this->parseAuthData();
143
-
144
-        $check_hash = $auth_data['hash'];
145
-        unset($auth_data['hash']);
146
-        $data_check_arr = [];
147
-
148
-        foreach ($auth_data as $key => $value) {
149
-            if (!empty($value)) {
150
-                $data_check_arr[] = $key . '=' . $value;
151
-            }
152
-        }
153
-        sort($data_check_arr);
154
-
155
-        $data_check_string = implode("\n", $data_check_arr);
156
-        $secret_key = hash('sha256', $this->botSecret, true);
157
-        $hash = hash_hmac('sha256', $data_check_string, $secret_key);
158
-
159
-        if (strcmp($hash, $check_hash) !== 0) {
160
-            throw new InvalidAuthorizationCodeException(
161
-                sprintf('Provider returned an error: %s', 'Data is NOT from Telegram')
162
-            );
163
-        }
164
-
165
-        if ((time() - $auth_data['auth_date']) > 86400) {
166
-            throw new InvalidAuthorizationCodeException(
167
-                sprintf('Provider returned an error: %s', 'Data is outdated')
168
-            );
169
-        }
170
-    }
171
-
172
-    /**
173
-     * See: https://telegram.im/widget-login.php
174
-     */
175
-    protected function authenticateBegin()
176
-    {
177
-        $this->logger->debug(sprintf('%s::authenticateBegin(), redirecting user to:', get_class($this)));
178
-
179
-        $nonce = $this->config->get('nonce');
180
-        $nonce_code = empty($nonce) ? '' : "nonce=\"{$nonce}\"";
181
-
182
-        exit(
183
-            <<<HTML
47
+	protected $botId = '';
48
+
49
+	protected $botSecret = '';
50
+
51
+	protected $callbackUrl = '';
52
+
53
+	/**
54
+	 * IPD API Documentation
55
+	 *
56
+	 * OPTIONAL.
57
+	 *
58
+	 * @var string
59
+	 */
60
+	protected $apiDocumentation = 'https://core.telegram.org/bots';
61
+
62
+	/**
63
+	 * {@inheritdoc}
64
+	 */
65
+	protected function configure()
66
+	{
67
+		$this->botId = $this->config->filter('keys')->get('id');
68
+		$this->botSecret = $this->config->filter('keys')->get('secret');
69
+		$this->callbackUrl = $this->config->get('callback');
70
+
71
+		if (!$this->botId || !$this->botSecret) {
72
+			throw new InvalidApplicationCredentialsException(
73
+				'Your application id is required in order to connect to ' . $this->providerId
74
+			);
75
+		}
76
+	}
77
+
78
+	/**
79
+	 * {@inheritdoc}
80
+	 */
81
+	protected function initialize()
82
+	{
83
+	}
84
+
85
+	/**
86
+	 * {@inheritdoc}
87
+	 */
88
+	public function authenticate()
89
+	{
90
+		$this->logger->info(sprintf('%s::authenticate()', get_class($this)));
91
+		if (!filter_input(INPUT_GET, 'hash')) {
92
+			$this->authenticateBegin();
93
+		} else {
94
+			$this->authenticateCheckError();
95
+			$this->authenticateFinish();
96
+		}
97
+		return null;
98
+	}
99
+
100
+	/**
101
+	 * {@inheritdoc}
102
+	 */
103
+	public function isConnected()
104
+	{
105
+		$authData = $this->getStoredData('auth_data');
106
+		return !empty($authData);
107
+	}
108
+
109
+	/**
110
+	 * {@inheritdoc}
111
+	 */
112
+	public function getUserProfile()
113
+	{
114
+		$data = new Collection($this->getStoredData('auth_data'));
115
+
116
+		if (!$data->exists('id')) {
117
+			throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
118
+		}
119
+
120
+		$userProfile = new Profile();
121
+
122
+		$userProfile->identifier = $data->get('id');
123
+		$userProfile->firstName = $data->get('first_name');
124
+		$userProfile->lastName = $data->get('last_name');
125
+		$userProfile->displayName = $data->get('username');
126
+		$userProfile->photoURL = $data->get('photo_url');
127
+		$username = $data->get('username');
128
+		if (!empty($username)) {
129
+			// Only some accounts have usernames.
130
+			$userProfile->profileURL = "https://t.me/{$username}";
131
+		}
132
+
133
+		return $userProfile;
134
+	}
135
+
136
+	/**
137
+	 * See: https://telegram.im/widget-login.php
138
+	 * See: https://gist.github.com/anonymous/6516521b1fb3b464534fbc30ea3573c2
139
+	 */
140
+	protected function authenticateCheckError()
141
+	{
142
+		$auth_data = $this->parseAuthData();
143
+
144
+		$check_hash = $auth_data['hash'];
145
+		unset($auth_data['hash']);
146
+		$data_check_arr = [];
147
+
148
+		foreach ($auth_data as $key => $value) {
149
+			if (!empty($value)) {
150
+				$data_check_arr[] = $key . '=' . $value;
151
+			}
152
+		}
153
+		sort($data_check_arr);
154
+
155
+		$data_check_string = implode("\n", $data_check_arr);
156
+		$secret_key = hash('sha256', $this->botSecret, true);
157
+		$hash = hash_hmac('sha256', $data_check_string, $secret_key);
158
+
159
+		if (strcmp($hash, $check_hash) !== 0) {
160
+			throw new InvalidAuthorizationCodeException(
161
+				sprintf('Provider returned an error: %s', 'Data is NOT from Telegram')
162
+			);
163
+		}
164
+
165
+		if ((time() - $auth_data['auth_date']) > 86400) {
166
+			throw new InvalidAuthorizationCodeException(
167
+				sprintf('Provider returned an error: %s', 'Data is outdated')
168
+			);
169
+		}
170
+	}
171
+
172
+	/**
173
+	 * See: https://telegram.im/widget-login.php
174
+	 */
175
+	protected function authenticateBegin()
176
+	{
177
+		$this->logger->debug(sprintf('%s::authenticateBegin(), redirecting user to:', get_class($this)));
178
+
179
+		$nonce = $this->config->get('nonce');
180
+		$nonce_code = empty($nonce) ? '' : "nonce=\"{$nonce}\"";
181
+
182
+		exit(
183
+			<<<HTML
184 184
 <center>
185 185
     <script async src="https://telegram.org/js/telegram-widget.js?7"
186 186
             {$nonce_code}
@@ -191,31 +191,31 @@  discard block
 block discarded – undo
191 191
     </script>
192 192
 </center>
193 193
 HTML
194
-        );
195
-    }
196
-
197
-    protected function authenticateFinish()
198
-    {
199
-        $this->logger->debug(
200
-            sprintf('%s::authenticateFinish(), callback url:', get_class($this)),
201
-            [Util::getCurrentUrl(true)]
202
-        );
203
-
204
-        $this->storeData('auth_data', $this->parseAuthData());
205
-
206
-        $this->initialize();
207
-    }
208
-
209
-    protected function parseAuthData()
210
-    {
211
-        return [
212
-            'id' => filter_input(INPUT_GET, 'id'),
213
-            'first_name' => filter_input(INPUT_GET, 'first_name'),
214
-            'last_name' => filter_input(INPUT_GET, 'last_name'),
215
-            'username' => filter_input(INPUT_GET, 'username'),
216
-            'photo_url' => filter_input(INPUT_GET, 'photo_url'),
217
-            'auth_date' => filter_input(INPUT_GET, 'auth_date'),
218
-            'hash' => filter_input(INPUT_GET, 'hash'),
219
-        ];
220
-    }
194
+		);
195
+	}
196
+
197
+	protected function authenticateFinish()
198
+	{
199
+		$this->logger->debug(
200
+			sprintf('%s::authenticateFinish(), callback url:', get_class($this)),
201
+			[Util::getCurrentUrl(true)]
202
+		);
203
+
204
+		$this->storeData('auth_data', $this->parseAuthData());
205
+
206
+		$this->initialize();
207
+	}
208
+
209
+	protected function parseAuthData()
210
+	{
211
+		return [
212
+			'id' => filter_input(INPUT_GET, 'id'),
213
+			'first_name' => filter_input(INPUT_GET, 'first_name'),
214
+			'last_name' => filter_input(INPUT_GET, 'last_name'),
215
+			'username' => filter_input(INPUT_GET, 'username'),
216
+			'photo_url' => filter_input(INPUT_GET, 'photo_url'),
217
+			'auth_date' => filter_input(INPUT_GET, 'auth_date'),
218
+			'hash' => filter_input(INPUT_GET, 'hash'),
219
+		];
220
+	}
221 221
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -68,9 +68,9 @@  discard block
 block discarded – undo
68 68
         $this->botSecret = $this->config->filter('keys')->get('secret');
69 69
         $this->callbackUrl = $this->config->get('callback');
70 70
 
71
-        if (!$this->botId || !$this->botSecret) {
71
+        if ( ! $this->botId || ! $this->botSecret) {
72 72
             throw new InvalidApplicationCredentialsException(
73
-                'Your application id is required in order to connect to ' . $this->providerId
73
+                'Your application id is required in order to connect to '.$this->providerId
74 74
             );
75 75
         }
76 76
     }
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
     public function authenticate()
89 89
     {
90 90
         $this->logger->info(sprintf('%s::authenticate()', get_class($this)));
91
-        if (!filter_input(INPUT_GET, 'hash')) {
91
+        if ( ! filter_input(INPUT_GET, 'hash')) {
92 92
             $this->authenticateBegin();
93 93
         } else {
94 94
             $this->authenticateCheckError();
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
     public function isConnected()
104 104
     {
105 105
         $authData = $this->getStoredData('auth_data');
106
-        return !empty($authData);
106
+        return ! empty($authData);
107 107
     }
108 108
 
109 109
     /**
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
     {
114 114
         $data = new Collection($this->getStoredData('auth_data'));
115 115
 
116
-        if (!$data->exists('id')) {
116
+        if ( ! $data->exists('id')) {
117 117
             throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
118 118
         }
119 119
 
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
         $userProfile->displayName = $data->get('username');
126 126
         $userProfile->photoURL = $data->get('photo_url');
127 127
         $username = $data->get('username');
128
-        if (!empty($username)) {
128
+        if ( ! empty($username)) {
129 129
             // Only some accounts have usernames.
130 130
             $userProfile->profileURL = "https://t.me/{$username}";
131 131
         }
@@ -146,8 +146,8 @@  discard block
 block discarded – undo
146 146
         $data_check_arr = [];
147 147
 
148 148
         foreach ($auth_data as $key => $value) {
149
-            if (!empty($value)) {
150
-                $data_check_arr[] = $key . '=' . $value;
149
+            if ( ! empty($value)) {
150
+                $data_check_arr[] = $key.'='.$value;
151 151
             }
152 152
         }
153 153
         sort($data_check_arr);
Please login to merge, or discard this patch.
src/Adapter/OAuth1.php 2 patches
Indentation   +586 added lines, -586 removed lines patch added patch discarded remove patch
@@ -27,590 +27,590 @@
 block discarded – undo
27 27
  */
28 28
 abstract class OAuth1 extends AbstractAdapter implements AdapterInterface
29 29
 {
30
-    /**
31
-     * Base URL to provider API
32
-     *
33
-     * This var will be used to build urls when sending signed requests
34
-     *
35
-     * @var string
36
-     */
37
-    protected $apiBaseUrl = '';
38
-
39
-    /**
40
-     * @var string
41
-     */
42
-    protected $authorizeUrl = '';
43
-
44
-    /**
45
-     * @var string
46
-     */
47
-    protected $requestTokenUrl = '';
48
-
49
-    /**
50
-     * @var string
51
-     */
52
-    protected $accessTokenUrl = '';
53
-
54
-    /**
55
-     * IPD API Documentation
56
-     *
57
-     * OPTIONAL.
58
-     *
59
-     * @var string
60
-     */
61
-    protected $apiDocumentation = '';
62
-
63
-    /**
64
-     * OAuth Version
65
-     *
66
-     *  '1.0' OAuth Core 1.0
67
-     * '1.0a' OAuth Core 1.0 Revision A
68
-     *
69
-     * @var string
70
-     */
71
-    protected $oauth1Version = '1.0a';
72
-
73
-    /**
74
-     * @var string
75
-     */
76
-    protected $consumerKey = null;
77
-
78
-    /**
79
-     * @var string
80
-     */
81
-    protected $consumerSecret = null;
82
-
83
-    /**
84
-     * @var object
85
-     */
86
-    protected $OAuthConsumer = null;
87
-
88
-    /**
89
-     * @var object
90
-     */
91
-    protected $sha1Method = null;
92
-
93
-    /**
94
-     * @var object
95
-     */
96
-    protected $consumerToken = null;
97
-
98
-    /**
99
-     * Authorization Url Parameters
100
-     *
101
-     * @var bool
102
-     */
103
-    protected $AuthorizeUrlParameters = [];
104
-
105
-    /**
106
-     * @var string
107
-     */
108
-    protected $requestTokenMethod = 'POST';
109
-
110
-    /**
111
-     * @var array
112
-     */
113
-    protected $requestTokenParameters = [];
114
-
115
-    /**
116
-     * @var array
117
-     */
118
-    protected $requestTokenHeaders = [];
119
-
120
-    /**
121
-     * @var string
122
-     */
123
-    protected $tokenExchangeMethod = 'POST';
124
-
125
-    /**
126
-     * @var array
127
-     */
128
-    protected $tokenExchangeParameters = [];
129
-
130
-    /**
131
-     * @var array
132
-     */
133
-    protected $tokenExchangeHeaders = [];
134
-
135
-    /**
136
-     * @var array
137
-     */
138
-    protected $apiRequestParameters = [];
139
-
140
-    /**
141
-     * @var array
142
-     */
143
-    protected $apiRequestHeaders = [];
144
-
145
-    /**
146
-     * {@inheritdoc}
147
-     */
148
-    protected function configure()
149
-    {
150
-        $this->consumerKey = $this->config->filter('keys')->get('id') ?: $this->config->filter('keys')->get('key');
151
-        $this->consumerSecret = $this->config->filter('keys')->get('secret');
152
-
153
-        if (!$this->consumerKey || !$this->consumerSecret) {
154
-            throw new InvalidApplicationCredentialsException(
155
-                'Your application id is required in order to connect to ' . $this->providerId
156
-            );
157
-        }
158
-
159
-        if ($this->config->exists('tokens')) {
160
-            $this->setAccessToken($this->config->get('tokens'));
161
-        }
162
-
163
-        $this->setCallback($this->config->get('callback'));
164
-        $this->setApiEndpoints($this->config->get('endpoints'));
165
-    }
166
-
167
-    /**
168
-     * {@inheritdoc}
169
-     */
170
-    protected function initialize()
171
-    {
172
-        /**
173
-         * Set up OAuth Signature and Consumer
174
-         *
175
-         * OAuth Core: All Token requests and Protected Resources requests MUST be signed
176
-         * by the Consumer and verified by the Service Provider.
177
-         *
178
-         * The protocol defines three signature methods: HMAC-SHA1, RSA-SHA1, and PLAINTEXT..
179
-         *
180
-         * The Consumer declares a signature method in the oauth_signature_method parameter..
181
-         *
182
-         * http://oauth.net/core/1.0a/#signing_process
183
-         */
184
-        $this->sha1Method = new OAuthSignatureMethodHMACSHA1();
185
-
186
-        $this->OAuthConsumer = new OAuthConsumer(
187
-            $this->consumerKey,
188
-            $this->consumerSecret
189
-        );
190
-
191
-        if ($this->getStoredData('request_token')) {
192
-            $this->consumerToken = new OAuthConsumer(
193
-                $this->getStoredData('request_token'),
194
-                $this->getStoredData('request_token_secret')
195
-            );
196
-        }
197
-
198
-        if ($this->getStoredData('access_token')) {
199
-            $this->consumerToken = new OAuthConsumer(
200
-                $this->getStoredData('access_token'),
201
-                $this->getStoredData('access_token_secret')
202
-            );
203
-        }
204
-    }
205
-
206
-    /**
207
-     * {@inheritdoc}
208
-     */
209
-    public function authenticate()
210
-    {
211
-        $this->logger->info(sprintf('%s::authenticate()', get_class($this)));
212
-
213
-        if ($this->isConnected()) {
214
-            return true;
215
-        }
216
-
217
-        try {
218
-            if (!$this->getStoredData('request_token')) {
219
-                // Start a new flow.
220
-                $this->authenticateBegin();
221
-            } elseif (empty($_GET['oauth_token']) && empty($_GET['denied'])) {
222
-                // A previous authentication was not finished, and this request is not finishing it.
223
-                $this->authenticateBegin();
224
-            } else {
225
-                // Finish a flow.
226
-                $this->authenticateFinish();
227
-            }
228
-        } catch (Exception $exception) {
229
-            $this->clearStoredData();
230
-
231
-            throw $exception;
232
-        }
233
-
234
-        return null;
235
-    }
236
-
237
-    /**
238
-     * {@inheritdoc}
239
-     */
240
-    public function isConnected()
241
-    {
242
-        return (bool)$this->getStoredData('access_token');
243
-    }
244
-
245
-    /**
246
-     * Initiate the authorization protocol
247
-     *
248
-     * 1. Obtaining an Unauthorized Request Token
249
-     * 2. Build Authorization URL for Authorization Request and redirect the user-agent to the
250
-     *    Authorization Server.
251
-     */
252
-    protected function authenticateBegin()
253
-    {
254
-        $response = $this->requestAuthToken();
255
-
256
-        $this->validateAuthTokenRequest($response);
257
-
258
-        $authUrl = $this->getAuthorizeUrl();
259
-
260
-        $this->logger->debug(sprintf('%s::authenticateBegin(), redirecting user to:', get_class($this)), [$authUrl]);
261
-
262
-        HttpClient\Util::redirect($authUrl);
263
-    }
264
-
265
-    /**
266
-     * Finalize the authorization process
267
-     *
268
-     * @throws AuthorizationDeniedException
269
-     * @throws \Hybridauth\Exception\HttpClientFailureException
270
-     * @throws \Hybridauth\Exception\HttpRequestFailedException
271
-     * @throws InvalidAccessTokenException
272
-     * @throws InvalidOauthTokenException
273
-     */
274
-    protected function authenticateFinish()
275
-    {
276
-        $this->logger->debug(
277
-            sprintf('%s::authenticateFinish(), callback url:', get_class($this)),
278
-            [HttpClient\Util::getCurrentUrl(true)]
279
-        );
280
-
281
-        $denied = filter_input(INPUT_GET, 'denied');
282
-        $oauth_problem = filter_input(INPUT_GET, 'oauth_problem');
283
-        $oauth_token = filter_input(INPUT_GET, 'oauth_token');
284
-        $oauth_verifier = filter_input(INPUT_GET, 'oauth_verifier');
285
-
286
-        if ($denied) {
287
-            throw new AuthorizationDeniedException(
288
-                'User denied access request. Provider returned a denied token: ' . htmlentities($denied)
289
-            );
290
-        }
291
-
292
-        if ($oauth_problem) {
293
-            throw new InvalidOauthTokenException(
294
-                'Provider returned an error. oauth_problem: ' . htmlentities($oauth_problem)
295
-            );
296
-        }
297
-
298
-        if (!$oauth_token) {
299
-            throw new InvalidOauthTokenException(
300
-                'Expecting a non-null oauth_token to continue the authorization flow.'
301
-            );
302
-        }
303
-
304
-        $response = $this->exchangeAuthTokenForAccessToken($oauth_token, $oauth_verifier);
305
-
306
-        $this->validateAccessTokenExchange($response);
307
-
308
-        $this->initialize();
309
-    }
310
-
311
-    /**
312
-     * Build Authorization URL for Authorization Request
313
-     *
314
-     * @param array $parameters
315
-     *
316
-     * @return string
317
-     */
318
-    protected function getAuthorizeUrl($parameters = [])
319
-    {
320
-        $this->AuthorizeUrlParameters = !empty($parameters)
321
-            ? $parameters
322
-            : array_replace(
323
-                (array)$this->AuthorizeUrlParameters,
324
-                (array)$this->config->get('authorize_url_parameters')
325
-            );
326
-
327
-        $this->AuthorizeUrlParameters['oauth_token'] = $this->getStoredData('request_token');
328
-
329
-        return $this->authorizeUrl . '?' . http_build_query($this->AuthorizeUrlParameters, '', '&');
330
-    }
331
-
332
-    /**
333
-     * Unauthorized Request Token
334
-     *
335
-     * OAuth Core: The Consumer obtains an unauthorized Request Token by asking the Service Provider
336
-     * to issue a Token. The Request Token's sole purpose is to receive User approval and can only
337
-     * be used to obtain an Access Token.
338
-     *
339
-     * http://oauth.net/core/1.0/#auth_step1
340
-     * 6.1.1. Consumer Obtains a Request Token
341
-     *
342
-     * @return string Raw Provider API response
343
-     * @throws \Hybridauth\Exception\HttpClientFailureException
344
-     * @throws \Hybridauth\Exception\HttpRequestFailedException
345
-     */
346
-    protected function requestAuthToken()
347
-    {
348
-        /**
349
-         * OAuth Core 1.0 Revision A: oauth_callback: An absolute URL to which the Service Provider will redirect
350
-         * the User back when the Obtaining User Authorization step is completed.
351
-         *
352
-         * http://oauth.net/core/1.0a/#auth_step1
353
-         */
354
-        if ('1.0a' == $this->oauth1Version) {
355
-            $this->requestTokenParameters['oauth_callback'] = $this->callback;
356
-        }
357
-
358
-        $response = $this->oauthRequest(
359
-            $this->requestTokenUrl,
360
-            $this->requestTokenMethod,
361
-            $this->requestTokenParameters,
362
-            $this->requestTokenHeaders
363
-        );
364
-
365
-        return $response;
366
-    }
367
-
368
-    /**
369
-     * Validate Unauthorized Request Token Response
370
-     *
371
-     * OAuth Core: The Service Provider verifies the signature and Consumer Key. If successful,
372
-     * it generates a Request Token and Token Secret and returns them to the Consumer in the HTTP
373
-     * response body.
374
-     *
375
-     * http://oauth.net/core/1.0/#auth_step1
376
-     * 6.1.2. Service Provider Issues an Unauthorized Request Token
377
-     *
378
-     * @param string $response
379
-     *
380
-     * @return \Hybridauth\Data\Collection
381
-     * @throws InvalidOauthTokenException
382
-     */
383
-    protected function validateAuthTokenRequest($response)
384
-    {
385
-        /**
386
-         * The response contains the following parameters:
387
-         *
388
-         *    - oauth_token               The Request Token.
389
-         *    - oauth_token_secret        The Token Secret.
390
-         *    - oauth_callback_confirmed  MUST be present and set to true.
391
-         *
392
-         * http://oauth.net/core/1.0/#auth_step1
393
-         * 6.1.2. Service Provider Issues an Unauthorized Request Token
394
-         *
395
-         * Example of a successful response:
396
-         *
397
-         *  HTTP/1.1 200 OK
398
-         *  Content-Type: text/html; charset=utf-8
399
-         *  Cache-Control: no-store
400
-         *  Pragma: no-cache
401
-         *
402
-         *  oauth_token=80359084-clg1DEtxQF3wstTcyUdHF3wsdHM&oauth_token_secret=OIF07hPmJB:P
403
-         *  6qiHTi1znz6qiH3tTcyUdHnz6qiH3tTcyUdH3xW3wsDvV08e&example_parameter=example_value
404
-         *
405
-         * OAuthUtil::parse_parameters will attempt to decode the raw response into an array.
406
-         */
407
-        $tokens = OAuthUtil::parse_parameters($response);
408
-
409
-        $collection = new Data\Collection($tokens);
410
-
411
-        if (!$collection->exists('oauth_token')) {
412
-            throw new InvalidOauthTokenException(
413
-                'Provider returned no oauth_token: ' . htmlentities($response)
414
-            );
415
-        }
416
-
417
-        $this->consumerToken = new OAuthConsumer(
418
-            $tokens['oauth_token'],
419
-            $tokens['oauth_token_secret']
420
-        );
421
-
422
-        $this->storeData('request_token', $tokens['oauth_token']);
423
-        $this->storeData('request_token_secret', $tokens['oauth_token_secret']);
424
-
425
-        return $collection;
426
-    }
427
-
428
-    /**
429
-     * Requests an Access Token
430
-     *
431
-     * OAuth Core: The Request Token and Token Secret MUST be exchanged for an Access Token and Token Secret.
432
-     *
433
-     * http://oauth.net/core/1.0a/#auth_step3
434
-     * 6.3.1. Consumer Requests an Access Token
435
-     *
436
-     * @param string $oauth_token
437
-     * @param string $oauth_verifier
438
-     *
439
-     * @return string Raw Provider API response
440
-     * @throws \Hybridauth\Exception\HttpClientFailureException
441
-     * @throws \Hybridauth\Exception\HttpRequestFailedException
442
-     */
443
-    protected function exchangeAuthTokenForAccessToken($oauth_token, $oauth_verifier = '')
444
-    {
445
-        $this->tokenExchangeParameters['oauth_token'] = $oauth_token;
446
-
447
-        /**
448
-         * OAuth Core 1.0 Revision A: oauth_verifier: The verification code received from the Service Provider
449
-         * in the "Service Provider Directs the User Back to the Consumer" step.
450
-         *
451
-         * http://oauth.net/core/1.0a/#auth_step3
452
-         */
453
-        if ('1.0a' == $this->oauth1Version) {
454
-            $this->tokenExchangeParameters['oauth_verifier'] = $oauth_verifier;
455
-        }
456
-
457
-        $response = $this->oauthRequest(
458
-            $this->accessTokenUrl,
459
-            $this->tokenExchangeMethod,
460
-            $this->tokenExchangeParameters,
461
-            $this->tokenExchangeHeaders
462
-        );
463
-
464
-        return $response;
465
-    }
466
-
467
-    /**
468
-     * Validate Access Token Response
469
-     *
470
-     * OAuth Core: If successful, the Service Provider generates an Access Token and Token Secret and returns
471
-     * them in the HTTP response body.
472
-     *
473
-     * The Access Token and Token Secret are stored by the Consumer and used when signing Protected Resources requests.
474
-     *
475
-     * http://oauth.net/core/1.0a/#auth_step3
476
-     * 6.3.2. Service Provider Grants an Access Token
477
-     *
478
-     * @param string $response
479
-     *
480
-     * @return \Hybridauth\Data\Collection
481
-     * @throws InvalidAccessTokenException
482
-     */
483
-    protected function validateAccessTokenExchange($response)
484
-    {
485
-        /**
486
-         * The response contains the following parameters:
487
-         *
488
-         *    - oauth_token         The Access Token.
489
-         *    - oauth_token_secret  The Token Secret.
490
-         *
491
-         * http://oauth.net/core/1.0/#auth_step3
492
-         * 6.3.2. Service Provider Grants an Access Token
493
-         *
494
-         * Example of a successful response:
495
-         *
496
-         *  HTTP/1.1 200 OK
497
-         *  Content-Type: text/html; charset=utf-8
498
-         *  Cache-Control: no-store
499
-         *  Pragma: no-cache
500
-         *
501
-         *  oauth_token=sHeLU7Far428zj8PzlWR75&oauth_token_secret=fXb30rzoG&oauth_callback_confirmed=true
502
-         *
503
-         * OAuthUtil::parse_parameters will attempt to decode the raw response into an array.
504
-         */
505
-        $tokens = OAuthUtil::parse_parameters($response);
506
-
507
-        $collection = new Data\Collection($tokens);
508
-
509
-        if (!$collection->exists('oauth_token')) {
510
-            throw new InvalidAccessTokenException(
511
-                'Provider returned no access_token: ' . htmlentities($response)
512
-            );
513
-        }
514
-
515
-        $this->consumerToken = new OAuthConsumer(
516
-            $collection->get('oauth_token'),
517
-            $collection->get('oauth_token_secret')
518
-        );
519
-
520
-        $this->storeData('access_token', $collection->get('oauth_token'));
521
-        $this->storeData('access_token_secret', $collection->get('oauth_token_secret'));
522
-
523
-        $this->deleteStoredData('request_token');
524
-        $this->deleteStoredData('request_token_secret');
525
-
526
-        return $collection;
527
-    }
528
-
529
-    /**
530
-     * Send a signed request to provider API
531
-     *
532
-     * Note: Since the specifics of error responses is beyond the scope of RFC6749 and OAuth specifications,
533
-     * Hybridauth will consider any HTTP status code that is different than '200 OK' as an ERROR.
534
-     *
535
-     * @param string $url
536
-     * @param string $method
537
-     * @param array $parameters
538
-     * @param array $headers
539
-     * @param bool $multipart
540
-     *
541
-     * @return mixed
542
-     * @throws \Hybridauth\Exception\HttpClientFailureException
543
-     * @throws \Hybridauth\Exception\HttpRequestFailedException
544
-     */
545
-    public function apiRequest($url, $method = 'GET', $parameters = [], $headers = [], $multipart = false)
546
-    {
547
-        // refresh tokens if needed
548
-        $this->maintainToken();
549
-
550
-        if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
551
-            $url = rtrim($this->apiBaseUrl, '/') . '/' . ltrim($url, '/');
552
-        }
553
-
554
-        $parameters = array_replace($this->apiRequestParameters, (array)$parameters);
555
-
556
-        $headers = array_replace($this->apiRequestHeaders, (array)$headers);
557
-
558
-        $response = $this->oauthRequest($url, $method, $parameters, $headers, $multipart);
559
-
560
-        $response = (new Data\Parser())->parse($response);
561
-
562
-        return $response;
563
-    }
564
-
565
-    /**
566
-     * Setup and Send a Signed Oauth Request
567
-     *
568
-     * This method uses OAuth Library.
569
-     *
570
-     * @param string $uri
571
-     * @param string $method
572
-     * @param array $parameters
573
-     * @param array $headers
574
-     * @param bool $multipart
575
-     *
576
-     * @return string Raw Provider API response
577
-     * @throws \Hybridauth\Exception\HttpClientFailureException
578
-     * @throws \Hybridauth\Exception\HttpRequestFailedException
579
-     */
580
-    protected function oauthRequest($uri, $method = 'GET', $parameters = [], $headers = [], $multipart = false)
581
-    {
582
-        $signing_parameters = $parameters;
583
-        if ($multipart) {
584
-            $signing_parameters = [];
585
-        }
586
-
587
-        $request = OAuthRequest::from_consumer_and_token(
588
-            $this->OAuthConsumer,
589
-            $this->consumerToken,
590
-            $method,
591
-            $uri,
592
-            $signing_parameters
593
-        );
594
-
595
-        $request->sign_request(
596
-            $this->sha1Method,
597
-            $this->OAuthConsumer,
598
-            $this->consumerToken
599
-        );
600
-
601
-        $uri = $request->get_normalized_http_url();
602
-        $headers = array_replace($request->to_header(), (array)$headers);
603
-
604
-        $response = $this->httpClient->request(
605
-            $uri,
606
-            $method,
607
-            $parameters,
608
-            $headers,
609
-            $multipart
610
-        );
611
-
612
-        $this->validateApiResponse('Signed API request to ' . $uri . ' has returned an error');
613
-
614
-        return $response;
615
-    }
30
+	/**
31
+	 * Base URL to provider API
32
+	 *
33
+	 * This var will be used to build urls when sending signed requests
34
+	 *
35
+	 * @var string
36
+	 */
37
+	protected $apiBaseUrl = '';
38
+
39
+	/**
40
+	 * @var string
41
+	 */
42
+	protected $authorizeUrl = '';
43
+
44
+	/**
45
+	 * @var string
46
+	 */
47
+	protected $requestTokenUrl = '';
48
+
49
+	/**
50
+	 * @var string
51
+	 */
52
+	protected $accessTokenUrl = '';
53
+
54
+	/**
55
+	 * IPD API Documentation
56
+	 *
57
+	 * OPTIONAL.
58
+	 *
59
+	 * @var string
60
+	 */
61
+	protected $apiDocumentation = '';
62
+
63
+	/**
64
+	 * OAuth Version
65
+	 *
66
+	 *  '1.0' OAuth Core 1.0
67
+	 * '1.0a' OAuth Core 1.0 Revision A
68
+	 *
69
+	 * @var string
70
+	 */
71
+	protected $oauth1Version = '1.0a';
72
+
73
+	/**
74
+	 * @var string
75
+	 */
76
+	protected $consumerKey = null;
77
+
78
+	/**
79
+	 * @var string
80
+	 */
81
+	protected $consumerSecret = null;
82
+
83
+	/**
84
+	 * @var object
85
+	 */
86
+	protected $OAuthConsumer = null;
87
+
88
+	/**
89
+	 * @var object
90
+	 */
91
+	protected $sha1Method = null;
92
+
93
+	/**
94
+	 * @var object
95
+	 */
96
+	protected $consumerToken = null;
97
+
98
+	/**
99
+	 * Authorization Url Parameters
100
+	 *
101
+	 * @var bool
102
+	 */
103
+	protected $AuthorizeUrlParameters = [];
104
+
105
+	/**
106
+	 * @var string
107
+	 */
108
+	protected $requestTokenMethod = 'POST';
109
+
110
+	/**
111
+	 * @var array
112
+	 */
113
+	protected $requestTokenParameters = [];
114
+
115
+	/**
116
+	 * @var array
117
+	 */
118
+	protected $requestTokenHeaders = [];
119
+
120
+	/**
121
+	 * @var string
122
+	 */
123
+	protected $tokenExchangeMethod = 'POST';
124
+
125
+	/**
126
+	 * @var array
127
+	 */
128
+	protected $tokenExchangeParameters = [];
129
+
130
+	/**
131
+	 * @var array
132
+	 */
133
+	protected $tokenExchangeHeaders = [];
134
+
135
+	/**
136
+	 * @var array
137
+	 */
138
+	protected $apiRequestParameters = [];
139
+
140
+	/**
141
+	 * @var array
142
+	 */
143
+	protected $apiRequestHeaders = [];
144
+
145
+	/**
146
+	 * {@inheritdoc}
147
+	 */
148
+	protected function configure()
149
+	{
150
+		$this->consumerKey = $this->config->filter('keys')->get('id') ?: $this->config->filter('keys')->get('key');
151
+		$this->consumerSecret = $this->config->filter('keys')->get('secret');
152
+
153
+		if (!$this->consumerKey || !$this->consumerSecret) {
154
+			throw new InvalidApplicationCredentialsException(
155
+				'Your application id is required in order to connect to ' . $this->providerId
156
+			);
157
+		}
158
+
159
+		if ($this->config->exists('tokens')) {
160
+			$this->setAccessToken($this->config->get('tokens'));
161
+		}
162
+
163
+		$this->setCallback($this->config->get('callback'));
164
+		$this->setApiEndpoints($this->config->get('endpoints'));
165
+	}
166
+
167
+	/**
168
+	 * {@inheritdoc}
169
+	 */
170
+	protected function initialize()
171
+	{
172
+		/**
173
+		 * Set up OAuth Signature and Consumer
174
+		 *
175
+		 * OAuth Core: All Token requests and Protected Resources requests MUST be signed
176
+		 * by the Consumer and verified by the Service Provider.
177
+		 *
178
+		 * The protocol defines three signature methods: HMAC-SHA1, RSA-SHA1, and PLAINTEXT..
179
+		 *
180
+		 * The Consumer declares a signature method in the oauth_signature_method parameter..
181
+		 *
182
+		 * http://oauth.net/core/1.0a/#signing_process
183
+		 */
184
+		$this->sha1Method = new OAuthSignatureMethodHMACSHA1();
185
+
186
+		$this->OAuthConsumer = new OAuthConsumer(
187
+			$this->consumerKey,
188
+			$this->consumerSecret
189
+		);
190
+
191
+		if ($this->getStoredData('request_token')) {
192
+			$this->consumerToken = new OAuthConsumer(
193
+				$this->getStoredData('request_token'),
194
+				$this->getStoredData('request_token_secret')
195
+			);
196
+		}
197
+
198
+		if ($this->getStoredData('access_token')) {
199
+			$this->consumerToken = new OAuthConsumer(
200
+				$this->getStoredData('access_token'),
201
+				$this->getStoredData('access_token_secret')
202
+			);
203
+		}
204
+	}
205
+
206
+	/**
207
+	 * {@inheritdoc}
208
+	 */
209
+	public function authenticate()
210
+	{
211
+		$this->logger->info(sprintf('%s::authenticate()', get_class($this)));
212
+
213
+		if ($this->isConnected()) {
214
+			return true;
215
+		}
216
+
217
+		try {
218
+			if (!$this->getStoredData('request_token')) {
219
+				// Start a new flow.
220
+				$this->authenticateBegin();
221
+			} elseif (empty($_GET['oauth_token']) && empty($_GET['denied'])) {
222
+				// A previous authentication was not finished, and this request is not finishing it.
223
+				$this->authenticateBegin();
224
+			} else {
225
+				// Finish a flow.
226
+				$this->authenticateFinish();
227
+			}
228
+		} catch (Exception $exception) {
229
+			$this->clearStoredData();
230
+
231
+			throw $exception;
232
+		}
233
+
234
+		return null;
235
+	}
236
+
237
+	/**
238
+	 * {@inheritdoc}
239
+	 */
240
+	public function isConnected()
241
+	{
242
+		return (bool)$this->getStoredData('access_token');
243
+	}
244
+
245
+	/**
246
+	 * Initiate the authorization protocol
247
+	 *
248
+	 * 1. Obtaining an Unauthorized Request Token
249
+	 * 2. Build Authorization URL for Authorization Request and redirect the user-agent to the
250
+	 *    Authorization Server.
251
+	 */
252
+	protected function authenticateBegin()
253
+	{
254
+		$response = $this->requestAuthToken();
255
+
256
+		$this->validateAuthTokenRequest($response);
257
+
258
+		$authUrl = $this->getAuthorizeUrl();
259
+
260
+		$this->logger->debug(sprintf('%s::authenticateBegin(), redirecting user to:', get_class($this)), [$authUrl]);
261
+
262
+		HttpClient\Util::redirect($authUrl);
263
+	}
264
+
265
+	/**
266
+	 * Finalize the authorization process
267
+	 *
268
+	 * @throws AuthorizationDeniedException
269
+	 * @throws \Hybridauth\Exception\HttpClientFailureException
270
+	 * @throws \Hybridauth\Exception\HttpRequestFailedException
271
+	 * @throws InvalidAccessTokenException
272
+	 * @throws InvalidOauthTokenException
273
+	 */
274
+	protected function authenticateFinish()
275
+	{
276
+		$this->logger->debug(
277
+			sprintf('%s::authenticateFinish(), callback url:', get_class($this)),
278
+			[HttpClient\Util::getCurrentUrl(true)]
279
+		);
280
+
281
+		$denied = filter_input(INPUT_GET, 'denied');
282
+		$oauth_problem = filter_input(INPUT_GET, 'oauth_problem');
283
+		$oauth_token = filter_input(INPUT_GET, 'oauth_token');
284
+		$oauth_verifier = filter_input(INPUT_GET, 'oauth_verifier');
285
+
286
+		if ($denied) {
287
+			throw new AuthorizationDeniedException(
288
+				'User denied access request. Provider returned a denied token: ' . htmlentities($denied)
289
+			);
290
+		}
291
+
292
+		if ($oauth_problem) {
293
+			throw new InvalidOauthTokenException(
294
+				'Provider returned an error. oauth_problem: ' . htmlentities($oauth_problem)
295
+			);
296
+		}
297
+
298
+		if (!$oauth_token) {
299
+			throw new InvalidOauthTokenException(
300
+				'Expecting a non-null oauth_token to continue the authorization flow.'
301
+			);
302
+		}
303
+
304
+		$response = $this->exchangeAuthTokenForAccessToken($oauth_token, $oauth_verifier);
305
+
306
+		$this->validateAccessTokenExchange($response);
307
+
308
+		$this->initialize();
309
+	}
310
+
311
+	/**
312
+	 * Build Authorization URL for Authorization Request
313
+	 *
314
+	 * @param array $parameters
315
+	 *
316
+	 * @return string
317
+	 */
318
+	protected function getAuthorizeUrl($parameters = [])
319
+	{
320
+		$this->AuthorizeUrlParameters = !empty($parameters)
321
+			? $parameters
322
+			: array_replace(
323
+				(array)$this->AuthorizeUrlParameters,
324
+				(array)$this->config->get('authorize_url_parameters')
325
+			);
326
+
327
+		$this->AuthorizeUrlParameters['oauth_token'] = $this->getStoredData('request_token');
328
+
329
+		return $this->authorizeUrl . '?' . http_build_query($this->AuthorizeUrlParameters, '', '&');
330
+	}
331
+
332
+	/**
333
+	 * Unauthorized Request Token
334
+	 *
335
+	 * OAuth Core: The Consumer obtains an unauthorized Request Token by asking the Service Provider
336
+	 * to issue a Token. The Request Token's sole purpose is to receive User approval and can only
337
+	 * be used to obtain an Access Token.
338
+	 *
339
+	 * http://oauth.net/core/1.0/#auth_step1
340
+	 * 6.1.1. Consumer Obtains a Request Token
341
+	 *
342
+	 * @return string Raw Provider API response
343
+	 * @throws \Hybridauth\Exception\HttpClientFailureException
344
+	 * @throws \Hybridauth\Exception\HttpRequestFailedException
345
+	 */
346
+	protected function requestAuthToken()
347
+	{
348
+		/**
349
+		 * OAuth Core 1.0 Revision A: oauth_callback: An absolute URL to which the Service Provider will redirect
350
+		 * the User back when the Obtaining User Authorization step is completed.
351
+		 *
352
+		 * http://oauth.net/core/1.0a/#auth_step1
353
+		 */
354
+		if ('1.0a' == $this->oauth1Version) {
355
+			$this->requestTokenParameters['oauth_callback'] = $this->callback;
356
+		}
357
+
358
+		$response = $this->oauthRequest(
359
+			$this->requestTokenUrl,
360
+			$this->requestTokenMethod,
361
+			$this->requestTokenParameters,
362
+			$this->requestTokenHeaders
363
+		);
364
+
365
+		return $response;
366
+	}
367
+
368
+	/**
369
+	 * Validate Unauthorized Request Token Response
370
+	 *
371
+	 * OAuth Core: The Service Provider verifies the signature and Consumer Key. If successful,
372
+	 * it generates a Request Token and Token Secret and returns them to the Consumer in the HTTP
373
+	 * response body.
374
+	 *
375
+	 * http://oauth.net/core/1.0/#auth_step1
376
+	 * 6.1.2. Service Provider Issues an Unauthorized Request Token
377
+	 *
378
+	 * @param string $response
379
+	 *
380
+	 * @return \Hybridauth\Data\Collection
381
+	 * @throws InvalidOauthTokenException
382
+	 */
383
+	protected function validateAuthTokenRequest($response)
384
+	{
385
+		/**
386
+		 * The response contains the following parameters:
387
+		 *
388
+		 *    - oauth_token               The Request Token.
389
+		 *    - oauth_token_secret        The Token Secret.
390
+		 *    - oauth_callback_confirmed  MUST be present and set to true.
391
+		 *
392
+		 * http://oauth.net/core/1.0/#auth_step1
393
+		 * 6.1.2. Service Provider Issues an Unauthorized Request Token
394
+		 *
395
+		 * Example of a successful response:
396
+		 *
397
+		 *  HTTP/1.1 200 OK
398
+		 *  Content-Type: text/html; charset=utf-8
399
+		 *  Cache-Control: no-store
400
+		 *  Pragma: no-cache
401
+		 *
402
+		 *  oauth_token=80359084-clg1DEtxQF3wstTcyUdHF3wsdHM&oauth_token_secret=OIF07hPmJB:P
403
+		 *  6qiHTi1znz6qiH3tTcyUdHnz6qiH3tTcyUdH3xW3wsDvV08e&example_parameter=example_value
404
+		 *
405
+		 * OAuthUtil::parse_parameters will attempt to decode the raw response into an array.
406
+		 */
407
+		$tokens = OAuthUtil::parse_parameters($response);
408
+
409
+		$collection = new Data\Collection($tokens);
410
+
411
+		if (!$collection->exists('oauth_token')) {
412
+			throw new InvalidOauthTokenException(
413
+				'Provider returned no oauth_token: ' . htmlentities($response)
414
+			);
415
+		}
416
+
417
+		$this->consumerToken = new OAuthConsumer(
418
+			$tokens['oauth_token'],
419
+			$tokens['oauth_token_secret']
420
+		);
421
+
422
+		$this->storeData('request_token', $tokens['oauth_token']);
423
+		$this->storeData('request_token_secret', $tokens['oauth_token_secret']);
424
+
425
+		return $collection;
426
+	}
427
+
428
+	/**
429
+	 * Requests an Access Token
430
+	 *
431
+	 * OAuth Core: The Request Token and Token Secret MUST be exchanged for an Access Token and Token Secret.
432
+	 *
433
+	 * http://oauth.net/core/1.0a/#auth_step3
434
+	 * 6.3.1. Consumer Requests an Access Token
435
+	 *
436
+	 * @param string $oauth_token
437
+	 * @param string $oauth_verifier
438
+	 *
439
+	 * @return string Raw Provider API response
440
+	 * @throws \Hybridauth\Exception\HttpClientFailureException
441
+	 * @throws \Hybridauth\Exception\HttpRequestFailedException
442
+	 */
443
+	protected function exchangeAuthTokenForAccessToken($oauth_token, $oauth_verifier = '')
444
+	{
445
+		$this->tokenExchangeParameters['oauth_token'] = $oauth_token;
446
+
447
+		/**
448
+		 * OAuth Core 1.0 Revision A: oauth_verifier: The verification code received from the Service Provider
449
+		 * in the "Service Provider Directs the User Back to the Consumer" step.
450
+		 *
451
+		 * http://oauth.net/core/1.0a/#auth_step3
452
+		 */
453
+		if ('1.0a' == $this->oauth1Version) {
454
+			$this->tokenExchangeParameters['oauth_verifier'] = $oauth_verifier;
455
+		}
456
+
457
+		$response = $this->oauthRequest(
458
+			$this->accessTokenUrl,
459
+			$this->tokenExchangeMethod,
460
+			$this->tokenExchangeParameters,
461
+			$this->tokenExchangeHeaders
462
+		);
463
+
464
+		return $response;
465
+	}
466
+
467
+	/**
468
+	 * Validate Access Token Response
469
+	 *
470
+	 * OAuth Core: If successful, the Service Provider generates an Access Token and Token Secret and returns
471
+	 * them in the HTTP response body.
472
+	 *
473
+	 * The Access Token and Token Secret are stored by the Consumer and used when signing Protected Resources requests.
474
+	 *
475
+	 * http://oauth.net/core/1.0a/#auth_step3
476
+	 * 6.3.2. Service Provider Grants an Access Token
477
+	 *
478
+	 * @param string $response
479
+	 *
480
+	 * @return \Hybridauth\Data\Collection
481
+	 * @throws InvalidAccessTokenException
482
+	 */
483
+	protected function validateAccessTokenExchange($response)
484
+	{
485
+		/**
486
+		 * The response contains the following parameters:
487
+		 *
488
+		 *    - oauth_token         The Access Token.
489
+		 *    - oauth_token_secret  The Token Secret.
490
+		 *
491
+		 * http://oauth.net/core/1.0/#auth_step3
492
+		 * 6.3.2. Service Provider Grants an Access Token
493
+		 *
494
+		 * Example of a successful response:
495
+		 *
496
+		 *  HTTP/1.1 200 OK
497
+		 *  Content-Type: text/html; charset=utf-8
498
+		 *  Cache-Control: no-store
499
+		 *  Pragma: no-cache
500
+		 *
501
+		 *  oauth_token=sHeLU7Far428zj8PzlWR75&oauth_token_secret=fXb30rzoG&oauth_callback_confirmed=true
502
+		 *
503
+		 * OAuthUtil::parse_parameters will attempt to decode the raw response into an array.
504
+		 */
505
+		$tokens = OAuthUtil::parse_parameters($response);
506
+
507
+		$collection = new Data\Collection($tokens);
508
+
509
+		if (!$collection->exists('oauth_token')) {
510
+			throw new InvalidAccessTokenException(
511
+				'Provider returned no access_token: ' . htmlentities($response)
512
+			);
513
+		}
514
+
515
+		$this->consumerToken = new OAuthConsumer(
516
+			$collection->get('oauth_token'),
517
+			$collection->get('oauth_token_secret')
518
+		);
519
+
520
+		$this->storeData('access_token', $collection->get('oauth_token'));
521
+		$this->storeData('access_token_secret', $collection->get('oauth_token_secret'));
522
+
523
+		$this->deleteStoredData('request_token');
524
+		$this->deleteStoredData('request_token_secret');
525
+
526
+		return $collection;
527
+	}
528
+
529
+	/**
530
+	 * Send a signed request to provider API
531
+	 *
532
+	 * Note: Since the specifics of error responses is beyond the scope of RFC6749 and OAuth specifications,
533
+	 * Hybridauth will consider any HTTP status code that is different than '200 OK' as an ERROR.
534
+	 *
535
+	 * @param string $url
536
+	 * @param string $method
537
+	 * @param array $parameters
538
+	 * @param array $headers
539
+	 * @param bool $multipart
540
+	 *
541
+	 * @return mixed
542
+	 * @throws \Hybridauth\Exception\HttpClientFailureException
543
+	 * @throws \Hybridauth\Exception\HttpRequestFailedException
544
+	 */
545
+	public function apiRequest($url, $method = 'GET', $parameters = [], $headers = [], $multipart = false)
546
+	{
547
+		// refresh tokens if needed
548
+		$this->maintainToken();
549
+
550
+		if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
551
+			$url = rtrim($this->apiBaseUrl, '/') . '/' . ltrim($url, '/');
552
+		}
553
+
554
+		$parameters = array_replace($this->apiRequestParameters, (array)$parameters);
555
+
556
+		$headers = array_replace($this->apiRequestHeaders, (array)$headers);
557
+
558
+		$response = $this->oauthRequest($url, $method, $parameters, $headers, $multipart);
559
+
560
+		$response = (new Data\Parser())->parse($response);
561
+
562
+		return $response;
563
+	}
564
+
565
+	/**
566
+	 * Setup and Send a Signed Oauth Request
567
+	 *
568
+	 * This method uses OAuth Library.
569
+	 *
570
+	 * @param string $uri
571
+	 * @param string $method
572
+	 * @param array $parameters
573
+	 * @param array $headers
574
+	 * @param bool $multipart
575
+	 *
576
+	 * @return string Raw Provider API response
577
+	 * @throws \Hybridauth\Exception\HttpClientFailureException
578
+	 * @throws \Hybridauth\Exception\HttpRequestFailedException
579
+	 */
580
+	protected function oauthRequest($uri, $method = 'GET', $parameters = [], $headers = [], $multipart = false)
581
+	{
582
+		$signing_parameters = $parameters;
583
+		if ($multipart) {
584
+			$signing_parameters = [];
585
+		}
586
+
587
+		$request = OAuthRequest::from_consumer_and_token(
588
+			$this->OAuthConsumer,
589
+			$this->consumerToken,
590
+			$method,
591
+			$uri,
592
+			$signing_parameters
593
+		);
594
+
595
+		$request->sign_request(
596
+			$this->sha1Method,
597
+			$this->OAuthConsumer,
598
+			$this->consumerToken
599
+		);
600
+
601
+		$uri = $request->get_normalized_http_url();
602
+		$headers = array_replace($request->to_header(), (array)$headers);
603
+
604
+		$response = $this->httpClient->request(
605
+			$uri,
606
+			$method,
607
+			$parameters,
608
+			$headers,
609
+			$multipart
610
+		);
611
+
612
+		$this->validateApiResponse('Signed API request to ' . $uri . ' has returned an error');
613
+
614
+		return $response;
615
+	}
616 616
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -150,9 +150,9 @@  discard block
 block discarded – undo
150 150
         $this->consumerKey = $this->config->filter('keys')->get('id') ?: $this->config->filter('keys')->get('key');
151 151
         $this->consumerSecret = $this->config->filter('keys')->get('secret');
152 152
 
153
-        if (!$this->consumerKey || !$this->consumerSecret) {
153
+        if ( ! $this->consumerKey || ! $this->consumerSecret) {
154 154
             throw new InvalidApplicationCredentialsException(
155
-                'Your application id is required in order to connect to ' . $this->providerId
155
+                'Your application id is required in order to connect to '.$this->providerId
156 156
             );
157 157
         }
158 158
 
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
         }
216 216
 
217 217
         try {
218
-            if (!$this->getStoredData('request_token')) {
218
+            if ( ! $this->getStoredData('request_token')) {
219 219
                 // Start a new flow.
220 220
                 $this->authenticateBegin();
221 221
             } elseif (empty($_GET['oauth_token']) && empty($_GET['denied'])) {
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
      */
240 240
     public function isConnected()
241 241
     {
242
-        return (bool)$this->getStoredData('access_token');
242
+        return (bool) $this->getStoredData('access_token');
243 243
     }
244 244
 
245 245
     /**
@@ -285,17 +285,17 @@  discard block
 block discarded – undo
285 285
 
286 286
         if ($denied) {
287 287
             throw new AuthorizationDeniedException(
288
-                'User denied access request. Provider returned a denied token: ' . htmlentities($denied)
288
+                'User denied access request. Provider returned a denied token: '.htmlentities($denied)
289 289
             );
290 290
         }
291 291
 
292 292
         if ($oauth_problem) {
293 293
             throw new InvalidOauthTokenException(
294
-                'Provider returned an error. oauth_problem: ' . htmlentities($oauth_problem)
294
+                'Provider returned an error. oauth_problem: '.htmlentities($oauth_problem)
295 295
             );
296 296
         }
297 297
 
298
-        if (!$oauth_token) {
298
+        if ( ! $oauth_token) {
299 299
             throw new InvalidOauthTokenException(
300 300
                 'Expecting a non-null oauth_token to continue the authorization flow.'
301 301
             );
@@ -317,16 +317,16 @@  discard block
 block discarded – undo
317 317
      */
318 318
     protected function getAuthorizeUrl($parameters = [])
319 319
     {
320
-        $this->AuthorizeUrlParameters = !empty($parameters)
320
+        $this->AuthorizeUrlParameters = ! empty($parameters)
321 321
             ? $parameters
322 322
             : array_replace(
323
-                (array)$this->AuthorizeUrlParameters,
324
-                (array)$this->config->get('authorize_url_parameters')
323
+                (array) $this->AuthorizeUrlParameters,
324
+                (array) $this->config->get('authorize_url_parameters')
325 325
             );
326 326
 
327 327
         $this->AuthorizeUrlParameters['oauth_token'] = $this->getStoredData('request_token');
328 328
 
329
-        return $this->authorizeUrl . '?' . http_build_query($this->AuthorizeUrlParameters, '', '&');
329
+        return $this->authorizeUrl.'?'.http_build_query($this->AuthorizeUrlParameters, '', '&');
330 330
     }
331 331
 
332 332
     /**
@@ -408,9 +408,9 @@  discard block
 block discarded – undo
408 408
 
409 409
         $collection = new Data\Collection($tokens);
410 410
 
411
-        if (!$collection->exists('oauth_token')) {
411
+        if ( ! $collection->exists('oauth_token')) {
412 412
             throw new InvalidOauthTokenException(
413
-                'Provider returned no oauth_token: ' . htmlentities($response)
413
+                'Provider returned no oauth_token: '.htmlentities($response)
414 414
             );
415 415
         }
416 416
 
@@ -506,9 +506,9 @@  discard block
 block discarded – undo
506 506
 
507 507
         $collection = new Data\Collection($tokens);
508 508
 
509
-        if (!$collection->exists('oauth_token')) {
509
+        if ( ! $collection->exists('oauth_token')) {
510 510
             throw new InvalidAccessTokenException(
511
-                'Provider returned no access_token: ' . htmlentities($response)
511
+                'Provider returned no access_token: '.htmlentities($response)
512 512
             );
513 513
         }
514 514
 
@@ -548,12 +548,12 @@  discard block
 block discarded – undo
548 548
         $this->maintainToken();
549 549
 
550 550
         if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
551
-            $url = rtrim($this->apiBaseUrl, '/') . '/' . ltrim($url, '/');
551
+            $url = rtrim($this->apiBaseUrl, '/').'/'.ltrim($url, '/');
552 552
         }
553 553
 
554
-        $parameters = array_replace($this->apiRequestParameters, (array)$parameters);
554
+        $parameters = array_replace($this->apiRequestParameters, (array) $parameters);
555 555
 
556
-        $headers = array_replace($this->apiRequestHeaders, (array)$headers);
556
+        $headers = array_replace($this->apiRequestHeaders, (array) $headers);
557 557
 
558 558
         $response = $this->oauthRequest($url, $method, $parameters, $headers, $multipart);
559 559
 
@@ -599,7 +599,7 @@  discard block
 block discarded – undo
599 599
         );
600 600
 
601 601
         $uri = $request->get_normalized_http_url();
602
-        $headers = array_replace($request->to_header(), (array)$headers);
602
+        $headers = array_replace($request->to_header(), (array) $headers);
603 603
 
604 604
         $response = $this->httpClient->request(
605 605
             $uri,
@@ -609,7 +609,7 @@  discard block
 block discarded – undo
609 609
             $multipart
610 610
         );
611 611
 
612
-        $this->validateApiResponse('Signed API request to ' . $uri . ' has returned an error');
612
+        $this->validateApiResponse('Signed API request to '.$uri.' has returned an error');
613 613
 
614 614
         return $response;
615 615
     }
Please login to merge, or discard this patch.
src/Provider/Patreon.php 2 patches
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -18,177 +18,177 @@
 block discarded – undo
18 18
  */
19 19
 class Patreon extends OAuth2
20 20
 {
21
-    /**
22
-     * {@inheritdoc}
23
-     */
24
-    protected $scope = 'identity identity[email]';
25
-
26
-    /**
27
-     * {@inheritdoc}
28
-     */
29
-    protected $apiBaseUrl = 'https://www.patreon.com/api';
30
-
31
-    /**
32
-     * {@inheritdoc}
33
-     */
34
-    protected $authorizeUrl = 'https://www.patreon.com/oauth2/authorize';
35
-
36
-    /**
37
-     * {@inheritdoc}
38
-     */
39
-    protected $accessTokenUrl = 'https://www.patreon.com/api/oauth2/token';
40
-
41
-    /**
42
-     * {@inheritdoc}
43
-     */
44
-    protected $apiDocumentation = 'https://docs.patreon.com/#oauth';
45
-
46
-    /**
47
-     * {@inheritdoc}
48
-     */
49
-    protected function initialize()
50
-    {
51
-        parent::initialize();
52
-
53
-        if ($this->isRefreshTokenAvailable()) {
54
-            $this->tokenRefreshParameters += [
55
-                'client_id' => $this->clientId,
56
-                'client_secret' => $this->clientSecret,
57
-            ];
58
-        }
59
-    }
60
-
61
-    /**
62
-     * {@inheritdoc}
63
-     */
64
-    public function getUserProfile()
65
-    {
66
-        $response = $this->apiRequest('oauth2/v2/identity', 'GET', [
67
-            'fields[user]' => 'created,first_name,last_name,email,full_name,is_email_verified,thumb_url,url',
68
-        ]);
69
-
70
-        $collection = new Collection($response);
71
-        if (!$collection->exists('data')) {
72
-            throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
73
-        }
74
-
75
-        $userProfile = new Profile();
76
-
77
-        $data = $collection->filter('data');
78
-        $attributes = $data->filter('attributes');
79
-
80
-        $userProfile->identifier = $data->get('id');
81
-        $userProfile->email = $attributes->get('email');
82
-        $userProfile->firstName = $attributes->get('first_name');
83
-        $userProfile->lastName = $attributes->get('last_name');
84
-        $userProfile->displayName = $attributes->get('full_name') ?: $data->get('id');
85
-        $userProfile->photoURL = $attributes->get('thumb_url');
86
-        $userProfile->profileURL = $attributes->get('url');
87
-
88
-        $userProfile->emailVerified = $attributes->get('is_email_verified') ? $userProfile->email : '';
89
-
90
-        return $userProfile;
91
-    }
92
-
93
-    /**
94
-     * Contacts are defined as Patrons here
95
-     */
96
-    public function getUserContacts()
97
-    {
98
-        $campaignId = $this->config->get('campaign_id') ?: null;
99
-        $tierFilter = $this->config->get('tier_filter') ?: null;
100
-
101
-        $campaigns = [];
102
-        if ($campaignId === null) {
103
-            $campaignsUrl = 'oauth2/v2/campaigns';
104
-            do {
105
-                $response = $this->apiRequest($campaignsUrl);
106
-                $data = new Collection($response);
107
-
108
-                if (!$data->exists('data')) {
109
-                    throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
110
-                }
111
-
112
-                foreach ($data->filter('data')->toArray() as $item) {
113
-                    $campaign = new Collection($item);
114
-                    $campaigns[] = $campaign->get('id');
115
-                }
116
-
117
-                if ($data->filter('links')->exists('next')) {
118
-                    $campaignsUrl = $data->filter('links')->get('next');
119
-
120
-                    $pagedList = true;
121
-                } else {
122
-                    $pagedList = false;
123
-                }
124
-            } while ($pagedList);
125
-        } else {
126
-            $campaigns[] = $campaignId;
127
-        }
128
-
129
-        $contacts = [];
130
-
131
-        foreach ($campaigns as $campaignId) {
132
-            $params = [
133
-                'include' => 'currently_entitled_tiers',
134
-                'fields[member]' => 'full_name,patron_status,email',
135
-                'fields[tier]' => 'title',
136
-            ];
137
-            $membersUrl = 'oauth2/v2/campaigns/' . $campaignId . '/members?' . http_build_query($params);
138
-
139
-            do {
140
-                $response = $this->apiRequest($membersUrl);
141
-
142
-                $data = new Collection($response);
143
-
144
-                if (!$data->exists('data')) {
145
-                    throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
146
-                }
147
-
148
-                $tierTitles = [];
149
-
150
-                foreach ($data->filter('included')->toArray() as $item) {
151
-                    $includedItem = new Collection($item);
152
-                    if ($includedItem->get('type') == 'tier') {
153
-                        $tierTitles[$includedItem->get('id')] = $includedItem->filter('attributes')->get('title');
154
-                    }
155
-                }
156
-
157
-                foreach ($data->filter('data')->toArray() as $item) {
158
-                    $member = new Collection($item);
159
-
160
-                    if ($member->filter('attributes')->get('patron_status') == 'active_patron') {
161
-                        $tiers = [];
162
-                        $tierObs = $member->filter('relationships')->filter('currently_entitled_tiers')->get('data');
163
-                        foreach ($tierObs as $item) {
164
-                            $tier = new Collection($item);
165
-                            $tierId = $tier->get('id');
166
-                            $tiers[] = $tierTitles[$tierId];
167
-                        }
168
-
169
-                        if (($tierFilter === null) || (in_array($tierFilter, $tiers))) {
170
-                            $userContact = new User\Contact();
171
-
172
-                            $userContact->identifier = $member->get('id');
173
-                            $userContact->email = $member->filter('attributes')->get('email');
174
-                            $userContact->displayName = $member->filter('attributes')->get('full_name');
175
-                            $userContact->description = json_encode($tiers);
176
-
177
-                            $contacts[] = $userContact;
178
-                        }
179
-                    }
180
-                }
181
-
182
-                if ($data->filter('links')->exists('next')) {
183
-                    $membersUrl = $data->filter('links')->get('next');
184
-
185
-                    $pagedList = true;
186
-                } else {
187
-                    $pagedList = false;
188
-                }
189
-            } while ($pagedList);
190
-        }
191
-
192
-        return $contacts;
193
-    }
21
+	/**
22
+	 * {@inheritdoc}
23
+	 */
24
+	protected $scope = 'identity identity[email]';
25
+
26
+	/**
27
+	 * {@inheritdoc}
28
+	 */
29
+	protected $apiBaseUrl = 'https://www.patreon.com/api';
30
+
31
+	/**
32
+	 * {@inheritdoc}
33
+	 */
34
+	protected $authorizeUrl = 'https://www.patreon.com/oauth2/authorize';
35
+
36
+	/**
37
+	 * {@inheritdoc}
38
+	 */
39
+	protected $accessTokenUrl = 'https://www.patreon.com/api/oauth2/token';
40
+
41
+	/**
42
+	 * {@inheritdoc}
43
+	 */
44
+	protected $apiDocumentation = 'https://docs.patreon.com/#oauth';
45
+
46
+	/**
47
+	 * {@inheritdoc}
48
+	 */
49
+	protected function initialize()
50
+	{
51
+		parent::initialize();
52
+
53
+		if ($this->isRefreshTokenAvailable()) {
54
+			$this->tokenRefreshParameters += [
55
+				'client_id' => $this->clientId,
56
+				'client_secret' => $this->clientSecret,
57
+			];
58
+		}
59
+	}
60
+
61
+	/**
62
+	 * {@inheritdoc}
63
+	 */
64
+	public function getUserProfile()
65
+	{
66
+		$response = $this->apiRequest('oauth2/v2/identity', 'GET', [
67
+			'fields[user]' => 'created,first_name,last_name,email,full_name,is_email_verified,thumb_url,url',
68
+		]);
69
+
70
+		$collection = new Collection($response);
71
+		if (!$collection->exists('data')) {
72
+			throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
73
+		}
74
+
75
+		$userProfile = new Profile();
76
+
77
+		$data = $collection->filter('data');
78
+		$attributes = $data->filter('attributes');
79
+
80
+		$userProfile->identifier = $data->get('id');
81
+		$userProfile->email = $attributes->get('email');
82
+		$userProfile->firstName = $attributes->get('first_name');
83
+		$userProfile->lastName = $attributes->get('last_name');
84
+		$userProfile->displayName = $attributes->get('full_name') ?: $data->get('id');
85
+		$userProfile->photoURL = $attributes->get('thumb_url');
86
+		$userProfile->profileURL = $attributes->get('url');
87
+
88
+		$userProfile->emailVerified = $attributes->get('is_email_verified') ? $userProfile->email : '';
89
+
90
+		return $userProfile;
91
+	}
92
+
93
+	/**
94
+	 * Contacts are defined as Patrons here
95
+	 */
96
+	public function getUserContacts()
97
+	{
98
+		$campaignId = $this->config->get('campaign_id') ?: null;
99
+		$tierFilter = $this->config->get('tier_filter') ?: null;
100
+
101
+		$campaigns = [];
102
+		if ($campaignId === null) {
103
+			$campaignsUrl = 'oauth2/v2/campaigns';
104
+			do {
105
+				$response = $this->apiRequest($campaignsUrl);
106
+				$data = new Collection($response);
107
+
108
+				if (!$data->exists('data')) {
109
+					throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
110
+				}
111
+
112
+				foreach ($data->filter('data')->toArray() as $item) {
113
+					$campaign = new Collection($item);
114
+					$campaigns[] = $campaign->get('id');
115
+				}
116
+
117
+				if ($data->filter('links')->exists('next')) {
118
+					$campaignsUrl = $data->filter('links')->get('next');
119
+
120
+					$pagedList = true;
121
+				} else {
122
+					$pagedList = false;
123
+				}
124
+			} while ($pagedList);
125
+		} else {
126
+			$campaigns[] = $campaignId;
127
+		}
128
+
129
+		$contacts = [];
130
+
131
+		foreach ($campaigns as $campaignId) {
132
+			$params = [
133
+				'include' => 'currently_entitled_tiers',
134
+				'fields[member]' => 'full_name,patron_status,email',
135
+				'fields[tier]' => 'title',
136
+			];
137
+			$membersUrl = 'oauth2/v2/campaigns/' . $campaignId . '/members?' . http_build_query($params);
138
+
139
+			do {
140
+				$response = $this->apiRequest($membersUrl);
141
+
142
+				$data = new Collection($response);
143
+
144
+				if (!$data->exists('data')) {
145
+					throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
146
+				}
147
+
148
+				$tierTitles = [];
149
+
150
+				foreach ($data->filter('included')->toArray() as $item) {
151
+					$includedItem = new Collection($item);
152
+					if ($includedItem->get('type') == 'tier') {
153
+						$tierTitles[$includedItem->get('id')] = $includedItem->filter('attributes')->get('title');
154
+					}
155
+				}
156
+
157
+				foreach ($data->filter('data')->toArray() as $item) {
158
+					$member = new Collection($item);
159
+
160
+					if ($member->filter('attributes')->get('patron_status') == 'active_patron') {
161
+						$tiers = [];
162
+						$tierObs = $member->filter('relationships')->filter('currently_entitled_tiers')->get('data');
163
+						foreach ($tierObs as $item) {
164
+							$tier = new Collection($item);
165
+							$tierId = $tier->get('id');
166
+							$tiers[] = $tierTitles[$tierId];
167
+						}
168
+
169
+						if (($tierFilter === null) || (in_array($tierFilter, $tiers))) {
170
+							$userContact = new User\Contact();
171
+
172
+							$userContact->identifier = $member->get('id');
173
+							$userContact->email = $member->filter('attributes')->get('email');
174
+							$userContact->displayName = $member->filter('attributes')->get('full_name');
175
+							$userContact->description = json_encode($tiers);
176
+
177
+							$contacts[] = $userContact;
178
+						}
179
+					}
180
+				}
181
+
182
+				if ($data->filter('links')->exists('next')) {
183
+					$membersUrl = $data->filter('links')->get('next');
184
+
185
+					$pagedList = true;
186
+				} else {
187
+					$pagedList = false;
188
+				}
189
+			} while ($pagedList);
190
+		}
191
+
192
+		return $contacts;
193
+	}
194 194
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
         ]);
69 69
 
70 70
         $collection = new Collection($response);
71
-        if (!$collection->exists('data')) {
71
+        if ( ! $collection->exists('data')) {
72 72
             throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
73 73
         }
74 74
 
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
                 $response = $this->apiRequest($campaignsUrl);
106 106
                 $data = new Collection($response);
107 107
 
108
-                if (!$data->exists('data')) {
108
+                if ( ! $data->exists('data')) {
109 109
                     throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
110 110
                 }
111 111
 
@@ -134,14 +134,14 @@  discard block
 block discarded – undo
134 134
                 'fields[member]' => 'full_name,patron_status,email',
135 135
                 'fields[tier]' => 'title',
136 136
             ];
137
-            $membersUrl = 'oauth2/v2/campaigns/' . $campaignId . '/members?' . http_build_query($params);
137
+            $membersUrl = 'oauth2/v2/campaigns/'.$campaignId.'/members?'.http_build_query($params);
138 138
 
139 139
             do {
140 140
                 $response = $this->apiRequest($membersUrl);
141 141
 
142 142
                 $data = new Collection($response);
143 143
 
144
-                if (!$data->exists('data')) {
144
+                if ( ! $data->exists('data')) {
145 145
                     throw new UnexpectedApiResponseException('Provider API returned an unexpected response.');
146 146
                 }
147 147
 
Please login to merge, or discard this patch.
src/Provider/AutoDesk.php 2 patches
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -17,80 +17,80 @@
 block discarded – undo
17 17
  */
18 18
 class AutoDesk extends OAuth2
19 19
 {
20
-    /**
21
-     * {@inheritdoc}
22
-     */
23
-    protected $scope = 'data:read';
20
+	/**
21
+	 * {@inheritdoc}
22
+	 */
23
+	protected $scope = 'data:read';
24 24
 
25
-    /**
26
-     * {@inheritdoc}
27
-     */
28
-    protected $apiBaseUrl = 'https://developer.api.autodesk.com/';
25
+	/**
26
+	 * {@inheritdoc}
27
+	 */
28
+	protected $apiBaseUrl = 'https://developer.api.autodesk.com/';
29 29
 
30
-    /**
31
-     * {@inheritdoc}
32
-     */
33
-    protected $authorizeUrl
34
-        = 'https://developer.api.autodesk.com/authentication/v1/authorize';
30
+	/**
31
+	 * {@inheritdoc}
32
+	 */
33
+	protected $authorizeUrl
34
+		= 'https://developer.api.autodesk.com/authentication/v1/authorize';
35 35
 
36
-    /**
37
-     * {@inheritdoc}
38
-     */
39
-    protected $accessTokenUrl
40
-        = 'https://developer.api.autodesk.com/authentication/v1/gettoken';
36
+	/**
37
+	 * {@inheritdoc}
38
+	 */
39
+	protected $accessTokenUrl
40
+		= 'https://developer.api.autodesk.com/authentication/v1/gettoken';
41 41
 
42
-    /**
43
-     * {@inheritdoc}
44
-     */
45
-    protected $refreshTokenUrl
46
-        = 'https://developer.api.autodesk.com/authentication/v1/refreshtoken';
42
+	/**
43
+	 * {@inheritdoc}
44
+	 */
45
+	protected $refreshTokenUrl
46
+		= 'https://developer.api.autodesk.com/authentication/v1/refreshtoken';
47 47
 
48
-    /**
49
-     * {@inheritdoc}
50
-     */
51
-    protected $apiDocumentation
52
-        = 'https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/overview/';
48
+	/**
49
+	 * {@inheritdoc}
50
+	 */
51
+	protected $apiDocumentation
52
+		= 'https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/overview/';
53 53
 
54
-    /**
55
-     * {@inheritdoc}
56
-     */
57
-    protected function initialize()
58
-    {
59
-        parent::initialize();
54
+	/**
55
+	 * {@inheritdoc}
56
+	 */
57
+	protected function initialize()
58
+	{
59
+		parent::initialize();
60 60
         
61
-        if ($this->isRefreshTokenAvailable()) {
62
-            $this->tokenRefreshParameters += [
63
-                'client_id'     => $this->clientId,
64
-                'client_secret' => $this->clientSecret,
65
-                'grant_type'    => 'refresh_token',
66
-            ];
67
-        }
68
-    }
61
+		if ($this->isRefreshTokenAvailable()) {
62
+			$this->tokenRefreshParameters += [
63
+				'client_id'     => $this->clientId,
64
+				'client_secret' => $this->clientSecret,
65
+				'grant_type'    => 'refresh_token',
66
+			];
67
+		}
68
+	}
69 69
 
70
-    /**
71
-     * {@inheritdoc}
72
-     *
73
-     * See: https://forge.autodesk.com/en/docs/oauth/v2/reference/http/users-@me-GET/
74
-     */
75
-    public function getUserProfile()
76
-    {
77
-        $response = $this->apiRequest('userprofile/v1/users/@me');
70
+	/**
71
+	 * {@inheritdoc}
72
+	 *
73
+	 * See: https://forge.autodesk.com/en/docs/oauth/v2/reference/http/users-@me-GET/
74
+	 */
75
+	public function getUserProfile()
76
+	{
77
+		$response = $this->apiRequest('userprofile/v1/users/@me');
78 78
 
79
-        $collection = new Data\Collection($response);
79
+		$collection = new Data\Collection($response);
80 80
 
81
-        $userProfile = new User\Profile();
81
+		$userProfile = new User\Profile();
82 82
 
83
-        $userProfile->identifier = $collection->get('userId');
84
-        $userProfile->displayName
85
-            = $collection->get('firstName') .' '. $collection->get('lastName');
86
-        $userProfile->firstName = $collection->get('firstName');
87
-        $userProfile->lastName = $collection->get('lastName');
88
-        $userProfile->email = $collection->get('emailId');
89
-        $userProfile->language = $collection->get('language');
90
-        $userProfile->webSiteURL = $collection->get('websiteUrl');
91
-        $userProfile->photoURL
92
-            = $collection->filter('profileImages')->get('sizeX360');
83
+		$userProfile->identifier = $collection->get('userId');
84
+		$userProfile->displayName
85
+			= $collection->get('firstName') .' '. $collection->get('lastName');
86
+		$userProfile->firstName = $collection->get('firstName');
87
+		$userProfile->lastName = $collection->get('lastName');
88
+		$userProfile->email = $collection->get('emailId');
89
+		$userProfile->language = $collection->get('language');
90
+		$userProfile->webSiteURL = $collection->get('websiteUrl');
91
+		$userProfile->photoURL
92
+			= $collection->filter('profileImages')->get('sizeX360');
93 93
 
94
-        return $userProfile;
95
-    }
94
+		return $userProfile;
95
+	}
96 96
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@
 block discarded – undo
82 82
 
83 83
         $userProfile->identifier = $collection->get('userId');
84 84
         $userProfile->displayName
85
-            = $collection->get('firstName') .' '. $collection->get('lastName');
85
+            = $collection->get('firstName').' '.$collection->get('lastName');
86 86
         $userProfile->firstName = $collection->get('firstName');
87 87
         $userProfile->lastName = $collection->get('lastName');
88 88
         $userProfile->email = $collection->get('emailId');
Please login to merge, or discard this patch.