| 1 |
<?php |
| 2 |
/** |
| 3 |
* The file responsible for autoloading our classes and interfaces. |
| 4 |
* |
| 5 |
* @package ForceRefresh |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace JordanLeven\Plugins\ForceRefresh; |
| 9 |
|
| 10 |
/** |
| 11 |
* Function to handle the autoloading of our classes and interfaces. |
| 12 |
* |
| 13 |
* @param string $class_name The class attempting to load. |
| 14 |
* |
| 15 |
* @return void |
| 16 |
* @throws \Exception If the file isn't found. |
| 17 |
*/ |
| 18 |
function autoload_classes_and_interfaces( string $class_name ) { |
| 19 |
|
| 20 |
// If the autoloaded class is not of our namespace, do an early exit. |
| 21 |
if ( strpos( $class_name, __NAMESPACE__ ) === false ) { |
| 22 |
return; |
| 23 |
} |
| 24 |
|
| 25 |
// Format the string based on our agreed-upon file structure. |
| 26 |
$file_path = str_replace( |
| 27 |
array( __NAMESPACE__, '\\', '_' ), |
| 28 |
array( '', '/', '-' ), |
| 29 |
$class_name |
| 30 |
); |
| 31 |
|
| 32 |
$file_path_absolute = strtolower( sprintf( '%s%s.php', __DIR__, $file_path ) ); |
| 33 |
$file_name = basename( $file_path_absolute ); |
| 34 |
$file_name_adjusted = $file_name; |
| 35 |
|
| 36 |
// If the file is an interface, then we need to adjust the naming convention. |
| 37 |
if ( strpos( $file_name, 'interface' ) ) { |
| 38 |
$file_name_adjusted = 'interface-' . str_replace( '-interface', '', $file_name ); |
| 39 |
} else { |
| 40 |
$file_name_adjusted = 'classes/class-' . $file_name; |
| 41 |
} |
| 42 |
|
| 43 |
$file_path_absolute_adjusted = str_replace( $file_name, $file_name_adjusted, $file_path_absolute ); |
| 44 |
|
| 45 |
if ( ! file_exists( $file_path_absolute_adjusted ) ) { |
| 46 |
throw new \Exception( sprintf( 'Unable to locate file %s', esc_html( $file_path_absolute_adjusted ) ) ); |
| 47 |
} |
| 48 |
|
| 49 |
require_once $file_path_absolute_adjusted; |
| 50 |
} |
| 51 |
|
| 52 |
spl_autoload_register( __NAMESPACE__ . '\\autoload_classes_and_interfaces' ); |
| 53 |
|