Completed
Pull Request — master (#7)
by
unknown
01:27
created

Xero::getRedirectOnError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Invoiced\OAuth1\Client\Server;
4
5
use Exception;
6
use InvalidArgumentException;
7
use League\OAuth1\Client\Server\Server;
8
use GuzzleHttp\Client as GuzzleHttpClient;
9
use GuzzleHttp\Exception\BadResponseException;
10
use League\OAuth1\Client\Credentials\TokenCredentials;
11
use League\OAuth1\Client\Signature\SignatureInterface;
12
use League\OAuth1\Client\Credentials\ClientCredentials;
13
14
class Xero extends Server
15
{
16
    /**
17
     * @var string
18
     */
19
    protected $responseType = 'xml';
20
21
    /**
22
     * @var array
23
     */
24
    protected $httpClientOptions = [];
25
26
    /**
27
     * @var array
28
     */
29
    protected $lastTokenCredentialsResponse;
30
31
    /**
32
     * @var array
33
     */
34
    protected $scope = [];
35
36
    /**
37
     * @var bool
38
     */
39
    protected $redirectOnError = false;
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function __construct($clientCredentials, SignatureInterface $signature = null)
45
    {
46
        if (is_array($clientCredentials)) {
47
            $this->parseConfiguration($clientCredentials);
48
49
            $clientCredentials = $this->createClientCredentials($clientCredentials);
50
51
            if (!$signature && $clientCredentials instanceof RsaClientCredentials) {
52
                $signature = new RsaSha1Signature($clientCredentials);
53
            }
54
        }
55
56
        parent::__construct($clientCredentials, $signature);
57
    }
58
59
    /**
60
     * Sets the value of the scope parameter used during authorization.
61
     *
62
     * @param array $scope Enumerated array where each element is a string
63
     *                     containing a single privilege value (e.g. 'payroll.employees')
64
     */
65
    public function setScope(array $scope)
66
    {
67
        $this->scope = $scope;
68
    }
69
70
    /**
71
     * Sets the redirect on error parameter used during authorization.
72
     *
73
     * @param boolean $redirect Boolean to toggle this parameter.
74
     * @return void
75
     */
76
    public function setRedirectOnError(bool $redirect)
77
    {
78
        $this->redirectOnError = $redirect;
79
    }
80
81
    /**
82
     * Gets the current setting for redirect on error.
83
     *
84
     * @return boolean
85
     */
86
    public function getRedirectOnError()
87
    {
88
        return $this->redirectOnError;
89
    }
90
91
    /**
92
     * Creates a Guzzle HTTP client for the given URL.
93
     *
94
     * @return GuzzleHttpClient
95
     */
96
    public function createHttpClient()
97
    {
98
        return new GuzzleHttpClient($this->httpClientOptions);
99
    }
100
101
    public function urlTemporaryCredentials()
102
    {
103
        return 'https://api.xero.com/oauth/RequestToken';
104
    }
105
106
    public function urlAuthorization()
107
    {
108
        return 'https://api.xero.com/oauth/Authorize'
109
            . $this->buildUrlAuthorizationQueryString();
110
    }
111
112
    /**
113
     * @return string
114
     */
115
    protected function buildUrlAuthorizationQueryString()
116
    {
117
        if (!$this->scope && !$this->redirectOnError) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->scope of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
118
            return '';
119
        }
120
121
        if ($this->scope) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->scope of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
122
            $parameters[] = 'scope=' . implode(',', $this->scope);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$parameters was never initialized. Although not strictly required by PHP, it is generally a good practice to add $parameters = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
123
        }
124
125
        if ($this->redirectOnError) {
126
            $parameters[] = 'redirectOnError=true';
0 ignored issues
show
Bug introduced by
The variable $parameters does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
127
        }
128
129
        return '?' . implode('&', $parameters);
130
    }
131
132
    public function urlTokenCredentials()
133
    {
134
        return 'https://api.xero.com/oauth/AccessToken';
135
    }
136
137
    public function urlUserDetails()
138
    {
139
        return $this->notSupportedByXero();
140
    }
141
142
    public function userDetails($data, TokenCredentials $tokenCredentials)
143
    {
144
        return $this->notSupportedByXero();
145
    }
146
147
    public function userUid($data, TokenCredentials $tokenCredentials)
148
    {
149
        return $this->notSupportedByXero();
150
    }
151
152
    public function userEmail($data, TokenCredentials $tokenCredentials)
153
    {
154
        return $this->notSupportedByXero();
155
    }
156
157
    public function userScreenName($data, TokenCredentials $tokenCredentials)
158
    {
159
        return $this->notSupportedByXero();
160
    }
161
162
    /**
163
     * Gets the response of the last access token call. This might
164
     * be useful for partner applications to retrieve additional
165
     * OAuth parameters passed in by Xero.
166
     *
167
     * @return array|null
168
     */
169
    public function getLastTokenCredentialsResponse()
170
    {
171
        return $this->lastTokenCredentialsResponse;
172
    }
173
174
    /**
175
     * Refreshes an access token. Can be used by partner applications.
176
     *
177
     * @param TokenCredentials $tokenCredentials
178
     * @param string           $sessionHandle    Xero session handle
179
     *
180
     * @throws \League\OAuth1\Client\Credentials\CredentialsException when the access token cannot be refreshed
181
     *
182
     * @return TokenCredentials
183
     */
184
    public function refreshToken(TokenCredentials $tokenCredentials, $sessionHandle)
185
    {
186
        $client = $this->createHttpClient();
187
        $url = $this->urlTokenCredentials();
188
189
        $parameters = [
190
            'oauth_session_handle' => $sessionHandle,
191
        ];
192
193
        $headers = $this->getHeaders($tokenCredentials, 'POST', $url, $parameters);
194
195
        try {
196
            $response = $client->post($url, [
197
                'headers' => $headers,
198
                'form_params' => $parameters,
199
            ]);
200
        } catch (BadResponseException $e) {
201
            $this->handleTokenCredentialsBadResponse($e);
202
        }
203
204
        return $this->createTokenCredentials((string) $response->getBody());
205
    }
206
207
    protected function notSupportedByXero()
208
    {
209
        throw new Exception("Xero's API does not support retrieving the current user. Please see https://xero.uservoice.com/forums/5528-xero-accounting-api/suggestions/5688571-expose-which-user-connected-the-organization-via-o");
210
    }
211
212
    /**
213
     * Parse configuration array to set attributes.
214
     *
215
     * @param array $configuration
216
     */
217
    private function parseConfiguration(array $configuration = [])
218
    {
219
        $configToPropertyMap = [
220
            'http_client' => 'httpClientOptions',
221
        ];
222
        foreach ($configToPropertyMap as $config => $property) {
223
            if (isset($configuration[$config])) {
224
                $this->$property = $configuration[$config];
225
            }
226
        }
227
    }
228
229
    /**
230
     * Creates a client credentials instance from an array of credentials.
231
     *
232
     * @param array $clientCredentials
233
     *
234
     * @return ClientCredentials
235
     */
236
    protected function createClientCredentials(array $clientCredentials)
237
    {
238
        $keys = ['identifier', 'secret'];
239
240
        foreach ($keys as $key) {
241
            if (!isset($clientCredentials[$key])) {
242
                throw new InvalidArgumentException("Missing client credentials key [$key] from options.");
243
            }
244
        }
245
246
        if (isset($clientCredentials['rsa_private_key']) && isset($clientCredentials['rsa_public_key'])) {
247
            $_clientCredentials = new RsaClientCredentials();
248
            $_clientCredentials->setRsaPrivateKey($clientCredentials['rsa_private_key']);
249
            $_clientCredentials->setRsaPublicKey($clientCredentials['rsa_public_key']);
250
        } else {
251
            $_clientCredentials = new ClientCredentials();
252
        }
253
254
        $_clientCredentials->setIdentifier($clientCredentials['identifier']);
255
        $_clientCredentials->setSecret($clientCredentials['secret']);
256
257
        if (isset($clientCredentials['callback_uri'])) {
258
            $_clientCredentials->setCallbackUri($clientCredentials['callback_uri']);
259
        }
260
261
        return $_clientCredentials;
262
    }
263
264
    /**
265
     * Creates token credentials from the body response.
266
     *
267
     * @param string $body
268
     *
269
     * @return TokenCredentials
270
     */
271
    protected function createTokenCredentials($body)
272
    {
273
        parse_str($body, $data);
274
        $this->lastTokenCredentialsResponse = $data;
0 ignored issues
show
Documentation Bug introduced by
It seems like $data can be null. However, the property $lastTokenCredentialsResponse is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
275
276
        return parent::createTokenCredentials($body);
277
    }
278
}
279