Repository navigation
Expand file tree
/
Copy pathSimpleRESTResource.php
More file actions
87 lines (73 loc) · 1.88 KB
/
Copy pathSimpleRESTResource.php
File metadata and controls
87 lines (73 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/*
* A simple class for making get REST requests
* Authored by Rory Cartwright
* GPL2: https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html
*/
class SimpleRESTResource
{
//Properties
protected $api_url;
protected $api_key;
protected $req_string;
protected $result;
//Constructor
public function __construct($api_url, $api_key)
{
$this->api_url = (string)$api_url;
$this->api_key = (string)$api_key;
$this->req_string = '';
$this->result = false;
}
//Construct requests
//args: Formatted query url string/Array of key => value pairs
public function request($args)
{
//Empty request string
if(empty($args))
$this->result = $this->getRequestAsArray();
//if args are in string form
if(is_string($args) && $this->req_string = $this->validateURL($this->getAPIURL() . '&' . $args))
{
$this->result = $this->getRequestAsArray();
}
//if args are array of key-value pairs
if(is_array($args))
{
$request_parameters = '';
foreach($args as $arg => $val)
{
$request_parameters .= '&' . urlencode($arg) . '=' . urlencode($val);
}
if($this->req_string = $this->validateURL($this->getAPIURL() . $request_parameters))
$this->result = $this->getRequestAsArray();
}
return $this->result;
}
//Return the result
public function getResult()
{
return $this->result;
}
protected function performGetRequest()
{
return file_get_contents($this->req_string);
}
protected function getRequestAsArray()
{
return json_decode($this->performGetRequest($this->req_string), true);
}
//Return the requested url with the key appended as a parameter
protected function getAPIURL()
{
return $this->api_url . '?apikey=' . $this->api_key;
}
//A really simple function to test that we have a reasonably sensible URL
protected function validateURL($string)
{
if(parse_url($string))
return $string;
return false;
}
}
?>