酒店预订平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

85 lines
2.1 KiB

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