-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConstants.php
More file actions
113 lines (96 loc) · 2.83 KB
/
Copy pathConstants.php
File metadata and controls
113 lines (96 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace AssertWell\PHPUnitGlobalState;
use AssertWell\PHPUnitGlobalState\Exceptions\RedefineException;
use AssertWell\PHPUnitGlobalState\Support\Runkit;
trait Constants
{
/**
* All constants being handled by this trait.
*
* @var array{created:Array<string>,updated:Array<string,mixed>}
*/
private $constants = [
'created' => [],
'updated' => [],
];
/**
* @after
*
* @return void
*/
protected function restoreConstants()
{
foreach ($this->constants['updated'] as $name => $value) {
if (defined($name)) {
Runkit::constant_redefine($name, $value);
} else {
define($name, $value);
}
unset($this->constants['updated'][$name]);
}
foreach ($this->constants['created'] as $key => $name) {
if (defined($name)) {
Runkit::constant_remove($name);
}
unset($this->constants['created'][$key]);
}
Runkit::reset();
}
/**
* Register a new constant to be cleaned up.
*
* @see runkit_constant_define()
*
* @throws \AssertWell\PHPUnitGlobalState\Exceptions\RedefineException
*
* @param string $name The constant name.
* @param mixed $value The scalar value to store in the constant.
*
* @return self
*/
protected function setConstant($name, $value = null)
{
if (! Runkit::isAvailable()) {
$this->markTestSkipped('setConstant() requires Runkit be available, skipping.');
}
if (defined($name)) {
if (! isset($this->constants['updated'][$name])) {
$this->constants['updated'][$name] = constant($name);
}
try {
Runkit::constant_redefine($name, $value);
} catch (\Exception $e) {
throw new RedefineException(sprintf(
'Unable to redefine constant "%s" with value "%s".',
$name,
is_scalar($value) ? $value : json_encode($value)
));
}
} else {
$this->constants['created'][] = $name;
define($name, $value);
}
return $this;
}
/**
* Delete a constant.
*
* @param string $name The constant name.
*
* @return self
*/
protected function deleteConstant($name)
{
if (! defined($name)) {
return $this;
}
if (! Runkit::isAvailable()) {
$this->markTestSkipped('deleteConstant() requires Runkit be available, skipping.');
}
if (! isset($this->constants[$name])) {
$this->constants['updated'][$name] = constant($name);
}
Runkit::constant_remove($name);
return $this;
}
}