1
|
|
|
<?php |
2
|
|
|
namespace Chadicus; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* This class if for overriding global functions for use within unit tests. |
6
|
|
|
*/ |
7
|
|
|
final class FunctionRegistry |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Array of custom functions. |
11
|
|
|
* |
12
|
|
|
* @var callable[] |
13
|
|
|
*/ |
14
|
|
|
private static $functions = array(); |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Register a new function for testing. |
18
|
|
|
* |
19
|
|
|
* @param string $namespace The namespace from which the global function will be called. |
20
|
|
|
* @param string $name The function name. |
21
|
|
|
* @param callable $function The callable to execute. |
22
|
|
|
* |
23
|
|
|
* @return void |
24
|
|
|
*/ |
25
|
|
|
public static function set(string $namespace, string $name, callable $function) |
26
|
|
|
{ |
27
|
|
|
self::evaluate($namespace, $name); |
28
|
|
|
self::$functions[$name] = $function; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Returns the custom function or the global function. |
33
|
|
|
* |
34
|
|
|
* @param string $name The function name. |
35
|
|
|
* |
36
|
|
|
* @return callable |
37
|
|
|
*/ |
38
|
|
|
public static function get(string $name) |
39
|
|
|
{ |
40
|
|
|
if (\array_key_exists($name, self::$functions)) { |
41
|
|
|
return self::$functions[$name]; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// return reference to global function |
45
|
|
|
return "\\{$name}"; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Sets all custom function properties to null. |
50
|
|
|
* |
51
|
|
|
* @param string|null $namespace The namespace from which the global function will be called. |
52
|
|
|
* @param array $extensions Array of PHP extensions whose functions will be mocked. |
53
|
|
|
* |
54
|
|
|
* @return void |
55
|
|
|
*/ |
56
|
|
|
public static function reset(?string $namespace = null, array $extensions = array()) |
57
|
|
|
{ |
58
|
|
|
self::$functions = array(); |
59
|
|
|
foreach ($extensions as $extension) { |
60
|
|
|
foreach (\get_extension_funcs($extension) as $name) { |
61
|
|
|
self::evaluate($namespace, $name); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Helper function to eval a new function call. |
68
|
|
|
* |
69
|
|
|
* @param string $namespace The namespace from which the global function will be called. |
70
|
|
|
* @param string $name The function name. |
71
|
|
|
* |
72
|
|
|
* @return void |
73
|
|
|
*/ |
74
|
|
|
private static function evaluate($namespace, $name) |
75
|
|
|
{ |
76
|
|
|
//If it's already defined skip it. |
77
|
|
|
if (\function_exists("{$namespace}\\{$name}")) { |
78
|
|
|
return; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
eval(" |
|
|
|
|
82
|
|
|
namespace {$namespace}; |
83
|
|
|
function {$name}() { |
84
|
|
|
return \call_user_func_array(\Chadicus\FunctionRegistry::get('{$name}'), \\func_get_args()); |
85
|
|
|
} |
86
|
|
|
"); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|