CloudFrontResolver::resolve()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 10
cc 1
nc 1
nop 2
crap 2
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();
0 ignored issues
show
Bug introduced by
The property factory is declared read-only in Spiral\Distribution\Resolver\CloudFrontResolver.
Loading history...
31
        $this->signer = new UrlSigner($keyPairId, $privateKey);
0 ignored issues
show
Bug introduced by
The property signer is declared read-only in Spiral\Distribution\Resolver\CloudFrontResolver.
Loading history...
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