DroppingStream.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. if (!\is_string($string)) {
  28. \trigger_deprecation(
  29. 'guzzlehttp/psr7',
  30. '2.11',
  31. 'Passing %s to StreamInterface::write() is deprecated; guzzlehttp/psr7 3.0 requires string for $string.',
  32. \get_debug_type($string)
  33. );
  34. }
  35. $diff = $this->maxLength - $this->stream->getSize();
  36. // Begin returning 0 when the underlying stream is too large.
  37. if ($diff <= 0) {
  38. return 0;
  39. }
  40. // Write the stream or a subset of the stream if needed.
  41. if (strlen($string) < $diff) {
  42. return $this->stream->write($string);
  43. }
  44. return $this->stream->write(substr($string, 0, $diff));
  45. }
  46. }