1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Distribution\Resolver; |
6
|
|
|
|
7
|
|
|
use Aws\CloudFront\UrlSigner; |
8
|
|
|
use Psr\Http\Message\UriInterface; |
9
|
|
|
use Spiral\Distribution\Internal\AmazonUriFactory; |
10
|
|
|
use Spiral\Distribution\Internal\DateTimeIntervalFactoryInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Amazon CloudFront is a content delivery network (CDN) service. |
14
|
|
|
* |
15
|
|
|
* @psalm-import-type DateIntervalFormat from DateTimeIntervalFactoryInterface |
16
|
|
|
* @see DateTimeIntervalFactoryInterface |
17
|
|
|
*/ |
18
|
|
|
class CloudFrontResolver extends ExpirationAwareResolver |
19
|
|
|
{ |
20
|
|
|
private readonly UrlSigner $signer; |
21
|
|
|
private readonly AmazonUriFactory $factory; |
22
|
|
|
|
23
|
|
|
public function __construct( |
24
|
|
|
string $keyPairId, |
25
|
|
|
string $privateKey, |
26
|
|
|
private readonly string $domain, |
27
|
|
|
private readonly ?string $prefix = null, |
28
|
|
|
) { |
29
|
|
|
$this->assertCloudFrontAvailable(); |
30
|
|
|
$this->factory = new AmazonUriFactory(); |
|
|
|
|
31
|
|
|
$this->signer = new UrlSigner($keyPairId, $privateKey); |
|
|
|
|
32
|
|
|
|
33
|
|
|
parent::__construct(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @throws \Exception |
38
|
|
|
*/ |
39
|
|
|
public function resolve(string $file, mixed $expiration = null): UriInterface |
40
|
|
|
{ |
41
|
|
|
$date = $this->getExpirationDateTime($expiration); |
42
|
|
|
$url = $this->signer->getSignedUrl($this->createUrl($file), $date->getTimestamp()); |
43
|
|
|
|
44
|
|
|
return $this->factory->createUri($url); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function assertCloudFrontAvailable(): void |
48
|
|
|
{ |
49
|
|
|
if (\class_exists(UrlSigner::class)) { |
50
|
|
|
return; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
throw new \DomainException('AWS SDK not available. Please install "aws/aws-sdk-php" package'); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function createUrl(string $file): string |
57
|
|
|
{ |
58
|
|
|
return \sprintf('https://%s/%s', $this->domain, $this->concat($file, $this->prefix)); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|