| 1 |
<?php |
| 2 |
namespace Aws\S3; |
| 3 |
|
| 4 |
use Aws\CommandInterface; |
| 5 |
use GuzzleHttp\Psr7\Uri; |
| 6 |
use Psr\Http\Message\RequestInterface; |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
class BucketEndpointMiddleware |
| 17 |
{ |
| 18 |
private static $exclusions = ['GetBucketLocation' => true]; |
| 19 |
private $nextHandler; |
| 20 |
private bool $useEndpointV2; |
| 21 |
private ?string $endpoint; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
public static function wrap( |
| 32 |
bool $useEndpointV2 = false, |
| 33 |
?string $endpoint = null |
| 34 |
): callable |
| 35 |
{ |
| 36 |
return function (callable $handler) use ($useEndpointV2, $endpoint) { |
| 37 |
return new self($handler, $useEndpointV2, $endpoint); |
| 38 |
}; |
| 39 |
} |
| 40 |
|
| 41 |
public function __construct( |
| 42 |
callable $nextHandler, |
| 43 |
bool $useEndpointV2, |
| 44 |
?string $endpoint = null |
| 45 |
) |
| 46 |
{ |
| 47 |
$this->nextHandler = $nextHandler; |
| 48 |
$this->useEndpointV2 = $useEndpointV2; |
| 49 |
$this->endpoint = $endpoint; |
| 50 |
} |
| 51 |
|
| 52 |
public function __invoke(CommandInterface $command, RequestInterface $request) |
| 53 |
{ |
| 54 |
$nextHandler = $this->nextHandler; |
| 55 |
$bucket = $command['Bucket']; |
| 56 |
|
| 57 |
if ($bucket && !isset(self::$exclusions[$command->getName()])) { |
| 58 |
$request = $this->modifyRequest($request, $command); |
| 59 |
} |
| 60 |
|
| 61 |
return $nextHandler($command, $request); |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
private function removeBucketFromPath(string $path, string $bucket): string |
| 71 |
{ |
| 72 |
$len = strlen($bucket) + 1; |
| 73 |
if (str_starts_with($path, "/{$bucket}")) { |
| 74 |
$path = substr($path, $len); |
| 75 |
} |
| 76 |
|
| 77 |
return $path ?: '/'; |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
private function modifyRequest( |
| 87 |
RequestInterface $request, |
| 88 |
CommandInterface $command |
| 89 |
): RequestInterface |
| 90 |
{ |
| 91 |
$uri = $request->getUri(); |
| 92 |
$path = $uri->getPath(); |
| 93 |
$host = $uri->getHost(); |
| 94 |
$bucket = $command['Bucket']; |
| 95 |
|
| 96 |
if ($this->useEndpointV2 && !empty($this->endpoint)) { |
| 97 |
|
| 98 |
|
| 99 |
$host = (new Uri($this->endpoint))->getHost(); |
| 100 |
} |
| 101 |
|
| 102 |
$path = $this->removeBucketFromPath($path, $bucket); |
| 103 |
|
| 104 |
|
| 105 |
if ($command['Key']) { |
| 106 |
$path = S3Client::encodeKey(rawurldecode($path)); |
| 107 |
} |
| 108 |
|
| 109 |
return $request->withUri($uri->withPath($path)->withHost($host)); |
| 110 |
} |
| 111 |
} |