> */ private array $decorators = []; /** @var array */ private array $extended = []; public function __construct( private readonly Application $app, private readonly ExtensionRepository $extensions, ) {} /** * @template TContract of object * * @param class-string $contract * @param Closure(TContract): TContract $decorator */ public function register(string $identifier, string $contract, Closure $decorator, ExtensionRegistration $registration): void { throw_unless( str_starts_with($contract, self::CONTRACT_NAMESPACE) && interface_exists($contract) && $this->app->bound($contract) && ! $this->app->isShared($contract), InvalidArgumentException::class, sprintf('Extension "%s" can only wrap action contracts under %s that the panel binds per caller; "%s" is not one.', $identifier, self::CONTRACT_NAMESPACE, $contract), ); throw_if( array_any(self::PROTECTED_NAMESPACES, fn (string $namespace): bool => str_starts_with(mb_strtolower($contract), mb_strtolower($namespace))), InvalidArgumentException::class, sprintf('Extension "%s" cannot wrap "%s": the actions that manage extensions and themes are never wrapped.', $identifier, $contract), ); $this->decorators[$contract][] = ['identifier' => $identifier, 'decorator' => $decorator, 'registration' => $registration]; if (isset($this->extended[$contract])) { return; } // Container extenders cannot be removed, so exactly one is installed per contract // and it consults this registry: rolling a registration back only edits the list. $this->extended[$contract] = true; $this->app->extend($contract, (new ExtensionActionExtender($this, $contract))(...)); } /** @return array> */ public function snapshot(): array { return $this->decorators; } /** @param array> $decorators */ public function restore(array $decorators): void { $this->decorators = $decorators; } /** * Apply every decorator that is currently active to a freshly resolved action. * * @template TContract of object * * @param class-string $contract * @param TContract $action * @return TContract */ public function decorate(string $contract, object $action): object { foreach ($this->decorators[$contract] ?? [] as $entry) { if (! $entry['registration']->isActive() || ! $this->extensions->isAvailable($entry['identifier'])) { continue; } try { $decorated = $entry['decorator']($action); throw_unless($decorated instanceof $contract, UnexpectedValueException::class, sprintf('The decorator for %s must return an implementation of that contract.', $contract)); $action = $decorated; } catch (Throwable $throwable) { $this->extensions->recordFailure($entry['identifier'], $throwable->getMessage(), $throwable, 'action'); } } return $action; } }