silverstripe-testsession/code/TestSessionStubCodeWriter.php
2015-12-18 07:17:16 +13:00

80 lines
2.1 KiB
PHP

<?php
/**
* 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;
}
}