<?php

declare(strict_types=1);

namespace PpPhp\Core\Platform\Services\Registry;

use PpPhp\Core\Platform\Services\Contracts\RegistryInterface;
use PpPhp\Core\Platform\Services\Definition\ServiceDefinition;

final class ServiceRegistry implements RegistryInterface
{
    /** @var array<string, ServiceDefinition> */
    private array $definitions = [];

    public function register(ServiceDefinition $definition): void
    {
        $this->definitions[$definition->metadata()->id()] = $definition;
    }

    public function has(string $id): bool
    {
        return isset($this->definitions[$id]);
    }

    public function get(string $id): ?ServiceDefinition
    {
        return $this->definitions[$id] ?? null;
    }

    /** @return ServiceDefinition[] */
    public function all(): array
    {
        return array_values($this->definitions);
    }

    public function toArray(): array
    {
        return array_map(static fn (ServiceDefinition $definition): array => $definition->toArray(), $this->all());
    }
}
