MockTrait.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace AlibabaCloud\Credentials;
  3. use Exception;
  4. use GuzzleHttp\Exception\RequestException;
  5. use GuzzleHttp\Handler\MockHandler;
  6. use GuzzleHttp\Psr7\Response;
  7. use GuzzleHttp\Middleware;
  8. use Psr\Http\Message\RequestInterface;
  9. use Psr\Http\Message\ResponseInterface;
  10. /**
  11. * Trait MockTrait
  12. *
  13. * @package AlibabaCloud\Credentials
  14. */
  15. trait MockTrait
  16. {
  17. /**
  18. * @var array
  19. */
  20. private static $mockQueue = [];
  21. /**
  22. * @var array
  23. */
  24. private static $history = [];
  25. /**
  26. * @var MockHandler
  27. */
  28. private static $mock;
  29. /**
  30. * @param integer $status
  31. * @param array $headers
  32. * @param array|string|object $body
  33. */
  34. public static function mockResponse($status = 200, array $headers = [], $body = null)
  35. {
  36. if (is_array($body) || is_object($body)) {
  37. $body = json_encode($body);
  38. }
  39. self::$mockQueue[] = new Response($status, $headers, $body);
  40. self::createHandlerStack();
  41. }
  42. private static function createHandlerStack()
  43. {
  44. self::$mock = new MockHandler(self::$mockQueue);
  45. }
  46. /**
  47. * @return MockHandler
  48. */
  49. public static function getHandlerHistory()
  50. {
  51. return Middleware::history(self::$history);
  52. }
  53. /**
  54. * @param string $message
  55. * @param RequestInterface $request
  56. * @param ResponseInterface|null $response
  57. * @param Exception|null $previous
  58. * @param array $handlerContext
  59. */
  60. public static function mockRequestException(
  61. $message,
  62. RequestInterface $request,
  63. ResponseInterface $response = null,
  64. Exception $previous = null,
  65. array $handlerContext = []
  66. ) {
  67. self::$mockQueue[] = new RequestException(
  68. $message,
  69. $request,
  70. $response,
  71. $previous,
  72. $handlerContext
  73. );
  74. self::createHandlerStack();
  75. }
  76. /**
  77. * @return void
  78. */
  79. public static function cancelMock()
  80. {
  81. self::$mockQueue = [];
  82. self::$mock = null;
  83. }
  84. /**
  85. * @return bool
  86. */
  87. public static function hasMock()
  88. {
  89. return (bool)self::$mockQueue;
  90. }
  91. /**
  92. * @return MockHandler
  93. */
  94. public static function getMock()
  95. {
  96. return self::$mock;
  97. }
  98. /**
  99. * @return array
  100. */
  101. public static function getHistroy()
  102. {
  103. return self::$history;
  104. }
  105. }