| 1 |
<?php |
| 2 |
/** |
| 3 |
* Autoloader for Nodeinfo. |
| 4 |
* |
| 5 |
* @package Nodeinfo |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Nodeinfo; |
| 9 |
|
| 10 |
/** |
| 11 |
* An Autoloader that respects WordPress filename standards. |
| 12 |
*/ |
| 13 |
class Autoloader { |
| 14 |
|
| 15 |
/** |
| 16 |
* Namespace separator. |
| 17 |
*/ |
| 18 |
const NS_SEPARATOR = '\\'; |
| 19 |
|
| 20 |
/** |
| 21 |
* The prefix to compare classes against. |
| 22 |
* |
| 23 |
* @var string |
| 24 |
*/ |
| 25 |
protected $prefix; |
| 26 |
|
| 27 |
/** |
| 28 |
* Length of the prefix string. |
| 29 |
* |
| 30 |
* @var int |
| 31 |
*/ |
| 32 |
protected $prefix_length; |
| 33 |
|
| 34 |
/** |
| 35 |
* Path to the files to be loaded. |
| 36 |
* |
| 37 |
* @var string |
| 38 |
*/ |
| 39 |
protected $path; |
| 40 |
|
| 41 |
/** |
| 42 |
* Constructor. |
| 43 |
* |
| 44 |
* @param string $prefix Namespace prefix all classes have in common. |
| 45 |
* @param string $path Path to the files to be loaded. |
| 46 |
*/ |
| 47 |
public function __construct( $prefix, $path ) { |
| 48 |
$this->prefix = $prefix; |
| 49 |
$this->prefix_length = \strlen( $prefix ); |
| 50 |
$this->path = \trailingslashit( $path ); |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Registers the autoloader. |
| 55 |
* |
| 56 |
* @param string $prefix Namespace prefix all classes have in common. |
| 57 |
* @param string $path Path to the files to be loaded. |
| 58 |
*/ |
| 59 |
public static function register_path( $prefix, $path ) { |
| 60 |
$loader = new self( $prefix, $path ); |
| 61 |
\spl_autoload_register( array( $loader, 'load' ) ); |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Loads a class if its namespace starts with `$this->prefix`. |
| 66 |
* |
| 67 |
* @param string $class_name The class to be loaded. |
| 68 |
*/ |
| 69 |
public function load( $class_name ) { |
| 70 |
if ( \strpos( $class_name, $this->prefix . self::NS_SEPARATOR ) !== 0 ) { |
| 71 |
return; |
| 72 |
} |
| 73 |
|
| 74 |
// Strip prefix from the start (PSR-4 style). |
| 75 |
$class_name = \substr( $class_name, $this->prefix_length + 1 ); |
| 76 |
$class_name = \strtolower( $class_name ); |
| 77 |
$dir = ''; |
| 78 |
|
| 79 |
$last_ns_pos = \strripos( $class_name, self::NS_SEPARATOR ); |
| 80 |
if ( false !== $last_ns_pos ) { |
| 81 |
$namespace = \substr( $class_name, 0, $last_ns_pos ); |
| 82 |
$namespace = \str_replace( '_', '-', $namespace ); |
| 83 |
$class_name = \substr( $class_name, $last_ns_pos + 1 ); |
| 84 |
$dir = \str_replace( self::NS_SEPARATOR, DIRECTORY_SEPARATOR, $namespace ) . DIRECTORY_SEPARATOR; |
| 85 |
} |
| 86 |
|
| 87 |
$class_name = \str_replace( '_', '-', $class_name ); |
| 88 |
$path = $this->path . $dir . 'class-' . $class_name . '.php'; |
| 89 |
|
| 90 |
if ( \file_exists( $path ) ) { |
| 91 |
require_once $path; |
| 92 |
} |
| 93 |
} |
| 94 |
} |
| 95 |
|