diff --git a/src/Compiler/CoreInitializationPass.php b/src/Compiler/CoreInitializationPass.php index da785a47..92b4bd81 100644 --- a/src/Compiler/CoreInitializationPass.php +++ b/src/Compiler/CoreInitializationPass.php @@ -63,7 +63,7 @@ public function process(ContainerBuilder $container) $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 468af3f4..dab5810a 100644 --- a/src/Context/BasicContext.php +++ b/src/Context/BasicContext.php @@ -97,7 +97,7 @@ private function getSubclassesOf($parent): array { $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 @@ public function handleAjaxBeforeStep(BeforeStepScope $event) } 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 @@ public function handleAjaxAfterStep(AfterStepScope $event) } 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 @@ protected function findNamedButton($title) { $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 @@ protected function findNamedButton($title) 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 @@ public function stepIPressTheButton($text) */ 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 @@ public function iPutABreakpoint() */ 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 @@ public function castRelativeToAbsoluteTime($prefix, $val) */ 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 @@ public function castRelativeToAbsoluteDatetime($prefix, $val) */ 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 @@ public function stepFieldShouldBeDisabled($name, $type, $negate) 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 @@ public function iSeeTextInRegion($negate, $text, $region) 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 @@ public function iSeeTextInRegion($negate, $text, $region) 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 @@ public function theTextBeforeAfter($textBefore, $order, $textAfter, $element) // 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 @@ public function iShouldSeeTheElement($not, $cssSelector = '') $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 @@ public function iPressTheKeyGlobally($keyCombo) 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 @@ public function iAttachTheFileToTheField($filename, $locator) { 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 @@ public function iFollowWithJavascript($locator) } 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 2c9a36b1..78d0b0ee 100644 --- a/src/Context/EmailContext.php +++ b/src/Context/EmailContext.php @@ -66,7 +66,7 @@ public function thereIsAnEmailFromTo($negate, $direction, $email) $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 @@ public function thereIsAnEmailFromToTitled($negate, $direction, $email, $subject $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 @@ public function thereTheEmailContains($negate, $content) $emailContent = $email->PlainContent; } - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertStringNotContainsString($content, $emailContent); } else { Assert::assertStringContainsString($content, $emailContent); @@ -154,8 +154,8 @@ public function thereTheEmailContainsPlainText($content) $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 @@ public function theEmailContainFollowingData($negate, TableNode $table) $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 @@ public function theEmailContainFollowingData($negate, TableNode $table) 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 @@ public function theEmailSentFrom($negate, $from) } $match = $this->lastMatchedEmail; - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertStringNotContainsString($from, $match->From); } else { Assert::assertStringContainsString($from, $match->From); @@ -326,7 +326,7 @@ public function theEmailSentTo($negate, $to) } $match = $this->lastMatchedEmail; - if (trim($negate)) { + if (trim($negate ?? '')) { Assert::assertStringNotContainsString($to, $match->To); } else { Assert::assertStringContainsString($to, $match->To); @@ -355,7 +355,7 @@ public function iClickOnHttpLinkInEmail($httpText) $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 209c7c5d..198da845 100644 --- a/src/Context/FixtureContext.php +++ b/src/Context/FixtureContext.php @@ -257,12 +257,12 @@ public function stepCreateRecordWithData($type, $id, $data) $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 @@ public function stepIAssignObjToObjInTheRelation($type, $value, $relationType, $ $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 @@ public function stepCreateMemberWithGroupAndData($id, $groupId, $data) { 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 @@ public function stepCreateMemberWithGroupAndData($id, $groupId, $data) 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 @@ public function iAddAnExtensionToTheClass($extension, $class) { // 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_exists($extension) && is_subclass_of($extension, Extension::class), $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 @@ public function stepThereShouldBeAFileWithTuple($filename, $hash) */ 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 @@ public function aRecordWasLastEditedRelative($type, $id, $mod, $time) $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 @@ protected function prepareAsset($class, $identifier, $data = null) $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 @@ protected function prepareAsset($class, $identifier, $data = null) $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 @@ protected function prepareAsset($class, $identifier, $data = null) // 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 @@ protected function prepareAsset($class, $identifier, $data = null) $data['FileVariant'] = $asset['Variant']; } if (!isset($data['Name'])) { - $data['Name'] = basename($relativeTargetPath); + $data['Name'] = basename($relativeTargetPath ?? ''); } // Save assets @@ -894,17 +894,17 @@ protected function getAssetStore() */ 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 @@ protected function convertFields($class, $fields) { $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 @@ protected function joinPaths() $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 @@ protected function clearConfigFiles() } 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 dbed6446..1a96cf75 100644 --- a/src/Context/LoginContext.php +++ b/src/Context/LoginContext.php @@ -32,7 +32,7 @@ public function stepIAmLoggedIn() $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 54f87987..d85c55c6 100644 --- a/src/Context/SilverStripeContext.php +++ b/src/Context/SilverStripeContext.php @@ -191,7 +191,7 @@ public function getRegionObj($region) $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 @@ public function getRegionObj($region) // 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 @@ public function getRegionObj($region) 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 @@ public function before(BeforeScenarioScope $event) } 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 @@ public function waitResponsesAfterStep(AfterStepScope $event) 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 @@ public function getTestSessionState() */ 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 @@ public function joinUrlParts($part = null) $parts = func_get_args(); $trimSlashes = function (&$part) { - $part = trim($part, '/'); + $part = trim($part ?? '', '/'); }; array_walk($parts, $trimSlashes); @@ -600,7 +600,7 @@ public function selectOptionWithJavascript($select, $option) $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 a4a572c4..d612b6dc 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 e8ba23eb..15609bb0 100644 --- a/src/Controllers/ModuleInitialisationController.php +++ b/src/Controllers/ModuleInitialisationController.php @@ -139,10 +139,10 @@ protected function initFeaturesPath(OutputInterface $output, Module $module) // 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 @@ protected function initClassPath(OutputInterface $output, Module $module, $names { $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 @@ protected function initClassPath(OutputInterface $output, Module $module, $names '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 @@ protected function initClassPath(OutputInterface $output, Module $module, $names // 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 @@ protected function initClassPath(OutputInterface $output, Module $module, $names } $composerData['autoload']['psr-4']["{$fullNamespace}\\"] = $classesPath; file_put_contents( - $composerFile, + $composerFile ?? '', json_encode($composerData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ); @@ -239,7 +239,7 @@ protected function getFixtureClass($namespaceRoot) 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 @@ protected function getFixtureNamespace($namespaceRoot) 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 @@ protected function initConfig($output, $module, $namespaceRoot) ] ] ]; - 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 a78eb959..63265120 100644 --- a/src/Controllers/ModuleSuiteLocator.php +++ b/src/Controllers/ModuleSuiteLocator.php @@ -158,7 +158,7 @@ protected function findModuleConfig(Module $module) // 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 @@ protected function loadSuiteConfiguration($suite, Module $module) { $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 24dffb17..7658b2b4 100644 --- a/src/Extension.php +++ b/src/Extension.php @@ -63,7 +63,7 @@ public function initialize(ExtensionManager $extensionManager) ]; 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 ca0a751f..6fa2a7ca 100644 --- a/src/Utility/DebugTools.php +++ b/src/Utility/DebugTools.php @@ -118,9 +118,9 @@ public function dumpRenderedHtml(StepScope $event) // 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 @@ public function takeScreenshot(StepScope $event) 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 @@ private function prepareScreenshotPath() 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 e7d832de..7a86b53a 100644 --- a/src/Utility/RetryableCallHandler.php +++ b/src/Utility/RetryableCallHandler.php @@ -112,10 +112,10 @@ private function executeCall(Call $call) // 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 @@ private function getBufferedStdOut() 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 19646acc..5f61b15e 100644 --- a/src/Utility/TestMailer.php +++ b/src/Utility/TestMailer.php @@ -38,7 +38,7 @@ public function findEmail($to = null, $from = null, $subject = null, $content = { $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 @@ public function findEmails($to = null, $from = null, $subject = null, $content = $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 @@ protected function saveEmail($data) if (!isset($state->emails)) { $state->emails = array(); } - $state->emails[] = array_filter($data); + $state->emails[] = array_filter($data ?? []); $this->testSessionEnvironment->applyState($state); } }