MockTrait.php 2.1 KB

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