| 1 |
<?php |
| 2 |
|
| 3 |
namespace React\Http\Middleware; |
| 4 |
|
| 5 |
use OverflowException; |
| 6 |
use Psr\Http\Message\ServerRequestInterface; |
| 7 |
use React\Http\Io\BufferedBody; |
| 8 |
use React\Http\Io\IniUtil; |
| 9 |
use React\Promise\Stream; |
| 10 |
use React\Stream\ReadableStreamInterface; |
| 11 |
|
| 12 |
final class RequestBodyBufferMiddleware |
| 13 |
{ |
| 14 |
private $sizeLimit; |
| 15 |
|
| 16 |
/** |
| 17 |
* @param int|string|null $sizeLimit Either an int with the max request body size |
| 18 |
* in bytes or an ini like size string |
| 19 |
* or null to use post_max_size from PHP's |
| 20 |
* configuration. (Note that the value from |
| 21 |
* the CLI configuration will be used.) |
| 22 |
*/ |
| 23 |
public function __construct($sizeLimit = null) |
| 24 |
{ |
| 25 |
if ($sizeLimit === null) { |
| 26 |
$sizeLimit = \ini_get('post_max_size'); |
| 27 |
} |
| 28 |
|
| 29 |
$this->sizeLimit = IniUtil::iniSizeToBytes($sizeLimit); |
| 30 |
} |
| 31 |
|
| 32 |
public function __invoke(ServerRequestInterface $request, $stack) |
| 33 |
{ |
| 34 |
$body = $request->getBody(); |
| 35 |
$size = $body->getSize(); |
| 36 |
|
| 37 |
// happy path: skip if body is known to be empty (or is already buffered) |
| 38 |
if ($size === 0 || !$body instanceof ReadableStreamInterface) { |
| 39 |
// replace with empty body if body is streaming (or buffered size exceeds limit) |
| 40 |
if ($body instanceof ReadableStreamInterface || $size > $this->sizeLimit) { |
| 41 |
$request = $request->withBody(new BufferedBody('')); |
| 42 |
} |
| 43 |
|
| 44 |
return $stack($request); |
| 45 |
} |
| 46 |
|
| 47 |
// request body of known size exceeding limit |
| 48 |
$sizeLimit = $this->sizeLimit; |
| 49 |
if ($size > $this->sizeLimit) { |
| 50 |
$sizeLimit = 0; |
| 51 |
} |
| 52 |
|
| 53 |
return Stream\buffer($body, $sizeLimit)->then(function ($buffer) use ($request, $stack) { |
| 54 |
$request = $request->withBody(new BufferedBody($buffer)); |
| 55 |
|
| 56 |
return $stack($request); |
| 57 |
}, function ($error) use ($stack, $request, $body) { |
| 58 |
// On buffer overflow keep the request body stream in, |
| 59 |
// but ignore the contents and wait for the close event |
| 60 |
// before passing the request on to the next middleware. |
| 61 |
if ($error instanceof OverflowException) { |
| 62 |
return Stream\first($body, 'close')->then(function () use ($stack, $request) { |
| 63 |
return $stack($request); |
| 64 |
}); |
| 65 |
} |
| 66 |
|
| 67 |
throw $error; |
| 68 |
}); |
| 69 |
} |
| 70 |
} |