Completed
Pull Request — master (#88)
by Kenji
03:16
created

PathChecker::setExcludePaths()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * Part of CI PHPUnit Test
4
 *
5
 * @author     Kenji Suzuki <https://github.com/kenjis>
6
 * @license    MIT License
7
 * @copyright  2015 Kenji Suzuki
8
 * @link       https://github.com/kenjis/ci-phpunit-test
9
 */
10
11
namespace Kenjis\MonkeyPatch;
12
13
use RuntimeException;
14
15
class PathChecker
16
{
17
	private static $include_paths = [];
18
	private static $exclude_paths = [];
19
20
	/**
21
	 * @param array $paths directory or file path
22
	 * @return array
23
	 * @throws RuntimeException
24
	 */
25
	protected static function normalizePaths(array $paths)
26
	{
27
		$new_paths = [];
28
		$excluded = false;
29
		foreach ($paths as $path)
30
		{
31
			// Path starting with '-' has special meaning (excluding it)
32
			if (substr($path, 0, 1) === '-')
33
			{
34
				$excluded = true;
35
				$path = ltrim($path, '-');
36
			}
37
38
			$real_path = realpath($path);
39
			if ($real_path === FALSE)
40
			{
41
				throw new RuntimeException($path . ' does not exist?');
42
			}
43
			if (is_dir($real_path))
44
			{
45
				$real_path = $real_path . '/';
46
			}
47
			$new_paths[] = $excluded ? '-'.$real_path : $real_path;
48
		}
49
		array_unique($new_paths, SORT_STRING);
50
		sort($new_paths, SORT_STRING);
51
		return $new_paths;
52
	}
53
54
	public static function setIncludePaths(array $dir)
55
	{
56
		self::$include_paths = self::normalizePaths($dir);
57
	}
58
59
	public static function setExcludePaths(array $dir)
60
	{
61
		self::$exclude_paths = self::normalizePaths($dir);
62
	}
63
64
	public static function getIncludePaths()
65
	{
66
		return self::$include_paths;
67
	}
68
69
	public static function getExcludePaths()
70
	{
71
		return self::$exclude_paths;
72
	}
73
74
	public static function check($path)
75
	{
76
		// Whitelist first
77
		$is_white = false;
78
		foreach (self::$include_paths as $white_dir) {
79
			$len = strlen($white_dir);
80
			if (substr($path, 0, $len) === $white_dir)
81
			{
82
				$is_white = true;
83
			}
84
		}
85
		if ($is_white === false)
86
		{
87
			return false;
88
		}
89
90
		// Then blacklist
91
		foreach (self::$exclude_paths as $black_dir) {
92
			// Check excluded path that starts with '-'.
93
			// '-' is smaller than '/', so this checking always comes first.
94
			if (substr($black_dir, 0, 1) === '-')
95
			{
96
				$black_dir = ltrim($black_dir, '-');
97
				$len = strlen($black_dir);
98
				if (substr($path, 0, $len) === $black_dir)
99
				{
100
					return true;
101
				}
102
			}
103
104
			$len = strlen($black_dir);
105
			if (substr($path, 0, $len) === $black_dir)
106
			{
107
				return false;
108
			}
109
		}
110
111
		return true;
112
	}
113
}
114