Skip to content

Instantly share code, notes, and snippets.

@holisticnetworking
Created January 13, 2018 02:34
Show Gist options
  • Save holisticnetworking/35db0c130775c2bbbc634b2985c93ab2 to your computer and use it in GitHub Desktop.
Save holisticnetworking/35db0c130775c2bbbc634b2985c93ab2 to your computer and use it in GitHub Desktop.
Autoloading for both WordPress classes and PSR2 files in a /vendor directory.
<?php
/**
* PSR4 autoloader using spl_autoload_register
* @package HN_Reactive
* @author Thomas J Belknap <tbelknap@holisticnetworking.net>
*/
namespace HN_Reactive;
spl_autoload_register( function ( $class ) {
$wordpress = wordpress_include( $class );
$psr2 = composer_include( $class );
if ( file_exists( plugin_dir_path( __FILE__ ) . $wordpress . '.php' ) ) :
require_once( plugin_dir_path( __FILE__ ) . $wordpress . '.php' );
else :
require_once( plugin_dir_path( __FILE__ ) . '/vendor/autoload.php' );
endif;
} );
/**
* Format the incoming class name to the WordPress file naming standard.
* @param $class
* @return string
*/
function wordpress_include( $class ) {
$parts = explode( '\\', $class );
// Remove HN_Reactive index:
unset( $parts[0] );
if ( ! empty( $parts ) ) :
$parts[ count( $parts ) ] = 'class-' . wp_class_to_file( $parts[ count( $parts ) ] );
$class_path = implode( '/', $parts );
return $class_path;
else :
return false;
endif;
}
/**
* Format the incoming class name to the PSR2 file name standard.
* @param $class
* @return mixed
*/
function composer_include( $class ) {
$class_path = preg_replace( '/\\\\/', '/', $class );
return $class_path;
}
/**
* Translates a WordPress-valid class name to a WordPress-valid file name (e.g. Class_Name - class-name)
* @param string $str String in camel case format
* @return string $str Translated into dashed format
*/
function wp_class_to_file( $str ) {
return implode(
'-',
explode(
'_',
preg_replace_callback(
'/[A-Z]*?/',
function( $matches ) {
return strtolower( $matches[0] );
},
$str
)
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment