Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/S3/BucketEndpointMiddleware.php

raw symbols SCIP
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 * Used to update the host used for S3 requests in the case of using a
10 * "bucket endpoint" or CNAME bucket.
11 *
12 * IMPORTANT: this middleware must be added after the "build" step.
13 *
14 * @internal
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 * Create a middleware wrapper function.
25 *
26 * @param bool $useEndpointV2
27 * @param string|null $endpoint
28 *
29 * @return callable
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 * @param string $path
66 * @param string $bucket
67 *
68 * @return string
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 * @param RequestInterface $request
82 * @param CommandInterface $command
83 *
84 * @return RequestInterface
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 // V2 provider adds bucket name to host by default
98 // preserve original host
99 $host = (new Uri($this->endpoint))->getHost();
100 }
101
102 $path = $this->removeBucketFromPath($path, $bucket);
103
104 // Modify the Key to make sure the key is encoded, but slashes are not.
105 if ($command['Key']) {
106 $path = S3Client::encodeKey(rawurldecode($path));
107 }
108
109 return $request->withUri($uri->withPath($path)->withHost($host));
110 }
111 }