CaiWuXiTong/modules/EcommerceFinance/Services/UpstreamSnapshotRefresherRegistry.php

42 lines
1.1 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Closure;
use InvalidArgumentException;
use Modules\EcommerceFinance\Contracts\UpstreamSnapshotRefresher;
use RuntimeException;
class UpstreamSnapshotRefresherRegistry
{
/** @var array<string,Closure():UpstreamSnapshotRefresher> */
private array $resolvers = [];
public function __construct(private readonly UpstreamSourceRegistry $sources)
{
}
public function register(string $source, Closure $resolver): void
{
$key = $this->sources->definition($source)['key'];
$this->resolvers[$key] = $resolver;
}
public function forSource(string $source): UpstreamSnapshotRefresher
{
$key = $this->sources->definition($source)['key'];
if (! isset($this->resolvers[$key])) {
throw new InvalidArgumentException('该上游尚未登记快照刷新器:' . $key);
}
$refresher = ($this->resolvers[$key])();
if ($refresher->sourceKey() !== $key) {
throw new RuntimeException('上游快照刷新器与数据源不匹配:' . $key);
}
return $refresher;
}
}