1: <?php
2: 3: 4: 5: 6: 7:
8:
9: namespace ApiAxle\Shared;
10: use ApiAxle\Shared\HttpRequest;
11: use ApiAxle\Shared\ApiException;
12:
13: 14: 15: 16: 17:
18: class Utilities
19: {
20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33:
34: public static function callApi($apiPath, $method='GET', $data=null, $config)
35: {
36: $headers = array(
37: "Accept: application/json",
38: );
39:
40: if(($method == 'POST' || $method == 'PUT') && is_array($data)){
41: $headers[] = "Content-Type: application/json";
42: }
43:
44: $api_key = $config->getKey();
45: $api_sig = $config->getSignature();
46:
47: if(strpos($apiPath,'?')){
48: $apiPath .= "&api_key=$api_key&api_sig=$api_sig";
49: } else {
50: $apiPath .= "?api_key=$api_key&api_sig=$api_sig";
51: }
52:
53: if($method == 'GET' && is_array($data)){
54: foreach($data as $param => $value){
55: $apiPath .= '&'.$param.'='.$value;
56: }
57: }
58:
59: $json_data = false;
60:
61: if(is_array($data)){
62: $json_data = json_encode($data);
63: $headers[] = "Content-Length: ". strlen($json_data);
64: }
65:
66: $url = $config->getEndpoint().'/'.$apiPath;
67: $request = HttpRequest::request($url, $method, $json_data, $headers, $config);
68: if($request){
69: $results = json_decode($request);
70: if($results->meta->status_code >= 200 && $results->meta->status_code < 300){
71: return $results->results;
72: } elseif($results->meta->status_code >= 300 && $results->meta->status_code < 400){
73: throw new ApiException('API returned a redirection', '200', null, $results->meta->status_code, $results);
74: } elseif($results->meta->status_code >= 400 && $results->meta->status_code < 600){
75: throw new ApiException('API returned error: '.$results->results->error->message, '201', null, $results->meta->status_code, $results);
76: }
77: } else {
78: throw new \ErrorException('API did not return properly.','202',null);
79: }
80: }
81: }