Skip to content

Commit

Permalink
Merge pull request #478 from creative-commoners/pulls/2/php81
Browse files Browse the repository at this point in the history
ENH PHP 8.1 compatibility
  • Loading branch information
GuySartorelli authored Apr 26, 2022
2 parents acf9715 + ed4663b commit 7860a03
Show file tree
Hide file tree
Showing 18 changed files with 61 additions and 59 deletions.
4 changes: 2 additions & 2 deletions src/Extensions/FileSubsites.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
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) {
Expand Down
12 changes: 6 additions & 6 deletions src/Extensions/GroupSubsites.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public function updateCMSFields(FieldList $fields)
$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'),
Expand All @@ -133,10 +133,10 @@ public function updateTreeTitle(&$title)
{
if ($this->owner->AccessAllSubsites) {
$title = _t(__CLASS__ . '.GlobalGroup', 'global group');
$title = htmlspecialchars($this->owner->Title, ENT_QUOTES) . ' <i>(' . $title . ')</i>';
$title = htmlspecialchars($this->owner->Title ?? '', ENT_QUOTES) . ' <i>(' . $title . ')</i>';
} else {
$subsites = Convert::raw2xml(implode(', ', $this->owner->Subsites()->column('Title')));
$title = htmlspecialchars($this->owner->Title) . " <i>($subsites)</i>";
$title = htmlspecialchars($this->owner->Title ?? '') . " <i>($subsites)</i>";
}
}

Expand Down Expand Up @@ -168,10 +168,10 @@ public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
$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)
) {
Expand Down Expand Up @@ -227,7 +227,7 @@ public function alternateCanEdit()

// 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()
Expand Down
6 changes: 3 additions & 3 deletions src/Extensions/LeftAndMainSubsites.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public function sectionSites($includeMainSite = true, $mainSiteTitle = 'Main sit
// 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]);
}
}
Expand Down Expand Up @@ -169,7 +169,7 @@ public function ListSubsites()

public function alternateMenuDisplayCheck($controllerName)
{
if (!class_exists($controllerName)) {
if (!class_exists($controllerName ?? '')) {
return false;
}

Expand Down Expand Up @@ -387,7 +387,7 @@ public function onAfterSave($record)
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.') ?? '')
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Extensions/SiteConfigSubsites.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
}
$regexp = '/^(.*\.)?("|`)?SubsiteID("|`)?\s?=/';
foreach ($query->getWhereParameterised($parameters) as $predicate) {
if (preg_match($regexp, $predicate)) {
if (preg_match($regexp ?? '', $predicate ?? '')) {
return;
}
}
Expand All @@ -48,7 +48,7 @@ public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
}

$froms = $query->getFrom();
$froms = array_keys($froms);
$froms = array_keys($froms ?? []);
$tableName = array_shift($froms);
if ($tableName !== SiteConfig::getSchema()->tableName(SiteConfig::class)) {
return;
Expand Down
22 changes: 12 additions & 10 deletions src/Extensions/SiteTreeSubsites.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
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)");
Expand Down Expand Up @@ -341,7 +341,7 @@ public function canEdit($member = null)
}

// 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;
}
}
Expand Down Expand Up @@ -413,7 +413,7 @@ public function alternateAbsoluteLink($action = null)
// 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;
}
Expand Down Expand Up @@ -471,11 +471,13 @@ public function augmentSyncLinkTracking()

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) {
Expand Down Expand Up @@ -548,9 +550,9 @@ public function canCreate($member = null)
$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)) {
Expand Down
2 changes: 1 addition & 1 deletion src/Forms/WildcardDomainField.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function validate($validator)
*/
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()
Expand Down
4 changes: 2 additions & 2 deletions src/Middleware/InitStateMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ public function getIsAdmin(HTTPRequest $request)
{
$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;
}
}
Expand Down
22 changes: 11 additions & 11 deletions src/Model/Subsite.php
Original file line number Diff line number Diff line change
Expand Up @@ -259,14 +259,14 @@ public static function getSubsiteIDForDomain($host = null, $checkPermissions = t
}

// 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;
Expand Down Expand Up @@ -301,9 +301,9 @@ public static function getSubsiteIDForDomain($host = null, $checkPermissions = t
}

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,
Expand Down Expand Up @@ -577,7 +577,7 @@ public static function writeHostMap($file = null)
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();
}
Expand All @@ -592,8 +592,8 @@ public static function writeHostMap($file = null)
$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);
}
}

Expand Down Expand Up @@ -624,7 +624,7 @@ public static function hasMainSitePermission($member = null, $permissionCodes =
return false;
}

if (!in_array('ADMIN', $permissionCodes)) {
if (!in_array('ADMIN', $permissionCodes ?? [])) {
$permissionCodes[] = 'ADMIN';
}

Expand Down Expand Up @@ -799,7 +799,7 @@ public function allowedThemes()
if ($theme[0] == '.') {
continue;
}
$theme = strtok($theme, '_');
$theme = strtok($theme ?? '', '_');
$themes[$theme] = $theme;
}
ksort($themes);
Expand Down Expand Up @@ -989,7 +989,7 @@ public function duplicate($doWrite = true, $manyMany = 'many_many')
* 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", '');

Expand Down
6 changes: 3 additions & 3 deletions src/Model/SubsiteDomain.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,14 @@ public function getSubstitutedDomain()

// 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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Pages/SubsitesVirtualPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ public function getVirtualFields()
}

foreach (self::$db as $field => $type) {
if (in_array($field, $fields)) {
if (in_array($field, $fields ?? [])) {
unset($fields[array_search($field, $fields)]);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Reports/SubsiteReportWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ public function parameterFields()
_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();
}

Expand Down Expand Up @@ -70,7 +70,7 @@ public function beforeQuery($params)
} 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 ?? []));
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/Service/ThemeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -56,18 +56,18 @@ public function getThemeList(Subsite $site)
}

// 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) {
Expand All @@ -94,6 +94,6 @@ public function getCustomThemeOptions()
return null;
}

return array_keys($config);
return array_keys($config ?? []);
}
}
2 changes: 1 addition & 1 deletion src/Tasks/SubsiteCopyPagesTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function run($request)
// 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", '');
Expand Down
4 changes: 2 additions & 2 deletions tests/php/Extensions/FolderFormFactoryExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public function testSubsitesFolderDropdown()
'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);
Expand Down
4 changes: 2 additions & 2 deletions tests/php/SiteTreeSubsitesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ public function testPageTypesBlacklistInCMSMain()

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);
Expand All @@ -285,7 +285,7 @@ public function testPageTypesBlacklistInCMSMain()
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);
Expand Down
4 changes: 2 additions & 2 deletions tests/php/SubsiteAdminTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ public function testBasicView()
."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(), '<head') !== false, 'Testing <head> exists');
$this->assertTrue(strpos($response->getBody() ?? '', '<head') !== false, 'Testing <head> exists');
}

/**
Expand Down
Loading

0 comments on commit 7860a03

Please sign in to comment.