EndlessCycleStream.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. declare(strict_types=1);
  3. namespace ZipStream\Test;
  4. use Psr\Http\Message\StreamInterface;
  5. use RuntimeException;
  6. class EndlessCycleStream implements StreamInterface
  7. {
  8. private int $offset = 0;
  9. public function __construct(private readonly string $toRepeat = '0') {}
  10. public function __toString(): string
  11. {
  12. throw new RuntimeException('Infinite Stream!');
  13. }
  14. public function close(): void
  15. {
  16. $this->detach();
  17. }
  18. /**
  19. * @return null
  20. */
  21. public function detach()
  22. {
  23. return;
  24. }
  25. public function getSize(): ?int
  26. {
  27. return null;
  28. }
  29. public function tell(): int
  30. {
  31. return $this->offset;
  32. }
  33. public function eof(): bool
  34. {
  35. return false;
  36. }
  37. public function isSeekable(): bool
  38. {
  39. return true;
  40. }
  41. public function seek(int $offset, int $whence = SEEK_SET): void
  42. {
  43. switch ($whence) {
  44. case SEEK_SET:
  45. $this->offset = $offset;
  46. break;
  47. case SEEK_CUR:
  48. $this->offset += $offset;
  49. break;
  50. case SEEK_END:
  51. throw new RuntimeException('Infinite Stream!');
  52. break;
  53. }
  54. }
  55. public function rewind(): void
  56. {
  57. $this->seek(0);
  58. }
  59. public function isWritable(): bool
  60. {
  61. return false;
  62. }
  63. public function write(string $string): int
  64. {
  65. throw new RuntimeException('Not writeable');
  66. }
  67. public function isReadable(): bool
  68. {
  69. return true;
  70. }
  71. public function read(int $length): string
  72. {
  73. $this->offset += $length;
  74. return substr(str_repeat($this->toRepeat, (int) ceil($length / strlen($this->toRepeat))), 0, $length);
  75. }
  76. public function getContents(): string
  77. {
  78. throw new RuntimeException('Infinite Stream!');
  79. }
  80. public function getMetadata(?string $key = null): array|null
  81. {
  82. return $key !== null ? null : [];
  83. }
  84. }