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

Xero::setRedirectOnError()   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 1
1
<?php
2
3
namespace Invoiced\OAuth1\Client\Server;
4
5
use Exception;
6
use GuzzleHttp\Client as GuzzleHttpClient;
7
use GuzzleHttp\Exception\BadResponseException;
8
use InvalidArgumentException;
9
use League\OAuth1\Client\Credentials\ClientCredentials;
10
use League\OAuth1\Client\Credentials\TokenCredentials;
11
use League\OAuth1\Client\Server\Server;
12
use League\OAuth1\Client\Signature\SignatureInterface;
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
     * Creates a Guzzle HTTP client for the given URL.
83
     *
84
     * @return GuzzleHttpClient
85
     */
86
    public function createHttpClient()
87
    {
88
        return new GuzzleHttpClient($this->httpClientOptions);
89
    }
90
91
    public function urlTemporaryCredentials()
92
    {
93
        return 'https://api.xero.com/oauth/RequestToken';
94
    }
95
96
    public function urlAuthorization()
97
    {
98
        return 'https://api.xero.com/oauth/Authorize'
99
            .$this->buildUrlAuthorizationQueryString();
100
    }
101
102
    /**
103
     * @return string
104
     */
105
    protected function buildUrlAuthorizationQueryString()
106
    {
107
        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...
108
            return '';
109
        }
110
111
        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...
112
            $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...
113
        }
114
115
        if ($this->redirectOnError) {
116
            $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...
117
        }
118
119
        return '?'.implode('&', $parameters);
120
    }
121
122
    public function urlTokenCredentials()
123
    {
124
        return 'https://api.xero.com/oauth/AccessToken';
125
    }
126
127
    public function urlUserDetails()
128
    {
129
        return $this->notSupportedByXero();
130
    }
131
132
    public function userDetails($data, TokenCredentials $tokenCredentials)
133
    {
134
        return $this->notSupportedByXero();
135
    }
136
137
    public function userUid($data, TokenCredentials $tokenCredentials)
138
    {
139
        return $this->notSupportedByXero();
140
    }
141
142
    public function userEmail($data, TokenCredentials $tokenCredentials)
143
    {
144
        return $this->notSupportedByXero();
145
    }
146
147
    public function userScreenName($data, TokenCredentials $tokenCredentials)
148
    {
149
        return $this->notSupportedByXero();
150
    }
151
152
    /**
153
     * Gets the response of the last access token call. This might
154
     * be useful for partner applications to retrieve additional
155
     * OAuth parameters passed in by Xero.
156
     *
157
     * @return array|null
158
     */
159
    public function getLastTokenCredentialsResponse()
160
    {
161
        return $this->lastTokenCredentialsResponse;
162
    }
163
164
    /**
165
     * Refreshes an access token. Can be used by partner applications.
166
     *
167
     * @param TokenCredentials $tokenCredentials
168
     * @param string           $sessionHandle    Xero session handle
169
     *
170
     * @throws \League\OAuth1\Client\Credentials\CredentialsException when the access token cannot be refreshed
171
     *
172
     * @return TokenCredentials
173
     */
174
    public function refreshToken(TokenCredentials $tokenCredentials, $sessionHandle)
175
    {
176
        $client = $this->createHttpClient();
177
        $url = $this->urlTokenCredentials();
178
179
        $parameters = [
180
            'oauth_session_handle' => $sessionHandle,
181
        ];
182
183
        $headers = $this->getHeaders($tokenCredentials, 'POST', $url, $parameters);
184
185
        try {
186
            $response = $client->post($url, [
187
                'headers' => $headers,
188
                'form_params' => $parameters,
189
            ]);
190
        } catch (BadResponseException $e) {
191
            $this->handleTokenCredentialsBadResponse($e);
192
        }
193
194
        return $this->createTokenCredentials((string) $response->getBody());
195
    }
196
197
    protected function notSupportedByXero()
198
    {
199
        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");
200
    }
201
202
    /**
203
     * Parse configuration array to set attributes.
204
     *
205
     * @param array $configuration
206
     */
207
    private function parseConfiguration(array $configuration = [])
208
    {
209
        $configToPropertyMap = [
210
            'http_client' => 'httpClientOptions',
211
        ];
212
        foreach ($configToPropertyMap as $config => $property) {
213
            if (isset($configuration[$config])) {
214
                $this->$property = $configuration[$config];
215
            }
216
        }
217
    }
218
219
    /**
220
     * Creates a client credentials instance from an array of credentials.
221
     *
222
     * @param array $clientCredentials
223
     *
224
     * @return ClientCredentials
225
     */
226
    protected function createClientCredentials(array $clientCredentials)
227
    {
228
        $keys = ['identifier', 'secret'];
229
230
        foreach ($keys as $key) {
231
            if (!isset($clientCredentials[$key])) {
232
                throw new InvalidArgumentException("Missing client credentials key [$key] from options.");
233
            }
234
        }
235
236
        if (isset($clientCredentials['rsa_private_key']) && isset($clientCredentials['rsa_public_key'])) {
237
            $_clientCredentials = new RsaClientCredentials();
238
            $_clientCredentials->setRsaPrivateKey($clientCredentials['rsa_private_key']);
239
            $_clientCredentials->setRsaPublicKey($clientCredentials['rsa_public_key']);
240
        } else {
241
            $_clientCredentials = new ClientCredentials();
242
        }
243
244
        $_clientCredentials->setIdentifier($clientCredentials['identifier']);
245
        $_clientCredentials->setSecret($clientCredentials['secret']);
246
247
        if (isset($clientCredentials['callback_uri'])) {
248
            $_clientCredentials->setCallbackUri($clientCredentials['callback_uri']);
249
        }
250
251
        return $_clientCredentials;
252
    }
253
254
    /**
255
     * Creates token credentials from the body response.
256
     *
257
     * @param string $body
258
     *
259
     * @return TokenCredentials
260
     */
261
    protected function createTokenCredentials($body)
262
    {
263
        parse_str($body, $data);
264
        $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...
265
266
        return parent::createTokenCredentials($body);
267
    }
268
}
269