AccelerateMiddleware.php
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace Aws\S3;
use Aws\CommandInterface;
use Psr\Http\Message\RequestInterface;
/**
* Used to update the URL used for S3 requests to suport S3 Accelerate.
*
* IMPORTANT: this middleware must be added after the "build" step.
*
* @internal
*/
class AccelerateMiddleware
{
private static $exclusions = [
'CreateBucket' => true,
'DeleteBucket' => true,
'ListBuckets' => true,
];
/** @var bool */
private $accelerateByDefault;
/** @var callable */
private $nextHandler;
/**
* Create a middleware wrapper function.
*
* @param bool $accelerateByDefault
*
* @return callable
*/
public static function wrap($accelerateByDefault = false)
{
return function (callable $handler) use ($accelerateByDefault) {
return new self($handler, $accelerateByDefault);
};
}
public function __construct(callable $nextHandler, $accelerateByDefault = false)
{
$this->accelerateByDefault = (bool) $accelerateByDefault;
$this->nextHandler = $nextHandler;
}
public function __invoke(CommandInterface $command, RequestInterface $request)
{
if ($this->shouldAccelerate($command)) {
$request = $request->withUri(
$request->getUri()
->withHost($this->getAccelerateHost($command))
->withPath($this->getBucketlessPath(
$request->getUri()->getPath(),
$command
))
);
}
$nextHandler = $this->nextHandler;
return $nextHandler($command, $request);
}
private function shouldAccelerate(CommandInterface $command)
{
if ($this->canAccelerate($command)) {
return isset($command['@use_accelerate_endpoint'])
? $command['@use_accelerate_endpoint']
: $this->accelerateByDefault;
}
return false;
}
private function canAccelerate(CommandInterface $command)
{
return empty(self::$exclusions[$command->getName()])
&& S3Client::isBucketDnsCompatible($command['Bucket']);
}
private function getAccelerateHost(CommandInterface $command)
{
return "{$command['Bucket']}.s3-accelerate.amazonaws.com";
}
private function getBucketlessPath($path, CommandInterface $command)
{
$pattern = '/^\\/' . preg_quote($command['Bucket'], '/') . '/';
return preg_replace($pattern, '', $path) ?: '/';
}
}