From ed4663be9bb5cc1612db968f46e0881d65605bc7 Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Wed, 13 Apr 2022 13:49:48 +1200 Subject: [PATCH] ENH PHP 8.1 compatibility --- src/Extensions/FileSubsites.php | 4 ++-- src/Extensions/GroupSubsites.php | 12 +++++----- src/Extensions/LeftAndMainSubsites.php | 6 ++--- src/Extensions/SiteConfigSubsites.php | 4 ++-- src/Extensions/SiteTreeSubsites.php | 22 ++++++++++--------- src/Forms/WildcardDomainField.php | 2 +- src/Middleware/InitStateMiddleware.php | 4 ++-- src/Model/Subsite.php | 22 +++++++++---------- src/Model/SubsiteDomain.php | 6 ++--- src/Pages/SubsitesVirtualPage.php | 2 +- src/Reports/SubsiteReportWrapper.php | 6 ++--- src/Service/ThemeResolver.php | 10 ++++----- src/Tasks/SubsiteCopyPagesTask.php | 2 +- .../FolderFormFactoryExtensionTest.php | 4 ++-- tests/php/SiteTreeSubsitesTest.php | 4 ++-- tests/php/SubsiteAdminTest.php | 4 ++-- tests/php/SubsiteTest.php | 2 +- tests/php/SubsitesVirtualPageTest.php | 4 ++-- 18 files changed, 61 insertions(+), 59 deletions(-) diff --git a/src/Extensions/FileSubsites.php b/src/Extensions/FileSubsites.php index 7d55fd7..85defa9 100644 --- a/src/Extensions/FileSubsites.php +++ b/src/Extensions/FileSubsites.php @@ -77,8 +77,8 @@ class FileSubsites extends DataExtension break; } - $sect = array_values($query->getSelect()); - $isCounting = strpos($sect[0], 'COUNT') !== false; + $sect = array_values($query->getSelect() ?? []); + $isCounting = strpos($sect[0] ?? '', 'COUNT') !== false; // Ordering when deleting or counting doesn't apply if (!$isCounting) { diff --git a/src/Extensions/GroupSubsites.php b/src/Extensions/GroupSubsites.php index f8440c9..4c02fce 100644 --- a/src/Extensions/GroupSubsites.php +++ b/src/Extensions/GroupSubsites.php @@ -106,7 +106,7 @@ class GroupSubsites extends DataExtension implements PermissionProvider $subsiteMap )); } else { - if (sizeof($subsiteMap) <= 1) { + if (sizeof($subsiteMap ?? []) <= 1) { $fields->addFieldToTab('Root.Subsites', new ReadonlyField( 'SubsitesHuman', _t(__CLASS__ . '.ACCESSRADIOTITLE', 'Give this group access to'), @@ -133,10 +133,10 @@ class GroupSubsites extends DataExtension implements PermissionProvider { if ($this->owner->AccessAllSubsites) { $title = _t(__CLASS__ . '.GlobalGroup', 'global group'); - $title = htmlspecialchars($this->owner->Title, ENT_QUOTES) . ' (' . $title . ')'; + $title = htmlspecialchars($this->owner->Title ?? '', ENT_QUOTES) . ' (' . $title . ')'; } else { $subsites = Convert::raw2xml(implode(', ', $this->owner->Subsites()->column('Title'))); - $title = htmlspecialchars($this->owner->Title) . " ($subsites)"; + $title = htmlspecialchars($this->owner->Title ?? '') . " ($subsites)"; } } @@ -168,10 +168,10 @@ class GroupSubsites extends DataExtension implements PermissionProvider $hasGroupSubsites = false; foreach ($query->getFrom() as $item) { if ((is_array($item) && strpos( - $item['table'], + $item['table'] ?? '', 'Group_Subsites' ) !== false) || (!is_array($item) && strpos( - $item, + $item ?? '', 'Group_Subsites' ) !== false) ) { @@ -227,7 +227,7 @@ class GroupSubsites extends DataExtension implements PermissionProvider // We are allowed to access this site if at we have CMS_ACCESS_SecurityAdmin permission on // at least one of the sites - return (bool)array_intersect($accessibleSites, $linkedSites); + return (bool)array_intersect($accessibleSites ?? [], $linkedSites); } public function providePermissions() diff --git a/src/Extensions/LeftAndMainSubsites.php b/src/Extensions/LeftAndMainSubsites.php index 877e30e..ed0b9e0 100644 --- a/src/Extensions/LeftAndMainSubsites.php +++ b/src/Extensions/LeftAndMainSubsites.php @@ -118,7 +118,7 @@ class LeftAndMainSubsites extends LeftAndMainExtension // Find sites that satisfy all codes conjuncitvely. $accessibleSites = new ArrayList(); foreach ($codesPerSite as $siteID => $siteCodes) { - if (count($siteCodes) == count($codes)) { + if (count($siteCodes ?? []) == count($codes ?? [])) { $accessibleSites->push($sitesArray[$siteID]); } } @@ -169,7 +169,7 @@ class LeftAndMainSubsites extends LeftAndMainExtension public function alternateMenuDisplayCheck($controllerName) { - if (!class_exists($controllerName)) { + if (!class_exists($controllerName ?? '')) { return false; } @@ -387,7 +387,7 @@ class LeftAndMainSubsites extends LeftAndMainExtension if ($record->hasMethod('NormalRelated') && ($record->NormalRelated() || $record->ReverseRelated())) { $this->owner->response->addHeader( 'X-Status', - rawurlencode(_t(__CLASS__ . '.Saved', 'Saved, please update related pages.')) + rawurlencode(_t(__CLASS__ . '.Saved', 'Saved, please update related pages.') ?? '') ); } } diff --git a/src/Extensions/SiteConfigSubsites.php b/src/Extensions/SiteConfigSubsites.php index fca8d99..7919e4b 100644 --- a/src/Extensions/SiteConfigSubsites.php +++ b/src/Extensions/SiteConfigSubsites.php @@ -37,7 +37,7 @@ class SiteConfigSubsites extends DataExtension } $regexp = '/^(.*\.)?("|`)?SubsiteID("|`)?\s?=/'; foreach ($query->getWhereParameterised($parameters) as $predicate) { - if (preg_match($regexp, $predicate)) { + if (preg_match($regexp ?? '', $predicate ?? '')) { return; } } @@ -48,7 +48,7 @@ class SiteConfigSubsites extends DataExtension } $froms = $query->getFrom(); - $froms = array_keys($froms); + $froms = array_keys($froms ?? []); $tableName = array_shift($froms); if ($tableName !== SiteConfig::getSchema()->tableName(SiteConfig::class)) { return; diff --git a/src/Extensions/SiteTreeSubsites.php b/src/Extensions/SiteTreeSubsites.php index a1a22db..bda8d90 100644 --- a/src/Extensions/SiteTreeSubsites.php +++ b/src/Extensions/SiteTreeSubsites.php @@ -90,7 +90,7 @@ class SiteTreeSubsites extends DataExtension foreach ($query->getFrom() as $tableName => $info) { // The tableName should be SiteTree or SiteTree_Live... $siteTreeTableName = SiteTree::getSchema()->tableName(SiteTree::class); - if (strpos($tableName, $siteTreeTableName) === false) { + if (strpos($tableName ?? '', $siteTreeTableName ?? '') === false) { break; } $query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)"); @@ -341,7 +341,7 @@ class SiteTreeSubsites extends DataExtension } // Return true if they have access to this object's site - if (!(in_array(0, $goodSites) || in_array($subsiteID, $goodSites))) { + if (!(in_array(0, $goodSites ?? []) || in_array($subsiteID, $goodSites ?? []))) { return false; } } @@ -413,7 +413,7 @@ class SiteTreeSubsites extends DataExtension // This helps deal with Link() returning an absolute URL. $url = Director::absoluteURL($this->owner->Link($action)); if ($this->owner->SubsiteID) { - $url = preg_replace('/\/\/[^\/]+\//', '//' . $this->owner->Subsite()->domain() . '/', $url); + $url = preg_replace('/\/\/[^\/]+\//', '//' . $this->owner->Subsite()->domain() . '/', $url ?? ''); } return $url; } @@ -471,11 +471,13 @@ class SiteTreeSubsites extends DataExtension if ($links) { foreach ($links as $link) { - if (substr($link, 0, strlen('http://')) == 'http://') { - $withoutHttp = substr($link, strlen('http://')); - if (strpos($withoutHttp, '/') && strpos($withoutHttp, '/') < strlen($withoutHttp)) { - $domain = substr($withoutHttp, 0, strpos($withoutHttp, '/')); - $rest = substr($withoutHttp, strpos($withoutHttp, '/') + 1); + if (substr($link ?? '', 0, strlen('http://')) == 'http://') { + $withoutHttp = substr($link ?? '', strlen('http://')); + if (strpos($withoutHttp ?? '', '/') && + strpos($withoutHttp ?? '', '/') < strlen($withoutHttp ?? '') + ) { + $domain = substr($withoutHttp ?? '', 0, strpos($withoutHttp ?? '', '/')); + $rest = substr($withoutHttp ?? '', strpos($withoutHttp ?? '', '/') + 1); $subsiteID = Subsite::getSubsiteIDForDomain($domain); if ($subsiteID == 0) { @@ -548,9 +550,9 @@ class SiteTreeSubsites extends DataExtension $subsite = Subsite::currentSubsite(); if ($subsite && $subsite->exists() && $subsite->PageTypeBlacklist) { // SS 4.1: JSON encoded. SS 4.0, comma delimited - $blacklist = json_decode($subsite->PageTypeBlacklist, true); + $blacklist = json_decode($subsite->PageTypeBlacklist ?? '', true); if ($blacklist === false) { - $blacklist = explode(',', $subsite->PageTypeBlacklist); + $blacklist = explode(',', $subsite->PageTypeBlacklist ?? ''); } if (in_array(get_class($this->owner), (array) $blacklist)) { diff --git a/src/Forms/WildcardDomainField.php b/src/Forms/WildcardDomainField.php index c20f0e6..81feb01 100644 --- a/src/Forms/WildcardDomainField.php +++ b/src/Forms/WildcardDomainField.php @@ -36,7 +36,7 @@ class WildcardDomainField extends TextField */ public function checkHostname($hostname) { - return (bool)preg_match('/^([a-z0-9\*]+[\-\.\:])*([a-z0-9\*]+)$/', $hostname); + return (bool)preg_match('/^([a-z0-9\*]+[\-\.\:])*([a-z0-9\*]+)$/', $hostname ?? ''); } public function Type() diff --git a/src/Middleware/InitStateMiddleware.php b/src/Middleware/InitStateMiddleware.php index f2c7199..7d962dd 100644 --- a/src/Middleware/InitStateMiddleware.php +++ b/src/Middleware/InitStateMiddleware.php @@ -69,9 +69,9 @@ class InitStateMiddleware implements HTTPMiddleware { $adminPaths = static::config()->get('admin_url_paths'); $adminPaths[] = AdminRootController::admin_url(); - $currentPath = rtrim($request->getURL(), '/') . '/'; + $currentPath = rtrim($request->getURL() ?? '', '/') . '/'; foreach ($adminPaths as $adminPath) { - if (substr($currentPath, 0, strlen($adminPath)) === $adminPath) { + if (substr($currentPath ?? '', 0, strlen($adminPath ?? '')) === $adminPath) { return true; } } diff --git a/src/Model/Subsite.php b/src/Model/Subsite.php index 60bfb3f..d78f60e 100644 --- a/src/Model/Subsite.php +++ b/src/Model/Subsite.php @@ -259,14 +259,14 @@ class Subsite extends DataObject } // Remove ports, we aren't concerned with them in terms of detecting subsites via domains - $hostParts = explode(':', $host, 2); + $hostParts = explode(':', $host ?? '', 2); $host = reset($hostParts); $matchingDomains = null; $cacheKey = null; if ($host) { if (!static::config()->get('strict_subdomain_matching')) { - $host = preg_replace('/^www\./', '', $host); + $host = preg_replace('/^www\./', '', $host ?? ''); } $currentUserId = Security::getCurrentUser() ? Security::getCurrentUser()->ID : 0; @@ -301,9 +301,9 @@ class Subsite extends DataObject } if ($matchingDomains && $matchingDomains->count()) { - $subsiteIDs = array_unique($matchingDomains->column('SubsiteID')); - $subsiteDomains = array_unique($matchingDomains->column('Domain')); - if (sizeof($subsiteIDs) > 1) { + $subsiteIDs = array_unique($matchingDomains->column('SubsiteID') ?? []); + $subsiteDomains = array_unique($matchingDomains->column('Domain') ?? []); + if (sizeof($subsiteIDs ?? []) > 1) { throw new UnexpectedValueException(sprintf( "Multiple subsites match on '%s': %s", $host, @@ -577,7 +577,7 @@ class Subsite extends DataObject foreach ($domains as $domain) { $domainStr = $domain->Domain; if (!static::config()->get('strict_subdomain_matching')) { - $domainStr = preg_replace('/^www\./', '', $domainStr); + $domainStr = preg_replace('/^www\./', '', $domainStr ?? ''); } $hostmap[$domainStr] = $subsite->domain(); } @@ -592,8 +592,8 @@ class Subsite extends DataObject $data .= "// Generated by Subsite::writeHostMap() on " . date('d/M/y') . "\n"; $data .= '$subsiteHostmap = ' . var_export($hostmap, true) . ';'; - if (is_writable(dirname($file)) || is_writable($file)) { - file_put_contents($file, $data); + if (is_writable(dirname($file ?? '')) || is_writable($file ?? '')) { + file_put_contents($file ?? '', $data); } } @@ -624,7 +624,7 @@ class Subsite extends DataObject return false; } - if (!in_array('ADMIN', $permissionCodes)) { + if (!in_array('ADMIN', $permissionCodes ?? [])) { $permissionCodes[] = 'ADMIN'; } @@ -799,7 +799,7 @@ class Subsite extends DataObject if ($theme[0] == '.') { continue; } - $theme = strtok($theme, '_'); + $theme = strtok($theme ?? '', '_'); $themes[$theme] = $theme; } ksort($themes); @@ -989,7 +989,7 @@ JS; * when a page, etc, is duplicated */ $stack = [[0, 0]]; - while (count($stack) > 0) { + while (count($stack ?? []) > 0) { list($sourceParentID, $destParentID) = array_pop($stack); $children = Versioned::get_by_stage('Page', 'Live', "\"ParentID\" = $sourceParentID", ''); diff --git a/src/Model/SubsiteDomain.php b/src/Model/SubsiteDomain.php index c21848c..2d93891 100644 --- a/src/Model/SubsiteDomain.php +++ b/src/Model/SubsiteDomain.php @@ -190,14 +190,14 @@ class SubsiteDomain extends DataObject // If there are wildcards in the primary domain (not recommended), make some // educated guesses about what to replace them with: - $domain = preg_replace('/\.\*$/', ".{$currentHost}", $this->Domain); + $domain = preg_replace('/\.\*$/', ".{$currentHost}", $this->Domain ?? ''); // Default to "subsite." prefix for first wildcard // TODO Whats the significance of "subsite" in this context?! - $domain = preg_replace('/^\*\./', "subsite.", $domain); + $domain = preg_replace('/^\*\./', "subsite.", $domain ?? ''); // *Only* removes "intermediate" subdomains, so 'subdomain.www.domain.com' becomes 'subdomain.domain.com' - $domain = str_replace('.www.', '.', $domain); + $domain = str_replace('.www.', '.', $domain ?? ''); return $domain; } diff --git a/src/Pages/SubsitesVirtualPage.php b/src/Pages/SubsitesVirtualPage.php index fcd39b3..c19eb40 100644 --- a/src/Pages/SubsitesVirtualPage.php +++ b/src/Pages/SubsitesVirtualPage.php @@ -174,7 +174,7 @@ class SubsitesVirtualPage extends VirtualPage } foreach (self::$db as $field => $type) { - if (in_array($field, $fields)) { + if (in_array($field, $fields ?? [])) { unset($fields[array_search($field, $fields)]); } } diff --git a/src/Reports/SubsiteReportWrapper.php b/src/Reports/SubsiteReportWrapper.php index 0e11d1d..e2da4c4 100644 --- a/src/Reports/SubsiteReportWrapper.php +++ b/src/Reports/SubsiteReportWrapper.php @@ -27,10 +27,10 @@ class SubsiteReportWrapper extends ReportWrapper _t(__CLASS__ . '.ReportDropdown', 'Sites'), $options ); - $subsiteField->setValue(array_keys($options)); + $subsiteField->setValue(array_keys($options ?? [])); // We don't need to make the field editable if only one subsite is available - if (sizeof($options) <= 1) { + if (sizeof($options ?? []) <= 1) { $subsiteField = $subsiteField->performReadonlyTransformation(); } @@ -70,7 +70,7 @@ class SubsiteReportWrapper extends ReportWrapper } else { $subsites = Subsite::accessible_sites('CMS_ACCESS_CMSMain'); $options = $subsites->toDropdownMap('ID', 'Title'); - Subsite::$force_subsite = join(',', array_keys($options)); + Subsite::$force_subsite = join(',', array_keys($options ?? [])); } } diff --git a/src/Service/ThemeResolver.php b/src/Service/ThemeResolver.php index 297a2bc..b91d3bd 100644 --- a/src/Service/ThemeResolver.php +++ b/src/Service/ThemeResolver.php @@ -43,7 +43,7 @@ class ThemeResolver */ public function getThemeList(Subsite $site) { - $themes = array_values(SSViewer::get_themes()); + $themes = array_values(SSViewer::get_themes() ?? []); $siteTheme = $site->Theme; if (!$siteTheme) { @@ -56,18 +56,18 @@ class ThemeResolver } // Ensure themes don't cascade "up" the list - $index = array_search($siteTheme, $themes); + $index = array_search($siteTheme, $themes ?? []); if ($index > 0) { // 4.0 didn't have support for themes in the public webroot $constant = SSViewer::class . '::PUBLIC_THEME'; - $publicConstantDefined = defined($constant); + $publicConstantDefined = defined($constant ?? ''); // Check if the default is public themes $publicDefault = $publicConstantDefined && $themes[0] === SSViewer::PUBLIC_THEME; // Take only those that appear after theme chosen (non-inclusive) - $themes = array_slice($themes, $index + 1); + $themes = array_slice($themes ?? [], $index + 1); // Add back in public if ($publicDefault) { @@ -94,6 +94,6 @@ class ThemeResolver return null; } - return array_keys($config); + return array_keys($config ?? []); } } diff --git a/src/Tasks/SubsiteCopyPagesTask.php b/src/Tasks/SubsiteCopyPagesTask.php index 95cfe86..375806a 100644 --- a/src/Tasks/SubsiteCopyPagesTask.php +++ b/src/Tasks/SubsiteCopyPagesTask.php @@ -56,7 +56,7 @@ class SubsiteCopyPagesTask extends BuildTask // issues with having to check whether or not the new parents have been added to the site tree // when a page, etc, is duplicated $stack = [[0, 0]]; - while (count($stack) > 0) { + while (count($stack ?? []) > 0) { list($sourceParentID, $destParentID) = array_pop($stack); $children = Versioned::get_by_stage(SiteTree::class, 'Live', "\"ParentID\" = $sourceParentID", ''); diff --git a/tests/php/Extensions/FolderFormFactoryExtensionTest.php b/tests/php/Extensions/FolderFormFactoryExtensionTest.php index ebb5574..8c3917d 100644 --- a/tests/php/Extensions/FolderFormFactoryExtensionTest.php +++ b/tests/php/Extensions/FolderFormFactoryExtensionTest.php @@ -24,8 +24,8 @@ class FolderFormFactoryExtensionTest extends SapphireTest 'Record' => $folder ]); - $source = array_values($folderForm->Fields()->fieldByName('SubsiteID')->getSource()); - $result = array_values($source); + $source = array_values($folderForm->Fields()->fieldByName('SubsiteID')->getSource() ?? []); + $result = array_values($source ?? []); $this->assertContains('Main site', $result); $this->assertContains('Subsite A', $result); diff --git a/tests/php/SiteTreeSubsitesTest.php b/tests/php/SiteTreeSubsitesTest.php index 4a9c667..63c5a0b 100644 --- a/tests/php/SiteTreeSubsitesTest.php +++ b/tests/php/SiteTreeSubsitesTest.php @@ -274,7 +274,7 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest Subsite::changeSubsite($s1); $cmsmain = CMSMain::create(); - $hints = json_decode($cmsmain->SiteTreeHints(), true); + $hints = json_decode($cmsmain->SiteTreeHints() ?? '', true); $classes = $hints['Root']['disallowedChildren']; $this->assertContains(ErrorPage::class, $classes); $this->assertContains(TestClassA::class, $classes); @@ -285,7 +285,7 @@ class SiteTreeSubsitesTest extends BaseSubsiteTest if ($cmsmain->hasMethod('getHintsCache')) { $cmsmain->getHintsCache()->clear(); } - $hints = json_decode($cmsmain->SiteTreeHints(), true); + $hints = json_decode($cmsmain->SiteTreeHints() ?? '', true); $classes = $hints['Root']['disallowedChildren']; $this->assertNotContains(ErrorPage::class, $classes); diff --git a/tests/php/SubsiteAdminTest.php b/tests/php/SubsiteAdminTest.php index 0fc10a8..3b0c6ab 100644 --- a/tests/php/SubsiteAdminTest.php +++ b/tests/php/SubsiteAdminTest.php @@ -33,10 +33,10 @@ class SubsiteAdminTest extends FunctionalTest ."SilverStripe-Subsites-Model-Subsite/item/$subsite1ID/edit" ); $this->assertTrue( - strpos($response->getBody(), 'id="Form_ItemEditForm_ID"') !== false, + strpos($response->getBody() ?? '', 'id="Form_ItemEditForm_ID"') !== false, 'Testing Form_ItemEditForm_ID exists' ); - $this->assertTrue(strpos($response->getBody(), ' exists'); + $this->assertTrue(strpos($response->getBody() ?? '', ' exists'); } /** diff --git a/tests/php/SubsiteTest.php b/tests/php/SubsiteTest.php index 1531315..ae218f4 100644 --- a/tests/php/SubsiteTest.php +++ b/tests/php/SubsiteTest.php @@ -407,7 +407,7 @@ class SubsiteTest extends BaseSubsiteTest 'Test Non-SSL', 'Test SSL', 'Test Vagrant VM on port 8080' - ], array_values($adminSiteTitles)); + ], array_values($adminSiteTitles ?? [])); $member2Sites = Subsite::accessible_sites( 'CMS_ACCESS_CMSMain', diff --git a/tests/php/SubsitesVirtualPageTest.php b/tests/php/SubsitesVirtualPageTest.php index af98f4b..140213e 100644 --- a/tests/php/SubsitesVirtualPageTest.php +++ b/tests/php/SubsitesVirtualPageTest.php @@ -35,8 +35,8 @@ class SubsitesVirtualPageTest extends BaseSubsiteTest $page = $this->objFromFixture(SiteTree::class, 'page1'); $fromPath = __DIR__ . '/testscript-test-file.pdf'; $destPath = TestAssetStore::getLocalPath($file); - Filesystem::makeFolder(dirname($destPath)); - copy($fromPath, $destPath); + Filesystem::makeFolder(dirname($destPath ?? '')); + copy($fromPath ?? '', $destPath ?? ''); // Hack in site link tracking after the fact $page->Content = '

';