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