Passed
Push — master ( 8b0c18...7367d6 )
by Bao
04:53
created

ModelObserver::deleteFromDynamoDb()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 11
ccs 0
cts 7
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace BaoPham\DynamoDb;
4
5
use Exception;
6
use Illuminate\Support\Facades\Log;
7
8
/**
9
 * Class ModelObserver.
10
 */
11
class ModelObserver
12
{
13
    /**
14
     * @var \Aws\DynamoDb\DynamoDbClient
15
     */
16
    protected $dynamoDbClient;
17
18
    /**
19
     * @var \Aws\DynamoDb\Marshaler
20
     */
21
    protected $marshaler;
22
23
    /**
24
     * @var \BaoPham\DynamoDb\EmptyAttributeFilter
25
     */
26
    protected $attributeFilter;
27
28
    public function __construct(DynamoDbClientInterface $dynamoDb)
29
    {
30
        $this->dynamoDbClient = $dynamoDb->getClient();
31
        $this->marshaler = $dynamoDb->getMarshaler();
32
        $this->attributeFilter = $dynamoDb->getAttributeFilter();
33
    }
34
35
    private function saveToDynamoDb($model)
36
    {
37
        $attrs = $model->attributesToArray();
38
        
39
        try {
40
            $this->dynamoDbClient->putItem([
41
                'TableName' => $model->getDynamoDbTableName(),
42
                'Item' => $this->marshaler->marshalItem($attrs),
43
            ]);
44
        } catch (Exception $e) {
45
            Log::error($e);
46
        }
47
    }
48
49
    private function deleteFromDynamoDb($model)
50
    {
51
        $key = [$model->getKeyName() => $model->getKey()];
52
53
        try {
54
            $this->dynamoDbClient->deleteItem([
55
                'TableName' => $model->getDynamoDbTableName(),
56
                'Key' => $this->marshaler->marshalItem($key),
57
            ]);
58
        } catch (Exception $e) {
59
            Log::error($e);
60
        }
61
    }
62
63
    public function created($model)
64
    {
65
        $this->saveToDynamoDb($model);
66
    }
67
68
    public function updated($model)
69
    {
70
        $this->saveToDynamoDb($model);
71
    }
72
73
    public function deleted($model)
74
    {
75
        $this->deleteFromDynamoDb($model);
76
    }
77
78
    public function restored($model)
79
    {
80
        $this->saveToDynamoDb($model);
81
    }
82
}
83