PluginProbe
Optimole – Optimize Images | Convert WebP & AVIF | CDN & Lazy Load | Image Optimization / 4.2.10
Optimole – Optimize Images | Convert WebP & AVIF | CDN & Lazy Load | Image Optimization v4.2.10
4.2.13 4.2.12 4.2.11 4.2.10 4.2.9 4.2.8 4.2.7 4.2.6 4.2.5 2.5.5 2.5.6 2.5.7 3.0.0 3.0.1 3.1.0 3.1.1 3.1.2 3.1.3 3.10.0 3.11.0 3.11.1 3.11.2 3.11.3 3.12.0 3.12.1 All 134 releases
optimole-wp / vendor / codeinwp / optimole-sdk / src / Http / WordPressClient.php

WordPressClient.php in Optimole – Optimize Images | Convert WebP & AVIF | CDN & Lazy Load | Image Optimization 4.2.10, at vendor/codeinwp/optimole-sdk/src/Http/WordPressClient.php

89 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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