functions.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is a part of the DiscordPHP project.
  5. *
  6. * Copyright (c) 2015-present David Cole <david.cole1340@gmail.com>
  7. *
  8. * This file is subject to the MIT license that is bundled
  9. * with this source code in the LICENSE.md file.
  10. */
  11. const TIMEOUT = 10;
  12. function wait(callable $callback, float $timeout = TIMEOUT, callable $timeoutFn = null)
  13. {
  14. $discord = DiscordSingleton::get();
  15. $result = null;
  16. $finally = null;
  17. $timedOut = false;
  18. $discord->getLoop()->futureTick(function () use ($callback, $discord, &$result, &$finally) {
  19. $resolve = function ($x = null) use ($discord, &$result) {
  20. $result = $x;
  21. $discord->getLoop()->stop();
  22. };
  23. try {
  24. $finally = $callback($discord, $resolve);
  25. } catch (\Throwable $e) {
  26. $resolve($e);
  27. }
  28. });
  29. $timeout = $discord->getLoop()->addTimer($timeout, function () use ($discord, &$timedOut) {
  30. $timedOut = true;
  31. $discord->getLoop()->stop();
  32. });
  33. $discord->getLoop()->run();
  34. $discord->getLoop()->cancelTimer($timeout);
  35. if ($result instanceof Exception) {
  36. throw $result;
  37. }
  38. if (is_callable($finally)) {
  39. $finally();
  40. }
  41. if ($timedOut) {
  42. if ($timeoutFn != null) {
  43. $timeoutFn();
  44. } else {
  45. throw new \Exception('Timed out');
  46. }
  47. }
  48. return $result;
  49. }