Skip to content

Commit

Permalink
ENH PHP 8.1 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Apr 13, 2022
1 parent 2be48cf commit 0c18046
Show file tree
Hide file tree
Showing 14 changed files with 50 additions and 49 deletions.
6 changes: 3 additions & 3 deletions code/AdminRootController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class AdminRootController extends Controller implements TemplateGlobalProvider
public static function get_admin_route()
{
$rules = Director::config()->get('rules');
$adminRoute = array_search(__CLASS__, $rules);
$adminRoute = array_search(__CLASS__, $rules ?? []);
return $adminRoute ?: static::config()->get('url_base');
}

Expand Down Expand Up @@ -73,7 +73,7 @@ public static function rules()

// Map over the array calling add_rule_for_controller on each
$classes = CMSMenu::get_cms_classes(null, true, CMSMenu::URL_PRIORITY);
array_map(array(__CLASS__, 'add_rule_for_controller'), $classes);
array_map(array(__CLASS__, 'add_rule_for_controller'), $classes ?? []);
}
return self::$adminRules;
}
Expand All @@ -92,7 +92,7 @@ protected static function add_rule_for_controller($controllerClass)
if ($urlSegment) {
// Make director rule
if ($urlRule[0] == '/') {
$urlRule = substr($urlRule, 1);
$urlRule = substr($urlRule ?? '', 1);
}
$rule = $urlSegment . '//' . $urlRule;

Expand Down
8 changes: 4 additions & 4 deletions code/CMSBatchAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public function response($successMessage, $status)
if ($response) {
$response->setStatusCode(
200,
sprintf($successMessage, $count, $errors)
sprintf($successMessage ?? '', $count, $errors)
);
}

Expand Down Expand Up @@ -106,7 +106,7 @@ public function batchaction(SS_List $objs, $helperMethod, $successMessage, $argu
foreach ($objs as $obj) {
// Perform the action
$id = $obj->ID;
if (!call_user_func_array(array($obj, $helperMethod), $arguments)) {
if (!call_user_func_array(array($obj, $helperMethod), $arguments ?? [])) {
$status['error'][$id] = $id;
} else {
$status['success'][$id] = $id;
Expand Down Expand Up @@ -154,7 +154,7 @@ public function applicablePagesHelper($ids, $methodName, $checkStagePages = true
$draftPages = DataObject::get($managedClass)->byIDs($ids);

// Filter out the live-only ids
$onlyOnLive = array_fill_keys($ids, true);
$onlyOnLive = array_fill_keys($ids ?? [], true);
if ($checkStagePages) {
foreach ($draftPages as $obj) {
unset($onlyOnLive[$obj->ID]);
Expand All @@ -163,7 +163,7 @@ public function applicablePagesHelper($ids, $methodName, $checkStagePages = true
}
}
}
$onlyOnLive = array_keys($onlyOnLive);
$onlyOnLive = array_keys($onlyOnLive ?? []);

if ($checkLivePages && $onlyOnLive && DataObject::has_extension($managedClass, Versioned::class)) {
// Get the pages that only exist on live (deleted from stage)
Expand Down
6 changes: 3 additions & 3 deletions code/CMSBatchActionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,11 @@ protected function buildAction($class)
*/
protected function cleanIDs($csvIDs)
{
$ids = preg_split('/ *, */', trim($csvIDs));
$ids = preg_split('/ *, */', trim($csvIDs ?? ''));
foreach ($ids as $k => $id) {
$ids[$k] = (int)$id;
}
return array_filter($ids);
return array_filter($ids ?? []);
}

/**
Expand All @@ -297,7 +297,7 @@ public function batchActions()
{
$actions = static::registeredActions();
$recordClass = $this->recordClass;
$actions = array_filter($actions, function ($action) use ($recordClass) {
$actions = array_filter($actions ?? [], function ($action) use ($recordClass) {
return $action['recordClass'] === $recordClass;
});
return $actions;
Expand Down
11 changes: 6 additions & 5 deletions code/CMSMenu.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public static function get_menu_item($code)
*/
public static function get_menu_code($cmsClass)
{
return Convert::raw2htmlname(str_replace('\\', '-', $cmsClass));
return Convert::raw2htmlname(str_replace('\\', '-', $cmsClass ?? ''));
}

/**
Expand Down Expand Up @@ -383,16 +383,16 @@ public static function get_cms_classes($root = null, $recursive = true, $sort =
}
/** @todo Make these actual abstract classes */
$abstractClasses = [LeftAndMain::class, CMSMain::class];
$subClasses = array_values(ClassInfo::subclassesFor($root));
$subClasses = array_values(ClassInfo::subclassesFor($root) ?? []);
foreach ($subClasses as $className) {
if ($recursive && $className != $root) {
$subClasses = array_merge($subClasses, array_values(ClassInfo::subclassesFor($className)));
$subClasses = array_merge($subClasses, array_values(ClassInfo::subclassesFor($className) ?? []));
}
}
$subClasses = array_unique($subClasses);
$subClasses = array_unique($subClasses ?? []);
foreach ($subClasses as $key => $className) {
// Remove abstract classes and LeftAndMain
if (in_array($className, $abstractClasses) || ClassInfo::classImplements($className, TestOnly::class)) {
if (in_array($className, $abstractClasses ?? []) || ClassInfo::classImplements($className, TestOnly::class)) {
unset($subClasses[$key]);
} else {
// Separate conditional to avoid autoloading the class
Expand All @@ -416,6 +416,7 @@ public static function get_cms_classes($root = null, $recursive = true, $sort =
/**
* IteratorAggregate Interface Method. Iterates over the menu items.
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new ArrayIterator(self::get_menu_items());
Expand Down
2 changes: 1 addition & 1 deletion code/CMSMenuItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public function getAttributesHTML($attrs = null)

// Remove empty or excluded values
foreach ($attrs as $key => $value) {
if (($excludeKeys && in_array($key, $excludeKeys))
if (($excludeKeys && in_array($key, $excludeKeys ?? []))
|| (!$value && $value !== 0 && $value !== '0')
) {
unset($attrs[$key]);
Expand Down
2 changes: 1 addition & 1 deletion code/Forms/UsedOnTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public function usage(HTTPRequest $request)
$tableRowData = [
'id' => $dataObject->ID,
'title' => $dataObject->getTitle() ?: _t(__CLASS__ . '.UNTITLED', 'Untitled'),
'type' => ucfirst($dataObject->i18n_singular_name()),
'type' => ucfirst($dataObject->i18n_singular_name() ?? ''),
'link' => $dataObject->hasMethod('CMSEditLink') ? $dataObject->CMSEditLink() : null,
'ancestors' => []
];
Expand Down
2 changes: 1 addition & 1 deletion code/GroupImportForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function __construct($controller, $name, $fields = null, $actions = null,
$importer = new GroupCsvBulkLoader();
$importSpec = $importer->getImportSpec();

$columns = implode(', ', array_keys($importSpec['fields']));
$columns = implode(', ', array_keys($importSpec['fields'] ?? []));
$helpHtml .= _t(
__CLASS__ . '.Help2',
'<div class="advanced">'
Expand Down
20 changes: 10 additions & 10 deletions code/LeftAndMain.php
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ public function getClientConfig()
// Trim leading/trailing slash to make it easier to concatenate URL
// and use in routing definitions.
'name' => $name,
'url' => trim($this->Link(), '/'),
'url' => trim($this->Link() ?? '', '/'),
'form' => [
'EditorExternalLink' => [
'schemaUrl' => $this->Link('methodSchema/Modals/EditorExternalLink'),
Expand Down Expand Up @@ -794,7 +794,7 @@ public function handleRequest(HTTPRequest $request)
$response->addHeader('X-Controller', static::class);
}
if (!$response->getHeader('X-Title')) {
$response->addHeader('X-Title', urlencode($title));
$response->addHeader('X-Title', urlencode($title ?? ''));
}

// Prevent clickjacking, see https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
Expand Down Expand Up @@ -926,7 +926,7 @@ public static function menu_title($class = null, $localise = true)
// Get default class title
$title = static::config()->get('menu_title');
if (!$title) {
$title = preg_replace('/Admin$/', '', $class);
$title = preg_replace('/Admin$/', '', $class ?? '');
}

// Check localisation
Expand All @@ -948,7 +948,7 @@ public static function menu_icon_for_class($class)
$icon = Config::inst()->get($class, 'menu_icon');
if (!empty($icon)) {
$iconURL = ModuleResourceLoader::resourceURL($icon);
$class = strtolower(Convert::raw2htmlname(str_replace('\\', '-', $class)));
$class = strtolower(Convert::raw2htmlname(str_replace('\\', '-', $class ?? '')) ?? '');
return ".icon.icon-16.icon-{$class} { background-image: url('{$iconURL}'); } ";
}
return '';
Expand Down Expand Up @@ -1053,7 +1053,7 @@ public function MainMenu($cached = true)

if ($menuItem->controller && get_class($this) == $menuItem->controller) {
$linkingmode = "current";
} elseif (strpos($this->Link(), $menuItem->url) !== false) {
} elseif (strpos($this->Link() ?? '', $menuItem->url ?? '') !== false) {
if ($this->Link() == $menuItem->url) {
$linkingmode = "current";

Expand Down Expand Up @@ -1100,7 +1100,7 @@ public function MainMenu($cached = true)
"AttributesHTML" => $menuItem->getAttributesHTML(),
"Title" => $title,
"Code" => $code,
"Icon" => strtolower($code),
"Icon" => strtolower($code ?? ''),
"IconClass" => $iconClass,
"HasCSSIcon" => $hasCSSIcon,
"Link" => $menuItem->url,
Expand Down Expand Up @@ -1287,7 +1287,7 @@ public function save($data, $form)
$response = $this->getResponseNegotiator()->respond($request);
}

$response->addHeader('X-Status', rawurlencode($message));
$response->addHeader('X-Status', rawurlencode($message ?? ''));
return $response;
}

Expand Down Expand Up @@ -1325,7 +1325,7 @@ public function delete($data, $form)

$this->getResponse()->addHeader(
'X-Status',
rawurlencode(_t(__CLASS__ . '.DELETED', 'Deleted.'))
rawurlencode(_t(__CLASS__ . '.DELETED', 'Deleted.') ?? '')
);
return $this->getResponseNegotiator()->respond(
$this->getRequest(),
Expand Down Expand Up @@ -1765,7 +1765,7 @@ public function CMSVersionNumber()
return '';
}
$version = $lockModules[$moduleName];
if (preg_match('#^([0-9]+)\.([0-9]+)#', $version, $m)) {
if (preg_match('#^([0-9]+)\.([0-9]+)#', $version ?? '', $m)) {
return $m[1] . '.' . $m[2];
}
return $version;
Expand Down Expand Up @@ -1821,7 +1821,7 @@ public function getHelpLinks()
}

foreach ($helpLinks as $key => $value) {
$translationKey = str_replace(' ', '', $key);
$translationKey = str_replace(' ', '', $key ?? '');

$formattedLinks[] = [
'Title' => _t(__CLASS__ . '.' . $translationKey, $key),
Expand Down
2 changes: 1 addition & 1 deletion code/MemberImportForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function __construct($controller, $name, $fields = null, $actions = null,
$importer = new MemberCsvBulkLoader();
$importSpec = $importer->getImportSpec();

$columns = implode(', ', array_keys($importSpec['fields']));
$columns = implode(', ', array_keys($importSpec['fields'] ?? []));
$helpHtml .= _t(
__CLASS__ . '.Help2',
'<div class="advanced">'
Expand Down
24 changes: 12 additions & 12 deletions code/ModelAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,15 @@ protected function init()
// if we've hit the "landing" page
if ($this->modelTab === null) {
reset($models);
$this->modelTab = key($models);
$this->modelTab = key($models ?? []);
}

// security check for valid models
if (!array_key_exists($this->modelTab, $models)) {
if (!array_key_exists($this->modelTab, $models ?? [])) {
// if it fails to match the string exactly, try reverse-engineering a classname
$this->modelTab = $this->unsanitiseClassName($this->modelTab);

if (!array_key_exists($this->modelTab, $models)) {
if (!array_key_exists($this->modelTab, $models ?? [])) {
throw new \RuntimeException(sprintf('ModelAdmin::init(): Invalid Model class %s', $this->modelTab));
}
}
Expand Down Expand Up @@ -267,7 +267,7 @@ function ($form) {
]));

if (!$this->showSearchForm ||
(is_array($this->showSearchForm) && !in_array($this->modelClass, $this->showSearchForm))
(is_array($this->showSearchForm) && !in_array($this->modelClass, $this->showSearchForm ?? []))
) {
$config->removeComponentsByType(GridFieldFilterHeader::class);
}
Expand Down Expand Up @@ -358,7 +358,7 @@ public function SearchForm()
Deprecation::notice('4.3', 'Will be removed in favor of GridFieldFilterHeader in 5.0');

if (!$this->showSearchForm
|| (is_array($this->showSearchForm) && !in_array($this->modelClass, $this->showSearchForm))
|| (is_array($this->showSearchForm) && !in_array($this->modelClass, $this->showSearchForm ?? []))
) {
return false;
}
Expand Down Expand Up @@ -443,7 +443,7 @@ protected function getManagedModelTabs()
*/
protected function sanitiseClassName($class)
{
return str_replace('\\', '-', $class);
return str_replace('\\', '-', $class ?? '');
}

/**
Expand All @@ -454,7 +454,7 @@ protected function sanitiseClassName($class)
*/
protected function unsanitiseClassName($class)
{
return str_replace('-', '\\', $class);
return str_replace('-', '\\', $class ?? '');
}

/**
Expand All @@ -466,7 +466,7 @@ public function getManagedModels()
if (is_string($models)) {
$models = array($models);
}
if (!count($models)) {
if (!count($models ?? [])) {
throw new \RuntimeException(
'ModelAdmin::getManagedModels():
You need to specify at least one DataObject subclass in private static $managed_models.
Expand Down Expand Up @@ -526,7 +526,7 @@ public function ImportForm()
$modelName = $modelSNG->i18n_singular_name();
// check if a import form should be generated
if (!$this->showImportForm ||
(is_array($this->showImportForm) && !in_array($this->modelTab, $this->showImportForm))
(is_array($this->showImportForm) && !in_array($this->modelTab, $this->showImportForm ?? []))
) {
return false;
}
Expand Down Expand Up @@ -609,7 +609,7 @@ public function ImportForm()
public function import($data, $form, $request)
{
if (!$this->showImportForm || (is_array($this->showImportForm)
&& !in_array($this->modelClass, $this->showImportForm))
&& !in_array($this->modelClass, $this->showImportForm ?? []))
) {
return false;
}
Expand All @@ -620,7 +620,7 @@ public function import($data, $form, $request)

// File wasn't properly uploaded, show a reminder to the user
if (empty($_FILES['_CsvFile']['tmp_name']) ||
file_get_contents($_FILES['_CsvFile']['tmp_name']) == ''
file_get_contents($_FILES['_CsvFile']['tmp_name'] ?? '') == ''
) {
$form->sessionMessage(
_t('SilverStripe\\Admin\\ModelAdmin.NOCSVFILE', 'Please browse for a CSV file to import'),
Expand Down Expand Up @@ -688,7 +688,7 @@ public function Breadcrumbs($unlinked = false)
$items[0]->Title = $models[$this->modelTab]['title'];
$items[0]->Link = Controller::join_links(
$this->Link($this->sanitiseClassName($this->modelTab)),
'?' . http_build_query($params)
'?' . http_build_query($params ?? [])
);

return $items;
Expand Down
8 changes: 4 additions & 4 deletions tests/behat/src/AdminContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ class AdminContext implements Context
*/
public function iShouldSeeAnInvalidTabIcon(string $not, string $tabLabel)
{
$id = str_replace('Main Content', 'Main', $tabLabel);
$id = str_replace(' ', '_', $id);
$id = str_replace('Main Content', 'Main', $tabLabel ?? '');
$id = str_replace(' ', '_', $id ?? '');
$id = "tab-Root_$id";
$selector = "[aria-labelledby=$id] .font-icon-attention-1";
$hiddenSelector = ".ss-tabset-tabshidden $selector";
Expand Down Expand Up @@ -52,12 +52,12 @@ public function iCanSeeTheFormValidationErrorMessage($not)
Assert::assertTrue(true);
} else {
$message = 'Form validation error message is present when it should not be';
Assert::assertFalse(strpos($element->getText(), $text), $message);
Assert::assertFalse(strpos($element->getText() ?? '', $text ?? ''), $message);
}
} else {
$message = sprintf('Element %s not found', $selector);
Assert::assertNotNull($element, $message);
Assert::assertTrue(strpos($element->getText(), $text) !== false, $message);
Assert::assertTrue(strpos($element->getText() ?? '', $text ?? '') !== false, $message);
}
}
}
2 changes: 1 addition & 1 deletion tests/php/LeftAndMainTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public function testLeftAndMainSubclasses()
$this->resetMenu();

$menuItems = LeftAndMain::singleton()->MainMenu(false);
$this->assertGreaterThan(0, count($menuItems));
$this->assertGreaterThan(0, count($menuItems ?? []));

$adminUrl = AdminRootController::admin_url();
$menuItem = $menuItems->find('Link', $adminUrl . 'security/');
Expand Down
2 changes: 1 addition & 1 deletion tests/php/ModelAdminTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function testMultiModelAdminOpensEachTab()
$this->logInWithPermission();
foreach ($admin->getManagedModelTabs()->toNestedArray() as $tab) {
$request = new HTTPRequest('GET', $tab['Link']);
$request->setRouteParams(['ModelClass' => substr($tab['Link'], strlen('admin/multi/'))]);
$request->setRouteParams(['ModelClass' => substr($tab['Link'] ?? '', strlen('admin/multi/'))]);
$request->setSession(new Session([]));
Injector::inst()->registerService($request, HTTPRequest::class);
$admin->setRequest($request);
Expand Down
Loading

0 comments on commit 0c18046

Please sign in to comment.