Completed
Push — feature/httplug ( f5571c )
by Maxime
10:26
created

RequestBuilder::setUri()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace Knp\FriendlyContexts\Builder;
4
5
use Http\Client\Common\Plugin;
6
use Http\Message\CookieJar;
7
use Http\Message\RequestFactory;
8
use Knp\FriendlyContexts\Http\ClientFactory;
9
use Knp\FriendlyContexts\Http\Security\SecurityExtensionInterface;
10
11
class RequestBuilder
12
{
13
    /**
14
     * @var RequestFactory
15
     */
16
    private $requestFactory;
17
18
    /**
19
     * @var ClientFactory
20
     */
21
    private $clientFactory;
22
23
    /**
24
     * @var boolean
25
     */
26
    private $keepCookies;
27
28
    /**
29
     * @var CookieJar
30
     */
31
    protected $cookieJar;
32
33
    /**
34
     * @var string
35
     */
36
    private $method;
37
38
    /**
39
     * @var string[]
40
     */
41
    private $headers;
42
43
    /**
44
     * @var string[]
45
     */
46
    private $queries;
47
48
    /**
49
     * @var string|array
50
     */
51
    private $body;
52
53
    /**
54
     * @var array
55
     */
56
    private $options;
57
58
    private $postBody;
59
60
    /**
61
     * @var SecurityExtensionInterface[]
62
     */
63
    private $securityExtensions;
64
65
    /**
66
     * @var Plugin[]
67
     */
68
    private $plugins;
69
70
    private $uri;
71
72
    private $files;
73
74
    private static function getAcceptedMethods()
75
    {
76
        return [
77
            'GET',
78
            'PUT',
79
            'POST',
80
            'DELETE',
81
            'HEAD',
82
            'OPTIONS',
83
            'PATCH'
84
        ];
85
    }
86
87
    public function __construct(ClientFactory $clientFactory)
88
    {
89
        $this->clientFactory = $clientFactory;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
90
        $this->options            = [];
91
        $this->securityExtensions = [];
92
        $this->files              = [];
93
        $this->keepCookies = false;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
94
    }
95
96
    public function build($uri = null, array $queries = null, array $headers = null, array $postBody = null, $body = null, array $options = [])
97
    {
98
        $this->setUri($uri ?: $this->uri);
99
        $this->setQueries($queries ?: $this->queries);
100
        $this->setHeaders($headers ?: $this->headers);
101
        $this->setPostBody($postBody ?: $this->postBody);
102
        $this->setBody($body ?: $this->body);
103
        $this->setOptions($options ?: $this->options);
104
105
        if (null === $this->method) {
106
            throw new \RuntimeException('You can\'t build a request without any methods');
107
        }
108
109
        // BC Layer: to be remove in 1.0
110
        foreach ($this->securityExtensions as $extension) {
111
            $extension->secure($this);
0 ignored issues
show
Bug introduced by
The method secure() does not exist on Knp\FriendlyContexts\Htt...urityExtensionInterface. Did you maybe mean secureRequest()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
112
        }
113
        // End of BC Layer
114
115
        $request = $this->requestFactory->createRequest(
116
            $this->method,
117
            $this->getUri(),
118
            $this->getHeaders()
119
        );
120
//            ,
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
121
//            $this->getQueries(),
122
//            ,
123
//            $this->getPostBody(),
124
//            $this->getBody(),
125
//            $this->getOptions()
126
//        );
127
//
128
//        if (null !== $this->cookies) {
129
//            foreach ($this->cookies as $name => $cookie) {
130
//                $request->addCookie($name, $cookie);
131
//            }
132
//        }
133
//
134
//        foreach ($this->securityExtensions as $extension) {
135
//            $extension->secureRequest($request, $this);
136
//        }
137
//
138
//        foreach ($this->files as $file) {
139
//            $request->addPostFile($file['name'], $file['path']);
140
//        }
141
//
142
        $this->clean(); // Make the builder reusable
143
144
        return $request;
145
    }
146
147
    /**
148
     * @param Plugin $plugin
149
     * @return RequestBuilder
150
     */
151
    public function addPlugin(Plugin $plugin)
152
    {
153
        $this->plugins[] = $plugin;
154
155
        return $this;
156
    }
157
158
    /**
159
     * @return Plugin[]
160
     */
161
    public function getPlugins()
162
    {
163
        return $this->plugins;
164
    }
165
166
    public function setMethod($method)
167
    {
168
        $method = strtoupper($method);
169
170
        if (!in_array($method, self::getAcceptedMethods())) {
171
            throw new \InvalidArgumentException(sprintf(
172
                'The requets method "%s" is not a valid HTTP method (valid method are "%s")',
173
                $method,
174
                implode(', ', self::getAcceptedMethods())
175
            ));
176
        }
177
178
        $this->method = $method;
179
180
        return $this;
181
    }
182
183
    public function getMethod()
184
    {
185
        return $this->method;
186
    }
187
188
    public function setHeaders(array $headers = null)
189
    {
190
        $this->headers = $headers;
0 ignored issues
show
Documentation Bug introduced by
It seems like $headers can be null. However, the property $headers 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...
191
192
        return $this;
193
    }
194
195
    public function getHeaders()
196
    {
197
        return $this->headers;
198
    }
199
200
    public function setBody($body = null)
201
    {
202
        $this->body = $body;
203
204
        return $this;
205
    }
206
207
    public function getQueries()
208
    {
209
        return $this->queries;
210
    }
211
212
    public function setQueries(array $queries = null)
213
    {
214
        $this->queries = $queries;
0 ignored issues
show
Documentation Bug introduced by
It seems like $queries can be null. However, the property $queries 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...
215
216
        return $this;
217
    }
218
219
    public function getBody()
220
    {
221
        return $this->body;
222
    }
223
224
    public function setOptions(array $options = null)
225
    {
226
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
It seems like $options can be null. However, the property $options 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...
227
228
        return $this;
229
    }
230
231
    public function getOptions()
232
    {
233
        return $this->options;
234
    }
235
236
    public function setPostBody(array $postBody = null)
237
    {
238
        $this->postBody = $postBody;
239
240
        return $this;
241
    }
242
243
    public function getPostBody()
244
    {
245
        return $this->postBody;
246
    }
247
248
    public function getCookies()
249
    {
250
        return $this->cookieJar->getCookies();
251
    }
252
253
    public function setCookies(array $cookies = null)
254
    {
255
        $this->cookieJar->setCookies($cookies);
0 ignored issues
show
Documentation introduced by
$cookies is of type null|array, but the function expects a array<integer,object<Http\Message\Cookie>>.

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...
256
257
        return $this;
258
    }
259
260
    /**
261
     * @return SecurityExtensionInterface[]
262
     */
263
    public function getSecurityExtensions()
264
    {
265
        return $this->securityExtensions;
266
    }
267
268
    public function setUri($uri = null)
269
    {
270
        $this->uri = substr($uri, 0, 1) === '/' ? substr($uri, 1) : $uri;
271
272
        return $this;
273
    }
274
275
    public function getUri()
276
    {
277
        return $this->uri;
278
    }
279
280
    public function addFile($name, $path)
281
    {
282
        $this->files[] = ['name' => $name, 'path' => $path];
283
284
        return $this;
285
    }
286
287
    /**
288
     * @param boolean $keepCookies
289
     * @return RequestBuilder
290
     */
291
    public function keepCookies($keepCookies=true)
292
    {
293
        $this->keepCookies = $keepCookies;
294
295
        return $this;
296
    }
297
298
    protected function clean()
299
    {
300
        $this->uri                = null;
301
        $this->method             = null;
302
        $this->queries            = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array<integer,string> of property $queries.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

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

Loading history...
303
        $this->body               = null;
304
        $this->postBody           = null;
305
        $this->headers            = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array<integer,string> of property $headers.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

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

Loading history...
306
        $this->options            = [];
307
        $this->securityExtensions = [];
308
        $this->files              = [];
309
        $this->plugins = [];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 12 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
310
311
        if (!$this->keepCookies) {
312
            $this->cookieJar = new CookieJar();
313
        }
314
    }
315
316
    public function addSecurityExtension(SecurityExtensionInterface $extension)
317
    {
318
        trigger_error("Deprecated. To be remove in 1.0. Use `addPlugin` instead.", E_USER_DEPRECATED);
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Deprecated. To be remove...se `addPlugin` instead. does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
319
        $this->securityExtensions[] = $extension;
320
321
        return $this;
322
    }
323
324
    public function setSecurity(SecurityExtensionInterface $extension)
325
    {
326
        trigger_error("Deprecated. To be remove in 1.0. Use `addPlugin` instead.", E_USER_DEPRECATED);
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Deprecated. To be remove...se `addPlugin` instead. does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
327
        $this->securityExtensions = [$extension];
328
    }
329
}
330