Skip to content

Instantly share code, notes, and snippets.

@eteubert
Created February 1, 2013 15:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eteubert/4692154 to your computer and use it in GitHub Desktop.
Save eteubert/4692154 to your computer and use it in GitHub Desktop.
<?php
spl_autoload_register( function ( $class_name ) {
$camelcase_to_snakecase = function ( $string ) {
return preg_replace( '/([a-z])([A-Z])/', '$1_$2', $string );
};
$split = explode( '\\\\', $class_name );
// remove "Inpsyde" namespace
$vendor = array_shift( $split );
if ( ! strlen( $vendor ) )
$vendor = array_shift( $split );
// only load classes prefixed inside "Inpsyde" namespace
if ( $vendor != "Inpsyde" )
return false;
// remove plugin namespace as it is not represented as dir
array_shift( $split );
// class name without namespace
$class_name = array_pop( $split );
// CamelCase to snake_case
$class_name = $camelcase_to_snakecase( $class_name );
// the rest of the namespace, if any
$namespaces = $split;
// library directory
$base_dir = dirname( dirname( __FILE__ ) );
$libs = array(
$base_dir . '/inc/',
$base_dir . '/lib/'
);
$class_file_name = "class-$class_name.php";
// register all possible paths for the class
$possibilities = array();
foreach ( $libs as $lib ) {
if ( count( $namespaces ) >= 1 ) {
$possibilities[] = $lib . strtolower( implode( '/', array_map( $camelcase_to_snakecase, $namespaces ) ) . '/' . $class_file_name );
} else {
$possibilities[] = $lib . strtolower( $class_file_name );
}
}
// search for the class
foreach ( $possibilities as $file ) {
if ( file_exists( $file ) ) {
require_once( $file );
return true;
}
}
return false;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment