silverstripe-testsession/code/TestSessionStubCodeWriter.php

80 lines
2.1 KiB
PHP
Raw Permalink Normal View History

<?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}.
*/
2015-12-17 19:17:16 +01:00
class TestSessionStubCodeWriter
{
2015-12-17 19:17:16 +01:00
/**
* @var boolean Add debug statements to the generated PHP about
* the generator's origin code location.
*/
protected $debug = false;
2015-12-17 19:17:16 +01:00
/**
* @var String Absolute path to a PHP file, essentially the "name" of the stub.
*/
protected $filePath;
2015-12-17 19:17:16 +01:00
public function __construct($filePath = null)
{
$this->filePath = $filePath ? $filePath : BASE_PATH . '/testSessionStubCode.php';
}
2015-12-17 19:17:16 +01:00
/**
* 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 = '';
2015-12-17 19:17:16 +01:00
// 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";
}
}
2015-12-17 19:17:16 +01:00
// Add content
if ($this->debug) {
$header .= "// Added by " . $trace[1]['class'] . '::' . $trace[1]['function'] . "\n";
}
file_put_contents($path, $header . $php . "\n", FILE_APPEND);
}
2015-12-17 19:17:16 +01:00
public function reset()
{
if (file_exists($this->getFilePath())) {
unlink($this->getFilePath());
}
}
2015-12-17 19:17:16 +01:00
public function getFilePath()
{
return $this->filePath;
}
2015-12-17 19:17:16 +01:00
public function getDebug()
{
return $this->debug;
}
2015-12-17 19:17:16 +01:00
public function setDebug($debug)
{
$this->debug = $debug;
2015-12-17 19:17:16 +01:00
return $this;
}
}