| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws; |
| 4 |
|
| 5 |
use Dudlewebs\WPMCS\s3\Aws\Api\Service; |
| 6 |
use Dudlewebs\WPMCS\s3\Aws\Exception\IncalculablePayloadException; |
| 7 |
use Dudlewebs\WPMCS\s3\Psr\Http\Message\RequestInterface; |
| 8 |
/** |
| 9 |
* @internal |
| 10 |
*/ |
| 11 |
class StreamRequestPayloadMiddleware |
| 12 |
{ |
| 13 |
private $nextHandler; |
| 14 |
private $service; |
| 15 |
/** |
| 16 |
* Create a middleware wrapper function |
| 17 |
* |
| 18 |
* @param Service $service |
| 19 |
* @return \Closure |
| 20 |
*/ |
| 21 |
public static function wrap(Service $service) |
| 22 |
{ |
| 23 |
return function (callable $handler) use($service) { |
| 24 |
return new self($handler, $service); |
| 25 |
}; |
| 26 |
} |
| 27 |
public function __construct(callable $nextHandler, Service $service) |
| 28 |
{ |
| 29 |
$this->nextHandler = $nextHandler; |
| 30 |
$this->service = $service; |
| 31 |
} |
| 32 |
public function __invoke(CommandInterface $command, RequestInterface $request) |
| 33 |
{ |
| 34 |
$nextHandler = $this->nextHandler; |
| 35 |
$operation = $this->service->getOperation($command->getName()); |
| 36 |
$contentLength = $request->getHeader('content-length'); |
| 37 |
$hasStreaming = \false; |
| 38 |
$requiresLength = \false; |
| 39 |
// Check if any present input member is a stream and requires the |
| 40 |
// content length |
| 41 |
foreach ($operation->getInput()->getMembers() as $name => $member) { |
| 42 |
if (!empty($member['streaming']) && isset($command[$name])) { |
| 43 |
$hasStreaming = \true; |
| 44 |
if (!empty($member['requiresLength'])) { |
| 45 |
$requiresLength = \true; |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
if ($hasStreaming) { |
| 50 |
// Add 'transfer-encoding' header if payload size not required to |
| 51 |
// to be calculated and not already known |
| 52 |
if (empty($requiresLength) && empty($contentLength) && isset($operation['authtype']) && $operation['authtype'] == 'v4-unsigned-body') { |
| 53 |
$request = $request->withHeader('transfer-encoding', 'chunked'); |
| 54 |
// Otherwise, make sure 'content-length' header is added |
| 55 |
} else { |
| 56 |
if (empty($contentLength)) { |
| 57 |
$size = $request->getBody()->getSize(); |
| 58 |
if (\is_null($size)) { |
| 59 |
throw new IncalculablePayloadException('Payload' . ' content length is required and can not be' . ' calculated.'); |
| 60 |
} |
| 61 |
$request = $request->withHeader('content-length', $size); |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
return $nextHandler($command, $request); |
| 66 |
} |
| 67 |
} |
| 68 |
|