Conditions | 11 |
Paths | 247 |
Total Lines | 71 |
Code Lines | 47 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
13 | public function request($url, array $data, $method = 'POST', array $headers = null) { |
||
14 | try { |
||
15 | $ch = curl_init(); |
||
16 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
||
17 | |||
18 | if (!boolval($headers)) { |
||
19 | $headers = ['Content-Type: application/json; charset=utf-8']; |
||
20 | } |
||
21 | |||
22 | switch ($method) { |
||
23 | case 'GET': |
||
24 | $url .= '?'; |
||
25 | |||
26 | foreach ($data as $key => $value) { |
||
27 | $url .= $key . '=' . $value . '&'; |
||
28 | } |
||
29 | |||
30 | rtrim($url, '&'); |
||
31 | break; |
||
32 | case 'POST': |
||
33 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); |
||
34 | curl_setopt($ch, CURLOPT_POST, true); |
||
35 | break; |
||
36 | case 'HEAD': |
||
37 | curl_setopt($ch, CURLOPT_HEADER, true); |
||
38 | curl_setopt($ch, CURLOPT_NOBODY, true); |
||
39 | break; |
||
40 | default: |
||
41 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); |
||
42 | } |
||
43 | |||
44 | if (in_array($method, ['POST', 'PUT'])) { |
||
45 | if (!empty($data)) { |
||
46 | curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); |
||
47 | } |
||
48 | } |
||
49 | |||
50 | $url = rtrim($this->baseUrl, '/') . '/' . ltrim($url, '/'); |
||
51 | curl_setopt($ch, CURLOPT_URL, $url); |
||
52 | |||
53 | $resultJson = curl_exec($ch); |
||
54 | |||
55 | $content = json_decode($resultJson, true); |
||
56 | $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
||
57 | |||
58 | curl_close($ch); |
||
59 | |||
60 | if (is_null($content) && in_array($httpcode, [400, 500])) { |
||
61 | return array( |
||
62 | 'status' => $httpcode, |
||
63 | 'content' => array( |
||
64 | 'error' => ['reason' => $resultJson] |
||
65 | ) |
||
66 | ); |
||
67 | } |
||
68 | |||
69 | return array( |
||
70 | 'status' => $httpcode, |
||
71 | 'content' => $content |
||
72 | ); |
||
73 | } catch (\Exception $ex) { |
||
74 | return array( |
||
75 | 'status' => 500, |
||
76 | 'content' => array( |
||
77 | 'error' => ['reason' => $ex->getMessage()], |
||
78 | 'detail' => $ex->getTraceAsString(), |
||
79 | 'line' => $ex->getLine() |
||
80 | ) |
||
81 | ); |
||
82 | } |
||
83 | } |
||
84 | |||
99 | } |