1
0

FakeHttpClient.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types=1);
  3. namespace Luolongfei\Tests\Support;
  4. use GuzzleHttp\Psr7\Response;
  5. final class FakeHttpClient
  6. {
  7. public array $requests = [];
  8. private array $queue = [
  9. 'get' => [],
  10. 'post' => [],
  11. ];
  12. public function queue(string $method, $response): void
  13. {
  14. $method = strtolower($method);
  15. $this->queue[$method][] = $response;
  16. }
  17. public function get(string $url, array $options = [])
  18. {
  19. return $this->dequeue('get', $url, $options);
  20. }
  21. public function post(string $url, array $options = [])
  22. {
  23. return $this->dequeue('post', $url, $options);
  24. }
  25. public static function jsonResponse(array $data, int $status = 200): Response
  26. {
  27. return new Response($status, ['Content-Type' => 'application/json'], json_encode($data, JSON_UNESCAPED_UNICODE));
  28. }
  29. public static function textResponse(string $body, int $status = 200): Response
  30. {
  31. return new Response($status, [], $body);
  32. }
  33. private function dequeue(string $method, string $url, array $options)
  34. {
  35. $this->requests[] = [
  36. 'method' => strtoupper($method),
  37. 'url' => $url,
  38. 'options' => $options,
  39. ];
  40. if (empty($this->queue[$method])) {
  41. throw new \RuntimeException(sprintf('No queued %s response for %s', strtoupper($method), $url));
  42. }
  43. $response = array_shift($this->queue[$method]);
  44. if ($response instanceof \Throwable) {
  45. throw $response;
  46. }
  47. return $response;
  48. }
  49. }