| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws\S3; |
| 4 |
|
| 5 |
use Dudlewebs\WPMCS\s3\Aws\CommandInterface; |
| 6 |
use Dudlewebs\WPMCS\s3\Psr\Http\Message\RequestInterface; |
| 7 |
/** |
| 8 |
* Used to update the host used for S3 requests in the case of using a |
| 9 |
* "bucket endpoint" or CNAME bucket. |
| 10 |
* |
| 11 |
* IMPORTANT: this middleware must be added after the "build" step. |
| 12 |
* |
| 13 |
* @internal |
| 14 |
*/ |
| 15 |
class BucketEndpointMiddleware |
| 16 |
{ |
| 17 |
private static $exclusions = ['GetBucketLocation' => \true]; |
| 18 |
private $nextHandler; |
| 19 |
/** |
| 20 |
* Create a middleware wrapper function. |
| 21 |
* |
| 22 |
* @return callable |
| 23 |
*/ |
| 24 |
public static function wrap() |
| 25 |
{ |
| 26 |
return function (callable $handler) { |
| 27 |
return new self($handler); |
| 28 |
}; |
| 29 |
} |
| 30 |
public function __construct(callable $nextHandler) |
| 31 |
{ |
| 32 |
$this->nextHandler = $nextHandler; |
| 33 |
} |
| 34 |
public function __invoke(CommandInterface $command, RequestInterface $request) |
| 35 |
{ |
| 36 |
$nextHandler = $this->nextHandler; |
| 37 |
$bucket = $command['Bucket']; |
| 38 |
if ($bucket && !isset(self::$exclusions[$command->getName()])) { |
| 39 |
$request = $this->modifyRequest($request, $command); |
| 40 |
} |
| 41 |
return $nextHandler($command, $request); |
| 42 |
} |
| 43 |
private function removeBucketFromPath($path, $bucket) |
| 44 |
{ |
| 45 |
$len = \strlen($bucket) + 1; |
| 46 |
if (\substr($path, 0, $len) === "/{$bucket}") { |
| 47 |
$path = \substr($path, $len); |
| 48 |
} |
| 49 |
return $path ?: '/'; |
| 50 |
} |
| 51 |
private function modifyRequest(RequestInterface $request, CommandInterface $command) |
| 52 |
{ |
| 53 |
$uri = $request->getUri(); |
| 54 |
$path = $uri->getPath(); |
| 55 |
$bucket = $command['Bucket']; |
| 56 |
$path = $this->removeBucketFromPath($path, $bucket); |
| 57 |
// Modify the Key to make sure the key is encoded, but slashes are not. |
| 58 |
if ($command['Key']) { |
| 59 |
$path = S3Client::encodeKey(\rawurldecode($path)); |
| 60 |
} |
| 61 |
return $request->withUri($uri->withPath($path)); |
| 62 |
} |
| 63 |
} |
| 64 |
|