BatchGetItemOperation::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 3
crap 1
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\Contract\AbstractBatchItemOperation;
9
use Guillermoandrae\DynamoDb\Factory\ExceptionFactory;
10
11
/**
12
 * BatchGetItem operation.
13
 *
14
 * @author Guillermo A. Fisher <[email protected]>
15
 * @link https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-dynamodb-2012-08-10.html#batchgetitem
16
 */
17
final class BatchGetItemOperation extends AbstractBatchItemOperation
18
{
19
    /**
20
     * Registers the DynamoDb client, Marshaler, and the mapping of tables and primary keys with this object.
21
     *
22
     * @param DynamoDbClient $client The DynamoDB client.
23
     * @param Marshaler $marshaler The Marshaler.
24
     * @param array $primaryKeys The tables and primary keys.
25
     */
26 3
    public function __construct(DynamoDbClient $client, Marshaler $marshaler, array $primaryKeys)
27
    {
28 3
        parent::__construct($client, $marshaler);
29 3
        $this->setPrimaryKeys($primaryKeys);
30 3
    }
31
32 3
    public function setPrimaryKeys(array $primaryKeys): BatchGetItemOperation
33
    {
34 3
        $requestItems = [];
35 3
        foreach ($primaryKeys as $tableName => $keys) {
36 3
            $requestItems[$tableName] = ['Keys' => []];
37 3
            foreach ($keys as $key) {
38 3
                $requestItems[$tableName]['Keys'][] = $this->getMarshaler()->marshalItem($key);
39
            }
40
        }
41 3
        $this->setRequestItems($requestItems);
42 3
        return $this;
43
    }
44
45 3
    public function execute(): array
46
    {
47
        try {
48 3
            $items = [];
49 3
            $result = $this->client->batchGetItem($this->toArray());
50 2
            foreach ($result['Responses'] as $table => $itemArrays) {
51 2
                foreach ($itemArrays as $itemArray) {
52 2
                    $items[] = $this->getMarshaler()->unmarshalItem($itemArray);
53
                }
54
            }
55 2
            return $items;
56 1
        } catch (DynamoDbException $ex) {
57 1
            throw ExceptionFactory::factory($ex);
58
        }
59
    }
60
}
61