| 1 |
<?php |
| 2 |
|
| 3 |
namespace Yoast\WP\SEO\Wrappers; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use YoastSEO_Vendor\GuzzleHttp\Promise\FulfilledPromise; |
| 7 |
use YoastSEO_Vendor\GuzzleHttp\Promise\PromiseInterface; |
| 8 |
use YoastSEO_Vendor\GuzzleHttp\Promise\RejectedPromise; |
| 9 |
use YoastSEO_Vendor\GuzzleHttp\Psr7\Response; |
| 10 |
use YoastSEO_Vendor\Psr\Http\Message\RequestInterface; |
| 11 |
|
| 12 |
/** |
| 13 |
* Wraps wp_remote_get in an interface compatible with Guzzle. |
| 14 |
*/ |
| 15 |
class WP_Remote_Handler { |
| 16 |
|
| 17 |
/** |
| 18 |
* Calls the handler. |
| 19 |
* Cookies are currently not supported as they are not used by OAuth. |
| 20 |
* Writing responses to files is also not supported for the same reason. |
| 21 |
* |
| 22 |
* @param RequestInterface $request The request. |
| 23 |
* @param array $options The request options. |
| 24 |
* |
| 25 |
* @return PromiseInterface The promise interface. |
| 26 |
* |
| 27 |
* @throws Exception If the request fails. |
| 28 |
*/ |
| 29 |
public function __invoke( RequestInterface $request, array $options ) { |
| 30 |
$headers = []; |
| 31 |
foreach ( $request->getHeaders() as $name => $values ) { |
| 32 |
$headers[ $name ] = \implode( ',', $values ); |
| 33 |
} |
| 34 |
|
| 35 |
$args = [ |
| 36 |
'method' => $request->getMethod(), |
| 37 |
'headers' => $headers, |
| 38 |
'body' => (string) $request->getBody(), |
| 39 |
'httpVersion' => $request->getProtocolVersion(), |
| 40 |
]; |
| 41 |
|
| 42 |
if ( isset( $options['verify'] ) && $options['verify'] === false ) { |
| 43 |
$args['sslverify'] = false; |
| 44 |
} |
| 45 |
if ( isset( $options['timeout'] ) ) { |
| 46 |
$args['timeout'] = ( $options['timeout'] * 1000 ); |
| 47 |
} |
| 48 |
|
| 49 |
$raw_response = \wp_remote_request( (string) $request->getUri(), $args ); |
| 50 |
if ( \is_wp_error( $raw_response ) ) { |
| 51 |
$exception = new Exception( $raw_response->get_error_message() ); |
| 52 |
return new RejectedPromise( $exception ); |
| 53 |
} |
| 54 |
|
| 55 |
$response = new Response( |
| 56 |
$raw_response['response']['code'], |
| 57 |
$raw_response['headers']->getAll(), |
| 58 |
$raw_response['body'], |
| 59 |
$args['httpVersion'], |
| 60 |
$raw_response['response']['message'], |
| 61 |
); |
| 62 |
|
| 63 |
return new FulfilledPromise( $response ); |
| 64 |
} |
| 65 |
} |
| 66 |
|