Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created December 22, 2017 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/7cf4c0794ccaf4d4cdc1add5926c17ee to your computer and use it in GitHub Desktop.
Save kobus1998/7cf4c0794ccaf4d4cdc1add5926c17ee to your computer and use it in GitHub Desktop.
PHP curl request helper / utill
<?php
namespace App\Utill;
class Request
{
/**
* @var Object curl request
*/
private $curl = null;
/**
* @var String request url
*/
private $url = null;
/**
* @var Array request headers
*/
private $headers = [];
/**
* @var String request agent
*/
private $agent = null;
/**
* @var String request method
*/
private $method = null;
/**
* @var Array request payload
*/
private $payload = [];
/**
* @var Array query strings
*/
private $query = [];
/**
* @var Array response
*/
private $result = [];
/**
* Constructor
* @param Array options (optional)
* @param Callable callback (optional)
* @return self
*/
function __construct ($options = null, $callback = null)
{
$this->curl = curl_init();
$this->agent = $_SERVER['HTTP_USER_AGENT'];
if (is_array($options))
{
$this->url = isset($options['url']) ? $options['url'] : null;
$this->headers = isset($options['headers']) ? $options['headers'] : [];
$this->agent = isset($options['agent']) ? $options['agent'] : null;
$this->method = isset($options['method']) ? $options['method'] : null;
$this->data = isset($options['data']) ? $options['data'] : [];
$this->query = isset($options['query']) ? $options['query'] : [];
if (isset($options['auth']))
{
$this->auth(
$options['auth']['user'],
$options['auth']['pass']
);
}
if (is_callable($callback))
{
$this->exec($callback);
}
}
return $this;
}
/**
* Helper: stringify the headers
* @return Array<String>
*/
private function stringifyHeaders ()
{
$return = [];
foreach ($this->headers as $key => $value)
{
$return[] = "$key: $value";
}
return $return;
}
/**
* Helper: create the query string
* @return String
*/
private function stringifyQuery ()
{
$return = '';
$i = 0;
if ($this->query)
foreach ($this->query as $key => $value)
{
if ($i == 0)
{
$return .= "?$key=$value";
}
else
{
$return .= "&$key=$value";
}
}
return $return;
}
/**
* Setup curl object
* @return self
*/
private function setUp ()
{
\curl_setopt_array($this->curl, [
CURLOPT_URL => $this->url . $this->stringifyQuery(),
CURLOPT_HTTPHEADER => $this->stringifyHeaders(),
CURLOPT_CUSTOMREQUEST => $this->method,
CURLOPT_USERAGENT => $this->agent,
CURLOPT_POSTFIELDS => $this->payload,
CURLOPT_POST => ($this->method != 'GET' || $this->method != 'DELETE') ? 1 : 0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => false
]);
return $this;
}
/**
* Execute request
* @param Callable callback
* @return Array
*/
public function exec ($callback = null)
{
$this->setUp();
$this->result['data'] = curl_exec($this->curl);
$this->result['error'] = curl_errno($this->curl);
$this->result['errorMessage'] = curl_error($this->curl);
$this->result['headers'] = curl_getinfo($this->curl);
curl_close($this->curl);
if (is_callable($callback))
{
$callback($this->result['data'], $this->result['errorMessage'], $this);
}
return $this->result['data'];
}
/**
* Get response headers
* @return Array
*/
public function getHeaders ()
{
return $this->result['headers'];
}
/**
* Get errors
* @return String
*/
public function getError ()
{
return $this->result['errorMessage'];
}
/**
* Get response payload
* @return Any
*/
public function getData ()
{
return $this->result['data'];
}
/**
* Get response payload
* @return Any
*/
public function getPayload ()
{
return $this->result['data'];
}
/**
* Set headers
* @param Array headers
* @return self
*/
public function headers ($headers)
{
$this->headers = array_merge($headers, $this->headers);
return $this;
}
/**
* Set query string
* @param Array query
* @return self
*/
public function query ($query)
{
$this->query = $query;
return $this;
}
/**
* Set request payload
* @param Array payload
* @return self
*/
public function data ($payload)
{
$this->payload = $payload;
return $this;
}
/**
* Set request payload
* @param Array payload
* @return self
*/
public function payload ($payload)
{
$this->payload = $payload;
return $this;
}
/**
* Set basic auth header
* @param String username
* @param String password
* @return self
*/
public function auth ($user, $pass)
{
$this->headers['Authorization'] = 'Basic ' . \base64_encode("$user:$pass");
return $this;
}
/**
* Set request url
* @param String url
* @return self
*/
public function url ($url)
{
$this->url = $url;
return $this;
}
/**
* Set request to get
* @param url (optional)
* @return self
*/
public function get ($url = null)
{
$url == null ?: $this->url = $url;
$this->method = 'GET';
return $this;
}
/**
* Set request to post
* @param url (optional)
* @param data (optional)
* @return self
*/
public function post ($url = null, $data = null)
{
$url == null ?: $this->url = $url;
$this->method = 'POST';
return $this;
}
/**
* Set request to put
* @param url (optional)
* @param data (optional)
* @return self
*/
public function put ($url = null, $data = null)
{
$url == null ?: $this->url = $url;
$this->method = 'PUT';
return $this;
}
/**
* Set request to patch
* @param url (optional)
* @param data (optional)
* @return self
*/
public function patch ($url = null, $data = null)
{
$url == null ?: $this->url = $url;
$this->method = 'PATCH';
return $this;
}
/**
* Set request to delete
* @param url (optional)
* @return self
*/
public function delete ($url = null)
{
$url == null ?: $this->url = $url;
$this->method = 'DELETE';
return $this;
}
}
@kobus1998
Copy link
Author

use App\Utill\Request;

// multiple ways to use it

new Request([
  'url' => 'x',
  'method' => 'x',
  'data' => [],
  'auth' => ['user' => 'x', 'pass' => 'x'],
  'headers' => []
], function ($data, $err, $object) {

});

(new Request())
  ->get($url)
  ->auth('user', 'pass')
  ->query(['apiKey' => 'key'])
  ->exec(function ($data, $err, $object) {

    echo '<pre>';
    var_dump(json_decode($data));
    echo '</pre>';

  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment