Psr4::__invoke()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
rs 9.4285
cc 3
eloc 11
nc 3
nop 1
1
<?php
2
3
namespace Corpus\Autoloader;
4
5
/**
6
 * Implementation of a PSR-4 Autoloader
7
 *
8
 * <code>
9
 * spl_autoload_register( new Psr4('My\\Prefix', '/vendor/path/blah') );
10
 * </code>
11
 *
12
 * @package Corpus\Autoloader
13
 */
14
class Psr4 {
15
16
	/**
17
	 * @var string
18
	 */
19
	protected $namespace;
20
21
	/**
22
	 * @var string
23
	 */
24
	protected $path;
25
26
	/**
27
	 * @param string $root_namespace Namespace prefix
28
	 * @param string $path Root path
29
	 */
30
	public function __construct( $root_namespace, $path ) {
31
		$this->namespace = $this->trimSlashes($root_namespace);
32
		$this->path      = rtrim($path, DIRECTORY_SEPARATOR);
33
	}
34
35
	/**
36
	 * @param string $path
37
	 * @return string
38
	 */
39
	protected final function trimSlashes( $path ) {
40
		return trim($path, ' /\\');
41
	}
42
43
	/**
44
	 * @param $class
45
	 * @return bool|string
46
	 */
47
	public function __invoke( $class ) {
48
		$class    = $this->trimSlashes($class);
49
		$ns_count = count(explode('\\', $this->namespace));
50
51
		if( $this->isOfNamespace($class) ) {
52
			$class_parts = explode('\\', $class);
53
			$class_parts = array_slice($class_parts, $ns_count);
54
55
			$filename = $this->path . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $class_parts) . ".php";
56
57
			if( file_exists($filename) ) {
58
				require($filename);
59
			}
60
61
			return $filename;
62
		}
63
64
		return false;
65
	}
66
67
	/**
68
	 * @param $class_name
69
	 * @return bool
70
	 */
71
	protected function isOfNamespace( $class_name ) {
72
		return stripos($class_name, $this->namespace . '\\') === 0;
73
	}
74
75
}