Passed
Push — master ( 19875f...3a63b4 )
by Chris
13:30
created

CloudFront::reset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Meema\CloudFront;
4
5
use Aws\CloudFront\CloudFrontClient;
6
use Aws\Credentials\Credentials;
7
use Aws\Exception\AwsException;
8
use Meema\CloudFront\Contracts\CloudFront as CloudFrontInterface;
9
10
class CloudFront implements CloudFrontInterface
11
{
12
    /**
13
     * Client instance of CloudFront.
14
     *
15
     * @var \Aws\CloudFront\CloudFrontClient
16
     */
17
    protected CloudFrontClient $client;
18
19
    /**
20
     * Construct converter.
21
     *
22
     * @param \Aws\CloudFront\CloudFrontClient $client
23
     */
24
    public function __construct(CloudFrontClient $client)
25
    {
26
        $config = config('cloudfront');
27
28
        $this->client = new $client([
29
            'version' => $config['version'],
30
            'region' => $config['region'],
31
            'credentials' => new Credentials($config['credentials']['key'], $config['credentials']['secret']),
32
        ]);
33
    }
34
35
    /**
36
     * Get the CloudFront Client.
37
     *
38
     * @return \Aws\CloudFront\CloudFrontClient
39
     */
40
    public function getClient(): CloudFrontClient
41
    {
42
        return $this->client;
43
    }
44
45
    /**
46
     * Bust an item/s in CloudFront's cache.
47
     *
48
     * @param array|string $items
49
     * @param string|null $distributionId
50
     * @return \Aws\Result
51
     */
52
    public function invalidate($items, string $distributionId = null)
53
    {
54
        if (is_string($items)) {
55
            $items[] = $items;
56
        }
57
58
        return $this->client->createInvalidation([
59
            'DistributionId' => $distributionId ?? config('cloudfront.distribution_id'),
60
            'InvalidationBatch' => [
61
                // CallerReference is a unique value that you provide and that CloudFront uses to prevent replays of your request.
62
                // You must provide a new caller reference value and other new information in the request for CloudFront to create a new invalidation request.
63
                'CallerReference' => microtime(true),
64
                'Paths' => [
65
                    'Items' => $items,
66
                    'Quantity' => count($items),
0 ignored issues
show
Bug introduced by
It seems like $items can also be of type string; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

66
                    'Quantity' => count(/** @scrutinizer ignore-type */ $items),
Loading history...
67
                ],
68
            ],
69
        ]);
70
    }
71
72
    /**
73
     * Remove every item out of your CloudFront distribution.
74
     *
75
     * @param string|null $distributionId
76
     * @return \Aws\Result
77
     */
78
    public function reset(string $distributionId = null)
79
    {
80
        return $this->invalidate('/*', $distributionId ?? config('cloudfront.distribution_id'));
81
    }
82
83
    /**
84
     * Get a cache "invalidation".
85
     *
86
     * @param string $invalidationId
87
     * @param string|null $distributionId
88
     * @return string
89
     */
90
    public function getInvalidation(string $invalidationId, string $distributionId = null)
91
    {
92
        try {
93
            $result = $this->client->getInvalidation([
94
                'DistributionId' => $distributionId ?? config('cloudfront.distribution_id'),
95
                'Id' => $invalidationId,
96
            ]);
97
98
            $message = '';
99
100
            if (isset($result['Invalidation']['Status'])) {
101
                $message = 'The status for the invalidation with the ID of '.$result['Invalidation']['Id'].' is '.$result['Invalidation']['Status'];
102
            }
103
104
            if (isset($result['@metadata']['effectiveUri'])) {
105
                $message .= ', and the effective URI is '.$result['@metadata']['effectiveUri'].'.';
106
            } else {
107
                $message = 'Error: Could not get information about '.'the invalidation. The invalidation\'s status '.'was not available.';
108
            }
109
110
            return $message;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $message returns the type string which is incompatible with the return type mandated by Meema\CloudFront\Contrac...ront::getInvalidation() of Aws\Result.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
111
        } catch (AwsException $e) {
112
            throw($e->getAwsErrorMessage());
113
        }
114
    }
115
116
    /**
117
     * List all of the cache invalidations.
118
     *
119
     * @param string|null $distributionId
120
     * @return array
121
     */
122
    public function listInvalidations(string $distributionId = null)
123
    {
124
        try {
125
            $invalidations = $this->client->listInvalidations([
126
                'DistributionId' => $distributionId ?? config('cloudfront.distribution_id'),
127
            ]);
128
129
            $messages = [];
130
131
            if (isset($invalidations['InvalidationList'])) {
132
                if ($invalidations['InvalidationList']['Quantity'] > 0) {
133
                    foreach ($invalidations['InvalidationList']['Items'] as $invalidation) {
134
                        $message = 'The invalidation with the ID of '.$invalidation['Id'].' has the status of '.$invalidation['Status'].'.';
135
                        $messages[$invalidation['Id']] = $message;
136
                    }
137
                } else {
138
                    $message = 'Could not find any invalidations for the specified distribution.';
139
                    array_push($messages, $message);
140
                }
141
            } else {
142
                $message = 'Error: Could not get invalidation information. Could not get information about the specified distribution.';
143
                array_push($messages, $message);
144
            }
145
146
            return $messages;
147
        } catch (AwsException $e) {
148
            throw($e->getAwsErrorMessage());
149
        }
150
    }
151
}
152