ApplyChecksumMiddleware.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace Aws\S3;
  3. use Aws\Api\ApiProvider;
  4. use Aws\Api\Service;
  5. use Aws\CommandInterface;
  6. use GuzzleHttp\Psr7;
  7. use Psr\Http\Message\RequestInterface;
  8. /**
  9. * Apply required or optional MD5s to requests before sending.
  10. *
  11. * IMPORTANT: This middleware must be added after the "build" step.
  12. *
  13. * @internal
  14. */
  15. class ApplyChecksumMiddleware
  16. {
  17. private static $sha256 = [
  18. 'PutObject',
  19. 'UploadPart',
  20. ];
  21. /** @var Service */
  22. private $api;
  23. private $nextHandler;
  24. /**
  25. * Create a middleware wrapper function.
  26. *
  27. * @param Service $api
  28. * @return callable
  29. */
  30. public static function wrap(Service $api)
  31. {
  32. return function (callable $handler) use ($api) {
  33. return new self($handler, $api);
  34. };
  35. }
  36. public function __construct(callable $nextHandler, Service $api)
  37. {
  38. $this->api = $api;
  39. $this->nextHandler = $nextHandler;
  40. }
  41. public function __invoke(
  42. CommandInterface $command,
  43. RequestInterface $request
  44. ) {
  45. $next = $this->nextHandler;
  46. $name = $command->getName();
  47. $body = $request->getBody();
  48. $op = $this->api->getOperation($command->getName());
  49. if (!empty($op['httpChecksumRequired']) && !$request->hasHeader('Content-MD5')) {
  50. // Set the content MD5 header for operations that require it.
  51. $request = $request->withHeader(
  52. 'Content-MD5',
  53. base64_encode(Psr7\hash($body, 'md5', true))
  54. );
  55. } elseif (in_array($name, self::$sha256) && $command['ContentSHA256']) {
  56. // Set the content hash header if provided in the parameters.
  57. $request = $request->withHeader(
  58. 'X-Amz-Content-Sha256',
  59. $command['ContentSHA256']
  60. );
  61. }
  62. return $next($command, $request);
  63. }
  64. }