Skip to content

Commit 7f7d96d

Browse files
author
Felix Arntz
committed
Implement simple autoloader as Composer alternative and improve detection of whether autoloader needs to be loaded.
1 parent 1d1f406 commit 7f7d96d

1 file changed

Lines changed: 39 additions & 2 deletions

File tree

block-areas.php

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ function block_areas() {
3737
* Loads the plugin.
3838
*
3939
* @since 0.1.0
40+
* @access private
4041
*/
4142
function block_areas_load() {
4243
if ( version_compare( phpversion(), '7.0', '<' ) ) {
@@ -49,17 +50,52 @@ function block_areas_load() {
4950
return;
5051
}
5152

52-
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
53-
require __DIR__ . '/vendor/autoload.php';
53+
// Load Composer autoloader or custom autoloader.
54+
if ( ! class_exists( 'WP_Rig\\Block_Areas\\Plugin' ) ) {
55+
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
56+
require __DIR__ . '/vendor/autoload.php';
57+
} else {
58+
spl_autoload_register( 'block_areas_autoload' );
59+
}
5460
}
5561

5662
call_user_func( [ 'WP_Rig\\Block_Areas\\Plugin', 'load' ], __FILE__ );
5763
}
5864

65+
/**
66+
* Custom autoloader function for plugin classes.
67+
*
68+
* Simplified autoloader that respects PSR-4 specific to the plugin.
69+
*
70+
* @since 1.0.0
71+
* @access private
72+
*
73+
* @param string $class_name Class name to load.
74+
* @return bool True if the class was loaded, false otherwise.
75+
*/
76+
function block_areas_autoload( $class_name ) {
77+
$namespace = 'WP_Rig\Block_Areas';
78+
if ( strpos( $class_name, $namespace . '\\' ) !== 0 ) {
79+
return false;
80+
}
81+
$parts = explode( '\\', substr( $class_name, strlen( $namespace . '\\' ) ) );
82+
$path = plugin_dir_path( __FILE__ ) . 'src';
83+
foreach ( $parts as $part ) {
84+
$path .= '/' . $part;
85+
}
86+
$path .= '.php';
87+
if ( ! file_exists( $path ) ) {
88+
return false;
89+
}
90+
require_once $path;
91+
return true;
92+
}
93+
5994
/**
6095
* Displays an admin notice about an unmet PHP version requirement.
6196
*
6297
* @since 0.1.0
98+
* @access private
6399
*/
64100
function block_areas_display_php_version_notice() {
65101
?>
@@ -82,6 +118,7 @@ function block_areas_display_php_version_notice() {
82118
* Displays an admin notice about an unmet WordPress version requirement.
83119
*
84120
* @since 0.1.0
121+
* @access private
85122
*/
86123
function block_areas_display_wp_version_notice() {
87124
?>

0 commit comments

Comments
 (0)