-
Notifications
You must be signed in to change notification settings - Fork 20
/
TestSessionStubCodeWriter.php
81 lines (69 loc) · 2.21 KB
/
TestSessionStubCodeWriter.php
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
<?php
namespace SilverStripe\TestSession;
/**
* Writes PHP to a file which can be included in SilverStripe runs on existence.
* The generated file is included in page execution through {@link TestSessionRequestFilter}.
*/
class TestSessionStubCodeWriter
{
/**
* @var boolean Add debug statements to the generated PHP about
* the generator's origin code location.
*/
protected $debug = false;
/**
* @var String Absolute path to a PHP file, essentially the "name" of the stub.
*/
protected $filePath;
public function __construct($filePath = null)
{
$this->filePath = $filePath ? $filePath : BASE_PATH . '/testSessionStubCode.php';
}
/**
* Writes arbitrary PHP code to {@link $filePath} for later inclusion.
* Creates the file if it doesn't exist.
* Adds debug information about the origin of this code if {@link $debug} is set.
*
* @param String $php Block of PHP code (without preceding <?php)
* @param boolean $eval Sanity check on code.
*/
public function write($php, $eval = true)
{
$trace = $this->debug ? debug_backtrace() : null;
$path = $this->getFilePath();
$header = '';
// Create file incl. header if it doesn't exist
if (!file_exists($this->getFilePath() ?? '')) {
touch($this->getFilePath() ?? '');
if ($this->debug) {
$header .= "<?php\n// Generated by " . $trace[1]['class'] . " on " . date('Y-m-d H:i:s') . "\n\n";
} else {
$header .= "<?php\n";
}
}
// Add content
if ($this->debug) {
$header .= "// Added by " . $trace[1]['class'] . '::' . $trace[1]['function'] . "\n";
}
file_put_contents($path ?? '', $header . $php . "\n", FILE_APPEND);
}
public function reset()
{
if (file_exists($this->getFilePath() ?? '')) {
unlink($this->getFilePath() ?? '');
}
}
public function getFilePath()
{
return $this->filePath;
}
public function getDebug()
{
return $this->debug;
}
public function setDebug($debug)
{
$this->debug = $debug;
return $this;
}
}