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