phpOMS/Autoloader.php
2018-03-29 13:37:56 +02:00

102 lines
2.2 KiB
PHP

<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS;
spl_autoload_register('\phpOMS\Autoloader::defaultAutoloader');
/**
* Autoloader class.
*
* @package phpOMS
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class Autoloader
{
/**
* Base paths for autoloading
*
* @var string[]
* @since 1.0.0
*/
private static $paths = [
__DIR__ . '/../',
__DIR__ . '/../../',
__DIR__ . '/../vendor/',
__DIR__ . '/../../vendor/',
];
/**
* Add base path for autoloading
*
* @param string $path Absolute base path with / at the end
*
* @return void
*
* @since 1.0.0
*/
public static function addPath(string $path) : void
{
self::$paths[] = $path;
}
/**
* Loading classes by namespace + class name.
*
* @param string $class Class path
*
* @example Autoloader::defaultAutoloader('\phpOMS\Autoloader') // void
*
* @return void
*
* @throws AutoloadException Throws this exception if the class to autoload doesn't exist. This could also be related to a wrong namespace/file path correlation.
*
* @since 1.0.0
*/
public static function defaultAutoloader(string $class) : void
{
$class = ltrim($class, '\\');
$class = str_replace(['_', '\\'], '/', $class);
foreach (self::$paths as $path) {
if (file_exists($file = $path . $class . '.php')) {
include_once $file;
return;
}
}
}
/**
* Check if class exists.
*
* @param string $class Class path
*
* @example Autoloader::exists('\phpOMS\Autoloader') // true
*
* @return bool
*
* @since 1.0.0
*/
public static function exists(string $class) : bool
{
$class = ltrim($class, '\\');
$class = str_replace(['_', '\\'], '/', $class);
return file_exists(__DIR__ . '/../' . $class . '.php');
}
}