| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Autoloader class |
| 5 |
* |
| 6 |
* The Autoloader class is responsible for loading classes automatically based on their namespace. |
| 7 |
* |
| 8 |
* @package WowPlugin |
| 9 |
* @subpackage Autoloader |
| 10 |
* @author Dmytro Lobov <dev@wow-company.com>, Wow-Company |
| 11 |
* @copyright 2024 Dmytro Lobov |
| 12 |
* @license GPL-2.0+ |
| 13 |
*/ |
| 14 |
|
| 15 |
namespace FloatMenuLite; |
| 16 |
|
| 17 |
// Exit if accessed directly. |
| 18 |
defined( 'ABSPATH' ) || exit; |
| 19 |
|
| 20 |
class Autoloader { |
| 21 |
/** |
| 22 |
* @var mixed |
| 23 |
*/ |
| 24 |
private $namespace; |
| 25 |
private $directory; |
| 26 |
|
| 27 |
public function __construct( $namespace ) { |
| 28 |
$this->namespace = $namespace; |
| 29 |
$this->directory = __DIR__; |
| 30 |
spl_autoload_register( [ $this, 'autoload' ] ); |
| 31 |
} |
| 32 |
|
| 33 |
public function autoload( $class ): void { |
| 34 |
if ( strpos( $class, $this->namespace ) === 0 ) { |
| 35 |
$file = $this->get_file_path( $class ); |
| 36 |
|
| 37 |
if ( $file && file_exists( $file ) ) { |
| 38 |
require_once( $file ); |
| 39 |
|
| 40 |
return; |
| 41 |
} |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Get the file path for a class. |
| 47 |
* |
| 48 |
* @param string $class The fully qualified name of the class. |
| 49 |
* |
| 50 |
* @return string|null The file path, or null if the file could not be found. |
| 51 |
*/ |
| 52 |
public function get_file_path( string $class ): ?string { |
| 53 |
|
| 54 |
$relativeClass = substr( $class, strlen( $this->namespace ) ); |
| 55 |
|
| 56 |
$file = str_replace( '\\', DIRECTORY_SEPARATOR, $relativeClass ) . '.php'; |
| 57 |
|
| 58 |
$full_path = $this->directory . DIRECTORY_SEPARATOR . $file; |
| 59 |
|
| 60 |
if ( file_exists( $full_path ) ) { |
| 61 |
return $full_path; |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
return null; |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
} |