Files
zurawik.pl/core/class/RestRequest.class.php
2026-05-15 18:33:51 +02:00

115 lines
2.8 KiB
PHP

<?php
/**
* wideohosting-api-war-client
* Copyright (C) 2008 Wirtualna Polska SA
*
* File: RestRequest.php
* Created: 2008-11-04
*/
/**
* Abstrakcyjna klasa reprezentuj±ca ¿±danie REST.
*
* @author WP
*/
abstract class RestRequest {
/**
* Bazowy URL, pod jakim jest widoczne API.
*/
private $baseUrl = "http://wpapi.wp.pl/api";
/**
* Konstruktor.
*/
public function __construct() {
}
/**
* Wysy³a request HTTP do API.
*
* @param $ch cURL handler
*/
private function sendRequest($ch) {
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size -4);
$body = substr($response, $header_size);
$status = $this->checkResponse($headers, $body);
curl_close($ch);
return $body;
}
private function buildResourceUrl($resource) {
return $this->baseUrl . $resource;
}
// POST
public function doPostCall($resource, $postArgs) {
$ch = curl_init($this->buildResourceUrl($resource));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookies");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies");
return $this->sendRequest($ch);
}
// GET
public function doGetCall($resource) {
$ch = curl_init($this->buildResourceUrl($resource));
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookies");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies");
return $this->sendRequest($ch);
}
// DEL
public function doDelCall($resource) {
$ch = curl_init($this->buildResourceUrl($resource));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookies");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies");
return $this->sendRequest($ch);
}
// sprawdzenie statusu odpowiedzi
private function checkResponse($headers, $body) {
$status_code = array ();
preg_match('/\d\d\d/', $headers, $status_code);
switch ($status_code[0]) {
case 100:
case 200 :
case 201 :
case 202 :
break; //sukces
case 401:
throw new SecurityException('Raz');
case 403:
throw new SecurityException("Unauthorized");
break;
default :
throw new ApiException("Invocation error - code " + $status_code[0]);
}
echo "Response " + $status_code[0] . "\n";
return $status_code[0];
}
/**
* Metody wysy³aj±ce odpowiednie ¿±danie do API.
*/
public abstract function send();
public abstract function getStatus();
public abstract function authorize();
public abstract function delete();
}
?>