· 6 years ago · Sep 03, 2019, 03:42 PM
1<?php
2
3namespace erfanbagussetiana\rajaongkirpro\app;
4
5use Exception;
6
7abstract class Api {
8 protected $method;
9 protected $parameters;
10 protected $data;
11 protected $endPointAPI;
12 protected $overWriteOptions = [];
13 protected $apiKey;
14
15 public function __construct(){
16 $this->endPointAPI = config('rajaongkir.end_point_api', 'http://rajaongkir.com/api/starter');
17 $this->apiKey = config('rajaongkir.api_key');
18 }
19
20 public function all(){
21 return $this->GetData()->data;
22 }
23
24 public function find($id){
25 $this->parameters = "?id=".$id;
26 return $this->GetData()->data;
27 }
28
29 public function search($column, $searchKey){
30 $data = ( empty($this->data) ) ? $this->GetData()->data : $this->data;
31
32 $rowColumn = array_column($data, $column);
33 $s = preg_quote(ucwords($searchKey), '~');
34 $res = preg_grep('~' . $s . '~', $rowColumn);
35 $resKey = array_keys($res);
36 $temp = [];
37 foreach($data as $key => $val){
38 if(in_array($key, $resKey)){
39 array_push($temp, $val);
40 }
41 }
42
43 $this->data = $temp;
44
45 return $this;
46 }
47
48 public function get(){
49 return $this->data;
50 }
51
52 public function count(){
53 ( empty($this->data) ) ? $this->GetData()->data : $this->data;
54 return count($this->data);
55
56 }
57
58 protected function GetData(){
59 $curl = curl_init();
60
61 $options = [
62 CURLOPT_URL => $this->endPointAPI."/".$this->method.$this->parameters,
63 CURLOPT_RETURNTRANSFER => true,
64 CURLOPT_ENCODING => "",
65 CURLOPT_MAXREDIRS => 10,
66 CURLOPT_TIMEOUT => 30,
67 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
68 CURLOPT_CUSTOMREQUEST => "GET",
69 CURLOPT_HTTPHEADER => [
70 "key: ".$this->apiKey
71 ],
72 ];
73
74 foreach( $this->overWriteOptions as $key => $val){
75 $options[$key] = $val;
76 }
77
78 curl_setopt_array($curl, $options);
79
80 $response = curl_exec($curl);
81 $err = curl_error($curl);
82
83 curl_close($curl);
84
85 if ($err) {
86 throw new Exception($err, 1);
87 } else {
88 $data = json_decode($response, true);
89 $code = $data['rajaongkir']['status']['code'];
90 if($code == 400){
91 throw new Exception($data['rajaongkir']['status']['description'], 1);
92 }else{
93 $this->data = $data['rajaongkir']['results'];
94 return $this;
95 }
96 }
97 }
98}