Completed
Push — master ( 5c75ec...5ff604 )
by Peter
02:22
created

Client::authHeaders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace PeterColes\Betfair\Http;
4
5
use Exception;
6
use GuzzleHttp\Client;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, PeterColes\Betfair\Http\Client.

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 GuzzleHttp\Psr7\Response;
8
use PeterColes\Betfair\Api\Auth;
9
use stdClass;
10
11
class Client
12
{
13
    protected $guzzleClient;
14
15
    protected $method = 'get';
16
17
    protected $uri = '';
18
19
    protected $options = [ ];
20
21
    /**
22
     * instantiate Guzzle client (unless one is injected).
23
     *
24
     * @param GuzzleClient $client
25
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
26
     */
27
    public function __construct($client = null)
28
    {
29
        $this->guzzleClient = $client ?: new Client;
30
        $this->options[ 'headers' ] = [ 'Accept' => 'application/json' ];
31
    }
32
33
    /**
34
     * Setter for request method.
35
     *
36
     * @param string $method
37
     * @return Client
38
     */
39
    public function setMethod(string $method)
40
    {
41
        $this->method = $method;
42
        return $this;
43
    }
44
45
    /**
46
     * Setter for request end point URI.
47
     *
48
     * @param string $endPoint
49
     * @return Client
50
     */
51
    public function setEndPoint(string $endPoint)
52
    {
53
        $this->uri = $endPoint;
54
        return $this;
55
    }
56
57
    /**
58
     * Setter for request headers.
59
     *
60
     * @param array $headers
0 ignored issues
show
Documentation introduced by
There is no parameter named $headers. Did you maybe mean $header?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
61
     * @return Client
62
     */
63
    public function addHeader(array $header)
64
    {
65
        $this->options[ 'headers' ][] = $header;
66
        return $this;
67
    }
68
69
    /**
70
     * Setter for authentication headers.
71
     *
72
     * @param array $headers
73
     * @return Client
74
     */
75
    public function authHeaders(array $headers = [ ])
76
    {
77
        if (count($headers) == 0) {
78
            $headers = [ 'X-Application' => Auth::$appKey, 'X-Authentication' => Auth::$sessionToken ];
79
        }
80
        $this->options[ 'headers' ] = array_merge($this->options[ 'headers' ], $headers);
81
        return $this;
82
    }
83
84
    /**
85
     * Setter for request form data.
86
     *
87
     * @param array $formData
88
     * @return Client
89
     */
90
    public function setFormData(array $formData)
91
    {
92
        $this->options[ 'form_params' ] = $formData;
93
        return $this;
94
    }
95
96
    /**
97
     * Setter for request filter(s). mandatory, but can be empty
98
     *
99
     * @param  array|null $filter
100
     * @return Client
101
     */
102
    public function setFilter($filter = null)
103
    {
104
        $this->options[ 'json' ][ 'filter' ] = $filter ?: new stdClass;
105
        return $this;
106
    }
107
108
    /**
109
     * Setter for optional market projection, i.e. what market-related data should be returned.
110
     *
111
     * @param  array|null $marketProjection
112
     * @return Client
113
     */
114
    public function setMarketProjection($marketProjection = null)
115
    {
116
        if ($marketProjection) {
117
            $this->options[ 'json' ][ 'marketProjection' ] = $marketProjection;
118
        }
119
        return $this;
120
    }
121
122
    /**
123
     * Setter for optional request sort.
124
     *
125
     * @param string|null $locale
0 ignored issues
show
Bug introduced by
There is no parameter named $locale. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
126
     * @return Client
127
     */
128
    public function setSort($sort)
129
    {
130
        if ($sort) {
131
            $this->options[ 'json' ][ 'sort' ] = $sort;
132
        }
133
        return $this;
134
    }
135
136
    /**
137
     * Setter for mandatory request max results limiter.
138
     *
139
     * @param integer|null $maxResults
140
     * @return Client
141
     */
142
    public function setMaxresults($maxResults = 100)
143
    {
144
        if ($maxResults) {
145
            $this->options[ 'json' ][ 'maxResults' ] = $maxResults;
146
        }
147
        return $this;
148
    }
149
150
    /**
151
     * Setter for optional request locale.
152
     *
153
     * @param string|null $locale
154
     * @return Client
155
     */
156
    public function setLocale($locale)
157
    {
158
        if ($locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
159
            $this->options[ 'json' ][ 'locale' ] = $locale;
160
        }
161
        return $this;
162
    }
163
164
    /**
165
     * Dispatch the request and provide hooks for error handling for the response.
166
     *
167
     * @return object stdClass
168
     */
169
    public function send()
170
    {
171
        $response = $this->guzzleClient->request($this->method, $this->uri, $this->options);
172
173
        $status = $this->getStatus($response);
174
175
        if ($status != 200) {
176
            $this->handleHttpException($status);
177
        }
178
179
        $body = $this->getBody($response);
180
181
        if (is_object($body) && $body->status != 'SUCCESS') {
182
            $this->handleApiException($body->error);
183
        }
184
185
        return $body;
186
    }
187
188
    /**
189
     * Get status code from http response.
190
     *
191
     * @param Response $response
192
     * @return integer
193
     */
194
    protected function getStatus(Response $response)
195
    {
196
        return (int) $response->getStatusCode();
197
    }
198
199
    /**
200
     * Get http response body, cast to json and decode.
201
     *
202
     * @param Response object $response
203
     * @return array
204
     */
205
    protected function getBody(Response $response)
206
    {
207
        return json_decode((string) $response->getBody());
208
    }
209
210
    /**
211
     * Stub for http exception handling.
212
     *
213
     * @param Integer $status
214
     * @return void
215
     */
216
    protected function handleHttpException($status) {
217
        throw new Exception('Http request failure. Http Exception Code: '.$status);
218
    }
219
220
    /**
221
     * Stub for API exception handling.
222
     *
223
     * @param String $exception
224
     * @return void
225
     */
226
    protected function handleApiException($exception) {
227
        throw new Exception('API request failure. API Exception Message: '.$exception);
228
    }
229
}
230