<?php

namespace ProudNerds;

/**
 * Main bootstrap file. This file is the entrypoint to the functional classes included in the project. The file reads
 * the classes of the files that are located next to this bootstrap file and autoloads them using the PSR-0 standard.
 *
 * @author Bas de Kort <bas.dekort@proudnerds.com>
 */
class Bootstrap {
    private static bool $registered = false;

    /**
     * Initialise this class.
     */
    public static function init() {
        new Bootstrap();
    }

    /**
     * Bootstrap constructor.
     */
    private function __construct() {
        // Check whether this autoloader is already called
        if(!self::$registered) {
            spl_autoload_register("\ProudNerds\Bootstrap::autoload");
            self::$registered = true;
        }
    }

    /**
     * Create autoloader which conforms to the PSR-0 autoloading standard.
     */
    private static function autoload($className): bool {
        // Get file path
        $fileName = $namespace = '';
        if (false !== ($lastNsPos = strripos($className, '\\'))) {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }
        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
        $locatedFile = dirname(__DIR__) . '/' . $fileName;
        $locatedFile = str_replace('ProudNerds', 'includes', $locatedFile);

        // Include the file
        if (is_file($locatedFile)) {
            require_once $locatedFile;
            return true;
        }

        return false;
    }
}