Response.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\HttpMessage\Server;
  12. use Hyperf\Engine\Contract\Http\Writable;
  13. use Hyperf\HttpMessage\Cookie\Cookie;
  14. use Hyperf\HttpMessage\Server\Chunk\Chunkable;
  15. use Hyperf\HttpMessage\Server\Chunk\HasChunk;
  16. use Hyperf\HttpMessage\Stream\SwooleStream;
  17. class Response extends \Hyperf\HttpMessage\Base\Response implements Chunkable
  18. {
  19. use HasChunk;
  20. protected array $cookies = [];
  21. protected array $trailers = [];
  22. protected ?Writable $connection = null;
  23. /**
  24. * Returns an instance with body content.
  25. */
  26. public function withContent(string $content): static
  27. {
  28. $new = clone $this;
  29. $new->stream = new SwooleStream($content);
  30. return $new;
  31. }
  32. /**
  33. * Returns an instance with specified cookies.
  34. */
  35. public function withCookie(Cookie $cookie): static
  36. {
  37. $clone = clone $this;
  38. $clone->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
  39. return $clone;
  40. }
  41. /**
  42. * Returns an instance with specified cookies.
  43. */
  44. public function setCookie(Cookie $cookie): static
  45. {
  46. $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
  47. return $this;
  48. }
  49. /**
  50. * Retrieves all cookies.
  51. */
  52. public function getCookies(): array
  53. {
  54. return $this->cookies;
  55. }
  56. /**
  57. * Returns an instance with specified trailer.
  58. * @param string $value
  59. */
  60. public function withTrailer(string $key, mixed $value): static
  61. {
  62. $new = clone $this;
  63. $new->trailers[$key] = $value;
  64. return $new;
  65. }
  66. /**
  67. * Retrieves a specified trailer value, returns null if the value does not exists.
  68. */
  69. public function getTrailer(string $key): mixed
  70. {
  71. return $this->trailers[$key] ?? null;
  72. }
  73. /**
  74. * Retrieves all trailers values.
  75. */
  76. public function getTrailers(): array
  77. {
  78. return $this->trailers;
  79. }
  80. public function setConnection(Writable $connection)
  81. {
  82. $this->connection = $connection;
  83. return $this;
  84. }
  85. public function getConnection(): ?Writable
  86. {
  87. return $this->connection;
  88. }
  89. }