class-premium-autoloader.php
2.28 KB
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
107
<?php
/**
* @package WPSEO\Premium\Classes
*/
/**
* Class WPSEO_Premium_Autoloader
*/
class WPSEO_Premium_Autoloader {
/**
* The part of the class we wanted to search
*
* @var string
*/
private $search_pattern;
/**
* @var string
*/
private $directory;
/**
* This piece will be added
*
* @var string
*/
private $file_replace;
/**
* Setting up the class.
*
* @param string $search_pattern The pattern to match for the redirect.
* @param string $directory The directory where the classes could be found.
* @param string $file_replace The replacement for the file.
*/
public function __construct( $search_pattern, $directory, $file_replace = '' ) {
$this->search_pattern = $search_pattern;
$this->directory = $directory;
$this->file_replace = ( $file_replace === '' ) ? $search_pattern : $file_replace;
spl_autoload_register( array( $this, 'load' ) );
}
/**
* Autoloader load method. Load the class.
*
* @param string $class The requested class name.
*/
public function load( $class ) {
// Check & load file.
if ( $this->contains_search_pattern( $class ) && $found_file = $this->find_file( $class ) ) {
require_once( $found_file );
}
}
/**
* Does the filename contains the search pattern
*
* @param string $class The classname to match.
*
* @return bool
*/
private function contains_search_pattern( $class ) {
return 0 === strpos( $class, $this->search_pattern );
}
/**
* Searching for the file in the given directory
*
* @param string $class The class to search for.
*
* @return bool|string
*/
private function find_file( $class ) {
// String to lower.
$class = strtolower( $class );
// Format file name.
$file_name = $this->get_file_name( $class );
// Full file path.
$class_path = dirname( __FILE__ ) . '/';
// Append file name to clas path.
$full_path = $class_path . $this->directory . $file_name;
// Check & load file.
if ( file_exists( $full_path ) ) {
return $full_path;
}
return false;
}
/**
* Parsing the file name
*
* @param string $class The classname to convert to a file name.
*
* @return string
*/
private function get_file_name( $class ) {
return 'class-' . str_ireplace( '_', '-', str_ireplace( $this->file_replace, '', $class ) ) . '.php';
}
}