From 1f9fc6db0577b0609d5b46ede5a99b5efd71758c Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Wed, 13 Apr 2022 17:37:24 +1200 Subject: [PATCH] ENH PHP 8.1 compatibility --- src/Compiler/CoreInitializationPass.php | 2 +- src/Context/BasicContext.php | 86 +++++++++---------- src/Context/EmailContext.php | 24 +++--- src/Context/FixtureContext.php | 66 +++++++------- src/Context/LoginContext.php | 2 +- src/Context/SilverStripeContext.php | 18 ++-- src/Controllers/ModuleCommandTrait.php | 4 +- .../ModuleInitialisationController.php | 24 +++--- src/Controllers/ModuleSuiteLocator.php | 4 +- src/Extension.php | 2 +- src/Utility/DebugTools.php | 16 ++-- src/Utility/RetryableCallHandler.php | 6 +- src/Utility/TestMailer.php | 6 +- 13 files changed, 130 insertions(+), 130 deletions(-) diff --git a/src/Compiler/CoreInitializationPass.php b/src/Compiler/CoreInitializationPass.php index da785a4..92b4bd8 100644 --- a/src/Compiler/CoreInitializationPass.php +++ b/src/Compiler/CoreInitializationPass.php @@ -63,7 +63,7 @@ class CoreInitializationPass implements CompilerPassInterface $container->setParameter('paths.modules.'.$module->getShortName(), $module->getPath()); $composerName = $module->getComposerName(); if ($composerName) { - list($vendor,$name) = explode('/', $composerName); + list($vendor,$name) = explode('/', $composerName ?? ''); $container->setParameter('paths.modules.'.$vendor.'.'.$name, $module->getPath()); } } diff --git a/src/Context/BasicContext.php b/src/Context/BasicContext.php index 468af3f..dab5810 100644 --- a/src/Context/BasicContext.php +++ b/src/Context/BasicContext.php @@ -97,7 +97,7 @@ class BasicContext implements Context { $result = []; foreach (get_declared_classes() as $class) { - if (is_subclass_of($class, $parent)) { + if (is_subclass_of($class, $parent ?? '')) { $result[] = $class; } } @@ -211,9 +211,9 @@ JS; } try { $ajaxEnabledSteps = $this->getMainContext()->getAjaxSteps(); - $ajaxEnabledSteps = implode('|', array_filter($ajaxEnabledSteps)); + $ajaxEnabledSteps = implode('|', array_filter($ajaxEnabledSteps ?? [])); - if (empty($ajaxEnabledSteps) || !preg_match('/(' . $ajaxEnabledSteps . ')/i', $event->getStep()->getText())) { + if (empty($ajaxEnabledSteps) || !preg_match('/(' . $ajaxEnabledSteps . ')/i', $event->getStep()->getText() ?? '')) { return; } @@ -264,9 +264,9 @@ JS; } try { $ajaxEnabledSteps = $this->getMainContext()->getAjaxSteps(); - $ajaxEnabledSteps = implode('|', array_filter($ajaxEnabledSteps)); + $ajaxEnabledSteps = implode('|', array_filter($ajaxEnabledSteps ?? [])); - if (empty($ajaxEnabledSteps) || !preg_match('/(' . $ajaxEnabledSteps . ')/i', $event->getStep()->getText())) { + if (empty($ajaxEnabledSteps) || !preg_match('/(' . $ajaxEnabledSteps . ')/i', $event->getStep()->getText() ?? '')) { return; } @@ -377,7 +377,7 @@ JS; { $page = $this->getSession()->getPage(); // See https://mathiasbynens.be/notes/css-escapes - $escapedTitle = addcslashes($title, '!"#$%&\'()*+,-./:;<=>?@[\]^`{|}~'); + $escapedTitle = addcslashes($title ?? '', '!"#$%&\'()*+,-./:;<=>?@[\]^`{|}~'); $matchedEl = null; $searches = [ ['named', ['link_or_button', "'{$title}'"]], @@ -406,7 +406,7 @@ JS; public function iShouldSeeAButton($negative, $text) { $button = $this->findNamedButton($text); - if (trim($negative)) { + if (trim($negative ?? '')) { Assert::assertNull($button, sprintf('%s button found', $text)); } else { Assert::assertNotNull($button, sprintf('%s button not found', $text)); @@ -430,9 +430,9 @@ JS; */ public function stepIPressTheButtons($text) { - $buttonNames = explode('|', $text); + $buttonNames = explode('|', $text ?? ''); foreach ($buttonNames as $name) { - $button = $this->findNamedButton(trim($name)); + $button = $this->findNamedButton(trim($name ?? '')); if ($button) { break; } @@ -718,14 +718,14 @@ JS; */ public function castRelativeToAbsoluteTime($prefix, $val) { - $timestamp = strtotime($val); + $timestamp = strtotime($val ?? ''); if (!$timestamp) { throw new InvalidArgumentException(sprintf( "Can't resolve '%s' into a valid datetime value", $val )); } - return date($this->timeFormat, $timestamp); + return date($this->timeFormat ?? '', $timestamp); } /** @@ -740,14 +740,14 @@ JS; */ public function castRelativeToAbsoluteDatetime($prefix, $val) { - $timestamp = strtotime($val); + $timestamp = strtotime($val ?? ''); if (!$timestamp) { throw new InvalidArgumentException(sprintf( "Can't resolve '%s' into a valid datetime value", $val )); } - return date($this->datetimeFormat, $timestamp); + return date($this->datetimeFormat ?? '', $timestamp); } /** @@ -762,14 +762,14 @@ JS; */ public function castRelativeToAbsoluteDate($prefix, $val) { - $timestamp = strtotime($val); + $timestamp = strtotime($val ?? ''); if (!$timestamp) { throw new InvalidArgumentException(sprintf( "Can't resolve '%s' into a valid datetime value", $val )); } - return date($this->dateFormat, $timestamp); + return date($this->dateFormat ?? '', $timestamp); } public function getDateFormat() @@ -828,7 +828,7 @@ JS; Assert::assertNotNull($element, sprintf("Element '%s' not found", $name)); $disabledAttribute = $element->getAttribute('disabled'); - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertNull($disabledAttribute, sprintf("Failed asserting element '%s' is not disabled", $name)); } else { Assert::assertNotNull($disabledAttribute, sprintf("Failed asserting element '%s' is disabled", $name)); @@ -929,11 +929,11 @@ JS; Assert::assertNotNull($regionObj); $actual = $regionObj->getText(); - $actual = preg_replace('/\s+/u', ' ', $actual); - $regex = '/' . preg_quote($text, '/') . '/ui'; + $actual = preg_replace('/\s+/u', ' ', $actual ?? ''); + $regex = '/' . preg_quote($text ?? '', '/') . '/ui'; - if (trim($negate)) { - if (preg_match($regex, $actual)) { + if (trim($negate ?? '')) { + if (preg_match($regex ?? '', $actual ?? '')) { $message = sprintf( 'The text "%s" was found in the text of the "%s" region on the page %s.', $text, @@ -944,7 +944,7 @@ JS; throw new \Exception($message); } } else { - if (!preg_match($regex, $actual)) { + if (!preg_match($regex ?? '', $actual ?? '')) { $message = sprintf( 'The text "%s" was not found anywhere in the text of the "%s" region on the page %s.', $text, @@ -1079,15 +1079,15 @@ JS; // Check both of the texts exist in the element $text = $ele->getText(); - Assert::assertTrue(strpos($text, $textBefore) !== 'FALSE', sprintf('%s not found in the element %s', $textBefore, $element)); - Assert::assertTrue(strpos($text, $textAfter) !== 'FALSE', sprintf('%s not found in the element %s', $textAfter, $element)); + Assert::assertTrue(strpos($text ?? '', $textBefore ?? '') !== 'FALSE', sprintf('%s not found in the element %s', $textBefore, $element)); + Assert::assertTrue(strpos($text ?? '', $textAfter ?? '') !== 'FALSE', sprintf('%s not found in the element %s', $textAfter, $element)); /// Use strpos to get the position of the first occurrence of the two texts (case-sensitive) // and compare them with the given order (before or after) if ($order === 'before') { - Assert::assertTrue(strpos($text, $textBefore) < strpos($text, $textAfter)); + Assert::assertTrue(strpos($text ?? '', $textBefore ?? '') < strpos($text ?? '', $textAfter ?? '')); } else { - Assert::assertTrue(strpos($text, $textBefore) > strpos($text, $textAfter)); + Assert::assertTrue(strpos($text ?? '', $textBefore ?? '') > strpos($text ?? '', $textAfter ?? '')); } } @@ -1302,7 +1302,7 @@ JS; $not = ''; $cssSelector = $not; } - $sel = str_replace('"', '\\"', $cssSelector); + $sel = str_replace('"', '\\"', $cssSelector ?? ''); $js = <<selectOption($value); } else { $xpath = $field->getXpath(); - $xpath = str_replace(['"', "\n"], ['\"', ''], $xpath); - $value = str_replace('"', '\"', $value); + $xpath = str_replace(['"', "\n"], ['\"', ''], $xpath ?? ''); + $value = str_replace('"', '\"', $value ?? ''); $js = <<getSession()->getPage()->getOuterHtml(); - $htmlFragment = str_replace('\"', '"', $htmlFragment); - $contains = strpos($html, $htmlFragment) !== false; + $htmlFragment = str_replace('\"', '"', $htmlFragment ?? ''); + $contains = strpos($html ?? '', $htmlFragment ?? '') !== false; if ($not) { Assert::assertFalse($contains, "HTML fragment {$htmlFragment} was in rendered HTML when it should not have been"); } else { @@ -1463,18 +1463,18 @@ JS; return; } $modifier = null; - $pos = strpos($keyCombo, '-'); + $pos = strpos($keyCombo ?? '', '-'); if ($pos !== false && $pos !== 0) { - list($modifier, $char) = explode('-', $keyCombo); + list($modifier, $char) = explode('-', $keyCombo ?? ''); } else { $char = $keyCombo; } // handle special chars e.g. "space" - if (defined(WebDriverKeys::class . '::' . strtoupper($char))) { - $char = constant(WebDriverKeys::class . '::' . strtoupper($char)); + if (defined(WebDriverKeys::class . '::' . strtoupper($char ?? ''))) { + $char = constant(WebDriverKeys::class . '::' . strtoupper($char ?? '')); } if ($modifier) { - $modifier = strtoupper($modifier); + $modifier = strtoupper($modifier ?? ''); if (defined(WebDriverKeys::class . '::' . $modifier)) { $modifier = constant(WebDriverKeys::class . '::' . $modifier); } else { @@ -1495,13 +1495,13 @@ JS; { Assert::assertNotNull($this->fixtureContext, 'FixtureContext was not found so cannot know location of fixture files'); $path = $this->fixtureContext->getFilesPath() . '/' . $filename; - $path = str_replace('//', '/', $path); + $path = str_replace('//', '/', $path ?? ''); Assert::assertNotEmpty($path, 'Fixture files path is empty'); $field = $this->getElement($locator); $filesPath = $this->fixtureContext->getFilesPath(); if ($filesPath) { - $fullPath = rtrim(realpath($filesPath), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $path; - if (is_file($fullPath)) { + $fullPath = rtrim(realpath($filesPath ?? '') ?? '', DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $path; + if (is_file($fullPath ?? '')) { $path = $fullPath; } } @@ -1526,12 +1526,12 @@ JS; } Assert::assertNotNull($link, "Link {$locator} was not found"); $html = $link->getOuterHtml(); - preg_match('#href=([\'"])#', $html, $m); + preg_match('#href=([\'"])#', $html ?? '', $m); $q = $m[1]; - preg_match("#href={$q}(.+?){$q}#", $html, $m); - $href = str_replace("'", "\\'", $m[1]); - if (strpos($href, 'http') !== 0) { - $href = rtrim($href, '/'); + preg_match("#href={$q}(.+?){$q}#", $html ?? '', $m); + $href = str_replace("'", "\\'", $m[1] ?? ''); + if (strpos($href ?? '', 'http') !== 0) { + $href = rtrim($href ?? '', '/'); $href = "/{$href}"; } $this->getSession()->executeScript("document.location.href = '{$href}';"); diff --git a/src/Context/EmailContext.php b/src/Context/EmailContext.php index 2c9a36b..78d0b0e 100644 --- a/src/Context/EmailContext.php +++ b/src/Context/EmailContext.php @@ -66,7 +66,7 @@ class EmailContext implements Context $to = ($direction == 'to') ? $email : null; $from = ($direction == 'from') ? $email : null; $match = $this->mailer->findEmail($to, $from); - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertNull($match); } else { Assert::assertNotNull($match); @@ -90,7 +90,7 @@ class EmailContext implements Context $allTitles = $allMails ? '"' . implode('","', array_map(function ($email) { return $email->Subject; }, $allMails)) . '"' : null; - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertNull($match); } else { $msg = sprintf( @@ -130,7 +130,7 @@ class EmailContext implements Context $emailContent = $email->PlainContent; } - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertStringNotContainsString($content, $emailContent); } else { Assert::assertStringContainsString($content, $emailContent); @@ -154,8 +154,8 @@ class EmailContext implements Context $email = $this->lastMatchedEmail; $emailContent = ($email->Content) ? ($email->Content) : ($email->PlainContent); - $emailPlainText = strip_tags($emailContent); - $emailPlainText = preg_replace("/\h+/", " ", $emailPlainText); + $emailPlainText = strip_tags($emailContent ?? ''); + $emailPlainText = preg_replace("/\h+/", " ", $emailPlainText ?? ''); Assert::assertStringContainsString($content, $emailPlainText); } @@ -259,12 +259,12 @@ class EmailContext implements Context $emailContent = $email->PlainContent; } // Convert html content to plain text - $emailContent = strip_tags($emailContent); - $emailContent = preg_replace("/\h+/", " ", $emailContent); + $emailContent = strip_tags($emailContent ?? ''); + $emailContent = preg_replace("/\h+/", " ", $emailContent ?? ''); $rows = $table->getRows(); // For "should not contain" - if (trim($negate)) { + if (trim($negate ?? '')) { foreach ($rows as $row) { Assert::assertStringNotContainsString($row[0], $emailContent); } @@ -283,7 +283,7 @@ class EmailContext implements Context public function thereIsAnEmailTitled($negate, $subject) { $match = $this->mailer->findEmail(null, null, $subject); - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertNull($match); } else { $msg = sprintf( @@ -307,7 +307,7 @@ class EmailContext implements Context } $match = $this->lastMatchedEmail; - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertStringNotContainsString($from, $match->From); } else { Assert::assertStringContainsString($from, $match->From); @@ -326,7 +326,7 @@ class EmailContext implements Context } $match = $this->lastMatchedEmail; - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertStringNotContainsString($to, $match->To); } else { Assert::assertStringContainsString($to, $match->To); @@ -355,7 +355,7 @@ class EmailContext implements Context $href = null; foreach ($tags as $tag) { $linkText = $tag->nodeValue; - if (strpos($linkText, $httpText) !== false) { + if (strpos($linkText ?? '', $httpText ?? '') !== false) { $href = $linkText; break; } diff --git a/src/Context/FixtureContext.php b/src/Context/FixtureContext.php index 209c7c5..198da84 100644 --- a/src/Context/FixtureContext.php +++ b/src/Context/FixtureContext.php @@ -257,12 +257,12 @@ class FixtureContext implements Context $class = $this->convertTypeToClass($type); preg_match_all( '/"(?[^"]+)"\s*=\s*"(?[^"]+)"/', - $data, + $data ?? '', $matches ); $fields = $this->convertFields( $class, - array_combine($matches['key'], $matches['value']) + array_combine($matches['key'] ?? [], $matches['value'] ?? []) ); $fields = $this->prepareFixture($class, $id, $fields); // We should check if this fixture object already exists - if it does, we update it. If not, we create it @@ -403,20 +403,20 @@ class FixtureContext implements Context $manyField = null; $oneField = null; if ($relationObj->manyMany()) { - $manyField = array_search($class, $relationObj->manyMany()); - if ($manyField && strlen($relationName) > 0) { + $manyField = array_search($class, $relationObj->manyMany() ?? []); + if ($manyField && strlen($relationName ?? '') > 0) { $manyField = $relationName; } } if (empty($manyField) && $relationObj->hasMany(true)) { - $manyField = array_search($class, $relationObj->hasMany()); - if ($manyField && strlen($relationName) > 0) { + $manyField = array_search($class, $relationObj->hasMany() ?? []); + if ($manyField && strlen($relationName ?? '') > 0) { $manyField = $relationName; } } if (empty($manyField) && $relationObj->hasOne()) { - $oneField = array_search($class, $relationObj->hasOne()); - if ($oneField && strlen($relationName) > 0) { + $oneField = array_search($class, $relationObj->hasOne() ?? []); + if ($oneField && strlen($relationName ?? '') > 0) { $oneField = $relationName; } } @@ -555,12 +555,12 @@ class FixtureContext implements Context { preg_match_all( '/"(?[^"]+)"\s*=\s*"(?[^"]+)"/', - $data, + $data ?? '', $matches ); $fields = $this->convertFields( Member::class, - array_combine($matches['key'], $matches['value']) + array_combine($matches['key'] ?? [], $matches['value'] ?? []) ); /** @var Group $group */ @@ -587,7 +587,7 @@ class FixtureContext implements Context public function stepCreateGroupWithPermissions($id, $permissionStr) { // Convert natural language permissions to codes - preg_match_all('/"([^"]+)"/', $permissionStr, $matches); + preg_match_all('/"([^"]+)"/', $permissionStr ?? '', $matches); $permissions = $matches[1]; $codes = Permission::get_codes(false); @@ -652,7 +652,7 @@ class FixtureContext implements Context { // Validate the extension Assert::assertTrue( - class_exists($extension) && is_subclass_of($extension, Extension::class), + class_exists($extension ?? '') && is_subclass_of($extension, Extension::class), 'Given extension does not extend Extension' ); @@ -662,7 +662,7 @@ class FixtureContext implements Context $targetClass::add_extension($extension); // Write config for this extension too... - $snakedExtension = strtolower(str_replace('\\', '-', $extension)); + $snakedExtension = strtolower(str_replace('\\', '-', $extension ?? '') ?? ''); $config = <<getDestinationConfigFolder($filename); - file_put_contents($destPath, $config); + file_put_contents($destPath ?? '', $config); // Remember to cleanup... $this->activatedConfigFiles[] = $destPath; @@ -741,8 +741,8 @@ YAML; */ public function lookupFixtureReference($string) { - if (preg_match('/^=>/', $string)) { - list($className, $identifier) = explode('.', preg_replace('/^=>/', '', $string), 2); + if (preg_match('/^=>/', $string ?? '')) { + list($className, $identifier) = explode('.', preg_replace('/^=>/', '', $string ?? '') ?? '', 2); $id = $this->getFixtureFactory()->getId($className, $identifier); if (!$id) { throw new InvalidArgumentException(sprintf( @@ -768,7 +768,7 @@ YAML; $class = $this->convertTypeToClass($type); $fields = $this->prepareFixture($class, $id); $record = $this->getFixtureFactory()->createObject($class, $id, $fields); - $date = date("Y-m-d H:i:s", strtotime($time)); + $date = date("Y-m-d H:i:s", strtotime($time ?? '')); $table = $record->baseTable(); $field = ($mod == 'created') ? 'Created' : 'LastEdited'; DB::prepared_query( @@ -821,8 +821,8 @@ YAML; $relativeTargetPath = (isset($data['Filename'])) ? $data['Filename'] : $identifier; - $relativeTargetPath = preg_replace('/^' . ASSETS_DIR . '\/?/', '', $relativeTargetPath); - $sourcePath = $this->joinPaths($this->getFilesPath(), basename($relativeTargetPath)); + $relativeTargetPath = preg_replace('/^' . ASSETS_DIR . '\/?/', '', $relativeTargetPath ?? ''); + $sourcePath = $this->joinPaths($this->getFilesPath(), basename($relativeTargetPath ?? '')); // Create file or folder on filesystem if ($class == 'SilverStripe\\Assets\\Folder' || is_subclass_of($class, 'SilverStripe\\Assets\\Folder')) { @@ -830,7 +830,7 @@ YAML; $data['ID'] = $parent->ID; } else { // Check file exists - if (!file_exists($sourcePath)) { + if (!file_exists($sourcePath ?? '')) { throw new InvalidArgumentException(sprintf( 'Source file for "%s" cannot be found in "%s"', $relativeTargetPath, @@ -840,8 +840,8 @@ YAML; // Get parent $parentID = 0; - if (strstr($relativeTargetPath, '/')) { - $folderName = dirname($relativeTargetPath); + if (strstr($relativeTargetPath ?? '', '/')) { + $folderName = dirname($relativeTargetPath ?? ''); $parent = Folder::find_or_make($folderName); if ($parent) { $parentID = $parent->ID; @@ -865,7 +865,7 @@ YAML; $data['FileVariant'] = $asset['Variant']; } if (!isset($data['Name'])) { - $data['Name'] = basename($relativeTargetPath); + $data['Name'] = basename($relativeTargetPath ?? ''); } // Save assets @@ -894,17 +894,17 @@ YAML; */ protected function convertTypeToClass($type) { - $type = trim($type); + $type = trim($type ?? ''); // Try direct mapping - $class = str_replace(' ', '', ucwords($type)); - if (class_exists($class) && is_subclass_of($class, DataObject::class)) { + $class = str_replace(' ', '', ucwords($type ?? '')); + if (class_exists($class ?? '') && is_subclass_of($class, DataObject::class)) { return ClassInfo::class_name($class); } // Fall back to singular names - foreach (array_values(ClassInfo::subclassesFor(DataObject::class)) as $candidate) { - if (class_exists($candidate) && strcasecmp(singleton($candidate)->singular_name(), $type) === 0) { + foreach (array_values(ClassInfo::subclassesFor(DataObject::class) ?? []) as $candidate) { + if (class_exists($candidate ?? '') && strcasecmp(singleton($candidate)->singular_name() ?? '', $type ?? '') === 0) { return $candidate; } } @@ -927,7 +927,7 @@ YAML; { $labels = singleton($class)->fieldLabels(); foreach ($fields as $fieldName => $fieldVal) { - if ($fieldLabelKey = array_search($fieldName, $labels)) { + if ($fieldLabelKey = array_search($fieldName, $labels ?? [])) { unset($fields[$fieldName]); $fields[$labels[$fieldLabelKey]] = $fieldVal; } @@ -943,9 +943,9 @@ YAML; $paths = array_merge($paths, (array)$arg); } foreach ($paths as &$path) { - $path = trim($path, '/'); + $path = trim($path ?? '', '/'); } - if (substr($args[0], 0, 1) == '/') { + if (substr($args[0] ?? '', 0, 1) == '/') { $paths[0] = '/' . $paths[0]; } return join('/', $paths); @@ -959,8 +959,8 @@ YAML; } foreach ($this->activatedConfigFiles as $configFile) { - if (file_exists($configFile)) { - unlink($configFile); + if (file_exists($configFile ?? '')) { + unlink($configFile ?? ''); } } $this->activatedConfigFiles = []; diff --git a/src/Context/LoginContext.php b/src/Context/LoginContext.php index dbed644..1a96cf7 100644 --- a/src/Context/LoginContext.php +++ b/src/Context/LoginContext.php @@ -32,7 +32,7 @@ class LoginContext implements Context $this->getMainContext()->getSession()->visit($adminUrl); - if (0 == strpos($this->getMainContext()->getSession()->getCurrentUrl(), $loginUrl)) { + if (0 == strpos($this->getMainContext()->getSession()->getCurrentUrl() ?? '', $loginUrl ?? '')) { $this->stepILogInWith('admin', 'password'); Assert::assertStringStartsWith($adminUrl, $this->getMainContext()->getSession()->getCurrentUrl()); } diff --git a/src/Context/SilverStripeContext.php b/src/Context/SilverStripeContext.php index 54f8798..d85c55c 100644 --- a/src/Context/SilverStripeContext.php +++ b/src/Context/SilverStripeContext.php @@ -191,7 +191,7 @@ abstract class SilverStripeContext extends MinkContext implements SilverStripeAw $regionObj = $this->getSession()->getPage()->find( 'css', // Escape CSS selector - (false !== strpos($region, "'")) ? str_replace("'", "\\'", $region) : $region + (false !== strpos($region ?? '', "'")) ? str_replace("'", "\\'", $region) : $region ); if ($regionObj) { return $regionObj; @@ -203,7 +203,7 @@ abstract class SilverStripeContext extends MinkContext implements SilverStripeAw // Fall back to region identified by data-title. // Only apply if no double quotes exist in search string, // which would break the CSS selector. - if (false === strpos($region, '"')) { + if (false === strpos($region ?? '', '"')) { $regionObj = $this->getSession()->getPage()->find( 'css', '[data-title="' . $region . '"]' @@ -217,7 +217,7 @@ abstract class SilverStripeContext extends MinkContext implements SilverStripeAw if (!$this->regionMap) { throw new \LogicException("Cannot find 'region_map' in the behat.yml"); } - if (!array_key_exists($region, $this->regionMap)) { + if (!array_key_exists($region, $this->regionMap ?? [])) { throw new \LogicException("Cannot find the specified region in the behat.yml"); } $regionObj = $this->getSession()->getPage()->find('css', $region); @@ -265,7 +265,7 @@ abstract class SilverStripeContext extends MinkContext implements SilverStripeAw } if ($screenSize = Environment::getEnv('BEHAT_SCREEN_SIZE')) { - list($screenWidth, $screenHeight) = explode('x', $screenSize); + list($screenWidth, $screenHeight) = explode('x', $screenSize ?? ''); $this->getSession()->resizeWindow((int)$screenWidth, (int)$screenHeight); } else { $this->getSession()->resizeWindow(1024, 768); @@ -312,7 +312,7 @@ abstract class SilverStripeContext extends MinkContext implements SilverStripeAw public function getTestSessionState() { $extraParams = array(); - parse_str(Environment::getEnv('TESTSESSION_PARAMS'), $extraParams); + parse_str(Environment::getEnv('TESTSESSION_PARAMS') ?? '', $extraParams); return array_merge( array( 'database' => $this->databaseName, @@ -330,13 +330,13 @@ abstract class SilverStripeContext extends MinkContext implements SilverStripeAw */ public function parseUrl($url) { - $url = parse_url($url); + $url = parse_url($url ?? ''); $url['vars'] = array(); if (!isset($url['fragment'])) { $url['fragment'] = null; } if (isset($url['query'])) { - parse_str($url['query'], $url['vars']); + parse_str($url['query'] ?? '', $url['vars']); } return $url; @@ -401,7 +401,7 @@ abstract class SilverStripeContext extends MinkContext implements SilverStripeAw $parts = func_get_args(); $trimSlashes = function (&$part) { - $part = trim($part, '/'); + $part = trim($part ?? '', '/'); }; array_walk($parts, $trimSlashes); @@ -600,7 +600,7 @@ abstract class SilverStripeContext extends MinkContext implements SilverStripeAw $value = $field->getValue(); $newValue = $opt->getAttribute('value'); if (is_array($value)) { - if (!in_array($newValue, $value)) { + if (!in_array($newValue, $value ?? [])) { $value[] = $newValue; } } else { diff --git a/src/Controllers/ModuleCommandTrait.php b/src/Controllers/ModuleCommandTrait.php index a4a572c..d612b6d 100644 --- a/src/Controllers/ModuleCommandTrait.php +++ b/src/Controllers/ModuleCommandTrait.php @@ -17,8 +17,8 @@ trait ModuleCommandTrait */ protected function getModule($name, $error = true) { - if (strpos($name, '@') === 0) { - $name = substr($name, 1); + if (strpos($name ?? '', '@') === 0) { + $name = substr($name ?? '', 1); } $module = ModuleLoader::inst()->getManifest()->getModule($name); if (!$module && $error) { diff --git a/src/Controllers/ModuleInitialisationController.php b/src/Controllers/ModuleInitialisationController.php index e8ba23e..15609bb 100644 --- a/src/Controllers/ModuleInitialisationController.php +++ b/src/Controllers/ModuleInitialisationController.php @@ -139,10 +139,10 @@ class ModuleInitialisationController implements Controller // Create feature_path $features = $this->container->getParameter('silverstripe_extension.context.features_path'); $fullPath = $module->getResourcePath($features); - if (is_dir($fullPath)) { + if (is_dir($fullPath ?? '')) { return; } - mkdir($fullPath, 0777, true); + mkdir($fullPath ?? '', 0777, true); $output->writeln( "{$fullPath} - place your *.feature files here" ); @@ -165,13 +165,13 @@ class ModuleInitialisationController implements Controller { $classesPath = $this->container->getParameter('silverstripe_extension.context.class_path'); $dirPath = $module->getResourcePath($classesPath); - if (!is_dir($dirPath)) { - mkdir($dirPath, 0777, true); + if (!is_dir($dirPath ?? '')) { + mkdir($dirPath ?? '', 0777, true); } // Scaffold base context file $classPath = "{$dirPath}/FeatureContext.php"; - if (is_file($classPath)) { + if (is_file($classPath ?? '')) { return; } @@ -185,7 +185,7 @@ class ModuleInitialisationController implements Controller 'ClassName' => $class, ]); $classContent = $obj->renderWith(__DIR__.'/../../templates/FeatureContext.ss'); - file_put_contents($classPath, $classContent); + file_put_contents($classPath ?? '', $classContent); // Log $output->writeln( @@ -194,12 +194,12 @@ class ModuleInitialisationController implements Controller // Add to composer json $composerFile = $module->getResourcePath('composer.json'); - if (!file_exists($composerFile)) { + if (!file_exists($composerFile ?? '')) { return; } // Add autoload directive to composer - $composerData = json_decode(file_get_contents($composerFile), true); + $composerData = json_decode(file_get_contents($composerFile ?? '') ?? '', true); if (json_last_error()) { throw new Exception(json_last_error_msg()); } @@ -211,7 +211,7 @@ class ModuleInitialisationController implements Controller } $composerData['autoload']['psr-4']["{$fullNamespace}\\"] = $classesPath; file_put_contents( - $composerFile, + $composerFile ?? '', json_encode($composerData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ); @@ -239,7 +239,7 @@ class ModuleInitialisationController implements Controller protected function getFixtureNamespace($namespaceRoot) { $namespaceSuffix = $this->container->getParameter('silverstripe_extension.context.namespace_suffix'); - return trim($namespaceRoot, '/\\') . '\\' . $namespaceSuffix; + return trim($namespaceRoot ?? '', '/\\') . '\\' . $namespaceSuffix; } /** @@ -252,7 +252,7 @@ class ModuleInitialisationController implements Controller protected function initConfig($output, $module, $namespaceRoot) { $configPath = $module->getResourcePath('behat.yml'); - if (file_exists($configPath)) { + if (file_exists($configPath ?? '')) { return; } $class = $this->getFixtureClass($namespaceRoot); @@ -279,7 +279,7 @@ class ModuleInitialisationController implements Controller ] ] ]; - file_put_contents($configPath, Yaml::dump($data, 99999999, 2)); + file_put_contents($configPath ?? '', Yaml::dump($data, 99999999, 2)); $output->writeln( "{$configPath} - default behat.yml created" diff --git a/src/Controllers/ModuleSuiteLocator.php b/src/Controllers/ModuleSuiteLocator.php index a78eb95..6326512 100644 --- a/src/Controllers/ModuleSuiteLocator.php +++ b/src/Controllers/ModuleSuiteLocator.php @@ -158,7 +158,7 @@ class ModuleSuiteLocator implements Controller // Find all candidate paths foreach ([ "{$path}/", "{$path}/{$pathSuffix}"] as $parent) { foreach ([$parent.'behat.yml', $parent.'.behat.yml'] as $candidate) { - if (file_exists($candidate)) { + if (file_exists($candidate ?? '')) { return $candidate; } } @@ -178,7 +178,7 @@ class ModuleSuiteLocator implements Controller { $path = $this->findModuleConfig($module); $yamlParser = new Parser(); - $config = $yamlParser->parse(file_get_contents($path)); + $config = $yamlParser->parse(file_get_contents($path ?? '')); if (empty($config['default']['suites'][$suite])) { throw new Exception("Path {$path} does not contain default.suites.{$suite} config"); } diff --git a/src/Extension.php b/src/Extension.php index 24dffb1..7658b2b 100644 --- a/src/Extension.php +++ b/src/Extension.php @@ -63,7 +63,7 @@ class Extension implements ExtensionInterface ]; foreach ($options as $file) { - if (file_exists($file)) { + if (file_exists($file ?? '')) { require_once $file; $found = true; break; diff --git a/src/Utility/DebugTools.php b/src/Utility/DebugTools.php index ca0a751..6fa2a7c 100644 --- a/src/Utility/DebugTools.php +++ b/src/Utility/DebugTools.php @@ -118,9 +118,9 @@ trait DebugTools // prefix with zz_ so that it alpha sorts in the directory lower than screenshots which // will typically be referred to far more often. This is mainly for when you have // enabled `dumpRenderedHtmlAfterEveryStep` - $path = sprintf('%s/zz_%s_%d.html', $path, basename($feature->getFile()), $step->getLine()); + $path = sprintf('%s/zz_%s_%d.html', $path, basename($feature->getFile() ?? ''), $step->getLine()); $html = $this->getSession()->getPage()->getOuterHtml(); - file_put_contents($path, $html); + file_put_contents($path ?? '', $html); $this->logMessage(sprintf('Saving HTML into %s', $path)); } @@ -143,9 +143,9 @@ trait DebugTools if (!$path) { return; } - $path = sprintf('%s/%s_%d.png', $path, basename($feature->getFile()), $step->getLine()); + $path = sprintf('%s/%s_%d.png', $path, basename($feature->getFile() ?? ''), $step->getLine()); $screenshot = $driver->getScreenshot(); - file_put_contents($path, $screenshot); + file_put_contents($path ?? '', $screenshot); $this->logMessage(sprintf('Saving screenshot into %s', $path)); } @@ -161,16 +161,16 @@ trait DebugTools return; } Filesystem::makeFolder($path); - $path = realpath($path); - if (!file_exists($path)) { + $path = realpath($path ?? ''); + if (!file_exists($path ?? '')) { $this->logMessage(sprintf('"%s" is not valid directory and failed to create it', $path)); return; } - if (file_exists($path) && !is_dir($path)) { + if (file_exists($path ?? '') && !is_dir($path ?? '')) { $this->logMessage(sprintf('"%s" is not valid directory', $path)); return; } - if (file_exists($path) && !is_writable($path)) { + if (file_exists($path ?? '') && !is_writable($path ?? '')) { $this->logMessage(sprintf('"%s" directory is not writable', $path)); return; } diff --git a/src/Utility/RetryableCallHandler.php b/src/Utility/RetryableCallHandler.php index e7d832d..7a86b53 100644 --- a/src/Utility/RetryableCallHandler.php +++ b/src/Utility/RetryableCallHandler.php @@ -112,10 +112,10 @@ class RetryableCallHandler implements CallHandler // Determine whether to call with retries if ($retry) { $return = $this->retryThrowable(function () use ($callable, $arguments) { - return call_user_func_array($callable, $arguments); + return call_user_func_array($callable, $arguments ?? []); }, $this->retrySeconds); } else { - $return = call_user_func_array($callable, $arguments); + $return = call_user_func_array($callable, $arguments ?? []); } } catch (Exception $caught) { $exception = $caught; @@ -144,7 +144,7 @@ class RetryableCallHandler implements CallHandler private function startErrorAndOutputBuffering(Call $call) { $errorReporting = $call->getErrorReportingLevel() ? : $this->errorReportingLevel; - set_error_handler(array($this, 'handleError'), $errorReporting); + set_error_handler(array($this, 'handleError'), $errorReporting ?? 0); $this->obStarted = ob_start(); } diff --git a/src/Utility/TestMailer.php b/src/Utility/TestMailer.php index 19646ac..5f61b15 100644 --- a/src/Utility/TestMailer.php +++ b/src/Utility/TestMailer.php @@ -38,7 +38,7 @@ class TestMailer extends BaseTestMailer { $matches = $this->findEmails($to, $from, $subject, $content); //got the count of matches emails - $emailCount = count($matches); + $emailCount = count($matches ?? []); //get the last(latest) one return $matches ? $matches[$emailCount-1] : null; } @@ -70,7 +70,7 @@ class TestMailer extends BaseTestMailer $value = (isset($args[$i])) ? $args[$i] : null; if ($value) { if ($value[0] == '/') { - $matched = preg_match($value, $email->$field); + $matched = preg_match($value ?? '', $email->$field ?? ''); } else { $matched = ($value == $email->$field); } @@ -93,7 +93,7 @@ class TestMailer extends BaseTestMailer if (!isset($state->emails)) { $state->emails = array(); } - $state->emails[] = array_filter($data); + $state->emails[] = array_filter($data ?? []); $this->testSessionEnvironment->applyState($state); } }