Merge pull request #73 from creative-commoners/pulls/2/php81

ENH PHP 8.1 compatibility
This commit is contained in:
Guy Sartorelli 2022-04-22 16:16:50 +12:00 committed by GitHub
commit 0f5cb30743
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 42 additions and 41 deletions

View File

@ -104,7 +104,7 @@ class TestSessionController extends Controller
$id = null; $id = null;
} else { } else {
$generator = Injector::inst()->get(RandomGenerator::class); $generator = Injector::inst()->get(RandomGenerator::class);
$id = substr($generator->randomToken(), 0, 10); $id = substr($generator->randomToken() ?? '', 0, 10);
$this->getRequest()->getSession()->set('TestSessionId', $id); $this->getRequest()->getSession()->set('TestSessionId', $id);
} }
@ -113,7 +113,7 @@ class TestSessionController extends Controller
// Remove unnecessary items of form-specific data from being saved in the test session // Remove unnecessary items of form-specific data from being saved in the test session
$params = array_diff_key( $params = array_diff_key(
$params, $params ?? [],
array( array(
'action_set' => true, 'action_set' => true,
'action_start' => true, 'action_start' => true,
@ -170,7 +170,7 @@ class TestSessionController extends Controller
throw new LogicException("No test session in progress."); throw new LogicException("No test session in progress.");
} }
$newSessionStates = array_diff_key($request->getVars(), array('url' => true)); $newSessionStates = array_diff_key($request->getVars() ?? [], array('url' => true));
if (!$newSessionStates) { if (!$newSessionStates) {
throw new LogicException('No query parameters detected'); throw new LogicException('No query parameters detected');
} }
@ -288,7 +288,7 @@ class TestSessionController extends Controller
// Remove unnecessary items of form-specific data from being saved in the test session // Remove unnecessary items of form-specific data from being saved in the test session
$params = array_diff_key( $params = array_diff_key(
$params, $params ?? [],
array( array(
'action_set' => true, 'action_set' => true,
'action_start' => true, 'action_start' => true,
@ -399,7 +399,7 @@ class TestSessionController extends Controller
$path = BASE_PATH . '/' . $path; $path = BASE_PATH . '/' . $path;
} }
if ($path && file_exists($path)) { if ($path && file_exists($path ?? '')) {
$it = new FilesystemIterator($path); $it = new FilesystemIterator($path);
foreach ($it as $fileinfo) { foreach ($it as $fileinfo) {
if ($fileinfo->getExtension() != 'sql') { if ($fileinfo->getExtension() != 'sql') {

View File

@ -102,7 +102,7 @@ class TestSessionEnvironment
public function getFilePath() public function getFilePath()
{ {
if ($this->id) { if ($this->id) {
$path = Director::getAbsFile(sprintf($this->config()->get('test_state_id_file'), $this->id)); $path = Director::getAbsFile(sprintf($this->config()->get('test_state_id_file') ?? '', $this->id));
} else { } else {
$path = Director::getAbsFile($this->config()->get('test_state_file')); $path = Director::getAbsFile($this->config()->get('test_state_file'));
} }
@ -115,7 +115,7 @@ class TestSessionEnvironment
*/ */
public function isRunningTests() public function isRunningTests()
{ {
return (file_exists($this->getFilePath())); return (file_exists($this->getFilePath() ?? ''));
} }
/** /**
@ -161,7 +161,7 @@ class TestSessionEnvironment
// Convert to JSON and back so we can share the applyState() code between this and ->loadFromFile() // Convert to JSON and back so we can share the applyState() code between this and ->loadFromFile()
$json = json_encode($state, JSON_FORCE_OBJECT); $json = json_encode($state, JSON_FORCE_OBJECT);
$state = json_decode($json); $state = json_decode($json ?? '');
$this->applyState($state); $this->applyState($state);
@ -177,7 +177,7 @@ class TestSessionEnvironment
// Convert to JSON and back so we can share the appleState() code between this and ->loadFromFile() // Convert to JSON and back so we can share the appleState() code between this and ->loadFromFile()
$json = json_encode($state, JSON_FORCE_OBJECT); $json = json_encode($state, JSON_FORCE_OBJECT);
$state = json_decode($json); $state = json_decode($json ?? '');
$this->applyState($state); $this->applyState($state);
@ -192,7 +192,7 @@ class TestSessionEnvironment
{ {
// Ensure files backed up to assets dir // Ensure files backed up to assets dir
$backupFolder = $this->getAssetsBackupfolder(); $backupFolder = $this->getAssetsBackupfolder();
if (!is_dir($backupFolder)) { if (!is_dir($backupFolder ?? '')) {
Filesystem::makeFolder($backupFolder); Filesystem::makeFolder($backupFolder);
} }
$this->moveRecursive(ASSETS_PATH, $backupFolder, ['.htaccess', 'web.config', '.protected']); $this->moveRecursive(ASSETS_PATH, $backupFolder, ['.htaccess', 'web.config', '.protected']);
@ -206,7 +206,7 @@ class TestSessionEnvironment
{ {
// Ensure files backed up to assets dir // Ensure files backed up to assets dir
$backupFolder = $this->getAssetsBackupfolder(); $backupFolder = $this->getAssetsBackupfolder();
if (is_dir($backupFolder)) { if (is_dir($backupFolder ?? '')) {
// Move all files // Move all files
Filesystem::makeFolder(ASSETS_PATH); Filesystem::makeFolder(ASSETS_PATH);
$this->moveRecursive($backupFolder, ASSETS_PATH); $this->moveRecursive($backupFolder, ASSETS_PATH);
@ -224,12 +224,12 @@ class TestSessionEnvironment
protected function moveRecursive($src, $dest, $ignore = []) protected function moveRecursive($src, $dest, $ignore = [])
{ {
// If source is not a directory stop processing // If source is not a directory stop processing
if (!is_dir($src)) { if (!is_dir($src ?? '')) {
return; return;
} }
// If the destination directory does not exist create it // If the destination directory does not exist create it
if (!is_dir($dest) && !mkdir($dest)) { if (!is_dir($dest ?? '') && !mkdir($dest ?? '')) {
// If the destination directory could not be created stop processing // If the destination directory could not be created stop processing
return; return;
} }
@ -238,13 +238,13 @@ class TestSessionEnvironment
$iterator = new DirectoryIterator($src); $iterator = new DirectoryIterator($src);
foreach ($iterator as $file) { foreach ($iterator as $file) {
if ($file->isFile()) { if ($file->isFile()) {
if (!in_array($file->getFilename(), $ignore)) { if (!in_array($file->getFilename(), $ignore ?? [])) {
rename($file->getRealPath(), $dest . DIRECTORY_SEPARATOR . $file->getFilename()); rename($file->getRealPath() ?? '', $dest . DIRECTORY_SEPARATOR . $file->getFilename());
} }
} elseif (!$file->isDot() && $file->isDir()) { } elseif (!$file->isDot() && $file->isDir()) {
// If a dir is ignored, still move children but don't remove self // If a dir is ignored, still move children but don't remove self
$this->moveRecursive($file->getRealPath(), $dest . DIRECTORY_SEPARATOR . $file); $this->moveRecursive($file->getRealPath(), $dest . DIRECTORY_SEPARATOR . $file);
if (!in_array($file->getFilename(), $ignore)) { if (!in_array($file->getFilename(), $ignore ?? [])) {
Filesystem::removeFolder($file->getRealPath()); Filesystem::removeFolder($file->getRealPath());
} }
} }
@ -305,8 +305,8 @@ class TestSessionEnvironment
// Set existing one, assumes it already has been created // Set existing one, assumes it already has been created
$prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_'; $prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_';
$pattern = strtolower(sprintf('#^%stmpdb.*#', preg_quote($prefix, '#'))); $pattern = strtolower(sprintf('#^%stmpdb.*#', preg_quote($prefix ?? '', '#')));
if (!preg_match($pattern, $dbName)) { if (!preg_match($pattern ?? '', $dbName ?? '')) {
throw new InvalidArgumentException("Invalid database name format"); throw new InvalidArgumentException("Invalid database name format");
} }
@ -324,7 +324,7 @@ class TestSessionEnvironment
$mailer = (isset($state->mailer)) ? $state->mailer : null; $mailer = (isset($state->mailer)) ? $state->mailer : null;
if ($mailer) { if ($mailer) {
if (!class_exists($mailer) || !is_subclass_of($mailer, 'SilverStripe\\Control\\Email\\Mailer')) { if (!class_exists($mailer ?? '') || !is_subclass_of($mailer, 'SilverStripe\\Control\\Email\\Mailer')) {
throw new InvalidArgumentException(sprintf( throw new InvalidArgumentException(sprintf(
'Class "%s" is not a valid class, or subclass of Mailer', 'Class "%s" is not a valid class, or subclass of Mailer',
$mailer $mailer
@ -358,13 +358,13 @@ class TestSessionEnvironment
*/ */
public function importDatabase($path, $requireDefaultRecords = false) public function importDatabase($path, $requireDefaultRecords = false)
{ {
$sql = file_get_contents($path); $sql = file_get_contents($path ?? '');
// Split into individual query commands, removing comments // Split into individual query commands, removing comments
$sqlCmds = array_filter(preg_split( $sqlCmds = array_filter(preg_split(
'/;\n/', '/;\n/',
preg_replace(array('/^$\n/m', '/^(\/|#).*$\n/m'), '', $sql) preg_replace(array('/^$\n/m', '/^(\/|#).*$\n/m'), '', $sql ?? '') ?? ''
)); ) ?? []);
// Execute each query // Execute each query
foreach ($sqlCmds as $sqlCmd) { foreach ($sqlCmds as $sqlCmd) {
@ -401,7 +401,7 @@ class TestSessionEnvironment
$content = json_encode($state); $content = json_encode($state);
} }
$old = umask(0); $old = umask(0);
file_put_contents($this->getFilePath(), $content, LOCK_EX); file_put_contents($this->getFilePath() ?? '', $content, LOCK_EX);
umask($old); umask($old);
} }
@ -409,8 +409,8 @@ class TestSessionEnvironment
{ {
if ($this->isRunningTests()) { if ($this->isRunningTests()) {
try { try {
$contents = file_get_contents($this->getFilePath()); $contents = file_get_contents($this->getFilePath() ?? '');
$json = json_decode($contents); $json = json_decode($contents ?? '');
$this->applyState($json); $this->applyState($json);
} catch (Exception $e) { } catch (Exception $e) {
@ -428,8 +428,8 @@ class TestSessionEnvironment
{ {
$file = $this->getFilePath(); $file = $this->getFilePath();
if (file_exists($file)) { if (file_exists($file ?? '')) {
if (!unlink($file)) { if (!unlink($file ?? '')) {
throw new \Exception('Unable to remove the testsession state file, please remove it manually. File ' throw new \Exception('Unable to remove the testsession state file, please remove it manually. File '
. 'path: ' . $file); . 'path: ' . $file);
} }
@ -484,14 +484,14 @@ class TestSessionEnvironment
public function loadFixtureIntoDb($fixtureFile) public function loadFixtureIntoDb($fixtureFile)
{ {
$realFile = realpath(BASE_PATH . '/' . $fixtureFile); $realFile = realpath(BASE_PATH . '/' . $fixtureFile);
$baseDir = realpath(Director::baseFolder()); $baseDir = realpath(Director::baseFolder() ?? '');
if (!$realFile || !file_exists($realFile)) { if (!$realFile || !file_exists($realFile ?? '')) {
throw new LogicException("Fixture file doesn't exist"); throw new LogicException("Fixture file doesn't exist");
} elseif (substr($realFile, 0, strlen($baseDir)) != $baseDir) { } elseif (substr($realFile ?? '', 0, strlen($baseDir ?? '')) != $baseDir) {
throw new LogicException("Fixture file must be inside $baseDir"); throw new LogicException("Fixture file must be inside $baseDir");
} elseif (substr($realFile, -4) != '.yml') { } elseif (substr($realFile ?? '', -4) != '.yml') {
throw new LogicException("Fixture file must be a .yml file"); throw new LogicException("Fixture file must be a .yml file");
} elseif (!preg_match('/^([^\/.][^\/]+)\/tests\//', $fixtureFile)) { } elseif (!preg_match('/^([^\/.][^\/]+)\/tests\//', $fixtureFile ?? '')) {
throw new LogicException("Fixture file must be inside the tests subfolder of one of your modules."); throw new LogicException("Fixture file must be inside the tests subfolder of one of your modules.");
} }
@ -530,7 +530,7 @@ class TestSessionEnvironment
public function getState() public function getState()
{ {
$path = Director::getAbsFile($this->getFilePath()); $path = Director::getAbsFile($this->getFilePath());
return (file_exists($path)) ? json_decode(file_get_contents($path)) : new stdClass; return (file_exists($path ?? '')) ? json_decode(file_get_contents($path)) : new stdClass;
} }
/** /**
@ -548,7 +548,8 @@ class TestSessionEnvironment
* *
* @param mixed $state * @param mixed $state
*/ */
public function connectToDatabase($state = null) { public function connectToDatabase($state = null)
{
if ($state == null) { if ($state == null) {
$state = $this->getState(); $state = $this->getState();
} }

View File

@ -82,7 +82,7 @@ class TestSessionHTTPMiddleware implements HTTPMiddleware
// 'testsession.stubfile' state parameter. // 'testsession.stubfile' state parameter.
if (isset($testState->stubfile)) { if (isset($testState->stubfile)) {
$file = $testState->stubfile; $file = $testState->stubfile;
if (!Director::isLive() && $file && file_exists($file)) { if (!Director::isLive() && $file && file_exists($file ?? '')) {
include_once($file); include_once($file);
} }
} }

View File

@ -39,8 +39,8 @@ class TestSessionStubCodeWriter
$header = ''; $header = '';
// Create file incl. header if it doesn't exist // Create file incl. header if it doesn't exist
if (!file_exists($this->getFilePath())) { if (!file_exists($this->getFilePath() ?? '')) {
touch($this->getFilePath()); touch($this->getFilePath() ?? '');
if ($this->debug) { if ($this->debug) {
$header .= "<?php\n// Generated by " . $trace[1]['class'] . " on " . date('Y-m-d H:i:s') . "\n\n"; $header .= "<?php\n// Generated by " . $trace[1]['class'] . " on " . date('Y-m-d H:i:s') . "\n\n";
} else { } else {
@ -52,13 +52,13 @@ class TestSessionStubCodeWriter
if ($this->debug) { if ($this->debug) {
$header .= "// Added by " . $trace[1]['class'] . '::' . $trace[1]['function'] . "\n"; $header .= "// Added by " . $trace[1]['class'] . '::' . $trace[1]['function'] . "\n";
} }
file_put_contents($path, $header . $php . "\n", FILE_APPEND); file_put_contents($path ?? '', $header . $php . "\n", FILE_APPEND);
} }
public function reset() public function reset()
{ {
if (file_exists($this->getFilePath())) { if (file_exists($this->getFilePath() ?? '')) {
unlink($this->getFilePath()); unlink($this->getFilePath() ?? '');
} }
} }