Skip to content

Commit

Permalink
Update WpRemote with GET and POST method(s).
Browse files Browse the repository at this point in the history
  • Loading branch information
thefrosty committed Mar 23, 2022
1 parent 34585ee commit bb0e4c4
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions src/Api/WpRemote.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

/**
Expand All @@ -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) {
Expand Down Expand Up @@ -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
Expand All @@ -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));
Expand Down

0 comments on commit bb0e4c4

Please sign in to comment.