From bb0e4c414b4c9dcbea9ee9272f3f105d5ba1ec6f Mon Sep 17 00:00:00 2001 From: Austin Passy <367897+thefrosty@users.noreply.github.com> Date: Wed, 23 Mar 2022 16:24:13 -0700 Subject: [PATCH] Update WpRemote with GET and POST method(s). --- src/Api/WpRemote.php | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/src/Api/WpRemote.php b/src/Api/WpRemote.php index debcfff..c0421ff 100644 --- a/src/Api/WpRemote.php +++ b/src/Api/WpRemote.php @@ -2,6 +2,7 @@ namespace TheFrosty\WpUtilities\Api; +use TheFrosty\WpUtilities\Plugin\Plugin; use function apply_filters; use function array_filter; use function array_merge; @@ -10,7 +11,10 @@ use function get_bloginfo; use function is_wp_error; use function sprintf; +use function strtolower; +use function ucfirst; use function wp_remote_get; +use function wp_remote_post; use const DAY_IN_SECONDS; /** @@ -24,13 +28,18 @@ trait WpRemote /** * Get the remote GET request body. - * @param string $url - * @param array $args + * @param string $url The URL to make a remote request too. + * @param array $args Additional request args. + * @param string $method The method type (supports GET & POST only). * @return mixed */ - public function retrieveBody(string $url, array $args = []) + public function retrieveBody(string $url, array $args = [], string $method = 'GET') { - $response = wp_remote_retrieve_body(wp_remote_get(esc_url($url), $this->buildRequestArgs($args))); + if (!in_array($method, ['GET', 'POST'], true)) { + return false; + } + $function = sprintf('wpRemote%1$s', ucfirst(strtolower($method))); + $response = wp_remote_retrieve_body($this->$function(esc_url($url), $this->buildRequestArgs($args))); if (!is_wp_error($response) && $response !== '') { $body = json_decode($response); if ($body === null) { @@ -79,6 +88,28 @@ public function retrieveBodyCached( return $body; } + /** + * Return a remote GET request. + * @param string $url + * @param array $args + * @return array|\WP_Error + */ + public function wpRemoteGet(string $url, array $args = []) + { + return wp_remote_get(esc_url($url), $this->buildRequestArgs($args)); + } + + /** + * Return a remote POST request. + * @param string $url + * @param array $args + * @return array|\WP_Error + */ + public function wpRemotePost(string $url, array $args = []) + { + return wp_remote_post(esc_url($url), $this->buildRequestArgs($args)); + } + /** * Build Request args. * @param array $args @@ -87,7 +118,7 @@ public function retrieveBodyCached( private function buildRequestArgs(array $args): array { $defaults = [ - 'timeout' => apply_filters('cl_wp_remote_get_timeout', 15), + 'timeout' => apply_filters(Plugin::TAG . 'wp_remote_timeout', 15), ]; return array_filter(array_merge($defaults, $args));