Completed
Branch master (136588)
by
unknown
02:26
created

ALNP_Autoloader   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 75
rs 10
c 0
b 0
f 0
wmc 11
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A get_file_name_from_class() 0 3 1
A load_file() 0 7 3
A autoload() 0 18 5
1
<?php
2
/**
3
 * Auto Load Next Post - Autoloader.
4
 *
5
 * @since    1.5.0
6
 * @author   Sébastien Dumont
7
 * @category Classes
8
 * @package  Auto Load Next Post/Classes/AutoLoader
9
 * @license  GPL-2.0+
10
 *
11
 * @note This class was forked from WooCommerce and modified.
12
 */
13
14
 // Exit if accessed directly.
15
 if ( ! defined( 'ABSPATH' ) ) {
16
 	exit;
17
 }
18
19
if ( ! class_exists( 'ALNP_Autoloader' ) ) {
20
21
	class ALNP_Autoloader {
22
23
		/**
24
		 * Path to the includes directory.
25
		 *
26
		 * @access private
27
		 * @var    string
28
		 */
29
		private $include_path = '';
30
31
		/**
32
		 * The Constructor.
33
		 */
34
		public function __construct() {
35
			if ( function_exists( '__autoload' ) ) {
36
				spl_autoload_register( '__autoload' );
37
			}
38
39
			spl_autoload_register( array( $this, 'autoload' ) );
40
41
			$this->include_path = untrailingslashit( plugin_dir_path( AUTO_LOAD_NEXT_POST_FILE ) ) . '/includes/';
42
		}
43
44
		/**
45
		 * Take a class name and turn it into a file name.
46
		 *
47
		 * @access private
48
		 * @param  string $class Class name.
49
		 * @return string
50
		 */
51
		private function get_file_name_from_class( $class ) {
52
			return 'class-' . str_replace( '_', '-', $class ) . '.php';
53
		} // END get_file_name_from_class()
54
55
		/**
56
		 * Include a class file.
57
		 *
58
		 * @access private
59
		 * @param  string $path File path.
60
		 * @return bool Successful or not.
61
		 */
62
		private function load_file( $path ) {
63
			if ( $path && is_readable( $path ) ) {
64
				include_once $path;
65
				return true;
66
			}
67
			return false;
68
		} // END load_file()
69
70
		/**
71
		 * Auto-load ALNP classes on demand to reduce memory consumption.
72
		 *
73
		 * @access public
74
		 * @param  string $class Class name.
75
		 */
76
		public function autoload( $class ) {
77
			$class = strtolower( $class );
78
79
			if ( 0 !== strpos( $class, 'alnp_' ) ) {
80
				return;
81
			}
82
83
			$file = $this->get_file_name_from_class( $class );
84
			$path = '';
85
86
			if ( 0 === strpos( $class, 'alnp_admin' ) ) {
87
				$path = $this->include_path . 'admin/';
88
			}
89
90
			if ( empty( $path ) || ! $this->load_file( $path . $file ) ) {
91
				$this->load_file( $this->include_path . $file );
92
			}
93
		} // END autoload()
94
95
	} // END class.
96
97
} // END if class exists.
98
99
new ALNP_Autoloader();
100