Completed
Pull Request — master (#79)
by
unknown
07:26
created

Client::__construct()   C

Complexity

Conditions 9
Paths 50

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 9
eloc 13
nc 50
nop 4
dl 0
loc 22
rs 6.412
c 1
b 0
f 1
1
<?php
2
3
namespace SevenShores\Hubspot\Http;
4
5
use GuzzleHttp\Client as GuzzleClient;
6
use GuzzleHttp\Psr7\Response;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, SevenShores\Hubspot\Http\Response.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Psr\Http\Message\ResponseInterface;
8
use SevenShores\Hubspot\Exceptions\BadRequest;
9
use SevenShores\Hubspot\Exceptions\InvalidArgument;
10
11
class Client
12
{
13
    /** @var string */
14
    public $key;
15
    /** @var bool */
16
    public $oauth;
17
18
    /** @var bool */
19
    public $oauth2;
20
21
    /** @var int */
22
    public $userId;
23
24
    /** @var \GuzzleHttp\Client */
25
    public $client;
26
27
    /**
28
     * Guzzle allows options into its request method. Prepare for some defaults
29
     * @var array
30
     */
31
    protected $clientOptions = [];
32
33
    /**
34
     * if set to false, no Response object is created, but the one from Guzzle is directly returned
35
     * comes in handy own error handling
36
     *
37
     * @var bool
38
     */
39
    protected $wrapResponse = true;
40
41
    /** @var string */
42
    private $user_agent = "SevenShores_Hubspot_PHP/1.0.0-rc.1 (https://github.com/ryanwinchester/hubspot-php)";
43
44
    /**
45
     * Make it, baby.
46
     *
47
     * @param  array $config Configuration array
48
     * @param  GuzzleClient $client The Http Client (Defaults to Guzzle)
49
     * @param array $clientOptions options to be passed to Guzzle upon each request
50
     * @param bool $wrapResponse wrap request response in own Response object
51
     */
52
    public function __construct($config = [], $client = null, $clientOptions = [], $wrapResponse = true)
53
    {
54
        $this->clientOptions = $clientOptions;
55
        $this->wrapResponse = $wrapResponse;
56
57
        $this->key = isset($config["key"]) ? $config["key"] : getenv("HUBSPOT_SECRET");
58
        if (empty($this->key)) {
59
            throw new InvalidArgument("You must provide a Hubspot api key or token.");
60
        }
61
62
        if (isset($config['userId'])) {
63
            $this->userId = $config['userId'];
64
        }
65
66
        $this->oauth = isset($config["oauth"]) ? $config["oauth"] : false;
67
        $this->oauth2 = isset($config["oauth2"]) ? $config["oauth2"] : false;
68
        if ($this->oauth && $this->oauth2) {
69
            throw new InvalidArgument("Cannot sign requests with both OAuth1 and OAuth2");
70
        }
71
72
        $this->client = $client ?: new GuzzleClient();
73
    }
74
75
    /**
76
     * Send the request...
77
     *
78
     * @param  string $method The HTTP request verb
79
     * @param  string $endpoint The Hubspot API endpoint
80
     * @param  array $options An array of options to send with the request
81
     * @param  string $query_string A query string to send with the request
82
     * @param  boolean $requires_auth Whether or not this HubSpot API endpoint requires authentication
83
     * @return \SevenShores\Hubspot\Http\Response|ResponseInterface
84
     * @throws \SevenShores\Hubspot\Exceptions\BadRequest
85
     */
86
    public function request($method, $endpoint, $options = [], $query_string = null, $requires_auth = true)
87
    {
88
        $url = $this->generateUrl($endpoint, $query_string, $requires_auth);
89
90
        $options = array_merge($this->clientOptions, $options);
91
        $options["headers"]["User-Agent"] = $this->user_agent;
92
93
        if ($this->oauth2) {
94
            $options["headers"]["Authorization"] = "Bearer " . $this->key;
95
        }
96
97
        try {
98
            if ($this->wrapResponse === false) {
99
                return $this->client->request($method, $url, $options);
100
            }
101
            return new Response($this->client->request($method, $url, $options));
0 ignored issues
show
Documentation introduced by
$this->client->request($method, $url, $options) is of type object<Psr\Http\Message\ResponseInterface>, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
102
        } catch (\Exception $e) {
103
            throw new BadRequest($e->getMessage(), $e->getCode(), $e);
104
        }
105
    }
106
107
    /**
108
     * Generate the full endpoint url, including query string.
109
     *
110
     * @param  string  $endpoint      The HubSpot API endpoint.
111
     * @param  string  $query_string  The query string to send to the endpoint.
112
     * @param  boolean $requires_auth Whether or not this HubSpot API endpoint requires authentication
113
     * @return string
114
     */
115
    protected function generateUrl($endpoint, $query_string = null, $requires_auth = true)
116
    {
117
        $url = $endpoint."?";
118
119
        if ($requires_auth) {
120
            $authType = $this->oauth ? "access_token" : "hapikey";
121
122
            if (!$this->oauth2) {
123
                $url .= $authType."=".$this->key;
124
125
                if ($this->userId) {
126
                    $url .= "&userId={$this->userId}";
127
                }
128
            } else {
129
                if ($this->userId) {
130
                    $url .= "userId={$this->userId}";
131
                }
132
            }
133
        }
134
135
        return $url.$query_string;
136
    }
137
}
138