Lines 100.00% 44 / 44
Functions and Methods 100.00% 7 / 7
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
StoreAttributesPass 100.00% 44 / 44 100.00% 7 / 7 26 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 process 100.00% 9 / 9 100.00% 1 / 1 8
 bindStoreArguments 100.00% 7 / 7 100.00% 1 / 1 5
 storeReferenceFor 100.00% 13 / 13 100.00% 1 / 1 6
 definePeerStore 100.00% 9 / 9 100.00% 1 / 1 2
 resolvePeerAppId 100.00% 3 / 3 100.00% 1 / 1 2
 isWritable 100.00% 2 / 2 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Container;
6
7use ReflectionClass;
8use ReflectionNamedType;
9use ReflectionParameter;
10use Stewart\Contracts\App\AppId;
11use Stewart\Contracts\App\Collection\AppIdCollection;
12use Stewart\Contracts\Exception\IdentifierException;
13use Stewart\Contracts\Store\GlobalStore;
14use Stewart\Contracts\Store\PeerStore;
15use Stewart\Contracts\Store\ReadableStore;
16use Stewart\Contracts\Store\Store;
17use Stewart\Runtime\Exception\ContainerError;
18use Stewart\Runtime\Exception\ContainerException;
19use Stewart\Store\Exception\StoreSetupException;
20use Stewart\Support\Text\ClosestNameFinder;
21use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
22use Symfony\Component\DependencyInjection\ContainerBuilder;
23use Symfony\Component\DependencyInjection\Definition;
24use Symfony\Component\DependencyInjection\Reference;
25
26final readonly class StoreAttributesPass implements CompilerPassInterface
27{
28    public function __construct(
29        private AppIdCollection $knownAppIds,
30        private ClosestNameFinder $closestNameFinder,
31    ) {}
32
33    public function process(ContainerBuilder $container): void
34    {
35        foreach ($container->getDefinitions() as $definition) {
36            $class = $definition->getClass();
37
38            if (
39                $class === null
40                || !$definition->isAutowired()
41                || $definition->isAbstract()
42                || $definition->isSynthetic()
43                || $definition->getFactory() !== null
44                || !class_exists($class)
45            ) {
46                continue;
47            }
48
49            $this->bindStoreArguments($container, $definition, $class);
50        }
51    }
52
53    /** @param class-string $class */
54    private function bindStoreArguments(ContainerBuilder $container, Definition $definition, string $class): void
55    {
56        $parameters = new ReflectionClass($class)->getConstructor()?->getParameters() ?? [];
57        $arguments = $definition->getArguments();
58
59        foreach ($parameters as $parameter) {
60            // Whatever services.php or stewart.yaml set explicitly still wins.
61            if (\array_key_exists('$' . $parameter->getName(), $arguments) || \array_key_exists($parameter->getPosition(), $arguments)) {
62                continue;
63            }
64
65            $store = $this->storeReferenceFor($container, $class, $parameter);
66
67            if ($store !== null) {
68                $definition->setArgument('$' . $parameter->getName(), $store);
69            }
70        }
71    }
72
73    private function storeReferenceFor(ContainerBuilder $container, string $class, ReflectionParameter $parameter): ?Reference
74    {
75        $writable = $this->isWritable($parameter);
76
77        if ($parameter->getAttributes(GlobalStore::class) !== []) {
78            return new Reference($writable ? AppContainerBuilder::GLOBAL_STORE : AppContainerBuilder::READ_ONLY_GLOBAL_STORE);
79        }
80
81        $peer = ($parameter->getAttributes(PeerStore::class)[0] ?? null)?->newInstance();
82
83        if ($peer === null) {
84            return null;
85        }
86
87        if ($writable) {
88            throw ContainerException::createForReason(ContainerError::PeerStoreWritable, class: $class, parameter: $parameter->getName());
89        }
90
91        $peerAppId = $this->resolvePeerAppId($class, $parameter, $peer);
92        $id = AppContainerBuilder::buildPeerStoreServiceId($peerAppId);
93
94        if (!$container->hasDefinition($id)) {
95            $container->setDefinition($id, $this->definePeerStore($peerAppId));
96        }
97
98        return new Reference($id);
99    }
100
101    private function definePeerStore(AppId $peerAppId): Definition
102    {
103        $definition = new Definition(ReadableStore::class);
104
105        if (!$this->knownAppIds->containsId($peerAppId)) {
106            // An error, not a throw, so it fails only the services that take this peer store.
107            return $definition->addError(fn(): string => StoreSetupException::unknownPeerApp(
108                $peerAppId,
109                $this->closestNameFinder->findClosestName($peerAppId->value, $this->knownAppIds->toStrings()),
110            )->getMessage());
111        }
112
113        return $definition
114            ->setFactory([new Reference(AppContainerBuilder::STORES), 'openPeerStoreForReading'])
115            ->setArguments([$peerAppId]);
116    }
117
118    /** @throws ContainerException */
119    private function resolvePeerAppId(string $class, ReflectionParameter $parameter, PeerStore $peer): AppId
120    {
121        try {
122            return new AppId($peer->appId);
123        } catch (IdentifierException $e) {
124            throw ContainerException::createForReason(ContainerError::PeerStoreAppIdInvalid, $e, class: $class, parameter: $parameter->getName());
125        }
126    }
127
128    private function isWritable(ReflectionParameter $parameter): bool
129    {
130        $type = $parameter->getType();
131
132        return $type instanceof ReflectionNamedType && $type->getName() === Store::class;
133    }
134}