Last active
March 7, 2018 11:56
-
-
Save asqd/c58362c662e55a339f43d0fb9347037c to your computer and use it in GitHub Desktop.
HTTPHelper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace common\helpers; | |
/** | |
* HttpHelper provides an interface to make HTTP request | |
*/ | |
class HTTPHelper | |
{ | |
public static function GET($url, $params=[], $options=[]) | |
{ | |
return self::request($url, $params, $options); | |
} | |
public static function POST($url, $params=[], $options=[]) | |
{ | |
return self::request($url, $params, $options); | |
} | |
public static function PUT($url, $params=[], $options=[]) | |
{ | |
return self::request($url, $params, $options); | |
} | |
public static function DELETE($url, $params=[], $options=[]) | |
{ | |
return self::request($url, $params, $options); | |
} | |
private static function request($url, $params=[], $options=[]) | |
{ | |
$options = self::make_options($url, $params, $options); | |
return self::curl_request($options); | |
} | |
private static function curl_request($options) | |
{ | |
$ch = curl_init(); | |
self::set_curl_options($ch, $options); | |
$response = curl_exec($ch); | |
$curl_info = curl_getinfo($ch); | |
$curl_info['body'] = $response; | |
$curl_info['request_type'] = $options['request_type']; | |
$curl_info['query'] = $options['query']; | |
curl_close($ch); | |
return $curl_info; | |
} | |
private static function make_options($url, $params, $options) | |
{ | |
$caller = debug_backtrace(); | |
$caller = $caller[2]; | |
$query = http_build_query($params); | |
if ($caller['function'] === 'GET') { | |
$options['url'] = $url . "?" . $query; | |
} else { | |
$options['url'] = $url; | |
} | |
$options['query'] = $query; | |
$options['request_type'] = $caller['function']; | |
return $options; | |
} | |
private static function set_curl_options(&$ch, $options=[]) | |
{ | |
$isPostRequestType = isset($options['request_type']) && $options['request_type'] !== "GET"; | |
curl_setopt($ch, CURLOPT_URL, $options['url']); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_HEADER, $options['with_headers'] ?? false); | |
if (!empty($options['headers'])) { | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $options['headers']); | |
} | |
if ($isPostRequestType) { | |
curl_setopt($ch, CURLOPT_POST, true); | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $options['request_type'] ?? 'GET'); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $options['query']); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment