Completed
Pull Request — master (#366)
by Beñat
14:40
created

EventStoreUserRepository   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 6
dl 0
loc 29
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A get() 0 8 2
A save() 0 10 1
1
<?php
2
3
/*
4
 * This file is part of the Kreta package.
5
 *
6
 * (c) Beñat Espiña <[email protected]>
7
 * (c) Gorka Laucirica <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace Kreta\Notifier\Infrastructure\Persistence\EventStore\Inbox;
16
17
use Kreta\Notifier\Domain\Model\Inbox\User;
18
use Kreta\Notifier\Domain\Model\Inbox\UserDoesNotExist;
19
use Kreta\Notifier\Domain\Model\Inbox\UserId;
20
use Kreta\Notifier\Domain\Model\Inbox\UserRepository;
21
use Kreta\SharedKernel\Domain\Model\AggregateDoesNotExistException;
22
use Kreta\SharedKernel\Domain\Model\DomainEventCollection;
23
use Kreta\SharedKernel\Event\EventStore;
24
use Kreta\SharedKernel\Event\EventStream;
25
use Kreta\SharedKernel\Projection\Projector;
26
27
final class EventStoreUserRepository implements UserRepository
28
{
29
    private $eventStore;
30
31
    public function __construct(EventStore $eventStore)
32
    {
33
        $this->eventStore = $eventStore;
34
    }
35
36
    public function get(UserId $id) : User
37
    {
38
        try {
39
            return User::reconstitute($this->eventStore->streamOfId($id));
40
        } catch (AggregateDoesNotExistException $exception) {
41
            throw new UserDoesNotExist();
42
        }
43
    }
44
45
    public function save(User $user) : void
46
    {
47
        $events = new DomainEventCollection($user->recordedEvents());
48
        $eventStream = new EventStream($user->id(), $events);
49
50
        $this->eventStore->appendTo($eventStream);
51
        $user->clearEvents();
52
53
        Projector::instance()->project($events);
54
    }
55
}
56