<?php

/**
 * PSR-4 Autoloader Fallback
 *
 * @package _121Digital\Connect
 */

namespace _121Digital\Connect\Core;

/**
 * Autoloader Class
 *
 * Provides PSR-4 autoloading when Composer is not available
 */
class Autoloader
{
    /**
     * Namespace prefix
     *
     * @var string
     */
    private string $prefix = '_121Digital\\Connect\\';

    /**
     * Base directory for the namespace prefix
     *
     * @var string
     */
    private string $baseDir;

    /**
     * Constructor
     *
     * @param string|null $baseDir
     */
    public function __construct(?string $baseDir = null)
    {
        $this->baseDir = $baseDir ?? dirname(__DIR__) . '/';
    }

    /**
     * Register the autoloader
     *
     * @return void
     */
    public function register(): void
    {
        spl_autoload_register([$this, 'loadClass']);
    }

    /**
     * Load a class file
     *
     * @param string $class The fully-qualified class name
     * @return void
     */
    public function loadClass(string $class): void
    {
        // Does the class use the namespace prefix?
        $len = strlen($this->prefix);
        if (strncmp($this->prefix, $class, $len) !== 0) {
            return;
        }

        // Get the relative class name
        $relativeClass = substr($class, $len);

        // Replace namespace separators with directory separators
        // and append with .php
        $file = $this->baseDir . str_replace('\\', '/', $relativeClass) . '.php';

        // If the file exists, require it
        if (file_exists($file)) {
            require_once $file;
        }
    }

    /**
     * Unregister the autoloader
     *
     * @return void
     */
    public function unregister(): void
    {
        spl_autoload_unregister([$this, 'loadClass']);
    }
}
