Fullstack Portal Created by the HCMR for the Marine Strategy Framework Directive Program in order to cover demands and aspects considering extendability and maintainability
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

109 lines
3.2 KiB

<?php
namespace MSFD\Services;
use MSFD\Errors\ApiException;
use \Exception;
class API
{
public $url;
public $isBasicAuth;
private $curl;
public function __construct($url)
{
$this->url = $url;
$this->curl = curl_init();
}
public function get($endpoint, $data = [])
{
$url = $this->url . $endpoint;
curl_setopt($this->curl, CURLOPT_URL, $url);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
// Initialize cURL
if ($this->isBasicAuth) {
curl_setopt($this->curl, CURLOPT_USERPWD, "$this->username:$this->password");
curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
// Set cURL options
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl, CURLOPT_HTTPGET, true);
curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 30);
if (!empty($this->headers["Authorization"])) {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this::convert_headers($this->headers));
}
if (!empty($data)) {
// Set the HTTP method to GET
curl_setopt($this->curl, CURLOPT_URL, $url . "?" . http_build_query($data));
}
if ($this->hasFile) {
header('Content-Type: application/zip');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($url) . ".zip\"");
readfile($url . "?" . http_build_query($data));
exit();
}
// Check for errors
if (curl_errno($this->curl)) {
throw new \Exception(curl_error($this->curl));
}
return curl_exec($this->curl);
}
public function post($endpoint, $data = [], $isAuth = FALSE)
{
$url = $this->url . $endpoint;
curl_setopt($this->curl, CURLOPT_URL, $url);
// Set cURL options
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($this->curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 30);
curl_setopt($this->curl, CURLOPT_POST, TRUE);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
if (!empty($this->headers["Authorization"])) {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this::convert_headers($this->headers));
}
if ($isAuth) {
curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($this->curl, CURLINFO_HEADER_OUT, TRUE);
}
// Send the request
// Check for errors
if (curl_errno($this->curl)) {
throw new ApiException(curl_error($this->curl));
}
return curl_exec($this->curl);
}
public static function convert_headers($headerArray) {
foreach($headerArray as $key => $header) {
$headers[] = "{$key}: $header";
}
return $headers;
}
public function __destruct() {
curl_close($this->curl);
}
}