Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-12-18 07:17:16 +13:00
parent 4015611673
commit e40a0d0f1a
5 changed files with 916 additions and 852 deletions

View File

@ -2,7 +2,8 @@
/**
* Requires PHP's mycrypt extension in order to set the database name as an encrypted cookie.
*/
class TestSessionController extends Controller {
class TestSessionController extends Controller
{
private static $allowed_actions = array(
'index',
@ -27,13 +28,15 @@ class TestSessionController extends Controller {
*/
protected $environment;
public function __construct() {
public function __construct()
{
parent::__construct();
$this->environment = Injector::inst()->get('TestSessionEnvironment');
}
public function init() {
public function init()
{
parent::init();
$this->extend('init');
@ -42,17 +45,21 @@ class TestSessionController extends Controller {
!Director::isLive()
&& (Director::isDev() || Director::isTest() || Director::is_cli() || Permission::check("ADMIN"))
);
if(!$canAccess) return Security::permissionFailure($this);
if (!$canAccess) {
return Security::permissionFailure($this);
}
Requirements::javascript('framework/thirdparty/jquery/jquery.js');
Requirements::javascript('testsession/javascript/testsession.js');
}
public function Link($action = null) {
public function Link($action = null)
{
return Controller::join_links(Director::baseUrl(), 'dev/testsession', $action);
}
public function index() {
public function index()
{
if ($this->environment->isRunningTests()) {
return $this->renderWith('TestSession_inprogress');
} else {
@ -65,7 +72,8 @@ class TestSessionController extends Controller {
* then take a look at {@link TestSessionEnvironment::startTestSession()} and
* {@link TestSessionEnvironment::applyState()} to see the extension points.
*/
public function start() {
public function start()
{
$params = $this->request->requestVars();
if (!empty($params['globalTestSession'])) {
@ -130,7 +138,8 @@ class TestSessionController extends Controller {
/**
* Set $_SESSION state for the current browser session.
*/
public function browsersessionstate($request) {
public function browsersessionstate($request)
{
if (!$this->environment->isRunningTests()) {
throw new LogicException("No test session in progress.");
}
@ -150,7 +159,8 @@ class TestSessionController extends Controller {
Session::set('_TestSessionController.BrowserSessionState', array_merge($sessionStates, $newSessionStates));
}
public function StartForm() {
public function StartForm()
{
$databaseTemplates = $this->getDatabaseTemplates();
$fields = new FieldList(
new CheckboxField('createDatabase', 'Create temporary database?', 1)
@ -188,7 +198,8 @@ class TestSessionController extends Controller {
/**
* Shows state which is allowed to be modified while a test session is in progress.
*/
public function ProgressForm() {
public function ProgressForm()
{
$fields = $this->getBaseFields();
$form = new Form(
$this,
@ -207,7 +218,8 @@ class TestSessionController extends Controller {
return $form;
}
protected function getBaseFields() {
protected function getBaseFields()
{
$testState = $this->environment->getState();
$fields = new FieldList(
@ -230,7 +242,8 @@ class TestSessionController extends Controller {
return $fields;
}
public function DatabaseName() {
public function DatabaseName()
{
$db = DB::get_conn();
return $db->getSelectedDatabase();
}
@ -242,7 +255,8 @@ class TestSessionController extends Controller {
* @return HTMLText Rendered Template
* @throws LogicException
*/
public function set() {
public function set()
{
if (!$this->environment->isRunningTests()) {
throw new LogicException("No test session in progress.");
}
@ -269,7 +283,8 @@ class TestSessionController extends Controller {
return $this->renderWith('TestSession_inprogress');
}
public function clear() {
public function clear()
{
if (!$this->environment->isRunningTests()) {
throw new LogicException("No test session in progress.");
}
@ -294,7 +309,8 @@ class TestSessionController extends Controller {
* {@link TestSessionEnvironent::endTestSession()} as the extension points have moved to there now that the logic
* is there.
*/
public function end() {
public function end()
{
if (!$this->environment->isRunningTests()) {
throw new LogicException("No test session in progress.");
}
@ -317,11 +333,13 @@ class TestSessionController extends Controller {
/**
* @return boolean
*/
public function isTesting() {
public function isTesting()
{
return SapphireTest::using_temp_db();
}
public function setState($data) {
public function setState($data)
{
Deprecation::notice('3.1', 'TestSessionController::setState() is no longer used, please use '
. 'TestSessionEnvironment instead.');
}
@ -329,7 +347,8 @@ class TestSessionController extends Controller {
/**
* @return ArrayList
*/
public function getState() {
public function getState()
{
$stateObj = $this->environment->getState();
$state = array();
@ -351,7 +370,8 @@ class TestSessionController extends Controller {
* @param String $path Absolute folder path
* @return array
*/
protected function getDatabaseTemplates($path = null) {
protected function getDatabaseTemplates($path = null)
{
$templates = array();
if (!$path) {
@ -366,7 +386,9 @@ class TestSessionController extends Controller {
if ($path && file_exists($path)) {
$it = new FilesystemIterator($path);
foreach ($it as $fileinfo) {
if($fileinfo->getExtension() != 'sql') continue;
if ($fileinfo->getExtension() != 'sql') {
continue;
}
$templates[$fileinfo->getRealPath()] = $fileinfo->getFilename();
}
}
@ -378,7 +400,8 @@ class TestSessionController extends Controller {
* @param $params array The form fields as passed through from ->start() or ->set()
* @return array The form fields, after fixing the datetime field if necessary
*/
private function fixDatetimeFormField($params) {
private function fixDatetimeFormField($params)
{
if (isset($params['datetime']) && is_array($params['datetime']) && !empty($params['datetime']['date'])) {
// Convert DatetimeField format from array into string
$datetime = $params['datetime']['date'];
@ -391,5 +414,4 @@ class TestSessionController extends Controller {
return $params;
}
}

View File

@ -24,7 +24,8 @@
*
* See {@link $state} for default information stored in the test session.
*/
class TestSessionEnvironment extends Object {
class TestSessionEnvironment extends Object
{
/**
* @var int Optional identifier for the session.
@ -51,7 +52,8 @@ class TestSessionEnvironment extends Object {
*/
private static $test_state_id_file = 'TESTS_RUNNING-%s.json';
public function __construct($id = null) {
public function __construct($id = null)
{
parent::__construct();
if ($id) {
@ -67,7 +69,8 @@ class TestSessionEnvironment extends Object {
/**
* @return String Absolute path to the file persisting our state.
*/
public function getFilePath() {
public function getFilePath()
{
if ($this->id) {
$path = Director::getAbsFile(sprintf($this->config()->test_state_id_file, $this->id));
} else {
@ -80,21 +83,24 @@ class TestSessionEnvironment extends Object {
/**
* Tests for the existence of the file specified by $this->test_state_file
*/
public function isRunningTests() {
public function isRunningTests()
{
return(file_exists($this->getFilePath()));
}
/**
* @param String $id
*/
public function setId($id) {
public function setId($id)
{
$this->id = $id;
}
/**
* @return String
*/
public function getId() {
public function getId()
{
return $this->id;
}
@ -111,8 +117,11 @@ class TestSessionEnvironment extends Object {
*
* @param array $state An array of test state options to write.
*/
public function startTestSession($state = null, $id = null) {
if(!$state) $state = array();
public function startTestSession($state = null, $id = null)
{
if (!$state) {
$state = array();
}
$this->removeStateFile();
$this->id = $id;
@ -128,7 +137,8 @@ class TestSessionEnvironment extends Object {
$this->extend('onAfterStartTestSession');
}
public function updateTestSession($state) {
public function updateTestSession($state)
{
$this->extend('onBeforeUpdateTestSession', $state);
// Convert to JSON and back so we can share the appleState() code between this and ->loadFromFile()
@ -152,7 +162,8 @@ class TestSessionEnvironment extends Object {
* @throws LogicException
* @throws InvalidArgumentException
*/
public function applyState($state) {
public function applyState($state)
{
$this->extend('onBeforeApplyState', $state);
$database = (isset($state->database)) ? $state->database : null;
@ -259,7 +270,8 @@ class TestSessionEnvironment extends Object {
* @param String $path Absolute path to a SQL dump (include DROP TABLE commands)
* @return void
*/
public function importDatabase($path, $requireDefaultRecords = false) {
public function importDatabase($path, $requireDefaultRecords = false)
{
$sql = file_get_contents($path);
// Split into individual query commands, removing comments
@ -283,7 +295,8 @@ class TestSessionEnvironment extends Object {
/**
* Build the database with default records, see {@link DataObject->requireDefaultRecords()}.
*/
public function requireDefaultRecords() {
public function requireDefaultRecords()
{
$dbAdmin = new DatabaseAdmin();
Versioned::set_reading_mode('');
$dbAdmin->doBuild(true, true);
@ -293,7 +306,8 @@ class TestSessionEnvironment extends Object {
* Sliented as if the file already exists by another process, we don't want
* to modify.
*/
public function saveState($state) {
public function saveState($state)
{
if (defined('JSON_PRETTY_PRINT')) {
$content = json_encode($state, JSON_PRETTY_PRINT);
} else {
@ -304,7 +318,8 @@ class TestSessionEnvironment extends Object {
umask($old);
}
public function loadFromFile() {
public function loadFromFile()
{
if ($this->isRunningTests()) {
try {
$contents = file_get_contents($this->getFilePath());
@ -319,7 +334,8 @@ class TestSessionEnvironment extends Object {
}
}
private function removeStateFile() {
private function removeStateFile()
{
$file = $this->getFilePath();
if (file_exists($file)) {
@ -341,7 +357,8 @@ class TestSessionEnvironment extends Object {
* a queueing system (e.g. silverstripe-resque) is used, the behat module may call this first, and then the forked
* worker will call it as well - but there is only one state file that is created.
*/
public function endTestSession() {
public function endTestSession()
{
$this->extend('onBeforeEndTestSession');
if (SapphireTest::using_temp_db()) {
@ -362,7 +379,8 @@ class TestSessionEnvironment extends Object {
* @return FixtureFactory The loaded fixture
* @throws LogicException
*/
public function loadFixtureIntoDb($fixtureFile) {
public function loadFixtureIntoDb($fixtureFile)
{
$realFile = realpath(BASE_PATH.'/'.$fixtureFile);
$baseDir = realpath(Director::baseFolder());
if (!$realFile || !file_exists($realFile)) {
@ -389,7 +407,8 @@ class TestSessionEnvironment extends Object {
/**
* Reset the database connection to use the original database. Called by {@link self::endTestSession()}.
*/
public function resetDatabaseName() {
public function resetDatabaseName()
{
if ($this->oldDatabaseName) {
global $databaseConfig;
@ -406,7 +425,8 @@ class TestSessionEnvironment extends Object {
/**
* @return stdClass Data as taken from the JSON object in {@link self::loadFromFile()}
*/
public function getState() {
public function getState()
{
$path = Director::getAbsFile($this->getFilePath());
return (file_exists($path)) ? json_decode(file_get_contents($path)) : new stdClass;
}

View File

@ -2,19 +2,24 @@
/**
* Sets state previously initialized through {@link TestSessionController}.
*/
class TestSessionRequestFilter implements RequestFilter {
class TestSessionRequestFilter implements RequestFilter
{
/**
* @var TestSessionEnvironment
*/
protected $testSessionEnvironment;
public function __construct() {
public function __construct()
{
$this->testSessionEnvironment = Injector::inst()->get('TestSessionEnvironment');
}
public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) {
if(!$this->testSessionEnvironment->isRunningTests()) return;
public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
{
if (!$this->testSessionEnvironment->isRunningTests()) {
return;
}
$testState = $this->testSessionEnvironment->getState();
@ -40,14 +45,19 @@ class TestSessionRequestFilter implements RequestFilter {
if (!Director::isLive() && $file && file_exists($file)) {
// Connect to the database so the included code can interact with it
global $databaseConfig;
if ($databaseConfig) DB::connect($databaseConfig);
if ($databaseConfig) {
DB::connect($databaseConfig);
}
include_once($file);
}
}
}
public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) {
if(!$this->testSessionEnvironment->isRunningTests()) return;
public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
{
if (!$this->testSessionEnvironment->isRunningTests()) {
return;
}
// Store PHP session
$state = $this->testSessionEnvironment->getState();

View File

@ -3,7 +3,8 @@
* 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 {
class TestSessionStubCodeWriter
{
/**
* @var boolean Add debug statements to the generated PHP about
@ -16,7 +17,8 @@ class TestSessionStubCodeWriter {
*/
protected $filePath;
public function __construct($filePath = null) {
public function __construct($filePath = null)
{
$this->filePath = $filePath ? $filePath : BASE_PATH . '/testSessionStubCode.php';
}
@ -28,7 +30,8 @@ class TestSessionStubCodeWriter {
* @param String $php Block of PHP code (without preceding <?php)
* @param boolean $eval Sanity check on code.
*/
public function write($php, $eval = true) {
public function write($php, $eval = true)
{
$trace = $this->debug ? debug_backtrace() : null;
$path = $this->getFilePath();
$header = '';
@ -50,24 +53,27 @@ class TestSessionStubCodeWriter {
file_put_contents($path, $header . $php . "\n", FILE_APPEND);
}
public function reset() {
public function reset()
{
if (file_exists($this->getFilePath())) {
unlink($this->getFilePath());
}
}
public function getFilePath() {
public function getFilePath()
{
return $this->filePath;
}
public function getDebug() {
public function getDebug()
{
return $this->debug;
}
public function setDebug($debug) {
public function setDebug($debug)
{
$this->debug = $debug;
return $this;
}
}

View File

@ -1,14 +1,19 @@
<?php
class TestSessionStubCodeWriterTest extends SapphireTest {
class TestSessionStubCodeWriterTest extends SapphireTest
{
public function tearDown() {
public function tearDown()
{
parent::tearDown();
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
if(file_exists($file)) unlink($file);
if (file_exists($file)) {
unlink($file);
}
}
public function testWritesHeaderOnNewFile() {
public function testWritesHeaderOnNewFile()
{
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
$writer = new TestSessionStubCodeWriter($file);
$writer->write('foo();', false);
@ -19,7 +24,8 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
);
}
public function testWritesWithAppendOnExistingFile() {
public function testWritesWithAppendOnExistingFile()
{
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
$writer = new TestSessionStubCodeWriter($file);
$writer->write('foo();', false);
@ -31,7 +37,8 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
);
}
public function testReset() {
public function testReset()
{
$file = TEMP_FOLDER . '/TestSessionStubCodeWriterTest-file.php';
$writer = new TestSessionStubCodeWriter($file);
$writer->write('foo();', false);
@ -39,5 +46,4 @@ class TestSessionStubCodeWriterTest extends SapphireTest {
$writer->reset();
$this->assertFileNotExists($file);
}
}