Conditions | 13 |
Paths | 144 |
Total Lines | 44 |
Code Lines | 30 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 1 |
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 |
||
111 | public static function sendAsyncRequest($url, $params = [], $method = 'POST') |
||
112 | { |
||
113 | $method = strtoupper($method); |
||
114 | $method = $method == 'POST' ? 'POST' : 'GET'; |
||
115 | //构造传递的参数 |
||
116 | if (is_array($params)) { |
||
117 | $post_params = []; |
||
118 | foreach ($params as $k => &$v) { |
||
119 | if (is_array($v)) { |
||
120 | $v = implode(',', $v); |
||
121 | } |
||
122 | $post_params[] = $k . '=' . urlencode($v); |
||
123 | } |
||
124 | $post_string = implode('&', $post_params); |
||
125 | } else { |
||
126 | $post_string = $params; |
||
127 | } |
||
128 | $parts = parse_url($url); |
||
129 | //构造查询的参数 |
||
130 | if ($method == 'GET' && $post_string) { |
||
131 | $parts['query'] = isset($parts['query']) ? $parts['query'] . '&' . $post_string : $post_string; |
||
132 | $post_string = ''; |
||
133 | } |
||
134 | $parts['query'] = isset($parts['query']) && $parts['query'] ? '?' . $parts['query'] : ''; |
||
135 | //发送socket请求,获得连接句柄 |
||
136 | $fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 3); |
||
137 | if (!$fp) { |
||
|
|||
138 | return false; |
||
139 | } |
||
140 | //设置超时时间 |
||
141 | stream_set_timeout($fp, 3); |
||
142 | $out = "{$method} {$parts['path']}{$parts['query']} HTTP/1.1\r\n"; |
||
143 | $out .= "Host: {$parts['host']}\r\n"; |
||
144 | $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; |
||
145 | $out .= "Content-Length: " . strlen($post_string) . "\r\n"; |
||
146 | $out .= "Connection: Close\r\n\r\n"; |
||
147 | if ($post_string !== '') { |
||
148 | $out .= $post_string; |
||
149 | } |
||
150 | fwrite($fp, $out); |
||
151 | //不用关心服务器返回结果 |
||
152 | //echo fread($fp, 1024); |
||
153 | fclose($fp); |
||
154 | return true; |
||
155 | } |
||
186 |