Lines 100.00% 7 / 7
Functions and Methods 100.00% 5 / 5
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
KeyspacedStores 100.00% 7 / 7 100.00% 5 / 5 6 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 openAppStore 100.00% 1 / 1 100.00% 1 / 1 1
 openGlobalStore 100.00% 1 / 1 100.00% 1 / 1 1
 openPeerStoreForReading 100.00% 3 / 3 100.00% 1 / 1 2
 createScopedStore 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Store;
6
7use Stewart\Contracts\App\AppId;
8use Stewart\Contracts\App\Collection\AppIdCollection;
9use Stewart\Contracts\Store\ReadableStore;
10use Stewart\Contracts\Store\Store;
11use Stewart\Store\Exception\StoreSetupException;
12use Stewart\Support\Text\ClosestNameFinder;
13
14final readonly class KeyspacedStores implements Stores
15{
16    public function __construct(
17        private StoreBackend $backend,
18        private StorePrefix $prefix,
19        private AppIdCollection $knownAppIds,
20        private StoreValueCodec $codec,
21        private ClosestNameFinder $closestNameFinder,
22    ) {}
23
24    public function openAppStore(AppId $appId): Store
25    {
26        return $this->createScopedStore(Keyspace::forApp($this->prefix, $appId));
27    }
28
29    public function openGlobalStore(): Store
30    {
31        return $this->createScopedStore(Keyspace::forGlobalScope($this->prefix));
32    }
33
34    public function openPeerStoreForReading(AppId $appId): ReadableStore
35    {
36        if (!$this->knownAppIds->containsId($appId)) {
37            throw StoreSetupException::unknownPeerApp($appId, $this->closestNameFinder->findClosestName($appId->value, $this->knownAppIds->toStrings()));
38        }
39
40        return new ReadOnlyStore($this->createScopedStore(Keyspace::forApp($this->prefix, $appId)));
41    }
42
43    private function createScopedStore(Keyspace $keyspace): ScopedStore
44    {
45        return new ScopedStore($this->backend, $keyspace, $this->codec);
46    }
47}