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