S3ControlEndpointMiddleware.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Aws\S3Control;
  3. use Aws\CommandInterface;
  4. use Psr\Http\Message\RequestInterface;
  5. /**
  6. * Used to update the URL used for S3 Control requests to support S3 Control
  7. * DualStack. It will build to host style paths, including for S3 Control
  8. * DualStack.
  9. *
  10. * IMPORTANT: this middleware must be added after the "build" step.
  11. *
  12. * @internal
  13. */
  14. class S3ControlEndpointMiddleware
  15. {
  16. /** @var bool */
  17. private $dualStackByDefault;
  18. /** @var string */
  19. private $region;
  20. /** @var callable */
  21. private $nextHandler;
  22. /**
  23. * Create a middleware wrapper function
  24. *
  25. * @param string $region
  26. * @param array $options
  27. *
  28. * @return callable
  29. */
  30. public static function wrap($region, array $options)
  31. {
  32. return function (callable $handler) use ($region, $options) {
  33. return new self($handler, $region, $options);
  34. };
  35. }
  36. public function __construct(
  37. callable $nextHandler,
  38. $region,
  39. array $options
  40. ) {
  41. $this->dualStackByDefault = isset($options['dual_stack'])
  42. ? (bool) $options['dual_stack'] : false;
  43. $this->region = (string) $region;
  44. $this->nextHandler = $nextHandler;
  45. }
  46. public function __invoke(CommandInterface $command, RequestInterface $request)
  47. {
  48. if ($this->isDualStackRequest($command, $request)) {
  49. $request = $this->applyDualStackEndpoint($command, $request);
  50. }
  51. $nextHandler = $this->nextHandler;
  52. return $nextHandler($command, $request);
  53. }
  54. private function isDualStackRequest(
  55. CommandInterface $command,
  56. RequestInterface $request
  57. ) {
  58. return isset($command['@use_dual_stack_endpoint'])
  59. ? $command['@use_dual_stack_endpoint'] : $this->dualStackByDefault;
  60. }
  61. private function getDualStackHost($host)
  62. {
  63. $parts = explode(".{$this->region}.", $host);
  64. return $parts[0] . ".dualstack.{$this->region}." . $parts[1];
  65. }
  66. private function applyDualStackEndpoint(
  67. CommandInterface $command,
  68. RequestInterface $request
  69. ) {
  70. $uri = $request->getUri();
  71. return $request->withUri(
  72. $uri->withHost($this->getDualStackHost(
  73. $uri->getHost()
  74. ))
  75. );
  76. }
  77. }