Total Complexity | 44 |
Total Lines | 407 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like Client 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.
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 Client, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
19 | class Client |
||
20 | { |
||
21 | |||
22 | use ClientTrait; |
||
23 | |||
24 | /** |
||
25 | * This variable is used to defied is certificate self-signed or not |
||
26 | * |
||
27 | * @var bool |
||
28 | */ |
||
29 | private bool $isSelfSigned = true; |
||
30 | |||
31 | /** |
||
32 | * The temp directory to download files - default is $_SERVER['TEMP'] |
||
33 | * |
||
34 | * @var ?string |
||
35 | */ |
||
36 | private ?string $tempDir; |
||
37 | |||
38 | /** |
||
39 | * The constructor of the client |
||
40 | */ |
||
41 | public function __construct() |
||
42 | { |
||
43 | $this->tempDir = $_SERVER['TEMP'] ?? null; |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * Set has self-signed certificate |
||
48 | * |
||
49 | * This is used to set the curl option CURLOPT_SSL_VERIFYPEER |
||
50 | * and CURLOPT_SSL_VERIFYHOST to false. This is useful when you are |
||
51 | * in local environment, or you have self-signed certificate. |
||
52 | * |
||
53 | * @param bool $has |
||
54 | * |
||
55 | * @return void |
||
56 | */ |
||
57 | public function setHasSelfSignedCertificate(bool $has): void |
||
58 | { |
||
59 | $this->isSelfSigned = $has; |
||
60 | } |
||
61 | |||
62 | /** |
||
63 | * Set the temporary directory path to save the downloaded files |
||
64 | * |
||
65 | * @param string $path |
||
66 | * |
||
67 | * @return void |
||
68 | */ |
||
69 | public function setTempPath(string $path): void |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * This method is used to send a http request to a given url. |
||
79 | * |
||
80 | * @param string $method |
||
81 | * @param string $uri |
||
82 | * @param array|HttpOptions $options |
||
83 | * |
||
84 | * @return HttpResponse |
||
85 | */ |
||
86 | public function request(string $method, string $uri, array|HttpOptions $options = []): HttpResponse |
||
87 | { |
||
88 | $CurlHandle = $this->createCurlHandler($method, $uri, $options); |
||
89 | |||
90 | $result = new HttpResponse(); |
||
91 | $result->setCurlHandle($CurlHandle); |
||
92 | |||
93 | $response = curl_exec($CurlHandle); |
||
94 | if (curl_errno($CurlHandle)) { |
||
95 | $result->setError(curl_error($CurlHandle)); |
||
96 | $result->setErrorCode(curl_errno($CurlHandle)); |
||
97 | return $result; |
||
98 | } |
||
99 | |||
100 | $result->setStatusCode(curl_getinfo($CurlHandle, CURLINFO_HTTP_CODE)); |
||
101 | $result->setHeaderSize(curl_getinfo($CurlHandle, CURLINFO_HEADER_SIZE)); |
||
102 | $result->setHeaders(substr($response, 0, $result->getHeaderSize())); |
||
|
|||
103 | $result->setBody(substr($response, $result->getHeaderSize())); |
||
104 | |||
105 | curl_close($CurlHandle); |
||
106 | |||
107 | return $result; |
||
108 | } |
||
109 | |||
110 | /** |
||
111 | * Send multiple requests to a given url. |
||
112 | * |
||
113 | * @param array $requests [{method, uri, options}, ...] |
||
114 | * |
||
115 | * @return array<HttpResponse> |
||
116 | */ |
||
117 | public function bulk(array $requests): array |
||
171 | } |
||
172 | |||
173 | /** |
||
174 | * Create curl handler. |
||
175 | * |
||
176 | * @param ?string $method |
||
177 | * @param string $uri |
||
178 | * @param array|HttpOptions $options |
||
179 | * |
||
180 | * @return ?CurlHandle |
||
181 | */ |
||
182 | private function createCurlHandler(?string $method, string $uri, array|HttpOptions $options = []): ?CurlHandle |
||
183 | { |
||
184 | $cHandler = curl_init(); |
||
185 | |||
186 | if (gettype($options) === 'array') { |
||
187 | $options = new HttpOptions( |
||
188 | $this->getOptions($options) |
||
189 | ); |
||
190 | } |
||
191 | |||
192 | if (count($options->queries) > 0) { |
||
193 | if (!str_contains($uri, '?')) $uri .= '?'; |
||
194 | $uri .= $options->getQueryString(); |
||
195 | } |
||
196 | |||
197 | curl_setopt($cHandler, CURLOPT_URL, $uri); |
||
198 | |||
199 | $this->setCurlOpts($cHandler, $method, $options); |
||
200 | |||
201 | return $cHandler; |
||
202 | } |
||
203 | |||
204 | /** |
||
205 | * Setup curl options based on the given method and our options. |
||
206 | * |
||
207 | * @param CurlHandle $cHandler |
||
208 | * @param ?string $method |
||
209 | * @param HttpOptions $options |
||
210 | * |
||
211 | * @return void |
||
212 | */ |
||
213 | private function setCurlOpts(CurlHandle $cHandler, ?string $method, HttpOptions $options): void |
||
214 | { |
||
215 | curl_setopt($cHandler, CURLOPT_HEADER, true); |
||
216 | curl_setopt($cHandler, CURLOPT_CUSTOMREQUEST, $method ?? 'GET'); |
||
217 | |||
218 | # Fetch the header |
||
219 | $fetchedHeaders = []; |
||
220 | foreach ($options->headers as $header => $value) { |
||
221 | $fetchedHeaders[] = $header . ': ' . $value; |
||
222 | } |
||
223 | |||
224 | # Set headers |
||
225 | if ($fetchedHeaders != []) { |
||
226 | curl_setopt($cHandler, CURLOPT_HTTPHEADER, $fetchedHeaders); |
||
227 | } |
||
228 | |||
229 | # Add body if we have one. |
||
230 | if ($options->body) { |
||
231 | curl_setopt($cHandler, CURLOPT_CUSTOMREQUEST, $method ?? 'POST'); |
||
232 | curl_setopt($cHandler, CURLOPT_POSTFIELDS, $options->body); |
||
233 | curl_setopt($cHandler, CURLOPT_POST, true); |
||
234 | } |
||
235 | |||
236 | # Check for a proxy |
||
237 | if ($options->proxy != null) { |
||
238 | curl_setopt($cHandler, CURLOPT_PROXY, $options->proxy->getProxy()); |
||
239 | curl_setopt($cHandler, CURLOPT_PROXYUSERPWD, $options->proxy->getAuth()); |
||
240 | if ($options->proxy->type !== null) { |
||
241 | curl_setopt($cHandler, CURLOPT_PROXYTYPE, $options->proxy->type); |
||
242 | curl_setopt($cHandler, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); |
||
243 | } |
||
244 | } |
||
245 | |||
246 | curl_setopt($cHandler, CURLOPT_RETURNTRANSFER, true); |
||
247 | curl_setopt($cHandler, CURLOPT_FOLLOWLOCATION, true); |
||
248 | |||
249 | # Add and override the custom curl options. |
||
250 | if (count($options->curlOptions) > 0) { |
||
251 | foreach ($options->curlOptions as $option => $value) { |
||
252 | curl_setopt($cHandler, $option, $value); |
||
253 | } |
||
254 | } |
||
255 | |||
256 | # if we have a timeout, set it. |
||
257 | if ($options->timeout != null) { |
||
258 | curl_setopt($cHandler, CURLOPT_TIMEOUT, $options->timeout); |
||
259 | } |
||
260 | |||
261 | # If self-signed certs are allowed, set it. |
||
262 | if ($this->isSelfSigned === true) { |
||
263 | curl_setopt($cHandler, CURLOPT_SSL_VERIFYPEER, false); |
||
264 | curl_setopt($cHandler, CURLOPT_SSL_VERIFYHOST, false); |
||
265 | } |
||
266 | } |
||
267 | |||
268 | /** |
||
269 | * Initialize options from array. |
||
270 | * |
||
271 | * @param array $options |
||
272 | * @return array |
||
273 | */ |
||
274 | private function getOptions(array $options): array |
||
275 | { |
||
276 | $defaults = [ |
||
277 | 'headers' => [], |
||
278 | 'body' => null, |
||
279 | 'timeout' => null, |
||
280 | 'proxy' => null, |
||
281 | 'curlOptions' => [], |
||
282 | 'queries' => [] |
||
283 | ]; |
||
284 | |||
285 | return array_merge($defaults, $options); |
||
286 | } |
||
287 | |||
288 | /** |
||
289 | * Download large files. |
||
290 | * |
||
291 | * This method is used to download large files with |
||
292 | * creating multiple requests. |
||
293 | * |
||
294 | * @param string $url The direct url to the file. |
||
295 | * @param array|HttpOptions $options The options to use. |
||
296 | * |
||
297 | * @return DownloadResult |
||
298 | */ |
||
299 | public function download(string $url, array|HttpOptions $options = []): DownloadResult |
||
300 | { |
||
301 | if (empty($this->tempDir)) { |
||
302 | throw new \RuntimeException('No temp directory set.'); |
||
303 | } |
||
304 | |||
305 | if (!file_exists($this->tempDir)) { |
||
306 | if (mkdir($this->tempDir, 0777, true) === false) { |
||
307 | throw new \RuntimeException('Could not create temp directory.'); |
||
308 | } |
||
309 | } |
||
310 | |||
311 | if (gettype($options) === 'array') { |
||
312 | $options = new HttpOptions( |
||
313 | $this->getOptions($options) |
||
314 | ); |
||
315 | } |
||
316 | |||
317 | $fileSize = $this->getFileSize($url); |
||
318 | $chunkSize = $this->getChunkSize($fileSize); |
||
319 | |||
320 | $result = new DownloadResult(); |
||
321 | |||
322 | $result->id = uniqid(); |
||
323 | $result->chunksPath = $this->tempDir . '/' . $result->id . '/'; |
||
324 | mkdir($result->chunksPath, 0777, true); |
||
325 | |||
326 | $result->fileSize = $fileSize; |
||
327 | $result->chunkSize = $chunkSize; |
||
328 | $result->chunks = ceil($fileSize / $chunkSize); |
||
329 | |||
330 | $result->startTime = microtime(true); |
||
331 | |||
332 | $requests = []; |
||
333 | for ($i = 0; $i < $result->chunks; $i++) { |
||
334 | $range = $i * $chunkSize . '-' . ($i + 1) * $chunkSize; |
||
335 | if ($i + 1 === $result->chunks) { |
||
336 | $range = $i * $chunkSize . '-' . $fileSize; |
||
337 | } |
||
338 | $requests[] = [ |
||
339 | 'method' => 'GET', |
||
340 | 'uri' => $url, |
||
341 | 'options' => array_merge($options->toArray(), [ |
||
342 | 'CurlOptions' => [ |
||
343 | CURLOPT_RANGE => $range |
||
344 | ], |
||
345 | ]) |
||
346 | ]; |
||
347 | } |
||
348 | |||
349 | foreach ($this->bulk($requests) as $response) { |
||
350 | $result->addChunk( |
||
351 | Utils::randomString(16), |
||
352 | $response->getBody(), |
||
353 | $response->getCurlInfo()->TOTAL_TIME |
||
354 | ); |
||
355 | } |
||
356 | |||
357 | $result->endTime = microtime(true); |
||
358 | |||
359 | return $result; |
||
360 | } |
||
361 | |||
362 | /** |
||
363 | * Download a chunk of a file. |
||
364 | * |
||
365 | * @param DownloadResult $result The result object. |
||
366 | * @param HttpOptions $options The options to use. |
||
367 | * @param array $input ['id', 'url', 'range'=> "start-end"] |
||
368 | * |
||
369 | * @return void |
||
370 | */ |
||
371 | private function downloadChunk(DownloadResult &$result, HttpOptions $options, array $input): void |
||
372 | { |
||
373 | $options->setCurlOptions([ |
||
374 | CURLOPT_RANGE => $input['range'] |
||
375 | ]); |
||
376 | $response = self::get($input['url'], $options); |
||
377 | $result->addChunk( |
||
378 | $input['id'], |
||
379 | $response->getBody(), |
||
380 | $response->getCurlInfo()->TOTAL_TIME |
||
381 | ); |
||
382 | } |
||
383 | |||
384 | /** |
||
385 | * Get file size. |
||
386 | * |
||
387 | * @param string $url The direct url to the file. |
||
388 | * @return int |
||
389 | */ |
||
390 | private function getFileSize(string $url): int |
||
402 | } |
||
403 | |||
404 | /** |
||
405 | * Get the size of each chunk. |
||
406 | * |
||
407 | * For default, we're using (fileSize/5) as max chunk size. If the file size |
||
408 | * is smaller than 5MB, we'll use the file size as chunk size. |
||
409 | * |
||
410 | * @param int $fileSize The file size. |
||
411 | * @param ?int $maxChunkSize The maximum chunk size. (default: fileSize/5) |
||
412 | * |
||
413 | * @return int |
||
414 | */ |
||
415 | private function getChunkSize(int $fileSize, int $maxChunkSize = null): int |
||
426 | } |
||
427 | |||
428 | } |