4 use GuzzleHttp\Promise\PromiseInterface;
6 use Psr\Http\Message\RequestInterface;
9 * Prepares requests that contain a body, adding the Content-Length,
10 * Content-Type, and Expect headers.
12 class PrepareBodyMiddleware
18 * @param callable $nextHandler Next handler to invoke.
20 public function __construct(callable $nextHandler)
22 $this->nextHandler = $nextHandler;
26 * @param RequestInterface $request
27 * @param array $options
29 * @return PromiseInterface
31 public function __invoke(RequestInterface $request, array $options)
33 $fn = $this->nextHandler;
35 // Don't do anything if the request has no body.
36 if ($request->getBody()->getSize() === 0) {
37 return $fn($request, $options);
42 // Add a default content-type if possible.
43 if (!$request->hasHeader('Content-Type')) {
44 if ($uri = $request->getBody()->getMetadata('uri')) {
45 if ($type = Psr7\mimetype_from_filename($uri)) {
46 $modify['set_headers']['Content-Type'] = $type;
51 // Add a default content-length or transfer-encoding header.
52 if (!$request->hasHeader('Content-Length')
53 && !$request->hasHeader('Transfer-Encoding')
55 $size = $request->getBody()->getSize();
57 $modify['set_headers']['Content-Length'] = $size;
59 $modify['set_headers']['Transfer-Encoding'] = 'chunked';
63 // Add the expect header if needed.
64 $this->addExpectHeader($request, $options, $modify);
66 return $fn(Psr7\modify_request($request, $modify), $options);
69 private function addExpectHeader(
70 RequestInterface $request,
74 // Determine if the Expect header should be used
75 if ($request->hasHeader('Expect')) {
79 $expect = isset($options['expect']) ? $options['expect'] : null;
81 // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0
82 if ($expect === false || $request->getProtocolVersion() < 1.1) {
86 // The expect header is unconditionally enabled
87 if ($expect === true) {
88 $modify['set_headers']['Expect'] = '100-Continue';
92 // By default, send the expect header when the payload is > 1mb
93 if ($expect === null) {
97 // Always add if the body cannot be rewound, the size cannot be
98 // determined, or the size is greater than the cutoff threshold
99 $body = $request->getBody();
100 $size = $body->getSize();
102 if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
103 $modify['set_headers']['Expect'] = '100-Continue';