<?php

declare(strict_types=1);

namespace System\Autoload;

final class Autoloader
{
    /**
     * Registered namespaces.
     *
     * @var array<string, string>
     */
    private array $namespaces = [];

    /**
     * Register autoloader.
     */
    public function register(): void
    {
        spl_autoload_register([$this, 'load']);
    }

    /**
     * Add namespace.
     */
    public function addNamespace(string $prefix, string $baseDirectory): void
    {
        $this->namespaces[$prefix] = rtrim($baseDirectory, DIRECTORY_SEPARATOR);
    }

    /**
     * Load class.
     */
    private function load(string $class): void
    {
        foreach ($this->namespaces as $prefix => $directory) {

            if (!str_starts_with($class, $prefix)) {
                continue;
            }

            $relative = substr($class, strlen($prefix));

            $file = $directory
                . DIRECTORY_SEPARATOR
                . str_replace('\\', DIRECTORY_SEPARATOR, $relative)
                . '.php';

            if (is_file($file)) {
                require_once $file;
            }
        }
    }
}