Passed
Push — master ( ee094a...0581a6 )
by IRFA
02:19 queued 11s
created

Api::exceptCurl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
/*
4
    Raja Ongkir API
5
    Author: Irfa Ardiansyah <[email protected]>
6
*/
7
8
namespace Irfa\RajaOngkir\Ongkir\Func;
9
10
use Exception;
11
use Irfa\RajaOngkir\Caching\CacheCurl;
12
13
class Api extends CacheCurl
14
{
15
    private static $account_type;
16
    private static $api_key;
17
    private static $api_version;
18
    private static $url;
19
    private static $count = 0;
0 ignored issues
show
introduced by
The private property $count is not used, and could be removed.
Loading history...
20
21
    private static function setup_option()
22
    {
23
        if (function_exists('config') and function_exists('app')) {//Load Config For Laravel
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
24
            self::$account_type = strtolower(config('irfa.rajaongkir.account_type'));
25
            self::$api_key = config('irfa.rajaongkir.api_key');
26
            self::$api_version = config('irfa.rajaongkir.api_version');
27
        } else {//Load config For PHP Native
28
            require __DIR__.'../../../../config/config.php';
29
            self::$account_type = strtolower($config['account_type']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $config seems to be never defined.
Loading history...
30
            self::$api_key = $config['api_key'];
31
            self::$api_version = $config['api_version'];
32
        }
33
        if (self::$account_type == 'pro') {
34
            self::$url = 'https://pro.rajaongkir.com/api';
35
        } else {
36
            self::$url = 'https://api.rajaongkir.com/'.self::$account_type;
37
        }
38
    }
39
40
    protected static function cacheProvince()
41
    {
42
        self::setup_option();
43
        echo "Retrieving data from \033[96m".self::$url."...\033[0m".PHP_EOL;
44
        CacheCurl::caching(self::get_province())->province();
45
    }
46
47
    protected static function cacheCity()
48
    {
49
        self::setup_option();
50
        echo "Retrieving data from\033[96m ".self::$url."...\033[0m".PHP_EOL;
51
        CacheCurl::caching(self::get_city())->city();
52
    }
53
    protected static function cacheSubDistrict($arr)
54
    {
55
        self::setup_option();
56
        echo "Retrieving data from\033[96m ".self::$url."...\033[0m".PHP_EOL;
57
        CacheCurl::caching(self::getSubdistrict($arr))->subdistrict();
58
    }
59
    protected static function get_province($arr = null)
60
    {
61
        if ($arr != null) {
62
            $province_id = array_key_exists('province_id', $arr) ? '?id='.$arr['province_id'] : null;
63
        } else {
64
            $province_id = null;
65
        }
66
        self::setup_option();
67
        $curl = curl_init();
68
        curl_setopt_array($curl, [
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_setopt_array() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

68
        curl_setopt_array(/** @scrutinizer ignore-type */ $curl, [
Loading history...
69
            CURLOPT_URL            => self::$url.'/province'.$province_id,
70
            CURLOPT_RETURNTRANSFER => true,
71
            CURLOPT_ENCODING       => '',
72
            CURLOPT_MAXREDIRS      => 10,
73
            CURLOPT_TIMEOUT        => 30,
74
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
75
            CURLOPT_CUSTOMREQUEST  => 'GET',
76
            CURLOPT_HTTPHEADER     => [
77
                'key: '.self::$api_key,
78
            ],
79
        ]);
80
        $response = curl_exec($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

80
        $response = curl_exec(/** @scrutinizer ignore-type */ $curl);
Loading history...
81
        $err = curl_error($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_error() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

81
        $err = curl_error(/** @scrutinizer ignore-type */ $curl);
Loading history...
82
83
        curl_close($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

83
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
84
85
        if ($err) {
86
            self::exceptCurl($err);
87
        } else {
88
            $json = json_decode($response, false)->rajaongkir;
89
            if ($json->status->code == '400') {
90
                throw new Exception($json->status->description);
91
            } else {
92
                $res = $json->results;
93
94
                return $res;
95
            }
96
        }
97
    }
98
99
    protected static function get_city($arr = null)
100
    {
101
        if ($arr != null) {
102
            $province_id = array_key_exists('province_id', $arr) ? '?province='.$arr['province_id'] : null;
103
        } else {
104
            $province_id = null;
105
        }
106
        self::setup_option();
107
        $curl = curl_init();
108
        curl_setopt_array($curl, [
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_setopt_array() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

108
        curl_setopt_array(/** @scrutinizer ignore-type */ $curl, [
Loading history...
109
            CURLOPT_URL            => self::$url.'/city'.$province_id,
110
            CURLOPT_RETURNTRANSFER => true,
111
            CURLOPT_ENCODING       => '',
112
            CURLOPT_MAXREDIRS      => 10,
113
            CURLOPT_TIMEOUT        => 30,
114
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
115
            CURLOPT_CUSTOMREQUEST  => 'GET',
116
            CURLOPT_HTTPHEADER     => [
117
                'key: '.self::$api_key,
118
            ],
119
        ]);
120
        $response = curl_exec($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

120
        $response = curl_exec(/** @scrutinizer ignore-type */ $curl);
Loading history...
121
        $err = curl_error($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_error() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

121
        $err = curl_error(/** @scrutinizer ignore-type */ $curl);
Loading history...
122
123
        curl_close($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

123
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
124
125
        if ($err) {
126
           self::exceptCurl($err);
127
        } else {
128
            $json = json_decode($response, false)->rajaongkir;
129
            if ($json->status->code == '400') {
130
                throw new Exception($json->status->description);
131
            } else {
132
                $res = $json->results;
133
134
                return $res;
135
            }
136
        }
137
    }
138
139
    protected static function get_courier($arr)
140
    {
141
        $origin = $arr['origin'];
142
        $destination = $arr['destination'];
143
        $weight = $arr['weight'];
144
        $courier = $arr['courier'];
145
        $res = self::curl_cost_get($origin, $destination, $weight, $courier);
146
147
        return $res;
148
    }
149
150
    protected static function get_cost_details($arr)
151
    {
152
        $origin = $arr['origin'];
153
        $destination = $arr['destination'];
154
        $weight = $arr['weight'];
155
        $courier = $arr['courier'];
156
        $res = self::curl_cost_get($origin, $destination, $weight, $courier);
157
158
        return $res[0]->costs;
159
    }
160
161
    private static function curl_cost_get($origin, $destination, $weight, $courier)
162
    {
163
        $curl = curl_init();
164
165
        curl_setopt_array($curl, self::curl_cost_option($origin, $destination, $weight, $courier));
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_setopt_array() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

165
        curl_setopt_array(/** @scrutinizer ignore-type */ $curl, self::curl_cost_option($origin, $destination, $weight, $courier));
Loading history...
166
167
        $response = curl_exec($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

167
        $response = curl_exec(/** @scrutinizer ignore-type */ $curl);
Loading history...
168
        $err = curl_error($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_error() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

168
        $err = curl_error(/** @scrutinizer ignore-type */ $curl);
Loading history...
169
170
        curl_close($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

170
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
171
172
        if ($err) {
173
            echo "Can't connect to server, please check your internet connection.";
174
            exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
175
        } else {
176
            $json = json_decode($response, false)->rajaongkir;
177
            if ($json->status->code == '400') {
178
                throw new Exception($json->status->description);
179
            } else {
180
                $res = $json->results;
181
182
                return $res;
183
            }
184
        }
185
    }
186
187
    private static function curl_cost_option($origin, $destination, $weight, $courier)
188
    {
189
        self::setup_option();
190
191
        return [
192
            CURLOPT_URL            => self::$url.'/cost',
193
            CURLOPT_RETURNTRANSFER => true,
194
            CURLOPT_ENCODING       => '',
195
            CURLOPT_MAXREDIRS      => 10,
196
            CURLOPT_TIMEOUT        => 30,
197
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
198
            CURLOPT_CUSTOMREQUEST  => 'POST',
199
            CURLOPT_POSTFIELDS     => 'origin='.$origin.'&destination='.$destination.'&weight='.$weight.'&courier='.strtolower($courier),
200
            CURLOPT_HTTPHEADER     => [
201
                'content-type: application/x-www-form-urlencoded',
202
                'key: '.self::$api_key,
203
            ],
204
        ];
205
    }
206
///PRO
207
     protected static function getSubdistrict($arr = null)
208
    {
209
        if ($arr != null) {
210
            $city = array_key_exists('city', $arr) ? '?city='.$arr['city'] : null;
211
        } else {
212
            $city = null;
213
        }
214
        self::setup_option();
215
        $curl = curl_init();
216
        curl_setopt_array($curl, [
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_setopt_array() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

216
        curl_setopt_array(/** @scrutinizer ignore-type */ $curl, [
Loading history...
217
            CURLOPT_URL            => self::$url.'/subdistrict'.$city,
218
            CURLOPT_RETURNTRANSFER => true,
219
            CURLOPT_ENCODING       => '',
220
            CURLOPT_MAXREDIRS      => 10,
221
            CURLOPT_TIMEOUT        => 30,
222
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
223
            CURLOPT_CUSTOMREQUEST  => 'GET',
224
            CURLOPT_HTTPHEADER     => [
225
                'key: '.self::$api_key,
226
            ],
227
        ]);
228
        $response = curl_exec($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

228
        $response = curl_exec(/** @scrutinizer ignore-type */ $curl);
Loading history...
229
        $err = curl_error($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_error() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

229
        $err = curl_error(/** @scrutinizer ignore-type */ $curl);
Loading history...
230
231
        curl_close($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

231
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
232
233
        if ($err) {
234
            self::exceptCurl($err);
235
        } else {
236
            $json = json_decode($response, false)->rajaongkir;
237
            if ($json->status->code == '400') {
238
                throw new Exception($json->status->description);
239
            } else {
240
                $res = $json->results;
241
242
                return $res;
243
            }
244
        }
245
    }
246
247
private static function exceptCurl($err){
248
      if(php_sapi_name() == "cli"){
249
                echo "Can't connect to server, please check your internet connection.\n";
250
                echo "Exception: \033[31m".$err;
251
                exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
252
            } else{
253
                throw new Exception($err);
254
            }
255
}
256
257
protected static function test_connection($arr = null)
258
{
259
        if ($arr != null) {
260
            $province_id = array_key_exists('province_id', $arr) ? '?id='.$arr['province_id'] : null;
261
        } else {
262
            $province_id = null;
263
        }
264
        self::setup_option();
265
        $curl = curl_init();
266
        curl_setopt_array($curl, [
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_setopt_array() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

266
        curl_setopt_array(/** @scrutinizer ignore-type */ $curl, [
Loading history...
267
            CURLOPT_URL            => self::$url.'/province'.$province_id,
268
            CURLOPT_RETURNTRANSFER => true,
269
            CURLOPT_ENCODING       => '',
270
            CURLOPT_MAXREDIRS      => 10,
271
            CURLOPT_TIMEOUT        => 30,
272
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
273
            CURLOPT_CUSTOMREQUEST  => 'GET',
274
            CURLOPT_HTTPHEADER     => [
275
                'key: '.self::$api_key,
276
            ],
277
        ]);
278
        $response = curl_exec($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

278
        $response = curl_exec(/** @scrutinizer ignore-type */ $curl);
Loading history...
279
        $err = curl_error($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_error() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

279
        $err = curl_error(/** @scrutinizer ignore-type */ $curl);
Loading history...
280
281
        curl_close($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

281
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
282
283
        if ($err) {
284
            $result = false;
285
            return $result;
286
        } else {
287
            $data = json_decode($response, false);
288
            if(!empty($data)){
289
                $json = $data->rajaongkir;
290
                if ($json->status->code == '400') {
291
                    $result = ['res' => $json->status->code,'success'=> false];
292
                    return $result;
293
                } else {
294
                    $result = ['res' => "Connected to server.",'success'=> true];
295
                    return $result;
296
                }
297
             } else{
298
                 $result = ['res' => "Data is Empty.",'success'=> false];
299
                return $result;
300
             }
301
        }
302
    }
303
}
304