<?php

namespace Formatrica\Setup;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Minimalistic service locator for dependency sharing.
 */
final class Service_Locator
{
    /**
     * @var array<string, object>
     */
    private array $services = [];

    /**
     * Store a service instance for later reuse.
     */
    public function set(string $id, object $service): void
    {
        $this->services[$id] = $service;
    }

    /**
     * Retrieve a shared service instance.
     *
     * @throws \RuntimeException if service not found.
     */
    public function get(string $id): object
    {
        if (!isset($this->services[$id])) {
            throw new \RuntimeException(sprintf('Service "%s" not found.', sanitize_text_field($id))); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
        }

        return $this->services[$id];
    }

    /**
     * Determine if a service is registered.
     */
    public function has(string $id): bool
    {
        return isset($this->services[$id]);
    }
}
