Newer
Older
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
<?php
/**
* Autoloader class.
*
* @since 0.1
*/
namespace CiviCRM_WP_REST;
class Autoloader {
/**
* Instance.
*
* @since 0.1
* @var string
*/
private static $instance = null;
/**
* Namespace.
*
* @since 0.1
* @var string
*/
private $namespace = 'CiviCRM_WP_REST';
/**
* Autoloader directory sources.
*
* @since 0.1
* @var array
*/
private static $source_directories = [];
/**
* Constructor.
*
* @since 0.1
*/
private function __construct() {
$this->register_autoloader();
}
/**
* Creates an instance of this class.
*
* @since 0.1
*/
private static function instance() {
if ( ! self::$instance ) self::$instance = new self;
}
/**
* Adds a directory source.
*
* @since 0.1
* @param string $source The source path
*/
public static function add_source( string $source_path ) {
// make sure we have an instance
self::instance();
if ( ! is_readable( trailingslashit( $source_path ) ) )
return \WP_Error( 'civicrm_wp_rest_error', sprintf( __( 'The source %s is not readable.', 'civicrm' ), $source ) );
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
107
108
109
110
111
112
113
114
115
self::$source_directories[] = $source_path;
}
/**
* Registers the autoloader.
*
* @since 0.1
* @return bool Wehather the autoloader has been registered or not
*/
private function register_autoloader() {
return spl_autoload_register( [ $this, 'autoload' ] );
}
/**
* Loads the classes.
*
* @since 0.1
* @param string $class_name The class name to load
*/
private function autoload( $class_name ) {
if ( false === strpos( $class_name, $this->namespace ) ) return;
$parts = explode( '\\', $class_name );
// remove namespace and join class path
$class_path = str_replace( '_', '-', implode( DIRECTORY_SEPARATOR, array_slice( $parts, 1 ) ) );
array_map( function( $source_path ) use ( $class_path ) {
$path = $source_path . $class_path . '.php';
if ( ! file_exists( $path ) ) return;
require $path;
}, static::$source_directories );
}
}