mihdan
1/17/2020 - 7:35 AM

Fix performance problem with woodmart autoload.

Fix performance problem with woodmart autoload.

<?php
if( ! function_exists( 'woodmart_autoload' ) ) {
	function woodmart_autoload($className) {
		global $woodmart_files;

		$className = ltrim($className, '\\');
		$fileName  = '';
		$namespace = '';
		if ($lastNsPos = strripos($className, '\\')) {
			$namespace = substr($className, 0, $lastNsPos);
			$className = substr($className, $lastNsPos + 1);
			$fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
		}
		$className = str_replace('WOODMART_', '', $className);
		$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
		$fileName = get_template_directory() . '/inc/classes' . DIRECTORY_SEPARATOR . $fileName;
		$fileName = str_replace( '\\', '/', $fileName );

		if ( ! in_array( $fileName, $woodmart_files, true ) ) {
			return;
		}

		if( file_exists( $fileName )) {
			require $fileName;
		}
	}

	global $woodmart_files;

	$woodmart_files = glob( get_template_directory() . '/inc/classes/*.php' );
	$woodmart_files = array_map(
			function( $file ) {
				return str_replace( '\\', '/', $file );
			},
		$woodmart_files
	);

	spl_autoload_register('woodmart_autoload');
}