Completed
Push — master ( 26a8ff...1b95ce )
by Guillermo A.
02:31
created

CreateTableOperation::setSSESpecification()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 14
rs 9.9666
ccs 9
cts 9
cp 1
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
namespace Guillermoandrae\DynamoDb\Operation;
4
5
use Aws\DynamoDb\DynamoDbClient;
6
use Aws\DynamoDb\Exception\DynamoDbException;
7
use Aws\DynamoDb\Marshaler;
8
use Guillermoandrae\DynamoDb\Constant\BillingModes;
9
use Guillermoandrae\DynamoDb\Constant\KeyTypes;
10
use Guillermoandrae\DynamoDb\Contract\AbstractTableOperation;
11
use Guillermoandrae\DynamoDb\Exception\Exception;
12
use Guillermoandrae\DynamoDb\Factory\ExceptionFactory;
13
14
/**
15
 * @link https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-dynamodb-2012-08-10.html#createtable
16
 */
17
final class CreateTableOperation extends AbstractTableOperation
18
{
19
    /**
20
     * @var array Attributes describing the key schema.
21
     */
22
    private $attributeDefinitions = [];
23
24
    /**
25
     * @var array The primary key.
26
     */
27
    private $keySchema = [];
28
29
    /**
30
     * @var int The maximum number of strongly consistent reads consumed per second.
31
     */
32
    private $readCapacityUnits = 5;
33
34
    /**
35
     * @var int The maximum number of writes consumed per second.
36
     */
37
    private $writeCapacityUnits = 5;
38
39
    /**
40
     * @var string The billing mode.
41
     */
42
    private $billingMode = BillingModes::PROVISIONED;
43
44
    /**
45
     * @var array The server-side encryption settings.
46
     */
47
    private $sseSpecification = [];
48
49
    /**
50
     * @var array The global secondary indexes.
51
     */
52
    private $globalSecondaryIndexes = [];
53
54
    /**
55
     * @var array The tags.
56
     */
57
    private $tags = [];
58
59
    /**
60
     * CreateTableRequest constructor.
61
     *
62
     * @param DynamoDbClient $client The DynamoDb client.
63
     * @param Marshaler $marshaler The Marshaler.
64
     * @param string $tableName The table name.
65
     * @param array $keySchema OPTIONAL The key schema.
66
     */
67 18
    public function __construct(DynamoDbClient $client, Marshaler $marshaler, string $tableName, array $keySchema = [])
68
    {
69 18
        parent::__construct($client, $marshaler, $tableName);
70 18
        if (!empty($keySchema)) {
71 9
            $this->setKeySchema($keySchema);
72
        }
73 18
    }
74
75
    /**
76
     * Registers the key schema and attribute definitions.
77
     *
78
     * The key schema argument should be an associative array with the following keys:
79
     *
80
     * $keySchema = [
81
     *      'MyAttribute' => [ // this is the name of your attribute
82
     *          'S', // this must be one of the AttributeTypes constants
83
     *          'HASH' // this must be one of the KeyTypes constants
84
     *     ]
85
     * ];
86
     *
87
     * This method will use the information available in the provided array to build the 'KeySchema' and
88
     * 'AttributeDefinitions' arrays needed for table creation requests.
89
     *
90
     * @param array $keySchema The key schema.
91
     * @return CreateTableOperation This object.
92
     */
93 11
    public function setKeySchema(array $keySchema): CreateTableOperation
94
    {
95 11
        foreach ($keySchema as $name => $data) {
96 11
            $this->keySchema[] = [
97 11
                'AttributeName' => $name,
98 11
                'KeyType' => $data[1]
99
            ];
100 11
            $this->attributeDefinitions[] = [
101 11
                'AttributeName' => $name,
102 11
                'AttributeType' => $data[0]
103
            ];
104
        }
105 11
        return $this;
106
    }
107
108
    /**
109
     * Registers the partition key.
110
     *
111
     * @param string $name The name of the partition key.
112
     * @param string $attributeType The attribute type.
113
     * @return CreateTableOperation This object.
114
     */
115 1
    public function setPartitionKey(string $name, string $attributeType): CreateTableOperation
116
    {
117 1
        $this->setKeySchema([
118 1
            $name => [$attributeType, KeyTypes::HASH]
119
        ]);
120 1
        return $this;
121
    }
122
123
    /**
124
     * Registers the sort key.
125
     *
126
     * @param string $name The name of the sort key.
127
     * @param string $attributeType The attribute type.
128
     * @return CreateTableOperation This object.
129
     */
130 1
    public function setSortKey(string $name, string $attributeType): CreateTableOperation
131
    {
132 1
        $this->setKeySchema([
133 1
            $name => [$attributeType, KeyTypes::RANGE]
134
        ]);
135 1
        return $this;
136
    }
137
138
    /**
139
     * Registers the maximum number of strongly consistent reads consumed per second.
140
     *
141
     * @param integer $readCapacityUnits The maximum number of strongly consistent reads consumed per second.
142
     * @return CreateTableOperation This object.
143
     */
144 1
    public function setReadCapacityUnits(int $readCapacityUnits): CreateTableOperation
145
    {
146 1
        $this->readCapacityUnits = $readCapacityUnits;
147 1
        return $this;
148
    }
149
150
    /**
151
     * Registers the maximum number of writes consumed per second.
152
     *
153
     * @param integer $writeCapacityUnits The maximum number of writes consumed per second.
154
     * @return CreateTableOperation This object.
155
     */
156 1
    public function setWriteCapacityUnits(int $writeCapacityUnits): CreateTableOperation
157
    {
158 1
        $this->writeCapacityUnits = $writeCapacityUnits;
159 1
        return $this;
160
    }
161
162
    /**
163
     * Registers the billing mode.
164
     *
165
     * @param string $billingMode The billing mode.
166
     * @return CreateTableOperation This object.
167
     */
168 1
    public function setBillingMode(string $billingMode)
169
    {
170 1
        $this->billingMode = $billingMode;
171 1
        return $this;
172
    }
173
174
    /**
175
     * Registers the server-side encryption settings.
176
     *
177
     * @param bool $isEnabled Whether or not SSE is enabled.
178
     * @param string $masterKeyId OPTIONAL The ID of the master key.
179
     * @return CreateTableOperation This object.
180
     */
181 1
    public function setSSESpecification(bool $isEnabled, string $masterKeyId = '')
182
    {
183 1
        $sseSpecification = [];
184 1
        if ($isEnabled) {
185
            $sseSpecification = [
186 1
                'Enabled' => $isEnabled,
187 1
                'SSEType' => 'KMS'
188
            ];
189 1
            if (!empty($masterKeyId)) {
190 1
                $sseSpecification['KMSMasterKeyId'] = $masterKeyId;
191
            }
192
        }
193 1
        $this->sseSpecification = $sseSpecification;
194 1
        return $this;
195
    }
196
197 2
    public function addGlobalSecondaryIndex(
198
        string $indexName,
199
        array $keySchema,
200
        array $projection,
201
        ?array $provisionedThroughput = []
202
    ): CreateTableOperation {
203
        $index = [
204 2
            'IndexName' => $indexName,
205
            'KeySchema' => [],
206
            'Projection' => [
207 2
                'NonKeyAttributes' => $projection[0],
208 2
                'ProjectionType' => $projection[1]
209
            ]
210
        ];
211 2
        foreach ($keySchema as $key) {
212 2
            $index['KeySchema'][] = [
213 2
                'AttributeName' => $key[0],
214 2
                'KeyType' => $key[1]
215
            ];
216
        }
217 2
        if (!empty($provisionedThroughput)) {
218 1
            $index['ProvisionedThroughput'] = [
219 1
                'ReadCapacityUnits' => $provisionedThroughput[0],
220 1
                'WriteCapacityUnits' => $provisionedThroughput[1],
221
            ];
222
        }
223 2
        $this->globalSecondaryIndexes[] = $index;
224 2
        return $this;
225
    }
226
227
    /**
228
     * Registers a tag.
229
     *
230
     * @param string $key The tag key.
231
     * @param string $value The tag value.
232
     * @return CreateTableOperation This object.
233
     */
234 1
    public function addTag(string $key, string $value)
235
    {
236 1
        $this->tags[] = [
237 1
            'Key' => $key,
238 1
            'Value' => $value
239
        ];
240 1
        return $this;
241
    }
242
243
    /**
244
     * {@inheritDoc}
245
     */
246 9
    public function execute(): bool
247
    {
248
        try {
249 9
            $this->client->createTable($this->toArray());
250
            //$this->client->waitUntil('TableExists', ['TableName' => $this->toArray()['TableName']]);
251 7
            return true;
252 2
        } catch (DynamoDbException $ex) {
253 1
            throw ExceptionFactory::factory($ex);
254 1
        } catch (\Exception $ex) {
255 1
            throw new Exception($ex->getMessage());
256
        }
257
    }
258
259
    /**
260
     * {@inheritDoc}
261
     */
262 18
    public function toArray(): array
263
    {
264 18
        $operation = parent::toArray();
265 18
        $operation['KeySchema'] = $this->keySchema;
266 18
        $operation['AttributeDefinitions'] = $this->attributeDefinitions;
267 18
        $operation['BillingMode'] = $this->billingMode;
268 18
        $operation['ProvisionedThroughput'] = [
269 18
            'ReadCapacityUnits' => $this->readCapacityUnits,
270 18
            'WriteCapacityUnits' => $this->writeCapacityUnits,
271
        ];
272 18
        if (!empty($this->sseSpecification)) {
273 1
            $operation['SSESpecification'] = $this->sseSpecification;
274
        }
275 18
        if (!empty($this->globalSecondaryIndexes)) {
276 2
            $operation['GlobalSecondaryIndexes'] = $this->globalSecondaryIndexes;
277
        }
278 18
        if (!empty($this->tags)) {
279 1
            $operation['Tags'] = $this->tags;
280
        }
281 18
        return $operation;
282
    }
283
}
284