Complex classes like CurlFactory often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use CurlFactory, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
20 | class CurlFactory implements CurlFactoryInterface |
||
21 | { |
||
22 | public const CURL_VERSION_STR = 'curl_version'; |
||
23 | |||
24 | /** |
||
25 | * @deprecated |
||
26 | */ |
||
27 | public const LOW_CURL_VERSION_NUMBER = '7.21.2'; |
||
28 | |||
29 | /** |
||
30 | * @var resource[]|\CurlHandle[] |
||
31 | */ |
||
32 | private $handles = []; |
||
33 | |||
34 | /** |
||
35 | * @var int Total number of idle handles to keep in cache |
||
36 | */ |
||
37 | private $maxHandles; |
||
38 | |||
39 | /** |
||
40 | * @param int $maxHandles Maximum number of idle handles. |
||
41 | */ |
||
42 | public function __construct(int $maxHandles) |
||
46 | |||
47 | public function create(RequestInterface $request, array $options): EasyHandle |
||
48 | { |
||
49 | if (isset($options['curl']['body_as_string'])) { |
||
50 | $options['_body_as_string'] = $options['curl']['body_as_string']; |
||
51 | unset($options['curl']['body_as_string']); |
||
52 | } |
||
53 | |||
54 | $easy = new EasyHandle; |
||
55 | $easy->request = $request; |
||
56 | $easy->options = $options; |
||
57 | $conf = $this->getDefaultConf($easy); |
||
58 | $this->applyMethod($easy, $conf); |
||
59 | $this->applyHandlerOptions($easy, $conf); |
||
60 | $this->applyHeaders($easy, $conf); |
||
61 | unset($conf['_headers']); |
||
62 | |||
63 | // Add handler options from the request configuration options |
||
64 | if (isset($options['curl'])) { |
||
65 | $conf = \array_replace($conf, $options['curl']); |
||
66 | } |
||
67 | |||
68 | $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); |
||
69 | $easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init(); |
||
70 | curl_setopt_array($easy->handle, $conf); |
||
71 | |||
72 | return $easy; |
||
73 | } |
||
74 | |||
75 | public function release(EasyHandle $easy): void |
||
76 | { |
||
77 | $resource = $easy->handle; |
||
78 | unset($easy->handle); |
||
79 | |||
80 | if (\count($this->handles) >= $this->maxHandles) { |
||
81 | \curl_close($resource); |
||
82 | } else { |
||
83 | // Remove all callback functions as they can hold onto references |
||
84 | // and are not cleaned up by curl_reset. Using curl_setopt_array |
||
85 | // does not work for some reason, so removing each one |
||
86 | // individually. |
||
87 | \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null); |
||
88 | \curl_setopt($resource, \CURLOPT_READFUNCTION, null); |
||
89 | \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null); |
||
90 | \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null); |
||
91 | \curl_reset($resource); |
||
92 | $this->handles[] = $resource; |
||
93 | } |
||
94 | } |
||
95 | |||
96 | /** |
||
97 | * Completes a cURL transaction, either returning a response promise or a |
||
98 | * rejected promise. |
||
99 | * |
||
100 | * @param callable(RequestInterface, array): PromiseInterface $handler |
||
101 | * @param CurlFactoryInterface $factory Dictates how the handle is released |
||
102 | */ |
||
103 | public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface |
||
104 | { |
||
105 | if (isset($easy->options['on_stats'])) { |
||
106 | self::invokeStats($easy); |
||
107 | } |
||
108 | |||
109 | if (!$easy->response || $easy->errno) { |
||
110 | return self::finishError($handler, $easy, $factory); |
||
111 | } |
||
112 | |||
113 | // Return the response if it is present and there is no error. |
||
114 | $factory->release($easy); |
||
115 | |||
116 | // Rewind the body of the response if possible. |
||
117 | $body = $easy->response->getBody(); |
||
118 | if ($body->isSeekable()) { |
||
119 | $body->rewind(); |
||
120 | } |
||
121 | |||
122 | return new FulfilledPromise($easy->response); |
||
123 | } |
||
124 | |||
125 | private static function invokeStats(EasyHandle $easy): void |
||
126 | { |
||
127 | $curlStats = \curl_getinfo($easy->handle); |
||
128 | $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME); |
||
129 | $stats = new TransferStats( |
||
130 | $easy->request, |
||
131 | $easy->response, |
||
132 | $curlStats['total_time'], |
||
133 | $easy->errno, |
||
134 | $curlStats |
||
135 | ); |
||
136 | ($easy->options['on_stats'])($stats); |
||
137 | } |
||
138 | |||
139 | /** |
||
140 | * @param callable(RequestInterface, array): PromiseInterface $handler |
||
141 | */ |
||
142 | private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface |
||
143 | { |
||
144 | // Get error information and release the handle to the factory. |
||
145 | $ctx = [ |
||
146 | 'errno' => $easy->errno, |
||
147 | 'error' => \curl_error($easy->handle), |
||
148 | 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME), |
||
149 | ] + \curl_getinfo($easy->handle); |
||
150 | $ctx[self::CURL_VERSION_STR] = \curl_version()['version']; |
||
151 | $factory->release($easy); |
||
152 | |||
153 | // Retry when nothing is present or when curl failed to rewind. |
||
154 | if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) { |
||
155 | return self::retryFailedRewind($handler, $easy, $ctx); |
||
156 | } |
||
157 | |||
158 | return self::createRejection($easy, $ctx); |
||
159 | } |
||
160 | |||
161 | private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface |
||
162 | { |
||
163 | static $connectionErrors = [ |
||
164 | \CURLE_OPERATION_TIMEOUTED => true, |
||
165 | \CURLE_COULDNT_RESOLVE_HOST => true, |
||
166 | \CURLE_COULDNT_CONNECT => true, |
||
167 | \CURLE_SSL_CONNECT_ERROR => true, |
||
168 | \CURLE_GOT_NOTHING => true, |
||
169 | ]; |
||
170 | |||
171 | if ($easy->createResponseException) { |
||
172 | return P\Create::rejectionFor( |
||
173 | new RequestException( |
||
174 | 'An error was encountered while creating the response', |
||
175 | $easy->request, |
||
176 | $easy->response, |
||
177 | $easy->createResponseException, |
||
178 | $ctx |
||
179 | ) |
||
180 | ); |
||
181 | } |
||
182 | |||
183 | // If an exception was encountered during the onHeaders event, then |
||
184 | // return a rejected promise that wraps that exception. |
||
185 | if ($easy->onHeadersException) { |
||
186 | return P\Create::rejectionFor( |
||
187 | new RequestException( |
||
188 | 'An error was encountered during the on_headers event', |
||
189 | $easy->request, |
||
190 | $easy->response, |
||
191 | $easy->onHeadersException, |
||
192 | $ctx |
||
193 | ) |
||
194 | ); |
||
195 | } |
||
196 | |||
197 | $message = \sprintf( |
||
198 | 'cURL error %s: %s (%s)', |
||
199 | $ctx['errno'], |
||
200 | $ctx['error'], |
||
201 | 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html' |
||
202 | ); |
||
203 | $uriString = (string) $easy->request->getUri(); |
||
204 | if ($uriString !== '' && false === \strpos($ctx['error'], $uriString)) { |
||
205 | $message .= \sprintf(' for %s', $uriString); |
||
206 | } |
||
207 | |||
208 | // Create a connection exception if it was a specific error code. |
||
209 | $error = isset($connectionErrors[$easy->errno]) |
||
210 | ? new ConnectException($message, $easy->request, null, $ctx) |
||
211 | : new RequestException($message, $easy->request, $easy->response, null, $ctx); |
||
212 | |||
213 | return P\Create::rejectionFor($error); |
||
214 | } |
||
215 | |||
216 | /** |
||
217 | * @return array<int|string, mixed> |
||
|
|||
218 | */ |
||
219 | private function getDefaultConf(EasyHandle $easy): array |
||
220 | { |
||
221 | $conf = [ |
||
222 | '_headers' => $easy->request->getHeaders(), |
||
223 | \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), |
||
224 | \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), |
||
225 | \CURLOPT_RETURNTRANSFER => false, |
||
226 | \CURLOPT_HEADER => false, |
||
227 | \CURLOPT_CONNECTTIMEOUT => 150, |
||
228 | ]; |
||
229 | |||
230 | if (\defined('CURLOPT_PROTOCOLS')) { |
||
231 | $conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS; |
||
232 | } |
||
233 | |||
234 | $version = $easy->request->getProtocolVersion(); |
||
235 | if ($version == 1.1) { |
||
236 | $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; |
||
237 | } elseif ($version == 2.0) { |
||
238 | $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; |
||
239 | } else { |
||
240 | $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; |
||
241 | } |
||
242 | |||
243 | return $conf; |
||
244 | } |
||
245 | |||
246 | private function applyMethod(EasyHandle $easy, array &$conf): void |
||
247 | { |
||
248 | $body = $easy->request->getBody(); |
||
249 | $size = $body->getSize(); |
||
250 | |||
251 | if ($size === null || $size > 0) { |
||
252 | $this->applyBody($easy->request, $easy->options, $conf); |
||
253 | return; |
||
254 | } |
||
255 | |||
256 | $method = $easy->request->getMethod(); |
||
257 | if ($method === 'PUT' || $method === 'POST') { |
||
258 | // See https://tools.ietf.org/html/rfc7230#section-3.3.2 |
||
259 | if (!$easy->request->hasHeader('Content-Length')) { |
||
260 | $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; |
||
261 | } |
||
262 | } elseif ($method === 'HEAD') { |
||
263 | $conf[\CURLOPT_NOBODY] = true; |
||
264 | unset( |
||
265 | $conf[\CURLOPT_WRITEFUNCTION], |
||
266 | $conf[\CURLOPT_READFUNCTION], |
||
267 | $conf[\CURLOPT_FILE], |
||
268 | $conf[\CURLOPT_INFILE] |
||
269 | ); |
||
270 | } |
||
271 | } |
||
272 | |||
273 | private function applyBody(RequestInterface $request, array $options, array &$conf): void |
||
274 | { |
||
275 | $size = $request->hasHeader('Content-Length') |
||
276 | ? (int) $request->getHeaderLine('Content-Length') |
||
277 | : null; |
||
278 | |||
279 | // Send the body as a string if the size is less than 1MB OR if the |
||
280 | // [curl][body_as_string] request value is set. |
||
281 | if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) { |
||
282 | $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody(); |
||
283 | // Don't duplicate the Content-Length header |
||
284 | $this->removeHeader('Content-Length', $conf); |
||
285 | $this->removeHeader('Transfer-Encoding', $conf); |
||
286 | } else { |
||
287 | $conf[\CURLOPT_UPLOAD] = true; |
||
288 | if ($size !== null) { |
||
289 | $conf[\CURLOPT_INFILESIZE] = $size; |
||
290 | $this->removeHeader('Content-Length', $conf); |
||
291 | } |
||
292 | $body = $request->getBody(); |
||
293 | if ($body->isSeekable()) { |
||
294 | $body->rewind(); |
||
295 | } |
||
296 | $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) { |
||
297 | return $body->read($length); |
||
298 | }; |
||
299 | } |
||
300 | |||
301 | // If the Expect header is not present, prevent curl from adding it |
||
302 | if (!$request->hasHeader('Expect')) { |
||
303 | $conf[\CURLOPT_HTTPHEADER][] = 'Expect:'; |
||
304 | } |
||
305 | |||
306 | // cURL sometimes adds a content-type by default. Prevent this. |
||
307 | if (!$request->hasHeader('Content-Type')) { |
||
308 | $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:'; |
||
309 | } |
||
310 | } |
||
311 | |||
312 | private function applyHeaders(EasyHandle $easy, array &$conf): void |
||
332 | |||
333 | /** |
||
334 | * Remove a header from the options array. |
||
335 | * |
||
336 | * @param string $name Case-insensitive header to remove |
||
337 | * @param array $options Array of options to modify |
||
338 | */ |
||
339 | private function removeHeader(string $name, array &$options): void |
||
348 | |||
349 | private function applyHandlerOptions(EasyHandle $easy, array &$conf): void |
||
350 | { |
||
351 | $options = $easy->options; |
||
352 | if (isset($options['verify'])) { |
||
353 | if ($options['verify'] === false) { |
||
354 | unset($conf[\CURLOPT_CAINFO]); |
||
355 | $conf[\CURLOPT_SSL_VERIFYHOST] = 0; |
||
356 | $conf[\CURLOPT_SSL_VERIFYPEER] = false; |
||
357 | } else { |
||
501 | |||
502 | /** |
||
503 | * This function ensures that a response was set on a transaction. If one |
||
504 | * was not set, then the request is retried if possible. This error |
||
505 | * typically means you are sending a payload, curl encountered a |
||
506 | * "Connection died, retrying a fresh connect" error, tried to rewind the |
||
507 | * stream, and then encountered a "necessary data rewind wasn't possible" |
||
508 | * error, causing the request to be sent through curl_multi_info_read() |
||
509 | * without an error status. |
||
510 | * |
||
511 | * @param callable(RequestInterface, array): PromiseInterface $handler |
||
512 | */ |
||
513 | private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface |
||
546 | |||
547 | private function createHeaderFn(EasyHandle $easy): callable |
||
592 | } |
||
593 |
This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.