Passed
Push — master ( 928391...3be021 )
by Mike
04:22
created

Autoloader   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 57
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 3 1
A autoload_class() 0 16 3
A autoload_from_classmap() 0 7 3
1
<?php
2
/**
3
 * Custom Autoloader used when included inside another project as a package.
4
 *
5
 * Since this package can be included multiple times, but we want to ensure the latest version
6
 * is loaded (rather than the first package found), we need a custom autoloader.
7
 *
8
 * This autoloader is only loaded for the chosen (latest) package.
9
 *
10
 * For version 4 onwards, we use psr-4 class naming.
11
 * For version 3 and below, we use a classmap to maintain class naming/backwards compatibility.
12
 *
13
 * @package WooCommerce/RestApi
14
 */
15
16
namespace WooCommerce\RestApi;
17
18
defined( 'ABSPATH' ) || exit;
19
20
/**
21
 * Autoloader class.
22
 */
23
class Autoloader {
24
25
	/**
26
	 * Holds the classmap.
27
	 *
28
	 * @var array
29
	 */
30
	protected static $classmap = [];
31
32
	/**
33
	 * Register the autoloader.
34
	 *
35
	 * @param array $classmap Classmap of files to include.
36
	 */
37
	public static function register( $classmap ) {
38
		self::$classmap = (array) $classmap;
39
		spl_autoload_register( array( __CLASS__, 'autoload_class' ) );
40
	}
41
42
	/**
43
	 * Try to autoload a class.
44
	 *
45
	 * @param string $class Class being autoloaded.
46
	 * @return boolean
47
	 */
48
	public static function autoload_class( $class ) {
49
		$prefix   = 'WooCommerce\\RestApi\\';
50
		$base_dir = __DIR__ . '/';
51
52
		// does the class use the namespace prefix?
53
		$len = strlen( $prefix );
54
55
		if ( strncmp( $prefix, $class, $len ) !== 0 ) {
56
			return self::autoload_from_classmap( $class );
57
		}
58
59
		$relative_class = substr( $class, $len );
60
		$file           = $base_dir . str_replace( '\\', '/', $relative_class ) . '.php';
61
62
		if ( file_exists( $file ) ) {
63
			return include $file;
64
		}
65
	}
66
67
	/**
68
	 * Try to autoload a class from a classmap.
69
	 *
70
	 * @param string $class Class being autoloaded.
71
	 * @return boolean
72
	 */
73
	protected static function autoload_from_classmap( $class ) {
74
		if ( empty( self::$classmap ) ) {
75
			return false;
76
		}
77
78
		if ( array_key_exists( $class, self::$classmap ) ) {
79
			return include self::$classmap[ $class ];
80
		}
81
	}
82
}
83