Completed
Push — master ( c0bce4...52e213 )
by Kenji
10s
created

FunctionPatcher   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 190
Duplicated Lines 100 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
dl 190
loc 190
rs 10
c 0
b 0
f 0
wmc 20
lcom 2
cbo 2

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 4 4 1
A checkLock() 7 7 2
A addWhitelists() 9 9 2
A getFunctionWhitelist() 4 4 1
A addBlacklist() 6 6 1
A removeBlacklist() 7 7 1
A lockFunctionList() 4 4 1
A isWhitelisted() 9 9 2
A isBlacklisted() 9 9 2
C generateNewSource() 48 48 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 20 and the first side effect is on line 13.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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\Patcher;
12
13
require __DIR__ . '/FunctionPatcher/NodeVisitor.php';
14
require __DIR__ . '/FunctionPatcher/Proxy.php';
15
16
use LogicException;
17
18
use Kenjis\MonkeyPatch\Patcher\FunctionPatcher\NodeVisitor;
19
20 View Code Duplication
class FunctionPatcher extends AbstractPatcher
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
21
{
22
	private static $lock_function_list = false;
23
24
	/**
25
	 * @var array list of function names (in lower case) which you patch
26
	 */
27
	private static $whitelist = [
28
		'mt_rand',
29
		'rand',
30
		'uniqid',
31
		'hash_hmac',
32
		'md5',
33
		'sha1',
34
		'hash',
35
		'time',
36
		'microtime',
37
		'date',
38
		'function_exists',
39
		'header',
40
		'setcookie',
41
		// Functions that have param called by reference
42
		// Need to prepare method in FunctionPatcher\Proxy class
43
		'openssl_random_pseudo_bytes',
44
	];
45
46
	/**
47
	 * @var array list of function names (in lower case) which can't be patched
48
	 */
49
	private static $blacklist = [
50
		// Segmentation fault
51
		'call_user_func_array',
52
		'exit__',
53
		// Error: Only variables should be assigned by reference
54
		'get_instance',
55
		'get_config',
56
		'load_class',
57
		'get_mimes',
58
		'_get_validation_object',
59
		// has reference param
60
		'preg_replace',
61
		'preg_match',
62
		'preg_match_all',
63
		'array_unshift',
64
		'array_shift',
65
		'sscanf',
66
		'ksort',
67
		'krsort',
68
		'str_ireplace',
69
		'str_replace',
70
		'is_callable',
71
		'flock',
72
		'end',
73
		'idn_to_ascii',
74
		// Special functions for ci-phpunit-test
75
		'show_404',
76
		'show_error',
77
		'redirect',
78
	];
79
80
	public static $replacement;
81
82
	public function __construct()
83
	{
84
		$this->node_visitor = new NodeVisitor();
85
	}
86
87
	protected static function checkLock($error_msg)
88
	{
89
		if (self::$lock_function_list)
90
		{
91
			throw new LogicException($error_msg);
92
		}
93
	}
94
95
	public static function addWhitelists(array $function_list)
96
	{
97
		self::checkLock("You can't add to whitelist after initialization");
98
99
		foreach ($function_list as $function_name)
100
		{
101
			self::$whitelist[] = strtolower($function_name);
102
		}
103
	}
104
105
	/**
106
	 * @return array
107
	 */
108
	public static function getFunctionWhitelist()
109
	{
110
		return self::$whitelist;
111
	}
112
113
	public static function addBlacklist($function_name)
114
	{
115
		self::checkLock("You can't add to blacklist after initialization");
116
117
		self::$blacklist[] = strtolower($function_name);
118
	}
119
120
	public static function removeBlacklist($function_name)
121
	{
122
		self::checkLock("You can't remove from blacklist after initialization");
123
124
		$key = array_search(strtolower($function_name), self::$blacklist);
125
		array_splice(self::$blacklist, $key, 1);
126
	}
127
128
	public static function lockFunctionList()
129
	{
130
		self::$lock_function_list = true;
131
	}
132
133
	/**
134
	 * @param string $name function name
135
	 * @return boolean
136
	 */
137
	public static function isWhitelisted($name)
138
	{
139
		if (in_array(strtolower($name), self::$whitelist))
140
		{
141
			return true;
142
		}
143
144
		return false;
145
	}
146
147
	/**
148
	 * @param string $name function name
149
	 * @return boolean
150
	 */
151
	public static function isBlacklisted($name)
152
	{
153
		if (in_array(strtolower($name), self::$blacklist))
154
		{
155
			return true;
156
		}
157
158
		return false;
159
	}
160
161
	protected static function generateNewSource($source)
162
	{
163
		$tokens = token_get_all($source);
164
		$new_source = '';
165
		$i = -1;
166
167
		ksort(self::$replacement);
168
		reset(self::$replacement);
169
		$replacement['key'] = key(self::$replacement);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$replacement was never initialized. Although not strictly required by PHP, it is generally a good practice to add $replacement = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
170
		$replacement['value'] = current(self::$replacement);
171
		next(self::$replacement);
172
		if ($replacement['key'] === null)
173
		{
174
			$replacement = false;
175
		}
176
177
		foreach ($tokens as $token)
178
		{
179
			$i++;
180
181
			if (is_string($token))
182
			{
183
				$new_source .= $token;
184
			}
185
			elseif ($i == $replacement['key'])
186
			{
187
				$new_source .= $replacement['value'];
188
				$replacement['key'] = key(self::$replacement);
189
				$replacement['value'] = current(self::$replacement);
190
				next(self::$replacement);
191
				if ($replacement['key'] === null)
192
				{
193
					$replacement = false;
194
				}
195
			}
196
			else
197
			{
198
				$new_source .= $token[1];
199
			}
200
		}
201
202
		if ($replacement !== false)
203
		{
204
			throw new LogicException('Replacement data still remain');
205
		}
206
207
		return $new_source;
208
	}
209
}
210