| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
/* |
| 6 |
* This file is part of Optimole PHP SDK. |
| 7 |
* |
| 8 |
* (c) Optimole Team <friends@optimole.com> |
| 9 |
* |
| 10 |
* For the full copyright and license information, please view the LICENSE |
| 11 |
* file that was distributed with this source code. |
| 12 |
*/ |
| 13 |
|
| 14 |
namespace Optimole\Sdk\Http; |
| 15 |
|
| 16 |
use Optimole\Sdk\Exception\BadResponseException; |
| 17 |
use Optimole\Sdk\Exception\InvalidArgumentException; |
| 18 |
use Optimole\Sdk\Exception\RuntimeException; |
| 19 |
use Optimole\Sdk\Optimole; |
| 20 |
|
| 21 |
class WordPressClient implements ClientInterface |
| 22 |
{ |
| 23 |
/** |
| 24 |
* The WordPress HTTP client. |
| 25 |
*/ |
| 26 |
private \WP_Http $client; |
| 27 |
|
| 28 |
/** |
| 29 |
* Constructor. |
| 30 |
*/ |
| 31 |
public function __construct(\WP_Http $client) |
| 32 |
{ |
| 33 |
$this->client = $client; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* {@inheritdoc} |
| 38 |
*/ |
| 39 |
public function sendRequest(string $method, string $url, $body = null, array $headers = []): ?array |
| 40 |
{ |
| 41 |
if (is_array($body)) { |
| 42 |
$body = json_encode($body); |
| 43 |
} |
| 44 |
|
| 45 |
if (null !== $body && !is_string($body)) { |
| 46 |
throw new InvalidArgumentException('"body" must be a string or an array'); |
| 47 |
} |
| 48 |
|
| 49 |
$args = [ |
| 50 |
'method' => $method, |
| 51 |
'headers' => array_merge($headers, [ |
| 52 |
'User-Agent' => sprintf('optimole-sdk-php/%s', Optimole::VERSION), |
| 53 |
]), |
| 54 |
]; |
| 55 |
|
| 56 |
if (null !== $body) { |
| 57 |
$args['body'] = $body; |
| 58 |
} |
| 59 |
|
| 60 |
$response = $this->client->request($url, $args); |
| 61 |
|
| 62 |
if ($response instanceof \WP_Error) { |
| 63 |
throw new RuntimeException((string) $response->get_error_message(), (int) $response->get_error_code()); |
| 64 |
} elseif (200 !== $this->getResponseStatusCode($response)) { |
| 65 |
throw new BadResponseException(sprintf('Response status code: %s', $this->getResponseStatusCode($response))); |
| 66 |
} |
| 67 |
|
| 68 |
if (empty($response['body'])) { |
| 69 |
return null; |
| 70 |
} |
| 71 |
|
| 72 |
$body = (array) json_decode($response['body'], true); |
| 73 |
|
| 74 |
if (JSON_ERROR_NONE !== json_last_error()) { |
| 75 |
throw new BadResponseException(sprintf('Unable to decode JSON response: %s', json_last_error_msg())); |
| 76 |
} |
| 77 |
|
| 78 |
return $body; |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* Get the status code from the given response. |
| 83 |
*/ |
| 84 |
private function getResponseStatusCode(array $response): ?int |
| 85 |
{ |
| 86 |
return $response['response']['code'] ?? null; |
| 87 |
} |
| 88 |
} |
| 89 |
|