diff --git a/code/BatchActions/CMSBatchAction_Restore.php b/code/BatchActions/CMSBatchAction_Restore.php index 276b4a837b..340d9db05a 100644 --- a/code/BatchActions/CMSBatchAction_Restore.php +++ b/code/BatchActions/CMSBatchAction_Restore.php @@ -57,6 +57,6 @@ public function applicablePages($ids) // Get pages that exist in stage and remove them from the restore-able set $stageIDs = Versioned::get_by_stage($this->managedClass, Versioned::DRAFT)->column('ID'); - return array_values(array_diff($ids, $stageIDs)); + return array_values(array_diff($ids ?? [], $stageIDs)); } } diff --git a/code/Controllers/CMSMain.php b/code/Controllers/CMSMain.php index 8b75e3a91e..f88d01e05d 100644 --- a/code/Controllers/CMSMain.php +++ b/code/Controllers/CMSMain.php @@ -184,7 +184,7 @@ protected function init() { // set reading lang if (SiteTree::has_extension('Translatable') && !$this->getRequest()->isAjax()) { - Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages(SiteTree::class))); + Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages(SiteTree::class) ?? [])); } parent::init(); @@ -454,7 +454,7 @@ public function LinkWithSearch($link) ]; $link = Controller::join_links( $link, - array_filter(array_values($params)) ? '?' . http_build_query($params) : null + array_filter(array_values($params ?? [])) ? '?' . http_build_query($params) : null ); $this->extend('updateLinkWithSearch', $link); return $link; @@ -470,7 +470,7 @@ public function LinkPageAdd($extra = null, $placeholders = null) } if ($placeholders) { - $link .= (strpos($link, '?') === false ? "?$placeholders" : "&$placeholders"); + $link .= (strpos($link ?? '', '?') === false ? "?$placeholders" : "&$placeholders"); } return $link; @@ -627,7 +627,7 @@ public function getTreeNodeClasses(SiteTree $node) // Get status flag classes $flags = $node->getStatusFlags(); if ($flags) { - $statuses = array_keys($flags); + $statuses = array_keys($flags ?? []); foreach ($statuses as $s) { $classes .= ' status-' . $s; } @@ -642,7 +642,7 @@ public function getTreeNodeClasses(SiteTree $node) $classes .= ' ' . $filterClasses; } - return trim($classes); + return trim($classes ?? ''); } /** @@ -664,8 +664,8 @@ public function getsubtree($request) ); // Trim off the outer tag - $html = preg_replace('/^[\s\t\r\n]*]*>/', '', $html); - $html = preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/', '', $html); + $html = preg_replace('/^[\s\t\r\n]*]*>/', '', $html ?? ''); + $html = preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/', '', $html ?? ''); return $html; } @@ -682,7 +682,7 @@ public function getsubtree($request) public function updatetreenodes($request) { $data = []; - $ids = explode(',', $request->getVar('ids')); + $ids = explode(',', $request->getVar('ids') ?? ''); foreach ($ids as $id) { if ($id === "") { continue; // $id may be a blank string, which is invalid and should be skipped over @@ -824,7 +824,7 @@ public function savetreenode($request) $this->getResponse()->addHeader( 'X-Status', - rawurlencode(_t(__CLASS__.'.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.')) + rawurlencode(_t(__CLASS__.'.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.') ?? '') ); } @@ -852,7 +852,7 @@ public function savetreenode($request) $this->getResponse()->addHeader( 'X-Status', - rawurlencode(_t(__CLASS__.'.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.')) + rawurlencode(_t(__CLASS__.'.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.') ?? '') ); } @@ -923,7 +923,7 @@ public function getSearchFieldSchema() $searchParams = array_combine(array_map(function ($key) { return 'Search__' . $key; - }, array_keys($searchParams)), $searchParams); + }, array_keys($searchParams ?? [])), $searchParams ?? []); $schema = [ 'formSchemaUrl' => $schemaUrl, @@ -1082,7 +1082,7 @@ public function Breadcrumbs($unlinked = false) // Add all ancestors $ancestors = $record->getAncestors(); - $ancestors = new ArrayList(array_reverse($ancestors->toArray())); + $ancestors = new ArrayList(array_reverse($ancestors->toArray() ?? [])); $ancestors->push($record); /** @var SiteTree $ancestor */ foreach ($ancestors as $ancestor) { @@ -1144,7 +1144,7 @@ public function SiteTreeHints() // Check if can be created at the root $needsPerm = $obj->config()->get('need_permission'); if (!$obj->config()->get('can_be_root') - || (!array_key_exists($class, $canCreate) || !$canCreate[$class]) + || (!array_key_exists($class, $canCreate ?? []) || !$canCreate[$class]) || ($needsPerm && !$this->can($needsPerm)) ) { $def['Root']['disallowedChildren'][] = $class; @@ -1226,7 +1226,7 @@ public function getRecord($id, $versionID = null) if ($id instanceof $treeClass) { return $id; } - if (substr($id, 0, 3) == 'new') { + if (substr($id ?? '', 0, 3) == 'new') { return $this->getNewItem($id); } if (!is_numeric($id)) { @@ -1459,18 +1459,18 @@ protected function getArchiveWarningMessage($record) // Count number of affected change set $affectedChangeSetCount = 0; - if (count($inChangeSetIDs) > 0) { + if (count($inChangeSetIDs ?? []) > 0) { $affectedChangeSetCount = ChangeSet::get() ->filter(['ID' => $inChangeSetIDs, 'State' => ChangeSet::STATE_OPEN]) ->count(); } $numCampaigns = ChangeSet::singleton()->i18n_pluralise($affectedChangeSetCount); - $numCampaigns = mb_strtolower($numCampaigns); + $numCampaigns = mb_strtolower($numCampaigns ?? ''); - if (count($descendants) > 0 && $affectedChangeSetCount > 0) { + if (count($descendants ?? []) > 0 && $affectedChangeSetCount > 0) { $archiveWarningMsg = _t('SilverStripe\\CMS\\Controllers\\CMSMain.ArchiveWarningWithChildrenAndCampaigns', 'Warning: This page and all of its child pages will be unpublished and automatically removed from their associated {NumCampaigns} before being sent to the archive.\n\nAre you sure you want to proceed?', [ 'NumCampaigns' => $numCampaigns ]); - } elseif (count($descendants) > 0) { + } elseif (count($descendants ?? []) > 0) { $archiveWarningMsg = $defaultMessage; } elseif ($affectedChangeSetCount > 0) { $archiveWarningMsg = _t('SilverStripe\\CMS\\Controllers\\CMSMain.ArchiveWarningWithCampaigns', 'Warning: This page will be unpublished and automatically removed from their associated {NumCampaigns} before being sent to the archive.\n\nAre you sure you want to proceed?', [ 'NumCampaigns' => $numCampaigns ]); @@ -1693,9 +1693,9 @@ public function ListViewForm() ); $breadcrumbs = $item->Breadcrumbs(20, true, false, true, '/'); // Remove item's tile - $breadcrumbs = preg_replace('/[^\/]+$/', '', trim($breadcrumbs)); + $breadcrumbs = preg_replace('/[^\/]+$/', '', trim($breadcrumbs ?? '')); // Trim spaces around delimiters - $breadcrumbs = preg_replace('/\s?\/\s?/', '/', trim($breadcrumbs)); + $breadcrumbs = preg_replace('/\s?\/\s?/', '/', trim($breadcrumbs ?? '')); return $title . sprintf('

%s

', $breadcrumbs); } ]); @@ -1752,7 +1752,7 @@ public function save($data, $form) // Existing or new record? $id = $data['ID']; - if (substr($id, 0, 3) != 'new') { + if (substr($id ?? '', 0, 3) != 'new') { /** @var SiteTree $record */ $record = DataObject::get_by_id($className, $id); // Check edit permissions @@ -1810,7 +1810,7 @@ public function save($data, $form) ); } - $this->getResponse()->addHeader('X-Status', rawurlencode($message)); + $this->getResponse()->addHeader('X-Status', rawurlencode($message ?? '')); return $this->getResponseNegotiator()->respond($this->getRequest()); } @@ -1825,9 +1825,9 @@ public function save($data, $form) public function getNewItem($id, $setID = true) { $parentClass = $this->config()->get('tree_class'); - list(, $className, $parentID) = array_pad(explode('-', $id), 3, null); + list(, $className, $parentID) = array_pad(explode('-', $id ?? ''), 3, null); - if (!is_a($className, $parentClass, true)) { + if (!is_a($className, $parentClass ?? '', true)) { $response = Security::permissionFailure($this); if (!$response) { $response = $this->getResponse(); @@ -1931,7 +1931,7 @@ public function revert($data, $form) "Restored '{title}' successfully", 'Param {title} is a title', ['title' => $record->Title] - )) + ) ?? '') ); return $this->getResponseNegotiator()->respond($this->getRequest()); @@ -1967,7 +1967,7 @@ public function delete($data, $form) __CLASS__ . '.REMOVEDPAGEFROMDRAFT', "Removed '{title}' from the draft site", ['title' => $record->Title] - )) + ) ?? '') ); // Even if the record has been deleted from stage and live, it can be viewed in "archive mode" @@ -2003,7 +2003,7 @@ public function archive($data, $form) __CLASS__ . '.ARCHIVEDPAGE', "Archived page '{title}'", ['title' => $record->Title] - )) + ) ?? '') ); // Even if the record has been deleted from stage and live, it can be viewed in "archive mode" @@ -2038,7 +2038,7 @@ public function unpublish($data, $form) __CLASS__ . '.REMOVEDPAGE', "Removed '{title}' from the published site", ['title' => $record->Title] - )) + ) ?? '') ); return $this->getResponseNegotiator()->respond($this->getRequest()); @@ -2091,7 +2091,7 @@ public function doRollback($data, $form) ); } - $this->getResponse()->addHeader('X-Status', rawurlencode($message)); + $this->getResponse()->addHeader('X-Status', rawurlencode($message ?? '')); // Can be used in different contexts: In normal page edit view, in which case the redirect won't have any effect. // Or in history view, in which case a revert causes the CMS to re-load the edit view. @@ -2242,7 +2242,7 @@ public function restore($data, $form) __CLASS__ . '.RESTORED', "Restored '{title}' successfully", ['title' => $restoredPage->Title] - )) + ) ?? '') ); return $this->getResponseNegotiator()->respond($this->getRequest()); @@ -2280,7 +2280,7 @@ public function duplicate($request) __CLASS__ . '.DUPLICATED', "Duplicated '{title}' successfully", ['title' => $newPage->Title] - )) + ) ?? '') ); $url = $newPage->CMSEditLink(); $this->getResponse()->addHeader('X-ControllerURL', $url); @@ -2318,7 +2318,7 @@ public function duplicatewithchildren($request) __CLASS__ . '.DUPLICATEDWITHCHILDREN', "Duplicated '{title}' and children successfully", ['title' => $newPage->Title] - )) + ) ?? '') ); $url = $newPage->CMSEditLink(); $this->getResponse()->addHeader('X-ControllerURL', $url); @@ -2370,7 +2370,7 @@ protected function generateHintsCacheKey($memberID) $this->extend('updateHintsCacheKey', $baseKey); - return md5($baseKey); + return md5($baseKey ?? ''); } /** diff --git a/code/Controllers/CMSPageAddController.php b/code/Controllers/CMSPageAddController.php index a246826daf..d198d41f38 100644 --- a/code/Controllers/CMSPageAddController.php +++ b/code/Controllers/CMSPageAddController.php @@ -112,7 +112,7 @@ public function AddForm() "PageType", DBField::create_field( 'HTMLFragment', - sprintf($numericLabelTmpl, 2, _t('SilverStripe\\CMS\\Controllers\\CMSMain.ChoosePageType', 'Choose page type')) + sprintf($numericLabelTmpl ?? '', 2, _t('SilverStripe\\CMS\\Controllers\\CMSMain.ChoosePageType', 'Choose page type')) ), $pageTypes, 'Page' @@ -121,7 +121,7 @@ public function AddForm() $parentModeField->setTitle(DBField::create_field( 'HTMLFragment', - sprintf($numericLabelTmpl, 1, _t('SilverStripe\\CMS\\Controllers\\CMSMain.ChoosePageParentMode', 'Choose where to create this page')) + sprintf($numericLabelTmpl ?? '', 1, _t('SilverStripe\\CMS\\Controllers\\CMSMain.ChoosePageParentMode', 'Choose where to create this page')) )); $parentField->setSearchFunction(function ($sourceObject, $labelField, $search) { diff --git a/code/Controllers/CMSPagesController.php b/code/Controllers/CMSPagesController.php index 4c9a9e6edb..5fc962a977 100644 --- a/code/Controllers/CMSPagesController.php +++ b/code/Controllers/CMSPagesController.php @@ -55,7 +55,7 @@ public function Breadcrumbs($unlinked = false) $params['ParentID'] = $page->ID; $item = new stdClass(); $item->Title = $page->Title; - $item->Link = Controller::join_links($this->Link(), '?' . http_build_query($params)); + $item->Link = Controller::join_links($this->Link(), '?' . http_build_query($params ?? [])); $items->push(new ArrayData($item)); } } diff --git a/code/Controllers/CMSSiteTreeFilter.php b/code/Controllers/CMSSiteTreeFilter.php index 92e73c2a3b..d73fe96456 100644 --- a/code/Controllers/CMSSiteTreeFilter.php +++ b/code/Controllers/CMSSiteTreeFilter.php @@ -90,7 +90,7 @@ public static function get_all_filters() uasort($filterMap, function ($a, $b) { return ($a === CMSSiteTreeFilter_Search::title()) ? -1 - : strcasecmp($a, $b); + : strcasecmp($a ?? '', $b ?? ''); }); return $filterMap; @@ -164,7 +164,7 @@ protected function populateIDs() while (!empty($parents)) { $q = Versioned::get_including_deleted(SiteTree::class) - ->byIDs(array_keys($parents)); + ->byIDs(array_keys($parents ?? [])); $list = $q->map('ID', 'ParentID'); $parents = []; foreach ($list as $id => $parentID) { diff --git a/code/Controllers/ContentController.php b/code/Controllers/ContentController.php index 19e9eada18..3fcb51f972 100644 --- a/code/Controllers/ContentController.php +++ b/code/Controllers/ContentController.php @@ -156,7 +156,7 @@ protected function init() $getVars = $_GET; unset($getVars['url']); if ($getVars) { - $url = "?" . http_build_query($getVars); + $url = "?" . http_build_query($getVars ?? []); } else { $url = ""; } @@ -494,7 +494,7 @@ public function successfullyinstalled() // TODO Allow this to work when allow_url_fopen=0 if (isset($_SESSION['StatsID']) && $_SESSION['StatsID']) { $url = 'http://ss2stat.silverstripe.com/Installation/installed?ID=' . $_SESSION['StatsID']; - @file_get_contents($url); + @file_get_contents($url ?? ''); } global $project; @@ -532,11 +532,11 @@ public function deleteinstallfiles() $unsuccessful = new ArrayList(); foreach ($installfiles as $installfile) { $installfilepath = PUBLIC_PATH . '/' . $installfile; - if (file_exists($installfilepath)) { - @unlink($installfilepath); + if (file_exists($installfilepath ?? '')) { + @unlink($installfilepath ?? ''); } - if (file_exists($installfilepath)) { + if (file_exists($installfilepath ?? '')) { $unsuccessful->push(new ArrayData(['File' => $installfile])); } } diff --git a/code/Controllers/ModelAsController.php b/code/Controllers/ModelAsController.php index c266b45c42..8f9233ca65 100644 --- a/code/Controllers/ModelAsController.php +++ b/code/Controllers/ModelAsController.php @@ -41,8 +41,8 @@ public static function controller_for(SiteTree $sitetree, $action = null) { $controller = $sitetree->getControllerName(); - if ($action && class_exists($controller . '_' . ucfirst($action))) { - $controller = $controller . '_' . ucfirst($action); + if ($action && class_exists($controller . '_' . ucfirst($action ?? ''))) { + $controller = $controller . '_' . ucfirst($action ?? ''); } return Injector::inst()->create($controller, $sitetree); @@ -131,7 +131,7 @@ public function getNestedController() // url encode unless it's multibyte (already pre-encoded in the database) $filter = URLSegmentFilter::create(); if (!$filter->getAllowMultibyte()) { - $URLSegment = rawurlencode($URLSegment); + $URLSegment = rawurlencode($URLSegment ?? ''); } // Select child page diff --git a/code/Controllers/OldPageRedirector.php b/code/Controllers/OldPageRedirector.php index 52f8ad7331..5e526e1125 100644 --- a/code/Controllers/OldPageRedirector.php +++ b/code/Controllers/OldPageRedirector.php @@ -23,8 +23,8 @@ class OldPageRedirector extends Extension public function onBeforeHTTPError404($request) { // We need to get the URL ourselves because $request->allParams() only has a max of 4 params - $params = preg_split('|/+|', $request->getURL()); - $cleanURL = trim(Director::makeRelative($request->getURL(false)), '/'); + $params = preg_split('|/+|', $request->getURL() ?? ''); + $cleanURL = trim(Director::makeRelative($request->getURL(false)) ?? '', '/'); $getvars = $request->getVars(); unset($getvars['url']); @@ -33,7 +33,7 @@ public function onBeforeHTTPError404($request) if (!$page) { $page = self::find_old_page($params); } - $cleanPage = trim(Director::makeRelative($page), '/'); + $cleanPage = trim(Director::makeRelative($page) ?? '', '/'); if (!$cleanPage) { $cleanPage = Director::makeRelative(RootURLController::get_homepage_link()); } @@ -64,7 +64,7 @@ public static function find_old_page($params, $parent = null, $redirect = false) { $parent = is_numeric($parent) && $parent > 0 ? SiteTree::get()->byID($parent) : $parent; $params = (array)$params; - $URL = rawurlencode(array_shift($params)); + $URL = rawurlencode(array_shift($params) ?? ''); if (empty($URL)) { return false; } @@ -93,7 +93,7 @@ public static function find_old_page($params, $parent = null, $redirect = false) } if ($page && $page->canView()) { - if (count($params)) { + if (count($params ?? [])) { // We have to go deeper! $ret = self::find_old_page($params, $page, $redirect); if ($ret) { diff --git a/code/Controllers/RootURLController.php b/code/Controllers/RootURLController.php index f7641d34e9..e8522989f7 100644 --- a/code/Controllers/RootURLController.php +++ b/code/Controllers/RootURLController.php @@ -56,7 +56,7 @@ public static function get_homepage_link() */ public static function should_be_on_root(SiteTree $page) { - return (!self::$is_at_root && self::get_homepage_link() == trim($page->RelativeLink(true), '/')); + return (!self::$is_at_root && self::get_homepage_link() == trim($page->RelativeLink(true) ?? '', '/')); } /** diff --git a/code/Controllers/SilverStripeNavigator.php b/code/Controllers/SilverStripeNavigator.php index 2f5db31b83..dce05372ab 100644 --- a/code/Controllers/SilverStripeNavigator.php +++ b/code/Controllers/SilverStripeNavigator.php @@ -67,7 +67,7 @@ public function getItems() ksort($items); // Drop the keys and let the ArrayList handle the numbering, so $First, $Last and others work properly. - return new ArrayList(array_values($items)); + return new ArrayList(array_values($items ?? [])); } /** diff --git a/code/Controllers/SilverStripeNavigatorItem_ArchiveLink.php b/code/Controllers/SilverStripeNavigatorItem_ArchiveLink.php index b573b183a6..00dab1379d 100644 --- a/code/Controllers/SilverStripeNavigatorItem_ArchiveLink.php +++ b/code/Controllers/SilverStripeNavigatorItem_ArchiveLink.php @@ -20,7 +20,7 @@ public function getHTML() $linkTitle = _t('SilverStripe\\CMS\\Controllers\\ContentController.ARCHIVEDSITE', 'Preview version'); $recordLink = Convert::raw2att(Controller::join_links( $this->record->AbsoluteLink(), - '?archiveDate=' . urlencode($this->record->LastEdited) + '?archiveDate=' . urlencode($this->record->LastEdited ?? '') )); return "$linkTitle"; } @@ -48,7 +48,7 @@ public function getLink() { return Controller::join_links( $this->record->PreviewLink(), - '?archiveDate=' . urlencode($this->record->LastEdited) + '?archiveDate=' . urlencode($this->record->LastEdited ?? '') ); } diff --git a/code/Forms/SiteTreeURLSegmentField.php b/code/Forms/SiteTreeURLSegmentField.php index 2e3a44b0eb..c493018232 100644 --- a/code/Forms/SiteTreeURLSegmentField.php +++ b/code/Forms/SiteTreeURLSegmentField.php @@ -44,7 +44,7 @@ class SiteTreeURLSegmentField extends TextField public function Value() { - return rawurldecode($this->value); + return rawurldecode($this->value ?? ''); } public function getAttributes() @@ -82,7 +82,7 @@ public function suggest($request) $page->URLSegment = $page->generateURLSegment($request->getVar('value')); $count = 2; while (!$page->validURLSegment()) { - $page->URLSegment = preg_replace('/-[0-9]+$/', '', $page->URLSegment) . '-' . $count; + $page->URLSegment = preg_replace('/-[0-9]+$/', '', $page->URLSegment ?? '') . '-' . $count; $count++; } diff --git a/code/Model/RedirectorPage.php b/code/Model/RedirectorPage.php index 95b0dec3e9..97572142e7 100644 --- a/code/Model/RedirectorPage.php +++ b/code/Model/RedirectorPage.php @@ -173,8 +173,8 @@ protected function onBeforeWrite() { parent::onBeforeWrite(); - if ($this->ExternalURL && substr($this->ExternalURL, 0, 2) !== '//') { - $urlParts = parse_url($this->ExternalURL); + if ($this->ExternalURL && substr($this->ExternalURL ?? '', 0, 2) !== '//') { + $urlParts = parse_url($this->ExternalURL ?? ''); if ($urlParts) { if (empty($urlParts['scheme'])) { // no scheme, assume http diff --git a/code/Model/SiteTree.php b/code/Model/SiteTree.php index 458ec9c52b..e44dc2472c 100755 --- a/code/Model/SiteTree.php +++ b/code/Model/SiteTree.php @@ -430,16 +430,16 @@ public static function get_by_link($link, $cache = true) $urlSegmentExpr = sprintf('"%s"."URLSegment"', $tableName); $parentIDExpr = sprintf('"%s"."ParentID"', $tableName); - $link = trim(Director::makeRelative($link), '/'); + $link = trim(Director::makeRelative($link) ?? '', '/'); if (!$link) { $link = RootURLController::get_homepage_link(); } - $parts = preg_split('|/+|', $link); + $parts = preg_split('|/+|', $link ?? ''); // Grab the initial root level page to traverse down from. $URLSegment = array_shift($parts); - $conditions = [$urlSegmentExpr => rawurlencode($URLSegment)]; + $conditions = [$urlSegmentExpr => rawurlencode($URLSegment ?? '')]; if (self::config()->get('nested_urls')) { $conditions[] = [$parentIDExpr => 0]; } @@ -474,7 +474,7 @@ public static function get_by_link($link, $cache = true) } // Check if we have any more URL parts to parse. - if (!self::config()->get('nested_urls') || !count($parts)) { + if (!self::config()->get('nested_urls') || !count($parts ?? [])) { return $sitetree; } @@ -521,7 +521,7 @@ public static function page_type_classes() { $classes = ClassInfo::getValidSubClasses(); - $baseClassIndex = array_search(self::class, $classes); + $baseClassIndex = array_search(self::class, $classes ?? []); if ($baseClassIndex !== false) { unset($classes[$baseClassIndex]); } @@ -542,10 +542,10 @@ public static function page_type_classes() // If any of the descendents don't want any of the elders to show up, cruelly render the elders surplus to // requirements if ($kill_ancestors) { - $kill_ancestors = array_unique($kill_ancestors); + $kill_ancestors = array_unique($kill_ancestors ?? []); foreach ($kill_ancestors as $mark) { // unset from $classes - $idx = array_search($mark, $classes, true); + $idx = array_search($mark, $classes ?? [], true); if ($idx !== false) { unset($classes[$idx]); } @@ -733,7 +733,7 @@ public function CMSEditLink() */ public function ElementName() { - return str_replace('/', '-', trim($this->RelativeLink(true), '/')); + return str_replace('/', '-', trim($this->RelativeLink(true) ?? '', '/')); } /** @@ -762,7 +762,7 @@ public function isCurrent() public function isSection() { return $this->isCurrent() || ( - Director::get_current_page() instanceof SiteTree && in_array($this->ID, Director::get_current_page()->getAncestors()->column()) + Director::get_current_page() instanceof SiteTree && in_array($this->ID, Director::get_current_page()->getAncestors()->column() ?? []) ); } @@ -931,7 +931,7 @@ public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $sho while ($page && $page->exists() - && (!$maxDepth || count($pages) < $maxDepth) + && (!$maxDepth || count($pages ?? []) < $maxDepth) && (!$stopAtPageType || $page->ClassName != $stopAtPageType) ) { if ($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) { @@ -941,7 +941,7 @@ public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $sho $page = $page->Parent(); } - return new ArrayList(array_reverse($pages)); + return new ArrayList(array_reverse($pages ?? [])); } @@ -1013,7 +1013,7 @@ public function NestedTitle($level = 2, $separator = " - ") $item = $item->getParent(); $level--; } - return implode($separator, array_reverse($parts)); + return implode($separator ?? '', array_reverse($parts ?? [])); } /** @@ -1043,8 +1043,8 @@ public function can($perm, $member = null, $context = []) return true; } - if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) { - $method = 'can' . ucfirst($perm); + if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm ?? ''))) { + $method = 'can' . ucfirst($perm ?? ''); return $this->$method($member); } @@ -1266,7 +1266,7 @@ public function canCreate($member = null, $context = []) // Block children not allowed for this parent type $parent = isset($context['Parent']) ? $context['Parent'] : null; $strictParentInstance = ($parent && $parent instanceof SiteTree); - if ($strictParentInstance && !in_array(static::class, $parent->allowedChildren())) { + if ($strictParentInstance && !in_array(static::class, $parent->allowedChildren() ?? [])) { return false; } @@ -1341,7 +1341,7 @@ public function canEdit($member = null) public function getSiteConfig() { $configs = $this->invokeWithExtensions('alternateSiteConfig'); - foreach (array_filter($configs) as $config) { + foreach (array_filter($configs ?? []) as $config) { return $config; } @@ -1472,7 +1472,7 @@ public function MetaComponents() */ private function getGenerator(): string { - $generator = trim(Config::inst()->get(self::class, 'meta_generator')); + $generator = trim(Config::inst()->get(self::class, 'meta_generator') ?? ''); if ($generator === '') { return ''; } @@ -1480,7 +1480,7 @@ private function getGenerator(): string $version = $this->getVersionProvider()->getModuleVersion('silverstripe/framework'); // Only include stable version numbers so as not to clutter any aggregate reports // with non-standard versions e.g. forks - if (preg_match('#^([0-9]+\.[0-9]+)\.[0-9]+$#', $version, $m)) { + if (preg_match('#^([0-9]+\.[0-9]+)\.[0-9]+$#', $version ?? '', $m)) { $generator .= ' ' . $m[1]; } } @@ -1517,7 +1517,7 @@ public function MetaTags($includeTitle = true) { $tags = []; $tagsArray = $this->MetaComponents(); - if (!$includeTitle || strtolower($includeTitle) == 'false') { + if (!$includeTitle || strtolower($includeTitle ?? '') == 'false') { unset($tagsArray['title']); } @@ -1652,19 +1652,19 @@ protected function onBeforeWrite() // Ensure that this object has a non-conflicting URLSegment value. $count = 2; while (!$this->validURLSegment()) { - $this->URLSegment = preg_replace('/-[0-9]+$/', '', $this->URLSegment) . '-' . $count; + $this->URLSegment = preg_replace('/-[0-9]+$/', '', $this->URLSegment ?? '') . '-' . $count; $count++; } // Check to see if we've only altered fields that shouldn't affect versioning $fieldsIgnoredByVersioning = ['HasBrokenLink', 'Status', 'HasBrokenFile', 'ToDo', 'VersionID', 'SaveCount']; - $changedFields = array_keys($this->getChangedFields(true, 2)); + $changedFields = array_keys($this->getChangedFields(true, 2) ?? []); // This more rigorous check is inline with the test that write() does to decide whether or not to write to the // DB. We use that to avoid cluttering the system with a migrateVersion() call that doesn't get used - $oneChangedFields = array_keys($this->getChangedFields(true, 1)); + $oneChangedFields = array_keys($this->getChangedFields(true, 1) ?? []); - if ($oneChangedFields && !array_diff($changedFields, $fieldsIgnoredByVersioning)) { + if ($oneChangedFields && !array_diff($changedFields ?? [], $fieldsIgnoredByVersioning)) { $this->setNextWriteWithoutVersion(true); } @@ -1755,7 +1755,7 @@ public function validate() $subject = ($this instanceof VirtualPage && $this->CopyContentFromID) ? $this->CopyContentFrom() : $this; - if (!in_array($subject->ClassName, $allowed)) { + if (!in_array($subject->ClassName, $allowed ?? [])) { $result->addError( _t( 'SilverStripe\\CMS\\Model\\SiteTree.PageTypeNotAllowed', @@ -1804,7 +1804,7 @@ public function validURLSegment() return false; } } - } elseif (in_array(strtolower($this->URLSegment), $this->getExcludedURLSegments())) { + } elseif (in_array(strtolower($this->URLSegment ?? ''), $this->getExcludedURLSegments() ?? [])) { // Guard against url segments for the base page // Default to '-2', onBeforeWrite takes care of further possible clashes return false; @@ -2276,7 +2276,7 @@ public function getSettingsFields() $viewerGroupsField->setDescription(_t( 'SilverStripe\\CMS\\Model\\SiteTree.VIEWER_GROUPS_FIELD_DESC', 'Groups with global view permissions: {groupList}', - ['groupList' => implode(', ', array_values($viewAllGroupsMap))] + ['groupList' => implode(', ', array_values($viewAllGroupsMap ?? []))] )); } @@ -2284,7 +2284,7 @@ public function getSettingsFields() $editorGroupsField->setDescription(_t( 'SilverStripe\\CMS\\Model\\SiteTree.EDITOR_GROUPS_FIELD_DESC', 'Groups with global edit permissions: {groupList}', - ['groupList' => implode(', ', array_values($editAllGroupsMap))] + ['groupList' => implode(', ', array_values($editAllGroupsMap ?? []))] )); } @@ -2622,7 +2622,7 @@ public function isNew() return false; } - return stripos($this->ID, 'new') === 0; + return stripos($this->ID ?? '', 'new') === 0; } /** @@ -2673,9 +2673,9 @@ protected function getClassDropdown() if ($currentClass) { $currentPageTypeName = $result[$currentClass]; unset($result[$currentClass]); - $result = array_reverse($result); + $result = array_reverse($result ?? []); $result[$currentClass] = $currentPageTypeName; - $result = array_reverse($result); + $result = array_reverse($result ?? []); } return $result; @@ -2699,7 +2699,7 @@ public function allowedChildren() $candidates = Config::inst()->get($class, 'allowed_children', Config::UNINHERITED); break; } - $class = get_parent_class($class); + $class = get_parent_class($class ?? ''); } if (!$candidates || $candidates === 'none' || $candidates === 'SiteTree_root') { return []; @@ -2710,8 +2710,8 @@ public function allowedChildren() foreach ((array)$candidates as $candidate) { // If a classname is prefixed by "*", such as "*Page", then only that class is allowed - no subclasses. // Otherwise, the class and all its subclasses are allowed. - if (substr($candidate, 0, 1) == '*') { - $allowedChildren[] = substr($candidate, 1); + if (substr($candidate ?? '', 0, 1) == '*') { + $allowedChildren[] = substr($candidate ?? '', 1); } elseif (($candidate !== 'SiteTree_root') && ($subclasses = ClassInfo::subclassesFor($candidate)) ) { @@ -2802,7 +2802,7 @@ public function defaultChild() $default = $this->config()->get('default_child'); $allowed = $this->allowedChildren(); if ($allowed) { - if (!$default || !in_array($default, $allowed)) { + if (!$default || !in_array($default, $allowed ?? [])) { $default = reset($allowed); } return $default; @@ -2929,7 +2929,7 @@ public function getTreeTitle() Convert::raw2htmlid(static::class), $this->isHomePage() ? ' homepage' : '', Convert::raw2att(json_encode($children)), - Convert::raw2xml(str_replace(["\n","\r"], "", $this->MenuTitle)) + Convert::raw2xml(str_replace(["\n","\r"], "", $this->MenuTitle ?? '')) ); foreach ($flags as $class => $data) { if (is_string($data)) { @@ -3143,7 +3143,7 @@ public function getPageIconURL() if (!$icon) { return null; } - if (strpos($icon, 'data:image/') !== false) { + if (strpos($icon ?? '', 'data:image/') !== false) { return $icon; } @@ -3284,15 +3284,15 @@ protected function getExcludedURLSegments() // Build from rules foreach (Director::config()->get('rules') as $pattern => $rule) { - $route = explode('/', $pattern); - if (!empty($route) && strpos($route[0], '$') === false) { - $excludes[] = strtolower($route[0]); + $route = explode('/', $pattern ?? ''); + if (!empty($route) && strpos($route[0] ?? '', '$') === false) { + $excludes[] = strtolower($route[0] ?? ''); } } // Build from base folders foreach (glob(Director::publicFolder() . '/*', GLOB_ONLYDIR) as $folder) { - $excludes[] = strtolower(basename($folder)); + $excludes[] = strtolower(basename($folder ?? '')); } $this->extend('updateExcludedURLSegments', $excludes); @@ -3306,7 +3306,7 @@ public function getAnchorsOnPage() { $parseSuccess = preg_match_all( "/\\s+(name|id)\\s*=\\s*([\"'])([^\\2\\s>]*?)\\2|\\s+(name|id)\\s*=\\s*([^\"']+)[\\s +>]/im", - $this->Content, + $this->Content ?? '', $matches ); diff --git a/code/Model/SiteTreeFolderExtension.php b/code/Model/SiteTreeFolderExtension.php index 05d827ee87..164b66600c 100644 --- a/code/Model/SiteTreeFolderExtension.php +++ b/code/Model/SiteTreeFolderExtension.php @@ -41,7 +41,7 @@ public function getUnusedFilesListFilter() // Get all classes that aren't folder $fileClasses = array_diff_key( - ClassInfo::subclassesFor(File::class), + ClassInfo::subclassesFor(File::class) ?? [], ClassInfo::subclassesFor(Folder::class) ); @@ -58,7 +58,7 @@ public function getUnusedFilesListFilter() $where = []; $columns = []; foreach ($hasOnes as $relName => $joinClass) { - if (in_array($joinClass, $fileClasses)) { + if (in_array($joinClass, $fileClasses ?? [])) { $column = $relName . 'ID'; $columns[] = $column; $quotedColumn = $schema->sqlColumnForField($className, $column); diff --git a/code/Model/SiteTreeLinkTracking.php b/code/Model/SiteTreeLinkTracking.php index c3c2111d5e..c9b53826e0 100644 --- a/code/Model/SiteTreeLinkTracking.php +++ b/code/Model/SiteTreeLinkTracking.php @@ -190,13 +190,13 @@ public function trackLinksInField($fieldName, &$anyBroken = false) protected function toggleElementClass(DOMElement $domReference, $class, $toggle) { // Get all existing classes. - $classes = array_filter(explode(' ', trim($domReference->getAttribute('class')))); + $classes = array_filter(explode(' ', trim($domReference->getAttribute('class') ?? ''))); // Add or remove the broken class from the link, depending on the link status. if ($toggle) { $classes = array_unique(array_merge($classes, [$class])); } else { - $classes = array_diff($classes, [$class]); + $classes = array_diff($classes ?? [], [$class]); } if (!empty($classes)) { diff --git a/code/Model/SiteTreeLinkTracking_Parser.php b/code/Model/SiteTreeLinkTracking_Parser.php index 16ac823b04..857c6c12ab 100644 --- a/code/Model/SiteTreeLinkTracking_Parser.php +++ b/code/Model/SiteTreeLinkTracking_Parser.php @@ -59,7 +59,7 @@ public function process(HTMLValue $htmlValue) // Link to a page on this site. $matches = []; - if (preg_match('/\[sitetree_link(?:\s*|%20|,)?id=(?[0-9]+)\](#(?.*))?/i', $href, $matches)) { + if (preg_match('/\[sitetree_link(?:\s*|%20|,)?id=(?[0-9]+)\](#(?.*))?/i', $href ?? '', $matches)) { // Check if page link is broken /** @var SiteTree $page */ $page = DataObject::get_by_id(SiteTree::class, $matches['id']); @@ -68,7 +68,7 @@ public function process(HTMLValue $htmlValue) $broken = true; } elseif (!empty($matches['anchor'])) { // Ensure anchor isn't broken on target page - $broken = !in_array($matches['anchor'], $page->getAnchorsOnPage()); + $broken = !in_array($matches['anchor'], $page->getAnchorsOnPage() ?? []); } else { $broken = false; } @@ -85,14 +85,14 @@ public function process(HTMLValue $htmlValue) } // Local anchor. - if (preg_match('/^#(.*)/i', $href, $matches)) { - $anchor = preg_quote($matches[1], '#'); + if (preg_match('/^#(.*)/i', $href ?? '', $matches)) { + $anchor = preg_quote($matches[1] ?? '', '#'); $results[] = [ 'Type' => 'localanchor', 'Target' => null, 'Anchor' => $matches[1], 'DOMReference' => $link, - 'Broken' => !preg_match("#(name|id)=\"{$anchor}\"#", $htmlValue->getContent()) + 'Broken' => !preg_match("#(name|id)=\"{$anchor}\"#", $htmlValue->getContent() ?? '') ]; continue; diff --git a/code/Model/VirtualPage.php b/code/Model/VirtualPage.php index 2219225b95..dd4187cc01 100644 --- a/code/Model/VirtualPage.php +++ b/code/Model/VirtualPage.php @@ -96,9 +96,9 @@ public function getVirtualFields() } // Diff db with non-virtual fields - $fields = array_keys(static::getSchema()->fieldSpecs($record)); + $fields = array_keys(static::getSchema()->fieldSpecs($record) ?? []); $nonVirtualFields = $this->getNonVirtualisedFields(); - return array_diff($fields, $nonVirtualFields); + return array_diff($fields ?? [], $nonVirtualFields); } /** @@ -448,7 +448,7 @@ public function isFieldVirtualised($field) { // Don't defer if field is non-virtualised $ignore = $this->getNonVirtualisedFields(); - if (in_array($field, $ignore)) { + if (in_array($field, $ignore ?? [])) { return false; } @@ -474,7 +474,7 @@ public function __call($method, $args) if (parent::hasMethod($method)) { return parent::__call($method, $args); } else { - return call_user_func_array([$this->CopyContentFrom(), $method], $args); + return call_user_func_array([$this->CopyContentFrom(), $method], $args ?? []); } } diff --git a/code/Reports/BrokenFilesReport.php b/code/Reports/BrokenFilesReport.php index 3b1bfcc7cf..609428c328 100644 --- a/code/Reports/BrokenFilesReport.php +++ b/code/Reports/BrokenFilesReport.php @@ -29,7 +29,7 @@ public function sourceRecords($params = null) { // Get class names for page types that are not virtual pages or redirector pages $classes = array_diff( - ClassInfo::subclassesFor(SiteTree::class), + ClassInfo::subclassesFor(SiteTree::class) ?? [], ClassInfo::subclassesFor(VirtualPage::class), ClassInfo::subclassesFor(RedirectorPage::class) ); diff --git a/code/Reports/BrokenLinksReport.php b/code/Reports/BrokenLinksReport.php index 796df87447..4490658ab1 100644 --- a/code/Reports/BrokenLinksReport.php +++ b/code/Reports/BrokenLinksReport.php @@ -33,7 +33,7 @@ public function sourceRecords($params, $sort, $limit) $join = ''; $sortBrokenReason = false; if ($sort) { - $parts = explode(' ', $sort); + $parts = explode(' ', $sort ?? ''); $field = $parts[0]; $direction = $parts[1]; @@ -93,7 +93,7 @@ public function sourceRecords($params, $sort, $limit) } if ($reason) { - if (isset($params['Reason']) && $params['Reason'] && !in_array($params['Reason'], $reasonCodes)) { + if (isset($params['Reason']) && $params['Reason'] && !in_array($params['Reason'], $reasonCodes ?? [])) { continue; } $record->BrokenReason = $reason; diff --git a/code/Search/SearchForm.php b/code/Search/SearchForm.php index 12f81534db..7bb6654e2e 100644 --- a/code/Search/SearchForm.php +++ b/code/Search/SearchForm.php @@ -98,14 +98,14 @@ public function __construct( public function classesToSearch($classes) { $supportedClasses = [SiteTree::class, File::class]; - $illegalClasses = array_diff($classes, $supportedClasses); + $illegalClasses = array_diff($classes ?? [], $supportedClasses); if ($illegalClasses) { throw new BadMethodCallException( "SearchForm::classesToSearch() passed illegal classes '" . implode("', '", $illegalClasses) . "'. At this stage, only File and SiteTree are allowed" ); } - $legalClasses = array_intersect($classes, $supportedClasses); + $legalClasses = array_intersect($classes ?? [], $supportedClasses); $this->classesToSearch = $legalClasses; } @@ -155,10 +155,10 @@ public function getResults() return ' -' . $matches[3]; }; - $keywords = preg_replace_callback('/()("[^()"]+")( and )("[^"()]+")()/i', $andProcessor, $keywords); - $keywords = preg_replace_callback('/(^| )([^() ]+)( and )([^ ()]+)( |$)/i', $andProcessor, $keywords); - $keywords = preg_replace_callback('/(^| )(not )("[^"()]+")/i', $notProcessor, $keywords); - $keywords = preg_replace_callback('/(^| )(not )([^() ]+)( |$)/i', $notProcessor, $keywords); + $keywords = preg_replace_callback('/()("[^()"]+")( and )("[^"()]+")()/i', $andProcessor, $keywords ?? ''); + $keywords = preg_replace_callback('/(^| )([^() ]+)( and )([^ ()]+)( |$)/i', $andProcessor, $keywords ?? ''); + $keywords = preg_replace_callback('/(^| )(not )("[^"()]+")/i', $notProcessor, $keywords ?? ''); + $keywords = preg_replace_callback('/(^| )(not )([^() ]+)( |$)/i', $notProcessor, $keywords ?? ''); $keywords = $this->addStarsToKeywords($keywords); @@ -166,10 +166,10 @@ public function getResults() $start = max(0, (int)$request->requestVar('start')); $booleanSearch = - strpos($keywords, '"') !== false || - strpos($keywords, '+') !== false || - strpos($keywords, '-') !== false || - strpos($keywords, '*') !== false; + strpos($keywords ?? '', '"') !== false || + strpos($keywords ?? '', '+') !== false || + strpos($keywords ?? '', '-') !== false || + strpos($keywords ?? '', '*') !== false; $results = DB::get_conn()->searchEngine($this->classesToSearch, $keywords, $start, $pageLength, "\"Relevance\" DESC", "", $booleanSearch); // filter by permission @@ -197,19 +197,19 @@ public function getResults() protected function addStarsToKeywords($keywords) { - if (!trim($keywords)) { + if (!trim($keywords ?? '')) { return ""; } // Add * to each keyword - $splitWords = preg_split("/ +/", trim($keywords)); + $splitWords = preg_split("/ +/", trim($keywords ?? '')); $newWords = []; - for ($i = 0; $i < count($splitWords); $i++) { + for ($i = 0; $i < count($splitWords ?? []); $i++) { $word = $splitWords[$i]; if ($word[0] == '"') { - while (++$i < count($splitWords)) { + while (++$i < count($splitWords ?? [])) { $subword = $splitWords[$i]; $word .= ' ' . $subword; - if (substr($subword, -1) == '"') { + if (substr($subword ?? '', -1) == '"') { break; } } diff --git a/tests/behat/src/LoginContext.php b/tests/behat/src/LoginContext.php index 93d982a879..44fb3c04fc 100644 --- a/tests/behat/src/LoginContext.php +++ b/tests/behat/src/LoginContext.php @@ -25,7 +25,7 @@ public function pagesShouldBeEditableBy($negative, $permCode) $email = "{$permCode}@example.org"; $password = 'Password!456'; $member = $this->generateMemberWithPermission($email, $password, $permCode); - $canEdit = strstr($negative, 'not') ? false : true; + $canEdit = strstr($negative ?? '', 'not') ? false : true; if ($canEdit) { Assert::assertTrue($page->canEdit($member), 'The member can edit this page'); diff --git a/tests/behat/src/ThemeContext.php b/tests/behat/src/ThemeContext.php index a7dc6a6d0f..ead1f8265d 100644 --- a/tests/behat/src/ThemeContext.php +++ b/tests/behat/src/ThemeContext.php @@ -23,7 +23,7 @@ class ThemeContext implements Context */ public function stepCreateTheme($theme) { - if (!preg_match('/^[0-9a-zA-Z_-]+$/', $theme)) { + if (!preg_match('/^[0-9a-zA-Z_-]+$/', $theme ?? '')) { throw new \InvalidArgumentException("Bad theme '$theme'"); } @@ -42,10 +42,10 @@ public function stepCreateTheme($theme) */ public function stepCreateTemplate($template, $theme, $content) { - if (!preg_match('/^[0-9a-zA-Z_-]+$/', $theme)) { + if (!preg_match('/^[0-9a-zA-Z_-]+$/', $theme ?? '')) { throw new \InvalidArgumentException("Bad theme '$theme'"); } - if (!preg_match('/^(Layout\/)?[0-9a-zA-Z_-]+\.ss$/', $template)) { + if (!preg_match('/^(Layout\/)?[0-9a-zA-Z_-]+\.ss$/', $template ?? '')) { throw new \InvalidArgumentException("Bad template '$template'"); } @@ -56,16 +56,16 @@ public function stepCreateTemplate($template, $theme, $content) protected function requireFile($filename, $content) { // Already exists - if (file_exists($filename)) { + if (file_exists($filename ?? '')) { // If the content is different, remember old content for restoration - $origContent = file_get_contents($filename); + $origContent = file_get_contents($filename ?? ''); if ($origContent != $content) { - file_put_contents($filename, $content); + file_put_contents($filename ?? '', $content); $this->restoreFiles[$filename] = $origContent; } // Doesn't exist, mark it for deletion after test } else { - file_put_contents($filename, $content); + file_put_contents($filename ?? '', $content); $this->restoreFiles[$filename] = null; } } @@ -73,8 +73,8 @@ protected function requireFile($filename, $content) protected function requireDir($dirname) { // Directory doesn't exist, create it and mark it for deletion - if (!file_exists($dirname)) { - mkdir($dirname); + if (!file_exists($dirname ?? '')) { + mkdir($dirname ?? ''); $this->restoreDirectories[] = $dirname; } } @@ -92,9 +92,9 @@ public function cleanThemesAfterScenario() if ($this->restoreFiles) { foreach ($this->restoreFiles as $file => $origContent) { if ($origContent === null) { - unlink($file); + unlink($file ?? ''); } else { - file_put_contents($file, $origContent); + file_put_contents($file ?? '', $origContent); } } @@ -104,9 +104,9 @@ public function cleanThemesAfterScenario() // Restore any created directories: that is, delete them if ($this->restoreDirectories) { // Flip the order so that nested direcotires are unlinked() first - $this->restoreDirectories = array_reverse($this->restoreDirectories); + $this->restoreDirectories = array_reverse($this->restoreDirectories ?? []); foreach ($this->restoreDirectories as $dir) { - rmdir($dir); + rmdir($dir ?? ''); } $this->restoreDirectories = []; diff --git a/tests/bootstrap/app.php b/tests/bootstrap/app.php index 41372cf8d9..e8412b0fed 100644 --- a/tests/bootstrap/app.php +++ b/tests/bootstrap/app.php @@ -6,8 +6,8 @@ } else { $projectPath = getcwd() . '/app'; } -if (!is_dir($projectPath)) { - mkdir($projectPath, 02775); +if (!is_dir($projectPath ?? '')) { + mkdir($projectPath ?? '', 02775); mkdir($projectPath . '/code', 02775); mkdir($projectPath . '/_config', 02775); copy(__DIR__ . '/fixtures/Page.php.fixture', $projectPath . '/code/Page.php'); diff --git a/tests/php/Controllers/CMSBatchActionsTest.php b/tests/php/Controllers/CMSBatchActionsTest.php index 441e18b2f8..9a079b8073 100644 --- a/tests/php/Controllers/CMSBatchActionsTest.php +++ b/tests/php/Controllers/CMSBatchActionsTest.php @@ -142,7 +142,7 @@ public function testBatchRestore() $this->assertEquals($archivedID, $list->first()->ParentID); // Run restore - $result = json_decode($action->run($list), true); + $result = json_decode($action->run($list) ?? '', true); $this->assertEquals( [ $archivedxID => $archivedxID @@ -162,7 +162,7 @@ public function testBatchRestore() $this->assertEquals(0, $list->last()->ParentID); // archived (parent) // Run restore - $result = json_decode($action->run($list), true); + $result = json_decode($action->run($list) ?? '', true); $this->assertEquals( [ // Order of archived is opposite to order items are passed in, as diff --git a/tests/php/Controllers/CMSMainTest.php b/tests/php/Controllers/CMSMainTest.php index 6584f0b8d8..f61158f427 100644 --- a/tests/php/Controllers/CMSMainTest.php +++ b/tests/php/Controllers/CMSMainTest.php @@ -56,8 +56,8 @@ public function testSiteTreeHints() $rawHints = singleton(CMSMain::class)->SiteTreeHints(); $this->assertNotNull($rawHints); - $rawHints = preg_replace('/^"(.*)"$/', '$1', Convert::xml2raw($rawHints)); - $hints = json_decode($rawHints, true); + $rawHints = preg_replace('/^"(.*)"$/', '$1', Convert::xml2raw($rawHints) ?? ''); + $hints = json_decode($rawHints ?? '', true); $this->assertArrayHasKey('Root', $hints); $this->assertArrayHasKey('Page', $hints); @@ -100,7 +100,7 @@ public function testChildFilter() // Check query $response = $this->get('admin/pages/childfilter?ParentID=' . $pageA->ID); - $children = json_decode($response->getBody()); + $children = json_decode($response->getBody() ?? ''); $this->assertFalse($response->isError()); // Page A can't have unrelated children @@ -137,7 +137,7 @@ public function testPublish() $actions = CMSBatchActionHandler::config()->batch_actions; if (isset($actions['publish'])) { $response = $this->get('admin/pages/batchactions/publish?ajax=1&csvIDs=' . implode(',', [$page1->ID, $page2->ID])); - $responseData = json_decode($response->getBody(), true); + $responseData = json_decode($response->getBody() ?? '', true); $this->assertArrayHasKey($page1->ID, $responseData['modified']); $this->assertArrayHasKey($page2->ID, $responseData['modified']); } @@ -335,7 +335,7 @@ public function testCreationOfRestrictedPage() ] ); $this->assertFalse($response->isError()); - $ok = preg_match('/edit\/show\/(\d*)/', $response->getHeader('X-ControllerURL'), $matches); + $ok = preg_match('/edit\/show\/(\d*)/', $response->getHeader('X-ControllerURL') ?? '', $matches); $this->assertNotEmpty($ok); $newPageId = $matches[1]; @@ -360,7 +360,7 @@ public function testCreationOfRestrictedPage() // Verify that the page was created and redirected to accurately $newerPage = SiteTree::get()->byID($newPageId)->AllChildren()->first(); $this->assertNotEmpty($newerPage); - $ok = preg_match('/edit\/show\/(\d*)/', $response->getHeader('X-ControllerURL'), $matches); + $ok = preg_match('/edit\/show\/(\d*)/', $response->getHeader('X-ControllerURL') ?? '', $matches); $this->assertNotEmpty($ok); $newerPageID = $matches[1]; $this->assertEquals($newerPage->ID, $newerPageID); @@ -398,7 +398,7 @@ public function testBreadcrumbs() $crumbs = $parser->getBySelector('.breadcrumbs-wrapper .crumb'); $this->assertNotNull($crumbs); - $this->assertEquals(2, count($crumbs)); + $this->assertEquals(2, count($crumbs ?? [])); $this->assertEquals('Page 3', (string)$crumbs[0]); $this->assertEquals('Page 3.1', (string)$crumbs[1]); diff --git a/tests/php/Controllers/CMSPageHistoryControllerTest.php b/tests/php/Controllers/CMSPageHistoryControllerTest.php index 18ef6d7a7d..40d564b500 100755 --- a/tests/php/Controllers/CMSPageHistoryControllerTest.php +++ b/tests/php/Controllers/CMSPageHistoryControllerTest.php @@ -112,7 +112,7 @@ public function testVersionsForm() $form = $this->cssParser()->getBySelector('#Form_VersionsForm'); - $this->assertEquals(1, count($form)); + $this->assertEquals(1, count($form ?? [])); // check the page ID is present $hidden = $form[0]->xpath("fieldset/input[@type='hidden']"); @@ -122,7 +122,7 @@ public function testVersionsForm() // ensure that all the versions are present in the table and displayed $rows = $form[0]->xpath("fieldset/table/tbody/tr"); - $this->assertEquals(4, count($rows)); + $this->assertEquals(4, count($rows ?? [])); } public function testVersionsFormTableContainsInformation() diff --git a/tests/php/Controllers/CMSSiteTreeFilterTest.php b/tests/php/Controllers/CMSSiteTreeFilterTest.php index 9946894f1f..b76688f252 100644 --- a/tests/php/Controllers/CMSSiteTreeFilterTest.php +++ b/tests/php/Controllers/CMSSiteTreeFilterTest.php @@ -40,7 +40,7 @@ public function testSearchFilterByTitle() $this->assertTrue($f->isPageIncluded($page1)); $this->assertFalse($f->isPageIncluded($page2)); - $this->assertEquals(1, count($results)); + $this->assertEquals(1, count($results ?? [])); $this->assertEquals( ['ID' => $page1->ID, 'ParentID' => 0], $results[0] @@ -68,7 +68,7 @@ public function testIncludesParentsForNestedMatches() $this->assertTrue($f->isPageIncluded($parent)); $this->assertTrue($f->isPageIncluded($child)); - $this->assertEquals(1, count($results)); + $this->assertEquals(1, count($results ?? [])); $this->assertEquals( ['ID' => $child->ID, 'ParentID' => $parent->ID], $results[0] @@ -95,7 +95,7 @@ public function testChangedPagesFilter() $this->assertTrue($f->isPageIncluded($changedPage)); $this->assertFalse($f->isPageIncluded($unchangedPage)); - $this->assertEquals(1, count($results)); + $this->assertEquals(1, count($results ?? [])); $this->assertEquals( ['ID' => $changedPage->ID, 'ParentID' => 0], $results[0] @@ -104,7 +104,7 @@ public function testChangedPagesFilter() // Check that only changed pages are returned $f = new CMSSiteTreeFilter_ChangedPages(['Term' => 'No Matches']); $results = $f->pagesIncluded(); - $this->assertEquals(0, count($results)); + $this->assertEquals(0, count($results ?? [])); // If we roll back to an earlier version than what's on the published site, we should still show the changed $changedPage->Title = 'Changed 2'; @@ -115,7 +115,7 @@ public function testChangedPagesFilter() $f = new CMSSiteTreeFilter_ChangedPages(['Term' => 'Changed']); $results = $f->pagesIncluded(); - $this->assertEquals(1, count($results)); + $this->assertEquals(1, count($results ?? [])); $this->assertEquals(['ID' => $changedPage->ID, 'ParentID' => 0], $results[0]); } @@ -166,7 +166,7 @@ public function testDateFromToLastSameDate() { $draftPage = $this->objFromFixture('Page', 'page4'); // Grab the date - $date = substr($draftPage->LastEdited, 0, 10); + $date = substr($draftPage->LastEdited ?? '', 0, 10); // Filter with that date $filter = new CMSSiteTreeFilter_Search([ 'LastEditedFrom' => $date, diff --git a/tests/php/Controllers/CMSTreeTest.php b/tests/php/Controllers/CMSTreeTest.php index f4743c8376..c17b75cd33 100644 --- a/tests/php/Controllers/CMSTreeTest.php +++ b/tests/php/Controllers/CMSTreeTest.php @@ -98,7 +98,7 @@ public function testUpdateTreeNodes() $result = $this->get('admin/pages/edit/updatetreenodes?ids='.$page1->ID); $this->assertEquals(200, $result->getStatusCode()); $this->assertEquals('application/json', $result->getHeader('Content-Type')); - $data = json_decode($result->getBody(), true); + $data = json_decode($result->getBody() ?? '', true); $pageData = $data[$page1->ID]; $this->assertEquals(0, $pageData['ParentID']); $this->assertEquals($page2->ID, $pageData['NextID']); @@ -108,7 +108,7 @@ public function testUpdateTreeNodes() $result = $this->get('admin/pages/edit/updatetreenodes?ids='.$page31->ID); $this->assertEquals(200, $result->getStatusCode()); $this->assertEquals('application/json', $result->getHeader('Content-Type')); - $data = json_decode($result->getBody(), true); + $data = json_decode($result->getBody() ?? '', true); $pageData = $data[$page31->ID]; $this->assertEquals($page3->ID, $pageData['ParentID']); $this->assertEquals($page32->ID, $pageData['NextID']); @@ -118,14 +118,14 @@ public function testUpdateTreeNodes() $result = $this->get('admin/pages/edit/updatetreenodes?ids='.$page1->ID.','.$page2->ID); $this->assertEquals(200, $result->getStatusCode()); $this->assertEquals('application/json', $result->getHeader('Content-Type')); - $data = json_decode($result->getBody(), true); - $this->assertEquals(2, count($data)); + $data = json_decode($result->getBody() ?? '', true); + $this->assertEquals(2, count($data ?? [])); // Invalid IDs $result = $this->get('admin/pages/edit/updatetreenodes?ids=-3'); $this->assertEquals(200, $result->getStatusCode()); $this->assertEquals('application/json', $result->getHeader('Content-Type')); - $data = json_decode($result->getBody(), true); - $this->assertEquals(0, count($data)); + $data = json_decode($result->getBody() ?? '', true); + $this->assertEquals(0, count($data ?? [])); } } diff --git a/tests/php/Controllers/ContentControllerTest.php b/tests/php/Controllers/ContentControllerTest.php index b094c9d90a..e6acd9b5a8 100755 --- a/tests/php/Controllers/ContentControllerTest.php +++ b/tests/php/Controllers/ContentControllerTest.php @@ -172,7 +172,7 @@ public function testGetViewer() $page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); $response = $this->get($page->RelativeLink()); - $this->assertEquals("ContentControllerTestPageWithoutController", trim($response->getBody())); + $this->assertEquals("ContentControllerTestPageWithoutController", trim($response->getBody() ?? '')); // // This should fall over to user Page.ss $page = new ContentControllerTestPage(); @@ -181,7 +181,7 @@ public function testGetViewer() $page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); $response = $this->get($page->RelativeLink()); - $this->assertEquals("Page", trim($response->getBody())); + $this->assertEquals("Page", trim($response->getBody() ?? '')); // Test that the action template is rendered. @@ -191,12 +191,12 @@ public function testGetViewer() $page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); $response = $this->get($page->RelativeLink("test")); - $this->assertEquals("ContentControllerTestPage_test", trim($response->getBody())); + $this->assertEquals("ContentControllerTestPage_test", trim($response->getBody() ?? '')); // Test that an action without a template will default to the index template, which is // to say the default Page.ss template $response = $this->get($page->RelativeLink("testwithouttemplate")); - $this->assertEquals("Page", trim($response->getBody())); + $this->assertEquals("Page", trim($response->getBody() ?? '')); // Test that an action with a template will render the both action template *and* the // correct parent template diff --git a/tests/php/Controllers/SilverStripeNavigatorTest.php b/tests/php/Controllers/SilverStripeNavigatorTest.php index bfb3f7eece..18fd5832e6 100644 --- a/tests/php/Controllers/SilverStripeNavigatorTest.php +++ b/tests/php/Controllers/SilverStripeNavigatorTest.php @@ -23,7 +23,7 @@ public function testGetItems() $navigator = new SilverStripeNavigator($page); $items = $navigator->getItems(); - $classes = array_map('get_class', $items->toArray()); + $classes = array_map('get_class', $items->toArray() ?? []); $this->assertContains( SilverStripeNavigatorItem_StageLink::class, $classes, @@ -48,18 +48,18 @@ public function testCanView() // TODO Shouldn't be necessary but SapphireTest logs in as ADMIN by default $this->logInWithPermission('CMS_ACCESS_CMSMain'); $items = $navigator->getItems(); - $classes = array_map('get_class', $items->toArray()); + $classes = array_map('get_class', $items->toArray() ?? []); $this->assertNotContains(SilverStripeNavigatorTest_ProtectedTestItem::class, $classes); $this->logInWithPermission('ADMIN'); $items = $navigator->getItems(); - $classes = array_map('get_class', $items->toArray()); + $classes = array_map('get_class', $items->toArray() ?? []); $this->assertContains(SilverStripeNavigatorTest_ProtectedTestItem::class, $classes); // Unversioned record shouldn't be viewable in stage / live specific views $unversioned = new SilverStripeNavigatorTest\UnstagedRecord(); $navigator2 = new SilverStripeNavigator($unversioned); - $classes = array_map('get_class', $navigator2->getItems()->toArray()); + $classes = array_map('get_class', $navigator2->getItems()->toArray() ?? []); $this->assertNotContains(SilverStripeNavigatorItem_LiveLink::class, $classes); $this->assertNotContains(SilverStripeNavigatorItem_StageLink::class, $classes); $this->assertNotContains(SilverStripeNavigatorItem_ArchiveLink::class, $classes); diff --git a/tests/php/GraphQL/LinkablePluginTest.php b/tests/php/GraphQL/LinkablePluginTest.php index 6c832ec460..2687a39337 100644 --- a/tests/php/GraphQL/LinkablePluginTest.php +++ b/tests/php/GraphQL/LinkablePluginTest.php @@ -78,8 +78,8 @@ public function testResolver() $this->assertTrue($result->exists()); $this->assertCount(2, $result); $titles = $result->column('Title'); - $this->assertTrue(in_array('Test page', $titles)); - $this->assertTrue(in_array('Other test page', $titles)); + $this->assertTrue(in_array('Test page', $titles ?? [])); + $this->assertTrue(in_array('Other test page', $titles ?? [])); $result = LinkablePlugin::applyLinkFilter( 'test', diff --git a/tests/php/Model/SiteTreeBacklinksTest.php b/tests/php/Model/SiteTreeBacklinksTest.php index dc0a285150..927586db48 100644 --- a/tests/php/Model/SiteTreeBacklinksTest.php +++ b/tests/php/Model/SiteTreeBacklinksTest.php @@ -37,8 +37,8 @@ protected function setUp(): void $page3 = $this->objFromFixture('Page', 'page3'); $page3->Content = str_replace( '$page1.ID', - $this->objFromFixture('Page', 'page1')->ID, - $page3->Content + $this->objFromFixture('Page', 'page1')->ID ?? '', + $page3->Content ?? '' ); $page3->write(); } diff --git a/tests/php/Model/SiteTreeHTMLEditorFieldTest.php b/tests/php/Model/SiteTreeHTMLEditorFieldTest.php index a3daa927d6..d2324b45b1 100644 --- a/tests/php/Model/SiteTreeHTMLEditorFieldTest.php +++ b/tests/php/Model/SiteTreeHTMLEditorFieldTest.php @@ -26,8 +26,8 @@ protected function setUp(): void $files = File::get()->exclude('ClassName', Folder::class); foreach ($files as $file) { $destPath = TestAssetStore::getLocalPath($file); - Filesystem::makeFolder(dirname($destPath)); - file_put_contents($destPath, str_repeat('x', 1000000)); + Filesystem::makeFolder(dirname($destPath ?? '')); + file_put_contents($destPath ?? '', str_repeat('x', 1000000)); } // Ensure all pages are published diff --git a/tests/php/Model/SiteTreeLinkTrackingTest.php b/tests/php/Model/SiteTreeLinkTrackingTest.php index 5d0c50c81c..4247eee184 100644 --- a/tests/php/Model/SiteTreeLinkTrackingTest.php +++ b/tests/php/Model/SiteTreeLinkTrackingTest.php @@ -81,11 +81,11 @@ protected function highlight($content) public function testHighlighter() { $content = $this->highlight('link'); - $this->assertEquals(substr_count($content, 'ss-broken'), 1, 'A ss-broken class is added to the broken link.'); - $this->assertEquals(substr_count($content, 'existing-class'), 1, 'Existing class is not removed.'); + $this->assertEquals(substr_count($content ?? '', 'ss-broken'), 1, 'A ss-broken class is added to the broken link.'); + $this->assertEquals(substr_count($content ?? '', 'existing-class'), 1, 'Existing class is not removed.'); $content = $this->highlight('link'); - $this->assertEquals(substr_count($content, 'ss-broken'), 1, 'ss-broken class is added to the broken link.'); + $this->assertEquals(substr_count($content ?? '', 'ss-broken'), 1, 'ss-broken class is added to the broken link.'); $otherPage = new Page(); $otherPage->Content = ''; @@ -94,7 +94,7 @@ public function testHighlighter() $content = $this->highlight( "ID]\" class=\"existing-class ss-broken ss-broken\">link" ); - $this->assertEquals(substr_count($content, 'ss-broken'), 0, 'All ss-broken classes are removed from good link'); - $this->assertEquals(substr_count($content, 'existing-class'), 1, 'Existing class is not removed.'); + $this->assertEquals(substr_count($content ?? '', 'ss-broken'), 0, 'All ss-broken classes are removed from good link'); + $this->assertEquals(substr_count($content ?? '', 'existing-class'), 1, 'Existing class is not removed.'); } } diff --git a/tests/php/Model/SiteTreeTest.php b/tests/php/Model/SiteTreeTest.php index f801b7a532..0728ba4a14 100644 --- a/tests/php/Model/SiteTreeTest.php +++ b/tests/php/Model/SiteTreeTest.php @@ -146,7 +146,7 @@ public function testDisallowedURLGeneration($title, $urlSegment) public function testDisallowedChildURLGeneration($title, $urlSegment) { // Using the same dataprovider, strip out the -2 from the admin and dev segment - $urlSegment = str_replace('-2', '', $urlSegment); + $urlSegment = str_replace('-2', '', $urlSegment ?? ''); $page = Page::create(['Title' => $title, 'ParentID' => 1]); $id = $page->write(); $page = Page::get()->byID($id); @@ -821,9 +821,9 @@ public function testCompareVersions() $diff = $page->compareVersions(1, 2); - $processedContent = trim($diff->Content); - $processedContent = preg_replace('/\s*\s*/', '>', $processedContent); + $processedContent = trim($diff->Content ?? ''); + $processedContent = preg_replace('/\s*\s*/', '>', $processedContent ?? ''); $this->assertEquals("This is a test", $processedContent); Diff::$html_cleaner_class = $oldCleanerClass; @@ -1485,7 +1485,7 @@ public function testMetaComponents() // test the meta generator tag version can be configured off Config::modify()->set(SiteTree::class, 'show_meta_generator_version', false); $content = $expected['generator']['attributes']['content']; - $expected['generator']['attributes']['content'] = str_replace(' 4.50', '', $content); + $expected['generator']['attributes']['content'] = str_replace(' 4.50', '', $content ?? ''); $this->assertEquals($expected, $page->MetaComponents()); } diff --git a/tests/php/Model/VirtualPageTest_TestDBField.php b/tests/php/Model/VirtualPageTest_TestDBField.php index f9f602225f..5554567ff3 100644 --- a/tests/php/Model/VirtualPageTest_TestDBField.php +++ b/tests/php/Model/VirtualPageTest_TestDBField.php @@ -9,6 +9,6 @@ class VirtualPageTest_TestDBField extends DBVarchar implements TestOnly { public function forTemplate() { - return strtoupper($this->XML()); + return strtoupper($this->XML() ?? ''); } } diff --git a/tests/php/Reports/CmsReportsTest.php b/tests/php/Reports/CmsReportsTest.php index 6132eb3089..ffb8fdaaaa 100644 --- a/tests/php/Reports/CmsReportsTest.php +++ b/tests/php/Reports/CmsReportsTest.php @@ -52,12 +52,12 @@ public function isReportBroken($report, $isDraftBroken, $isPublishedBroken) // ASSERT that the "draft" report is returning the correct results. $parameters = ['CheckSite' => 'Draft']; - $results = count($report->sourceRecords($parameters, null, null)) > 0; + $results = count($report->sourceRecords($parameters, null, null) ?? []) > 0; $isDraftBroken ? $this->assertTrue($results, "{$class} has NOT returned the correct DRAFT results, as NO pages were found.") : $this->assertFalse($results, "{$class} has NOT returned the correct DRAFT results, as pages were found."); // ASSERT that the "published" report is returning the correct results. $parameters = ['CheckSite' => 'Published', 'OnLive' => 1]; - $results = count($report->sourceRecords($parameters, null, null)) > 0; + $results = count($report->sourceRecords($parameters, null, null) ?? []) > 0; $isPublishedBroken ? $this->assertTrue($results, "{$class} has NOT returned the correct PUBLISHED results, as NO pages were found.") : $this->assertFalse($results, "{$class} has NOT returned the correct PUBLISHED results, as pages were found."); } @@ -124,7 +124,7 @@ public function testBrokenLinks() // Correct the "draft" broken link. - $page->Content = str_replace('987654321', $page->ID, $page->Content); + $page->Content = str_replace('987654321', $page->ID ?? '', $page->Content ?? ''); $page->writeToStage('Stage'); // ASSERT that the "draft" report has NOT detected the page having a broken link. @@ -191,7 +191,7 @@ public function testBrokenFiles() $file = File::create(); $file->Filename = 'name.pdf'; $file->write(); - $page->Content = str_replace('987654321', $file->ID, $page->Content); + $page->Content = str_replace('987654321', $file->ID ?? '', $page->Content ?? ''); $page->writeToStage('Stage'); // ASSERT that the "draft" report has NOT detected the page having a broken file. diff --git a/tests/php/Search/CMSMainSearchFormTest.php b/tests/php/Search/CMSMainSearchFormTest.php index a59ad26a0f..9835552a43 100644 --- a/tests/php/Search/CMSMainSearchFormTest.php +++ b/tests/php/Search/CMSMainSearchFormTest.php @@ -25,7 +25,7 @@ public function testTitleFilter() ); $titles = $this->getPageTitles(); - $this->assertEquals(count($titles), 1); + $this->assertEquals(count($titles ?? []), 1); // For some reason the title gets split into two lines $this->assertStringContainsString('Page 1', $titles[0]); @@ -37,7 +37,7 @@ protected function getPageTitles() $links = $this->cssParser()->getBySelector('.col-getTreeTitle span.item'); if ($links) { foreach ($links as $link) { - $titles[] = preg_replace('/\n/', ' ', $link->asXML()); + $titles[] = preg_replace('/\n/', ' ', $link->asXML() ?? ''); } } return $titles; diff --git a/tests/php/Tasks/MigrateSiteTreeLinkingTaskTest.php b/tests/php/Tasks/MigrateSiteTreeLinkingTaskTest.php index 1181d268c1..12f92ccdc7 100644 --- a/tests/php/Tasks/MigrateSiteTreeLinkingTaskTest.php +++ b/tests/php/Tasks/MigrateSiteTreeLinkingTaskTest.php @@ -46,7 +46,7 @@ protected function setUp(): void ]; foreach (DB::query('SELECT "ID", "Content" FROM "SiteTree"') as $row) { $id = (int)$row['ID']; - $content = str_replace(array_keys($replacements), array_values($replacements), $row['Content']); + $content = str_replace(array_keys($replacements ?? []), array_values($replacements ?? []), $row['Content'] ?? ''); DB::prepared_query('UPDATE "SiteTree" SET "Content" = ? WHERE "ID" = ?', [$content, $id]); } DataObject::reset();