DroppingStream.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\StreamInterface;
  5. /**
  6. * Stream decorator that begins dropping data once the size of the underlying
  7. * stream becomes too full.
  8. */
  9. final class DroppingStream implements StreamInterface
  10. {
  11. use StreamDecoratorTrait;
  12. /** @var int */
  13. private $maxLength;
  14. /** @var StreamInterface */
  15. private $stream;
  16. /**
  17. * @param StreamInterface $stream Underlying stream to decorate.
  18. * @param int $maxLength Maximum size before dropping data.
  19. */
  20. public function __construct(StreamInterface $stream, int $maxLength)
  21. {
  22. $this->stream = $stream;
  23. $this->maxLength = $maxLength;
  24. }
  25. public function write($string): int
  26. {
  27. $diff = $this->maxLength - $this->stream->getSize();
  28. // Begin returning 0 when the underlying stream is too large.
  29. if ($diff <= 0) {
  30. return 0;
  31. }
  32. // Write the stream or a subset of the stream if needed.
  33. if (strlen($string) < $diff) {
  34. return $this->stream->write($string);
  35. }
  36. return $this->stream->write(substr($string, 0, $diff));
  37. }
  38. }