Total Complexity | 123 |
Total Lines | 546 |
Duplicated Lines | 0 % |
Changes | 45 | ||
Bugs | 3 | Features | 3 |
Complex classes like Async 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 Async, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
42 | class Async |
||
43 | { |
||
44 | const PROMISE_REACT = 'React\Promise\PromiseInterface'; |
||
45 | const PROMISE_AMP = 'Amp\Promise'; |
||
46 | const PROMISE_GUZZLE = 'GuzzleHttp\Promise\PromiseInterface'; |
||
47 | const PROMISE_HTTP = 'Http\Promise\Promise'; |
||
48 | |||
49 | /** @var string action to return a promise instead of awaiting the response of the process. */ |
||
50 | const promise = 'promise'; |
||
51 | /** @var string action to run current process side by side with the remainder of the process. */ |
||
52 | const parallel = 'parallel'; |
||
53 | /** @var string action to await for all parallel processes previously to finish. */ |
||
54 | const all = 'all'; |
||
55 | /** @var string action to await for current processes to finish. this is the default action. */ |
||
56 | const await = 'await'; |
||
57 | /** @var string action to run current process after finished executing the function. */ |
||
58 | const later = 'later'; |
||
59 | |||
60 | const ACTIONS = [self::await, self::parallel, self::all, self::promise, self::later]; |
||
61 | |||
62 | public static $knownPromises = [ |
||
63 | self::PROMISE_REACT, |
||
64 | self::PROMISE_AMP, |
||
65 | self::PROMISE_GUZZLE, |
||
66 | self::PROMISE_HTTP, |
||
67 | ]; |
||
68 | |||
69 | /** |
||
70 | * @var LoggerInterface |
||
71 | */ |
||
72 | protected $logger; |
||
73 | /** |
||
74 | * @var bool |
||
75 | */ |
||
76 | public $waitForGuzzleAndHttplug = true; |
||
77 | |||
78 | /** |
||
79 | * @var bool |
||
80 | */ |
||
81 | protected $parallelGuzzleLoading = false; |
||
82 | |||
83 | protected $guzzlePromises = []; |
||
84 | |||
85 | public function __construct(LoggerInterface $logger = null) |
||
86 | { |
||
87 | if ($logger) { |
||
88 | $this->logger = $logger; |
||
89 | } |
||
90 | } |
||
91 | |||
92 | public function __call($name, $arguments) |
||
137 | } |
||
138 | |||
139 | public static function __callStatic($name, $arguments) |
||
140 | { |
||
141 | if (empty($arguments) && in_array($name, self::ACTIONS)) { |
||
142 | return $name; |
||
143 | } |
||
144 | static $instance; |
||
145 | if (!$instance) { |
||
146 | $instance = new static(); |
||
147 | } |
||
148 | return $instance->__call($name, $arguments); |
||
149 | } |
||
150 | |||
151 | /** |
||
152 | * Throws specified or subclasses of specified exception inside the generator class so that it can be handled. |
||
153 | * |
||
154 | * @param string $throwable |
||
155 | * @return string command |
||
156 | * |
||
157 | * @throws TypeError when given value is not a valid exception |
||
158 | */ |
||
159 | public static function throw(string $throwable): string |
||
160 | { |
||
161 | if (is_a($throwable, Throwable::class, true)) { |
||
162 | return __FUNCTION__ . ':' . $throwable; |
||
163 | } |
||
164 | throw new TypeError('Invalid value for throwable, it must extend Throwable class'); |
||
165 | } |
||
166 | |||
167 | protected function _awaitAll(array $processes, callable $callback): void |
||
195 | } |
||
196 | |||
197 | /** |
||
198 | * Sets a logger instance on the object. |
||
199 | * |
||
200 | * @param LoggerInterface $logger |
||
201 | * |
||
202 | * @return void |
||
203 | */ |
||
204 | protected function _setLogger(LoggerInterface $logger) |
||
205 | { |
||
206 | $this->logger = $logger; |
||
207 | } |
||
208 | |||
209 | private function makePromise() |
||
210 | { |
||
211 | $resolver = $rejector = null; |
||
212 | $promise = new Promise(function ($resolve, $reject, $notify) use (&$resolver, &$rejector) { |
||
213 | $resolver = $resolve; |
||
214 | $rejector = $reject; |
||
215 | }); |
||
216 | return [$promise, $resolver, $rejector]; |
||
217 | } |
||
218 | |||
219 | protected function _wait($process, $loop = null) |
||
220 | { |
||
221 | if ($this->logger) { |
||
222 | $this->logger->info('start'); |
||
223 | } |
||
224 | $waiting = true; |
||
225 | $result = null; |
||
226 | $exception = null; |
||
227 | $isRejected = false; |
||
228 | |||
229 | $callback = function ($error = null, $r = null) use (&$result, &$waiting, &$isRejected, &$exception, $loop) { |
||
230 | $waiting = false; |
||
231 | if ($loop) { |
||
232 | $loop->stop(); |
||
233 | } |
||
234 | if ($error) { |
||
235 | $isRejected = true; |
||
236 | $exception = $error; |
||
237 | return; |
||
238 | } |
||
239 | $result = $r; |
||
240 | }; |
||
241 | $this->_handle($process, $callback, -1); |
||
242 | while ($waiting) { |
||
243 | if ($loop) { |
||
244 | $loop->run(); |
||
245 | } |
||
246 | } |
||
247 | if ($this->logger) { |
||
248 | $this->logger->info('end'); |
||
249 | } |
||
250 | if ($isRejected) { |
||
251 | if (!$exception instanceof \Exception) { |
||
252 | $exception = new \UnexpectedValueException( |
||
253 | 'process failed with ' . (is_object($exception) ? get_class($exception) : gettype($exception)) |
||
254 | ); |
||
255 | } |
||
256 | throw $exception; |
||
257 | } |
||
258 | |||
259 | return $result; |
||
260 | } |
||
261 | |||
262 | protected function _handle($process, callable $callback, int $depth = 0): void |
||
263 | { |
||
264 | $arguments = []; |
||
265 | $func = []; |
||
266 | if (is_array($process) && count($process) > 1) { |
||
267 | $copy = $process; |
||
268 | $func[] = array_shift($copy); |
||
269 | if (is_callable($func[0])) { |
||
270 | $func = $func[0]; |
||
271 | } else { |
||
272 | $func[] = array_shift($copy); |
||
273 | } |
||
274 | $arguments = $copy; |
||
275 | } else { |
||
276 | $func = $process; |
||
277 | } |
||
278 | if (is_callable($func)) { |
||
279 | $this->_handleCallback($func, $arguments, $callback, $depth); |
||
280 | } elseif ($process instanceof Generator) { |
||
281 | $this->_handleGenerator($process, $callback, 1 + $depth); |
||
282 | } elseif (is_object($process) && $implements = array_intersect(class_implements($process), |
||
283 | Async::$knownPromises)) { |
||
284 | $this->_handlePromise($process, array_shift($implements), $callback, $depth); |
||
285 | } else { |
||
286 | $callback(null, $process); |
||
287 | } |
||
288 | } |
||
289 | |||
290 | |||
291 | protected function _handleCallback(callable $callable, array $parameters, callable $callback, int $depth = 0) |
||
292 | { |
||
293 | $this->logCallback($callable, $parameters, $depth); |
||
294 | try { |
||
295 | if (is_array($callable)) { |
||
296 | $rf = new ReflectionMethod($callable[0], $callable[1]); |
||
297 | } elseif (is_string($callable)) { |
||
298 | $rf = new ReflectionFunction($callable); |
||
299 | } elseif (is_a($callable, 'Closure') || is_callable($callable, '__invoke')) { |
||
300 | $ro = new ReflectionObject($callable); |
||
301 | $rf = $ro->getMethod('__invoke'); |
||
302 | } |
||
303 | $current = count($parameters); |
||
304 | $total = $rf->getNumberOfParameters(); |
||
305 | $ps = $rf->getParameters(); |
||
306 | if ($current + 1 < $total) { |
||
307 | for ($i = $current; $i < $total - 1; $i++) { |
||
308 | $parameters[$i] = $ps[$i]->isDefaultValueAvailable() ? $ps[$i]->getDefaultValue() : null; |
||
309 | } |
||
310 | } |
||
311 | } catch (ReflectionException $e) { |
||
312 | //ignore |
||
313 | } |
||
314 | $parameters[] = $callback; |
||
315 | call_user_func_array($callable, $parameters); |
||
316 | } |
||
317 | |||
318 | protected function _handleGenerator(Generator $flow, callable $callback, int $depth = 0) |
||
319 | { |
||
320 | $this->logGenerator($flow, $depth - 1); |
||
321 | try { |
||
322 | if (!$flow->valid()) { |
||
323 | $callback(null, $flow->getReturn()); |
||
324 | if (!empty($flow->later)) { |
||
325 | $this->_awaitAll($flow->later, function ($error = null, $results = null) { |
||
326 | }); |
||
327 | unset($flow->later); |
||
328 | } |
||
329 | return; |
||
330 | } |
||
331 | $value = $flow->current(); |
||
332 | $actions = $this->parse($flow->key() ?: Async::await); |
||
333 | $next = function ($error = null, $result = null) use ($flow, $actions, $callback, $depth) { |
||
334 | $value = $error ?: $result; |
||
335 | if ($value instanceof Throwable) { |
||
336 | if (isset($actions['throw']) && is_a($value, $actions['throw'])) { |
||
337 | /** @scrutinizer ignore-call */ |
||
338 | $flow->throw($value); |
||
339 | $this->_handleGenerator($flow, $callback, $depth); |
||
340 | return; |
||
341 | } |
||
342 | $callback($value, null); |
||
343 | return; |
||
344 | } |
||
345 | $flow->send($value); |
||
346 | $this->_handleGenerator($flow, $callback, $depth); |
||
347 | }; |
||
348 | if (key_exists(self::later, $actions)) { |
||
349 | if (!isset($flow->later)) { |
||
350 | $flow->later = []; |
||
351 | } |
||
352 | if ($this->logger) { |
||
353 | $this->logger->info('later task scheduled', compact('depth')); |
||
354 | } |
||
355 | $flow->later[] = $value; |
||
356 | return $next(null, $value); |
||
357 | } |
||
358 | if (key_exists(self::parallel, $actions)) { |
||
359 | if (!isset($flow->parallel)) { |
||
360 | $flow->parallel = []; |
||
361 | } |
||
362 | $flow->parallel[] = $value; |
||
363 | if (!isset($this->action)) { |
||
364 | $this->action = []; |
||
365 | } |
||
366 | $this->action[] = self::parallel; |
||
367 | return $next(null, $value); |
||
368 | } |
||
369 | if (key_exists(self::all, $actions)) { |
||
370 | $tasks = Async::parallel === $value && isset($flow->parallel) ? $flow->parallel : $value; |
||
371 | unset($flow->parallel); |
||
372 | if (is_array($tasks) && count($tasks)) { |
||
373 | if ($this->logger) { |
||
374 | $this->logger->info( |
||
375 | sprintf("all {%d} tasks awaited.", count($tasks)), |
||
376 | compact('depth') |
||
377 | ); |
||
378 | } |
||
379 | return $this->_awaitAll($tasks, $next); |
||
380 | } |
||
381 | return $next(null, []); |
||
382 | } |
||
383 | $this->_handle($value, $next, $depth); |
||
384 | } catch (Throwable $throwable) { |
||
385 | $callback($throwable, null); |
||
386 | } |
||
387 | } |
||
388 | |||
389 | /** |
||
390 | * Handle known promise interfaces |
||
391 | * |
||
392 | * @param \React\Promise\PromiseInterface|\GuzzleHttp\Promise\PromiseInterface|\Amp\Promise|\Http\Promise\Promise $knownPromise |
||
393 | * @param string $interface |
||
394 | * @param callable $callback |
||
395 | * @param int $depth |
||
396 | * @return void |
||
397 | */ |
||
398 | protected function _handlePromise($knownPromise, string $interface, callable $callback, int $depth = 0) |
||
399 | { |
||
400 | $this->logPromise($knownPromise, $interface, $depth); |
||
401 | $resolver = function ($result) use ($callback) { |
||
402 | $callback(null, $result); |
||
403 | }; |
||
404 | $rejector = function ($error) use ($callback) { |
||
405 | $callback($error, null); |
||
406 | }; |
||
407 | try { |
||
408 | switch ($interface) { |
||
409 | case static::PROMISE_REACT: |
||
410 | $knownPromise->then($resolver, $rejector); |
||
411 | break; |
||
412 | case static::PROMISE_GUZZLE: |
||
413 | $knownPromise->then($resolver, $rejector); |
||
414 | if ($this->waitForGuzzleAndHttplug) { |
||
415 | if ($this->parallelGuzzleLoading) { |
||
416 | $this->guzzlePromises[] = $knownPromise; |
||
417 | } else { |
||
418 | $knownPromise->wait(false); |
||
419 | } |
||
420 | } |
||
421 | break; |
||
422 | case static::PROMISE_HTTP: |
||
423 | $knownPromise->then($resolver, $rejector); |
||
424 | if ($this->waitForGuzzleAndHttplug) { |
||
425 | $knownPromise->wait(false); |
||
426 | } |
||
427 | break; |
||
428 | case static::PROMISE_AMP: |
||
429 | $knownPromise->onResolve( |
||
430 | function ($error = null, $result = null) use ($resolver, $rejector) { |
||
431 | $error ? $rejector($error) : $resolver($result); |
||
432 | }); |
||
433 | break; |
||
434 | } |
||
435 | } catch (\Exception $e) { |
||
436 | $rejector($e); |
||
437 | } |
||
438 | } |
||
439 | |||
440 | private function handleCommands(Generator $flow, &$value, callable $callback, int $depth): bool |
||
441 | { |
||
442 | $commands = $this->parse($flow->key()); |
||
443 | if ($value instanceof Throwable) { |
||
444 | if (isset($commands['throw']) && is_a($value, $commands['throw'])) { |
||
445 | $flow->throw($value); |
||
446 | $this->_handleGenerator($flow, $callback, $depth); |
||
447 | return true; //stop |
||
448 | } |
||
449 | $callback($value, null); |
||
450 | return true; //stop |
||
451 | } |
||
452 | if (isset($commands[self::parallel])) { |
||
453 | if (!isset($flow->parallel)) { |
||
454 | $flow->parallel = []; |
||
455 | } |
||
456 | $flow->parallel [] = $value; |
||
457 | return false; //continue |
||
458 | } |
||
459 | |||
460 | if (isset($commands[self::all])) { |
||
461 | if (!isset($flow->parallel)) { |
||
462 | $callback(null, []); |
||
463 | return true; //stop |
||
464 | } |
||
465 | $this->_awaitAll( |
||
466 | $flow->parallel, |
||
467 | function ($error = null, $all = null) use ($flow, $callback, $depth) { |
||
468 | if ($error) { |
||
469 | $callback($error, false); |
||
470 | return; |
||
471 | } |
||
472 | $flow->send($all); |
||
473 | $this->_handleGenerator($flow, $callback, $depth); |
||
474 | } |
||
475 | ); |
||
476 | return true; //stop |
||
477 | } |
||
478 | |||
479 | return false; //continue |
||
480 | } |
||
481 | |||
482 | private function parse(string $command): array |
||
483 | { |
||
484 | $arr = []; |
||
485 | if (strlen($command)) { |
||
486 | parse_str(str_replace(['|', ':'], ['&', '='], $command), $arr); |
||
487 | } |
||
488 | return $arr; |
||
489 | } |
||
490 | |||
491 | private function action() |
||
497 | } |
||
498 | |||
499 | private function logCallback(callable $callable, array $parameters, int $depth = 0) |
||
500 | { |
||
501 | if ($depth < 0 || !$this->logger) { |
||
502 | return; |
||
503 | } |
||
504 | if (is_array($callable)) { |
||
505 | $name = $callable[0]; |
||
506 | if (is_object($name)) { |
||
507 | $name = '$' . lcfirst(get_class($name)) . '->' . $callable[1]; |
||
508 | } else { |
||
509 | $name .= '::' . $callable[1]; |
||
510 | } |
||
511 | |||
512 | } else { |
||
513 | if (is_string($callable)) { |
||
514 | $name = $callable; |
||
515 | } elseif ($callable instanceof Closure) { |
||
516 | $name = '$closure'; |
||
517 | } else { |
||
518 | $name = '$callable'; |
||
519 | } |
||
520 | } |
||
521 | $this->logger->info( |
||
522 | sprintf("%s %s%s", $this->action(), $name, $this->format($parameters)), |
||
523 | compact('depth') |
||
524 | ); |
||
525 | } |
||
526 | |||
527 | private function logPromise(/** @scrutinizer ignore-unused */ $promise, string $interface, int $depth) |
||
528 | { |
||
529 | if ($depth < 0 || !$this->logger) { |
||
530 | return; |
||
531 | } |
||
532 | $type = 'unknown'; |
||
533 | switch ($interface) { |
||
534 | case static::PROMISE_REACT: |
||
535 | $type = 'react'; |
||
536 | break; |
||
537 | case static::PROMISE_GUZZLE: |
||
538 | $type = 'guzzle'; |
||
539 | break; |
||
540 | case static::PROMISE_HTTP: |
||
541 | $type = 'httplug'; |
||
542 | break; |
||
543 | case static::PROMISE_AMP: |
||
544 | $type = 'amp'; |
||
545 | break; |
||
546 | } |
||
547 | $this->logger->info( |
||
548 | sprintf("%s \$%sPromise;", $this->action(), $type), |
||
549 | compact('depth') |
||
550 | ); |
||
551 | } |
||
552 | |||
553 | private function logGenerator(Generator $generator, int $depth = 0) |
||
560 | } |
||
561 | |||
562 | private function format($parameters) |
||
563 | { |
||
564 | return '(' . substr(json_encode($parameters), 1, -1) . ');'; |
||
565 | } |
||
566 | |||
567 | private function logReflectionFunction(ReflectionFunctionAbstract $function, int $depth = 0) |
||
568 | { |
||
569 | if ($function instanceof ReflectionMethod) { |
||
570 | $name = $function->getDeclaringClass()->getShortName(); |
||
571 | if ($function->isStatic()) { |
||
572 | $name .= '::' . $function->name; |
||
573 | } else { |
||
588 | ); |
||
589 | } |
||
590 | } |
||
591 |