17
17
/**
18
18
* Fetches a url.
19
19
*
20
+ * @param array<string, mixed> $options
21
+ *
20
22
* @throws ProtocolError when the server responds with an error
21
23
* @throws SocketError when a connection cannot be established
22
24
*/
23
25
function fetch (string $ url , array $ options = []): Response
24
26
{
25
- $ method = $ options ['method ' ] ?? 'GET ' ;
26
- $ headers = $ options ['headers ' ] ?? [];
27
- $ body = $ options ['body ' ] ?? null ;
28
- $ followRedirects = $ options ['follow_redirects ' ] ?? true ;
29
- $ maxRedirects = $ options ['max_redirects ' ] ?? 20 ;
30
- $ protocolVersion = $ options ['protocol_version ' ] ?? '1.1 ' ;
31
-
32
27
$ context = [
33
28
'http ' => [
34
- 'method ' => $ method ,
35
- 'header ' => Headers::fromMap ($ headers )->toArray (),
36
- 'contents ' => $ body ,
29
+ 'method ' => $ options [ ' method ' ] ?? ' GET ' ,
30
+ 'header ' => Headers::fromMap ($ options [ ' headers ' ] ?? [] )->toArray (),
31
+ 'contents ' => $ options [ ' body ' ] ?? null ,
37
32
'ignore_errors ' => true ,
38
- 'follow_location ' => $ followRedirects ? 1 : 0 ,
39
- 'max_redirects ' => $ maxRedirects ,
40
- 'protocol_version ' => (float ) $ protocolVersion ,
33
+ 'follow_location ' => ( $ options [ ' follow_redirects ' ] ?? true ) ? 1 : 0 ,
34
+ 'max_redirects ' => $ options [ ' max_redirects ' ] ?? 20 ,
35
+ 'protocol_version ' => (float ) ( $ options [ ' protocol_version ' ] ?? ' 1.1 ' ) ,
41
36
],
42
37
];
43
38
@@ -49,17 +44,16 @@ function fetch(string $url, array $options = []): Response
49
44
50
45
// We extract relevant stream meta data
51
46
$ meta = stream_get_meta_data ($ resource );
52
- $ rawHeaders = $ meta ['wrapper_data ' ];
53
47
54
48
// We create objects out of that data.
55
- $ partials = HttpPartialResponse::parseLines ($ rawHeaders );
49
+ $ partials = HttpPartialResponse::parseLines ($ meta ['wrapper_data ' ]);
50
+ /** @var HttpPartialResponse $mainPartial */
56
51
$ mainPartial = array_pop ($ partials );
57
- $ body = new ResourceReader ($ resource );
58
- $ response = new HttpResponse ($ mainPartial , $ body );
52
+ $ response = new HttpResponse ($ mainPartial , new ResourceReader ($ resource ));
59
53
60
54
// If there are still partials, we are dealing with a redirect here.
61
55
// We decorate the response on previous request.
62
- if (count ( $ partials) > 0 ) {
56
+ if ($ partials !== [] ) {
63
57
$ response = new RedirectedHttpResponse ($ response , ...$ partials );
64
58
}
65
59
0 commit comments