Skip to content

Commit 473a7ef

Browse files
StadlyNyholm
authored andcommitted
Split getUrlContents (#864)
* Split getUrlContents Since `getUrlContents()` takes the url as a string argument, it is not possible to set headers, such as `Accept-Language`, for the request. Therefore I created `getRequest()` to generate the request based on the url string, but without fetching the contents. Then headers can be added to the request, before the request is passed to `getRequestContents()` which fetches the content. * Rename method
1 parent 3f5f2e1 commit 473a7ef

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

Provider/AbstractHttpProvider.php

+29-3
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use Http\Message\MessageFactory;
2020
use Http\Discovery\MessageFactoryDiscovery;
2121
use Http\Client\HttpClient;
22+
use Psr\Http\Message\RequestInterface;
2223

2324
/**
2425
* @author William Durand <[email protected]>
@@ -57,7 +58,32 @@ public function __construct(HttpClient $client, MessageFactory $factory = null)
5758
*/
5859
protected function getUrlContents(string $url): string
5960
{
60-
$request = $this->getMessageFactory()->createRequest('GET', $url);
61+
$request = $this->getRequest($url);
62+
63+
return $this->getParsedResponse($request);
64+
}
65+
66+
/**
67+
* @param string $url
68+
*
69+
* @return RequestInterface
70+
*/
71+
protected function getRequest(string $url): RequestInterface
72+
{
73+
return $this->getMessageFactory()->createRequest('GET', $url);
74+
}
75+
76+
/**
77+
* Send request and return contents. If content is empty, an exception will be thrown.
78+
*
79+
* @param RequestInterface $request
80+
*
81+
* @return string
82+
*
83+
* @throws InvalidServerResponse
84+
*/
85+
protected function getParsedResponse(RequestInterface $request): string
86+
{
6187
$response = $this->getHttpClient()->sendRequest($request);
6288

6389
$statusCode = $response->getStatusCode();
@@ -66,12 +92,12 @@ protected function getUrlContents(string $url): string
6692
} elseif (429 === $statusCode) {
6793
throw new QuotaExceeded();
6894
} elseif ($statusCode >= 300) {
69-
throw InvalidServerResponse::create($url, $statusCode);
95+
throw InvalidServerResponse::create((string) $request->getUri(), $statusCode);
7096
}
7197

7298
$body = (string) $response->getBody();
7399
if (empty($body)) {
74-
throw InvalidServerResponse::emptyResponse($url);
100+
throw InvalidServerResponse::emptyResponse((string) $request->getUri());
75101
}
76102

77103
return $body;

0 commit comments

Comments
 (0)