<?php

declare(strict_types=1);

namespace PpPhp\Core\Platform\Foundation;

final class PlatformCollection
{
    /** @var array<string, PlatformObject> */
    private array $items = [];

    public function add(PlatformObject $object): void
    {
        $this->items[$object->type() . ':' . $object->id()] = $object;
    }

    public function has(string $type, string $id): bool
    {
        return isset($this->items[$type . ':' . $id]);
    }

    public function get(string $type, string $id): ?PlatformObject
    {
        return $this->items[$type . ':' . $id] ?? null;
    }

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

    /** @return PlatformObject[] */
    public function byType(string $type): array
    {
        return array_values(array_filter(
            $this->items,
            static fn (PlatformObject $object): bool => $object->type() === $type
        ));
    }

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