|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Zenstruck\Foundry\InMemory; |
| 6 | + |
| 7 | +use Symfony\Component\DependencyInjection\ServiceLocator; |
| 8 | +use Zenstruck\Foundry\Configuration; |
| 9 | +use Zenstruck\Foundry\Factory; |
| 10 | +use Zenstruck\Foundry\FactoryRegistryInterface; |
| 11 | +use Zenstruck\Foundry\Persistence\PersistentObjectFactory; |
| 12 | + |
| 13 | +/** |
| 14 | + * @internal |
| 15 | + */ |
| 16 | +final class InMemoryFactoryRegistry implements FactoryRegistryInterface |
| 17 | +{ |
| 18 | + public function __construct( // @phpstan-ignore-line |
| 19 | + private readonly FactoryRegistryInterface $decorated, |
| 20 | + /** @var ServiceLocator<InMemoryRepository> */ |
| 21 | + private readonly ServiceLocator $inMemoryRepositories, |
| 22 | + ) { |
| 23 | + } |
| 24 | + |
| 25 | + public function get(string $class): Factory |
| 26 | + { |
| 27 | + $factory = $this->decorated->get($class); |
| 28 | + |
| 29 | + if (!is_a($class, PersistentObjectFactory::class, allow_string: true)) { |
| 30 | + return $factory; |
| 31 | + } |
| 32 | + |
| 33 | + $configuration = Configuration::instance(); |
| 34 | + |
| 35 | + if ( |
| 36 | + !$factory instanceof PersistentObjectFactory |
| 37 | + || !$configuration->isPersistenceAvailable() |
| 38 | + || !$configuration->persistence()->isInMemoryEnabled() |
| 39 | + ) { |
| 40 | + return $factory; |
| 41 | + } |
| 42 | + |
| 43 | + $factory = $factory->withoutPersisting(); |
| 44 | + |
| 45 | + if ($inMemoryRepository = $this->findInMemoryRepository($class)) { |
| 46 | + $factory = $factory->afterInstantiate( |
| 47 | + static fn(object $object) => $inMemoryRepository->_save($object) |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + return $factory->withoutPersisting(); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @template T of object |
| 56 | + * |
| 57 | + * @param class-string<PersistentObjectFactory<T>> $class |
| 58 | + * |
| 59 | + * @return InMemoryRepository<T>|null |
| 60 | + */ |
| 61 | + private function findInMemoryRepository(string $class): InMemoryRepository|null |
| 62 | + { |
| 63 | + $targetClass = $class::class(); |
| 64 | + if (!$this->inMemoryRepositories->has($targetClass)) { |
| 65 | + // todo: should this behavior be opt-in from bundle's configuration? |
| 66 | + // ie: throwing here would warn if a class does not have a "in memory" repository |
| 67 | + return null; |
| 68 | + } |
| 69 | + |
| 70 | + return $this->inMemoryRepositories->get($targetClass); |
| 71 | + } |
| 72 | +} |
0 commit comments