<?php

namespace App\Framework\DI;

/**
 * Verwaltet alle instanziierten Objekte und Singletons
 */
final class InstanceRegistry
{
    private array $singletons = [];
    private array $instances = [];

    public function getSingleton(string $class): ?object
    {
        return $this->singletons[$class] ?? null;
    }

    public function hasSingleton(string $class): bool
    {
        return isset($this->singletons[$class]) && $this->singletons[$class] !== null;
    }

    public function setSingleton(string $class, object $instance): void
    {
        $this->singletons[$class] = $instance;
    }

    public function markAsSingleton(string $class): void
    {
        $this->singletons[$class] = null;
    }

    public function getInstance(string $class): ?object
    {
        return $this->instances[$class] ?? null;
    }

    public function hasInstance(string $class): bool
    {
        return isset($this->instances[$class]);
    }

    public function setInstance(string $class, object $instance): void
    {
        $this->instances[$class] = $instance;
    }

    public function forget(string $class): void
    {
        unset($this->instances[$class], $this->singletons[$class]);
    }

    public function flush(): void
    {
        $this->instances = [];
        $this->singletons = [];
    }

    public function getAllRegistered(): array
    {
        return array_merge(
            array_keys($this->singletons),
            array_keys($this->instances)
        );
    }
}
