<?php

namespace Formatrica;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Lightweight PSR-4 autoloader.
 */
final class Autoloader
{
    /**
     * Base namespace prefix.
     */
    private const PREFIX = __NAMESPACE__ . '\\';

    /**
     * Base directory for class files.
     */
    private const BASE_DIR = __DIR__ . '/';

    public static function register(): void
    {
        spl_autoload_register([self::class, 'autoload']);
    }

    /**
     * Attempt to autoload the provided class.
     */
    private static function autoload(string $class): void
    {
        if (strpos($class, self::PREFIX) !== 0) {
            return;
        }

        $relative = substr($class, strlen(self::PREFIX));
        $relative = str_replace('\\', DIRECTORY_SEPARATOR, $relative);
        $file = self::BASE_DIR . $relative . '.php';

        if (file_exists($file)) {
            /** @psalm-suppress UnresolvableInclude */
            require $file;
        }
    }
}
