Create.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Promise;
  4. final class Create
  5. {
  6. /**
  7. * Creates a promise for a value if the value is not a promise.
  8. *
  9. * @param mixed $value Promise or value.
  10. */
  11. public static function promiseFor($value): PromiseInterface
  12. {
  13. if ($value instanceof PromiseInterface) {
  14. return $value;
  15. }
  16. // Return a Guzzle promise that shadows the given promise.
  17. if (is_object($value) && method_exists($value, 'then')) {
  18. $wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null;
  19. $cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null;
  20. $promise = new Promise($wfn, $cfn);
  21. $value->then([$promise, 'resolve'], [$promise, 'reject']);
  22. return $promise;
  23. }
  24. return new FulfilledPromise($value);
  25. }
  26. /**
  27. * Creates a rejected promise for a reason if the reason is not a promise.
  28. * If the provided reason is a promise, then it is returned as-is.
  29. *
  30. * @param mixed $reason Promise or reason.
  31. */
  32. public static function rejectionFor($reason): PromiseInterface
  33. {
  34. if ($reason instanceof PromiseInterface) {
  35. return $reason;
  36. }
  37. return new RejectedPromise($reason);
  38. }
  39. /**
  40. * Create an exception for a rejected promise value.
  41. *
  42. * @param mixed $reason
  43. */
  44. public static function exceptionFor($reason): \Throwable
  45. {
  46. if ($reason instanceof \Throwable) {
  47. return $reason;
  48. }
  49. return new RejectionException($reason);
  50. }
  51. /**
  52. * Returns an iterator for the given value.
  53. *
  54. * @param mixed $value
  55. */
  56. public static function iterFor($value): \Iterator
  57. {
  58. if ($value instanceof \Iterator) {
  59. return $value;
  60. }
  61. if (is_array($value)) {
  62. return new \ArrayIterator($value);
  63. }
  64. return new \ArrayIterator([$value]);
  65. }
  66. }