MongoWallet   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 35
c 0
b 0
f 0
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A withdraw() 0 5 1
A deposit() 0 3 1
A __construct() 0 4 1
A balance() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\ChargeableApi\Wallet;
6
7
use Damax\ChargeableApi\Credit;
8
use MongoDB\Collection;
9
use MongoDB\Model\BSONDocument;
10
11
final class MongoWallet implements Wallet
12
{
13
    private const FIELD_BALANCE = 'balance';
14
15
    private $collection;
16
    private $filters;
17
18
    public function __construct(Collection $collection, string $identity)
19
    {
20
        $this->collection = $collection;
21
        $this->filters = ['_id' => $identity];
22
    }
23
24
    public function balance(): Credit
25
    {
26
        $options = ['projection' => [self::FIELD_BALANCE => 1]];
27
28
        /** @var BSONDocument $doc */
29
        if (null === $doc = $this->collection->findOne($this->filters, $options)) {
30
            return Credit::blank();
31
        }
32
33
        return Credit::fromInteger($doc[self::FIELD_BALANCE]);
34
    }
35
36
    public function deposit(Credit $credit): void
37
    {
38
        $this->collection->updateOne($this->filters, ['$inc' => [self::FIELD_BALANCE => $credit->toInteger()]], ['upsert' => true]);
39
    }
40
41
    public function withdraw(Credit $credit): void
42
    {
43
        $balance = $this->balance()->subtract($credit)->toInteger();
44
45
        $this->collection->replaceOne($this->filters, [self::FIELD_BALANCE => $balance], ['upsert' => true]);
46
    }
47
}
48