Completed
Pull Request — master (#192)
by
unknown
07:03
created

Client::__construct()   F

Complexity

Conditions 13
Paths 770

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
nc 770
nop 4
dl 0
loc 28
rs 2.7694
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SevenShores\Hubspot\Http;
4
5
use GuzzleHttp\Client as GuzzleClient;
6
use Psr\Http\Message\ResponseInterface;
7
use SevenShores\Hubspot\Exceptions\BadRequest;
8
use SevenShores\Hubspot\Exceptions\InvalidArgument;
9
10
class Client
11
{
12
    /** @var string */
13
    public $key;
14
    /** @var bool */
15
    public $oauth;
16
17
    /** @var bool */
18
    public $oauth2;
19
20
    /** @var int */
21
    public $userId;
22
23
    /** @var \GuzzleHttp\Client */
24
    public $client;
25
26
    /**
27
     * Guzzle allows options into its request method. Prepare for some defaults
28
     * @var array
29
     */
30
    protected $clientOptions = [];
31
32
    /**
33
     * if set to false, no Response object is created, but the one from Guzzle is directly returned
34
     * comes in handy own error handling
35
     *
36
     * @var bool
37
     */
38
    protected $wrapResponse = true;
39
40
    /** @var string */
41
    private $user_agent = "SevenShores_Hubspot_PHP/1.0.0-rc.1 (https://github.com/ryanwinchester/hubspot-php)";
42
43
    /**
44
     * @var int Number of requests remaining this second
45
     */
46
    private $requestsRemainingThisSecond = null;
47
48
    private $requestsRemainingThisSecondTime = null;
49
50
    /** @var int Max number of exceptions we can handle before aborting the re-try */
51
    private $exceptionMax = null;
52
53
    /** @var int Delay before retry in microseconds when an exception occurs */
54
    private $exceptionDelay = null;
55
56
    /** @var int Delay before we wait before requests when API reports low request credits  */
57
    private $backOffDelay = null;
58
59
    /** @var bool Handle rate limits automatically */
60
    private $handleRateLimits = null;
61
62
    /**
63
     * Make it, baby.
64
     *
65
     * @param  array $config Configuration array
66
     * @param  GuzzleClient $client The Http Client (Defaults to Guzzle)
67
     * @param array $clientOptions options to be passed to Guzzle upon each request
68
     * @param bool $wrapResponse wrap request response in own Response object
69
     */
70
    public function __construct($config = [], $client = null, $clientOptions = [], $wrapResponse = true)
71
    {
72
        $this->clientOptions = $clientOptions;
73
        $this->wrapResponse = $wrapResponse;
74
75
        $this->key = isset($config["key"]) ? $config["key"] : getenv("HUBSPOT_SECRET");
76
        if (empty($this->key)) {
77
            throw new InvalidArgument("You must provide a Hubspot api key or token.");
78
        }
79
80
        if (isset($config['userId'])) {
81
            $this->userId = $config['userId'];
82
        }
83
84
        $this->oauth = isset($config["oauth"]) ? $config["oauth"] : false;
85
        $this->oauth2 = isset($config["oauth2"]) ? $config["oauth2"] : false;
86
87
        $this->exceptionMax = isset($config["exceptionMax"]) ? $config["exceptionMax"] : 10;
88
        $this->exceptionDelay = isset($config["exceptionDelay"]) ? $config["exceptionDelay"] : 1000000;
89
        $this->backOffDelay = isset($config["backOffDelay"]) ? $config["backOffDelay"] : 1000000;
90
        $this->handleRateLimits = isset($config["handleRateLimits"]) ? $config["handleRateLimits"] : true;
91
92
        if ($this->oauth && $this->oauth2) {
93
            throw new InvalidArgument("Cannot sign requests with both OAuth1 and OAuth2");
94
        }
95
96
        $this->client = $client ?: new GuzzleClient();
97
    }
98
99
    /**
100
     * Send the request...
101
     *
102
     * @param  string $method The HTTP request verb
103
     * @param  string $endpoint The Hubspot API endpoint
104
     * @param  array $options An array of options to send with the request
105
     * @param  string $query_string A query string to send with the request
106
     * @param  boolean $requires_auth Whether or not this HubSpot API endpoint requires authentication
107
     * @return \SevenShores\Hubspot\Http\Response|ResponseInterface
108
     * @throws \SevenShores\Hubspot\Exceptions\BadRequest
109
     */
110
    public function request($method, $endpoint, $options = [], $query_string = null, $requires_auth = true)
111
    {
112
        $url = $this->generateUrl($endpoint, $query_string, $requires_auth);
113
114
        $options = array_merge($this->clientOptions, $options);
115
        $options["headers"]["User-Agent"] = $this->user_agent;
116
117
        if ($this->oauth2) {
118
            $options["headers"]["Authorization"] = "Bearer " . $this->key;
119
        }
120
121
        try {
122
            $keepTrying = true;
0 ignored issues
show
Unused Code introduced by
$keepTrying is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
123
            $exceptionCounter = 0;
124
            if($this->handleRateLimits
125
                && !is_null($this->requestsRemainingThisSecond)
126
                && (
127
                    ($this->requestsRemainingThisSecond <= 1)
128
                    ||
129
                    (($this->requestsRemainingThisSecond <= 2)
130
                        && ($this->requestsRemainingThisSecondTime == time()))
131
                )
132
            ){
133
                usleep($this->backOffDelay);
134
            }
135
            do {
136
                try {
137
                    $response = $this->client->request($method, $url, $options);
138
                    $keepTrying = false;
139
                } catch (\GuzzleHttp\Exception\BadResponseException $e) {
140
                    if(!$this->handleRateLimits) {
141
                        throw $e;
142
                    }
143
                    switch ($e->getCode()) {
144
                        /**
145
                         * @see https://developers.hubspot.com/docs/faq/api-error-responses
146
                         *
147
                         * 500 This is not documented but it happens. Seems like its part of the rate limiting but they
148
                         * choose this instead of 429 in some cases. If the message is "internal error" then that means
149
                         * we have to backoff, otherwise re-throw the user error for them to handle it
150
                         */
151
                        case 500:
152
                            if(strpos($e->getMessage(),'"message":"internal error"') === false) {
153
                                throw $e;
154
                            }
155
                        /**
156
                         * 502/504 timeouts - HubSpot has processing limits in place to prevent a single client causing
157
                         * degraded performance, and these responses indicate that those limits have been hit.
158
                         * You'll normally only see these timeout responses when making a a large number of requests
159
                         * over a sustained period.  If you get one of these responses, you should pause your requests
160
                         * for a few seconds, then retry.
161
                         */
162
                        case 502:
163
                        case 504:
164
                            /**
165
                             * 429 Too many requests - Returned when your portal or app is over the API rate limits.
166
                             * Please see this document for details on those rate limits and suggestions for working within
167
                             * those limits.
168
                             */
169
                        case 429:
170
                            $header = $e->getResponse()->getHeader('X-HubSpot-RateLimit-Daily-Remaining');
171
                            if(is_array($header) && sizeof($header)) {
172
                                $dailyLimitLeft = (int)$header[0];
173
                                if($dailyLimitLeft === 0) {
174
                                    throw $e;
175
                                }
176
                            }
177
                            $exceptionCounter++;
178
                            if ($exceptionCounter >= $this->exceptionMax) {
179
                                throw $e;
180
                            }
181
                            usleep($this->exceptionDelay);
182
                            $keepTrying = true;
183
                            break;
184
                        default: // Throw to outer handler
185
                            throw $e;
186
                    }
187
                }
188
            } while ($keepTrying === true);
189
190
            // Check headers for delay
191
            if($this->handleRateLimits) {
192
                $header = $response->getHeader('X-HubSpot-RateLimit-Secondly-Remaining');
193
                if(is_array($header) && sizeof($header)) {
194
                    $this->requestsRemainingThisSecond = (int)$header[0];
195
                    $this->requestsRemainingThisSecondTime = time();
196
                }
197
            }
198
199
            if ($this->wrapResponse === false) {
200
                return $response;
201
            }
202
            return new Response($response);
203
        } catch (\GuzzleHttp\Exception\BadResponseException $e) {
204
            throw new BadRequest(\GuzzleHttp\Psr7\str($e->getResponse()), $e->getCode(), $e);
0 ignored issues
show
Bug introduced by
It seems like $e->getResponse() can be null; however, GuzzleHttp\Psr7\str() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
205
        } catch (\Exception $e) {
206
            throw new BadRequest($e->getMessage(), $e->getCode(), $e);
207
        }
208
    }
209
210
    /**
211
     * Generate the full endpoint url, including query string.
212
     *
213
     * @param  string  $endpoint      The HubSpot API endpoint.
214
     * @param  string  $query_string  The query string to send to the endpoint.
215
     * @param  boolean $requires_auth Whether or not this HubSpot API endpoint requires authentication
216
     * @return string
217
     */
218
    protected function generateUrl($endpoint, $query_string = null, $requires_auth = true)
219
    {
220
        $url = $endpoint."?";
221
222
        if ($requires_auth) {
223
            $authType = $this->oauth ? "access_token" : "hapikey";
224
225
            if (!$this->oauth2) {
226
                $url .= $authType."=".$this->key;
227
228
                if ($this->userId) {
229
                    $url .= "&userId={$this->userId}";
230
                }
231
            } else {
232
                if ($this->userId) {
233
                    $url .= "userId={$this->userId}";
234
                }
235
            }
236
        }
237
238
        return $url.$query_string;
239
    }
240
}
241