-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathDefaultRepositoryManager.php
More file actions
76 lines (66 loc) · 2.78 KB
/
DefaultRepositoryManager.php
File metadata and controls
76 lines (66 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
declare(strict_types=1);
namespace Patchlevel\EventSourcing\Repository;
use Patchlevel\EventSourcing\Aggregate\AggregateRoot;
use Patchlevel\EventSourcing\Clock\SystemClock;
use Patchlevel\EventSourcing\EventBus\EventBus;
use Patchlevel\EventSourcing\Metadata\AggregateRoot\AggregateRootClassNotRegistered;
use Patchlevel\EventSourcing\Metadata\AggregateRoot\AggregateRootMetadataAwareMetadataFactory;
use Patchlevel\EventSourcing\Metadata\AggregateRoot\AggregateRootMetadataFactory;
use Patchlevel\EventSourcing\Metadata\AggregateRoot\AggregateRootRegistry;
use Patchlevel\EventSourcing\Repository\MessageDecorator\MessageDecorator;
use Patchlevel\EventSourcing\Repository\StoreAdapter\StoreAdapter;
use Patchlevel\EventSourcing\Snapshot\SnapshotStore;
use Psr\Clock\ClockInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use function array_key_exists;
final class DefaultRepositoryManager implements RepositoryManager
{
private ClockInterface $clock;
private AggregateRootMetadataFactory $metadataFactory;
private LoggerInterface $logger;
/** @var array<class-string<AggregateRoot>, Repository> */
private array $instances = [];
public function __construct(
private readonly AggregateRootRegistry $aggregateRootRegistry,
private readonly StoreAdapter $storeAdapter,
private readonly EventBus|null $eventBus = null,
private readonly SnapshotStore|null $snapshotStore = null,
private readonly MessageDecorator|null $messageDecorator = null,
ClockInterface|null $clock = null,
AggregateRootMetadataFactory|null $metadataFactory = null,
LoggerInterface|null $logger = null,
) {
$this->metadataFactory = $metadataFactory ?? new AggregateRootMetadataAwareMetadataFactory();
$this->clock = $clock ?? new SystemClock();
$this->logger = $logger ?? new NullLogger();
}
/**
* @param class-string<T> $aggregateClass
*
* @return Repository<T>
*
* @template T of AggregateRoot
*/
public function get(string $aggregateClass): Repository
{
if (array_key_exists($aggregateClass, $this->instances)) {
/** @var Repository<T> $repository */
$repository = $this->instances[$aggregateClass];
return $repository;
}
if (!$this->aggregateRootRegistry->hasAggregateClass($aggregateClass)) {
throw new AggregateRootClassNotRegistered($aggregateClass);
}
return $this->instances[$aggregateClass] = new DefaultRepository(
$this->storeAdapter,
$this->metadataFactory->metadata($aggregateClass),
$this->eventBus,
$this->snapshotStore,
$this->messageDecorator,
$this->clock,
$this->logger,
);
}
}