<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD;

defined('ABSPATH') || exit;

class Container
{
    protected array $entries = [];
    protected array $instances = [];

    public function set(string $id, mixed $concrete) : void
    {
        $this->entries[$id] = $concrete;
    }

    public function has(string $id) : bool
    {
        return array_key_exists($id, $this->entries) || array_key_exists($id, $this->instances);
    }

    public function get(string $id) : mixed
    {
        if (array_key_exists($id, $this->instances)) {
            return $this->instances[$id];
        }

        if (! array_key_exists($id, $this->entries)) {
            throw new \RuntimeException(esc_html(sprintf('Container entry not found: %s', sanitize_key($id))));
        }

        $entry = $this->entries[$id];
        $resolved = is_callable($entry) ? $entry($this) : $entry;
        $this->instances[$id] = $resolved;

        return $resolved;
    }
}
