ApplyChecksumMiddleware.php 1.8 KB

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