1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123:
<?php
namespace Guzzle\Http;
use Guzzle\Stream\StreamInterface;
class ReadLimitEntityBody extends AbstractEntityBodyDecorator
{
protected $limit;
protected $offset;
public function __construct(EntityBodyInterface $body, $limit, $offset = 0)
{
parent::__construct($body);
$this->setLimit($limit)->setOffset($offset);
}
public function __toString()
{
if (!$this->body->isReadable() ||
(!$this->body->isSeekable() && $this->body->isConsumed())
) {
return '';
}
$originalPos = $this->body->ftell();
$this->body->seek($this->offset);
$data = '';
while (!$this->feof()) {
$data .= $this->read(1048576);
}
$this->body->seek($originalPos);
return (string) $data ?: '';
}
public function isConsumed()
{
return $this->body->isConsumed() ||
($this->body->ftell() >= $this->offset + $this->limit);
}
public function getContentLength()
{
$length = $this->body->getContentLength();
return $length === false
? $this->limit
: min($this->limit, min($length, $this->offset + $this->limit) - $this->offset);
}
public function seek($offset, $whence = SEEK_SET)
{
return $whence === SEEK_SET
? $this->body->seek(max($this->offset, min($this->offset + $this->limit, $offset)))
: false;
}
public function setOffset($offset)
{
$this->body->seek($offset);
$this->offset = $offset;
return $this;
}
public function setLimit($limit)
{
$this->limit = $limit;
return $this;
}
public function read($length)
{
$remaining = ($this->offset + $this->limit) - $this->body->ftell();
if ($remaining > 0) {
return $this->body->read(min($remaining, $length));
} else {
return false;
}
}
}