From 1ddc16f9a64a2c272315fe4217e5d37aac753cb8 Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Wed, 20 Apr 2022 10:02:24 +1200 Subject: [PATCH] ENH PHP 8.1 compatibility --- .../ElementSiteTreeFilterSearch.php | 2 +- src/Controllers/ElementalAreaController.php | 12 ++++++------ src/Extensions/ElementalAreasExtension.php | 7 ++++--- src/Extensions/ElementalPageExtension.php | 2 +- src/Forms/EditFormFactory.php | 2 +- src/Forms/ElementalAreaField.php | 12 ++++++------ src/GraphQL/Resolvers/Resolver.php | 10 +++++----- src/Models/BaseElement.php | 18 +++++++++--------- src/Models/ElementalArea.php | 4 ++-- src/Reports/ElementsInUseReport.php | 2 +- src/Services/ElementTabProvider.php | 2 +- src/Tasks/MigrateContentToElement.php | 2 +- src/TopPage/DataExtension.php | 6 +++--- src/TopPage/SiteTreeExtension.php | 8 ++++---- tests/Behat/Context/FeatureContext.php | 2 +- tests/Behat/Context/FixtureContext.php | 2 +- .../Extensions/ElementalAreasExtensionTest.php | 6 +++--- 17 files changed, 50 insertions(+), 49 deletions(-) diff --git a/src/Controllers/ElementSiteTreeFilterSearch.php b/src/Controllers/ElementSiteTreeFilterSearch.php index 7f444df2..2313c556 100644 --- a/src/Controllers/ElementSiteTreeFilterSearch.php +++ b/src/Controllers/ElementSiteTreeFilterSearch.php @@ -49,7 +49,7 @@ protected function applyDefaultFilters($query) // Check whether the search term exists in the nested page content $pageContent = $siteTree->getElementsForSearch(); - return stripos($pageContent, $this->params['Term']) !== false; + return stripos($pageContent ?? '', $this->params['Term'] ?? '') !== false; }); if ($siteTrees->count()) { diff --git a/src/Controllers/ElementalAreaController.php b/src/Controllers/ElementalAreaController.php index 957c49ee..d8c79a27 100644 --- a/src/Controllers/ElementalAreaController.php +++ b/src/Controllers/ElementalAreaController.php @@ -48,7 +48,7 @@ public function getClientConfig() 'saveUrl' => $this->Link('api/saveForm'), 'saveMethod' => 'post', 'payloadFormat' => 'json', - 'formNameTemplate' => sprintf(static::FORM_NAME_TEMPLATE, '{id}'), + 'formNameTemplate' => sprintf(static::FORM_NAME_TEMPLATE ?? '', '{id}'), ]; // Configuration that is available per element type @@ -93,7 +93,7 @@ public function getElementForm($elementID) /** @var Form $form */ $form = $scaffolder->getForm( $this, - sprintf(static::FORM_NAME_TEMPLATE, $elementID), + sprintf(static::FORM_NAME_TEMPLATE ?? '', $elementID), ['Record' => $element] ); @@ -186,7 +186,7 @@ public function formAction(HTTPRequest $request) $formName = $request->param('FormName'); // Get the element ID from the form name - $id = substr($formName, strlen(sprintf(self::FORM_NAME_TEMPLATE, ''))); + $id = substr($formName ?? '', strlen(sprintf(self::FORM_NAME_TEMPLATE ?? '', ''))); $form = $this->getElementForm($id); $field = $form->getRequestHandler()->handleField($request); @@ -204,14 +204,14 @@ public function formAction(HTTPRequest $request) public static function removeNamespacesFromFields(array $data, $elementID) { $output = []; - $template = sprintf(EditFormFactory::FIELD_NAMESPACE_TEMPLATE, $elementID, ''); + $template = sprintf(EditFormFactory::FIELD_NAMESPACE_TEMPLATE ?? '', $elementID, ''); foreach ($data as $key => $value) { // Only look at fields that match the namespace template - if (substr($key, 0, strlen($template)) !== $template) { + if (substr($key ?? '', 0, strlen($template ?? '')) !== $template) { continue; } - $fieldName = substr($key, strlen($template)); + $fieldName = substr($key ?? '', strlen($template ?? '')); $output[$fieldName] = $value; } return $output; diff --git a/src/Extensions/ElementalAreasExtension.php b/src/Extensions/ElementalAreasExtension.php index 73853718..19878e89 100644 --- a/src/Extensions/ElementalAreasExtension.php +++ b/src/Extensions/ElementalAreasExtension.php @@ -16,6 +16,7 @@ use SilverStripe\ORM\DataExtension; use SilverStripe\ORM\DataObject; use SilverStripe\Versioned\Versioned; +use SilverStripe\View\ViewableData; /** * This extension handles most of the relationships between pages and element @@ -114,7 +115,7 @@ public function getElementalTypes() /** @var BaseElement $inst */ $inst = singleton($availableClass); - if (!in_array($availableClass, $disallowedElements) && $inst->canCreate()) { + if (!in_array($availableClass, $disallowedElements ?? []) && $inst->canCreate()) { if ($inst->hasMethod('canCreateElement') && !$inst->canCreateElement()) { continue; } @@ -260,7 +261,7 @@ public function supportsElemental() return false; } elseif ($ignored = Config::inst()->get(ElementalPageExtension::class, 'ignored_classes')) { foreach ($ignored as $check) { - if (is_a($this->owner, $check)) { + if (is_a($this->owner, $check ?? '')) { return false; } } @@ -327,7 +328,7 @@ public function requireDefaultRecords() } } - $needsPublishing = Extensible::has_extension($elementalObject, Versioned::class) + $needsPublishing = ViewableData::has_extension($elementalObject, Versioned::class) && $elementalObject->isPublished(); /** @var ElementalAreasExtension $elementalObject */ diff --git a/src/Extensions/ElementalPageExtension.php b/src/Extensions/ElementalPageExtension.php index 34881dee..dee8010b 100644 --- a/src/Extensions/ElementalPageExtension.php +++ b/src/Extensions/ElementalPageExtension.php @@ -70,7 +70,7 @@ public function getElementsForSearch() // CMS layout can break on the response. (SilverStripe 4.1.1) SSViewer::set_themes($oldThemes); } - return implode($this->owner->config()->get('search_index_element_delimiter'), $output); + return implode($this->owner->config()->get('search_index_element_delimiter') ?? '', $output); } public function MetaTags(&$tags) diff --git a/src/Forms/EditFormFactory.php b/src/Forms/EditFormFactory.php index b32e49b7..a3c46eee 100644 --- a/src/Forms/EditFormFactory.php +++ b/src/Forms/EditFormFactory.php @@ -66,7 +66,7 @@ protected function namespaceFields(FieldList $fields, array $context) $elementID = $context['Record']->ID; foreach ($fields->dataFields() as $field) { - $namespacedName = sprintf(self::FIELD_NAMESPACE_TEMPLATE, $elementID, $field->getName()); + $namespacedName = sprintf(self::FIELD_NAMESPACE_TEMPLATE ?? '', $elementID, $field->getName()); $field->setName($namespacedName); } } diff --git a/src/Forms/ElementalAreaField.php b/src/Forms/ElementalAreaField.php index 5fc2d1e4..ffc00936 100644 --- a/src/Forms/ElementalAreaField.php +++ b/src/Forms/ElementalAreaField.php @@ -102,7 +102,7 @@ public function FieldHolder($properties = array()) { $context = $this; - if (count($properties)) { + if (count($properties ?? [])) { $context = $this->customise($properties); } @@ -119,7 +119,7 @@ public function getSchemaDataDefaults() $schemaData['elemental-area-id'] = $area ? (int) $area->ID : null; $allowedTypes = $this->getTypes(); - $schemaData['allowed-elements'] = array_keys($allowedTypes); + $schemaData['allowed-elements'] = array_keys($allowedTypes ?? []); return $schemaData; } @@ -189,7 +189,7 @@ public function performReadonlyTransformation() $readOnlyField = $this->castedCopy(CompositeField::class); $blockReducer = $this->getReadOnlyBlockReducer(); $readOnlyField->setChildren( - FieldList::create(array_map($blockReducer, $this->getArea()->Elements()->toArray())) + FieldList::create(array_map($blockReducer, $this->getArea()->Elements()->toArray() ?? [])) ); $readOnlyField = $readOnlyField->performReadonlyTransformation(); @@ -213,7 +213,7 @@ public function performReadonlyTransformation() public function setSubmittedValue($value, $data = null) { // Content comes through as a JSON encoded list through a hidden field. - return $this->setValue(json_decode($value, true)); + return $this->setValue(json_decode($value ?? '', true)); } public function saveInto(DataObjectInterface $dataObject) @@ -221,7 +221,7 @@ public function saveInto(DataObjectInterface $dataObject) parent::saveInto($dataObject); $elementData = $this->Value(); - $idPrefixLength = strlen(sprintf(ElementalAreaController::FORM_NAME_TEMPLATE, '')); + $idPrefixLength = strlen(sprintf(ElementalAreaController::FORM_NAME_TEMPLATE ?? '', '')); if (!$elementData) { return; @@ -229,7 +229,7 @@ public function saveInto(DataObjectInterface $dataObject) foreach ($elementData as $form => $data) { // Extract the ID - $elementId = (int) substr($form, $idPrefixLength); + $elementId = (int) substr($form ?? '', $idPrefixLength ?? 0); /** @var BaseElement $element */ $element = $this->getArea()->Elements()->byID($elementId); diff --git a/src/GraphQL/Resolvers/Resolver.php b/src/GraphQL/Resolvers/Resolver.php index 03693b68..bcc23190 100644 --- a/src/GraphQL/Resolvers/Resolver.php +++ b/src/GraphQL/Resolvers/Resolver.php @@ -157,14 +157,14 @@ public static function newTitle(string $title = ''): ?string $parts = []; // does $title end with 'copy' (ignoring numbers for now)? - if (preg_match($hasCopyPattern, $title, $parts)) { + if (preg_match($hasCopyPattern ?? '', $title ?? '', $parts)) { $copy = $parts[1]; // does $title end with numbers? - if (preg_match($hasNumPattern, $copy, $parts)) { - $num = trim($parts[1]); - $len = strlen($num); + if (preg_match($hasNumPattern ?? '', $copy ?? '', $parts)) { + $num = trim($parts[1] ?? ''); + $len = strlen($num ?? ''); $inc = (int)$num + 1; - return substr($title, 0, -$len) . "$inc"; + return substr($title ?? '', 0, -$len) . "$inc"; } else { return $title . ' 2'; } diff --git a/src/Models/BaseElement.php b/src/Models/BaseElement.php index ca3cfebc..e402a10e 100644 --- a/src/Models/BaseElement.php +++ b/src/Models/BaseElement.php @@ -365,7 +365,7 @@ public function getCMSFields() $styles = $this->config()->get('styles'); - if ($styles && count($styles) > 0) { + if ($styles && count($styles ?? []) > 0) { $styleDropdown = DropdownField::create('Style', _t(__CLASS__.'.STYLE', 'Style variation'), $styles); $fields->insertBefore($styleDropdown, 'ExtraClass'); @@ -454,7 +454,7 @@ public function getController() $controllerClass = self::config()->controller_class; - if (!class_exists($controllerClass)) { + if (!class_exists($controllerClass ?? '')) { throw new Exception( 'Could not find controller class ' . $controllerClass . ' as defined in ' . static::class ); @@ -506,7 +506,7 @@ public function getSearchIndexable(): bool public function getContentForSearchIndex(): string { // Strips tags but be sure there's a space between words. - $content = trim(strip_tags(str_replace('<', ' <', $this->forTemplate()))); + $content = trim(strip_tags(str_replace('<', ' <', $this->forTemplate() ?? '') ?? '')); // Allow projects to update indexable content of third-party elements. $this->extend('updateContentForSearchIndex', $content); return $content; @@ -539,7 +539,7 @@ public function getRenderTemplates($suffix = '') { $classes = ClassInfo::ancestry($this->ClassName); $classes[static::class] = static::class; - $classes = array_reverse($classes); + $classes = array_reverse($classes ?? []); $templates = []; foreach ($classes as $key => $class) { @@ -599,7 +599,7 @@ public function updateFromFormData($data) */ protected function stripNamespacing($classname) { - $classParts = explode('\\', $classname); + $classParts = explode('\\', $classname ?? ''); return array_pop($classParts); } @@ -608,7 +608,7 @@ protected function stripNamespacing($classname) */ public function getSimpleClassName() { - return strtolower($this->sanitiseClassName($this->ClassName, '__')); + return strtolower($this->sanitiseClassName($this->ClassName, '__') ?? ''); } /** @@ -833,12 +833,12 @@ public function getAreaRelationName() */ public function sanitiseClassName($class, $delimiter = '-') { - return str_replace('\\', $delimiter, $class); + return str_replace('\\', $delimiter ?? '', $class ?? ''); } public function unsanitiseClassName($class, $delimiter = '-') { - return str_replace($delimiter, '\\', $class); + return str_replace($delimiter ?? '', '\\', $class ?? ''); } /** @@ -1041,7 +1041,7 @@ public function getStyleVariant() $styles = $this->config()->get('styles'); if (isset($styles[$style])) { - $style = strtolower($style); + $style = strtolower($style ?? ''); } else { $style = ''; } diff --git a/src/Models/ElementalArea.php b/src/Models/ElementalArea.php index d9f5bc9b..26a2ee03 100644 --- a/src/Models/ElementalArea.php +++ b/src/Models/ElementalArea.php @@ -4,7 +4,6 @@ use DNADesign\Elemental\Extensions\ElementalAreasExtension; use SilverStripe\Core\ClassInfo; -use SilverStripe\Core\Extensible; use SilverStripe\Core\Injector\Injector; use SilverStripe\Dev\TestOnly; use SilverStripe\ORM\ArrayList; @@ -14,6 +13,7 @@ use SilverStripe\ORM\HasManyList; use SilverStripe\ORM\UnsavedRelationList; use SilverStripe\Versioned\Versioned; +use SilverStripe\View\ViewableData; /** * Class ElementalArea @@ -79,7 +79,7 @@ public function supportedPageTypes() $elementalClasses = []; foreach (ClassInfo::getValidSubClasses(DataObject::class) as $class) { - if (Extensible::has_extension($class, ElementalAreasExtension::class)) { + if (ViewableData::has_extension($class, ElementalAreasExtension::class)) { $elementalClasses[] = $class; } } diff --git a/src/Reports/ElementsInUseReport.php b/src/Reports/ElementsInUseReport.php index c4e86403..0c5c4cb6 100644 --- a/src/Reports/ElementsInUseReport.php +++ b/src/Reports/ElementsInUseReport.php @@ -166,6 +166,6 @@ public function getBreadcrumbs() */ protected function unsanitiseClassName($class) { - return str_replace('-', '\\', $class); + return str_replace('-', '\\', $class ?? ''); } } diff --git a/src/Services/ElementTabProvider.php b/src/Services/ElementTabProvider.php index 8ab6d333..fd2a2f1a 100644 --- a/src/Services/ElementTabProvider.php +++ b/src/Services/ElementTabProvider.php @@ -140,6 +140,6 @@ protected function generateTabsForElement($elementClass) */ protected function getCacheKey($className) { - return 'Tabs.' . str_replace(['\\'], '-', $className); + return 'Tabs.' . str_replace(['\\'], '-', $className ?? ''); } } diff --git a/src/Tasks/MigrateContentToElement.php b/src/Tasks/MigrateContentToElement.php index 36e1f47b..ab98ea23 100644 --- a/src/Tasks/MigrateContentToElement.php +++ b/src/Tasks/MigrateContentToElement.php @@ -139,7 +139,7 @@ public function run($request) protected function isMigratable($pageType) { $migratable = SiteTree::has_extension($pageType, ElementalPageExtension::class); - if (in_array($pageType, Config::inst()->get(ElementalPageExtension::class, 'ignored_classes'))) { + if (in_array($pageType, Config::inst()->get(ElementalPageExtension::class, 'ignored_classes') ?? [])) { $migratable = false; } diff --git a/src/TopPage/DataExtension.php b/src/TopPage/DataExtension.php index f54d62f7..c4c5d117 100644 --- a/src/TopPage/DataExtension.php +++ b/src/TopPage/DataExtension.php @@ -6,12 +6,12 @@ use DNADesign\Elemental\Models\ElementalArea; use Page; use SilverStripe\Core\ClassInfo; -use SilverStripe\Core\Extensible; use SilverStripe\ORM\DataExtension as BaseDataExtension; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\Queries\SQLUpdate; use SilverStripe\ORM\ValidationException; use SilverStripe\Versioned\Versioned; +use SilverStripe\View\ViewableData; /** * Class DataExtension @@ -96,7 +96,7 @@ public function getTopPage(): ?Page { $list = [$this->owner]; - while (count($list) > 0) { + while (count($list ?? []) > 0) { /** @var DataObject|DataExtension $item */ $item = array_shift($list); @@ -380,7 +380,7 @@ protected function getTopPageTable(): string // Find the first ancestor table which has the extension applied // Note that this extension is expected to be subclassed foreach ($classes as $class) { - if (!Extensible::has_extension($class, static::class)) { + if (!ViewableData::has_extension($class, static::class)) { continue; } diff --git a/src/TopPage/SiteTreeExtension.php b/src/TopPage/SiteTreeExtension.php index 5e13a076..9a19f230 100644 --- a/src/TopPage/SiteTreeExtension.php +++ b/src/TopPage/SiteTreeExtension.php @@ -104,7 +104,7 @@ public function addDuplicatedObject(DataObject $object): void return; } - if (array_key_exists($key, $this->duplicatedObjects)) { + if (array_key_exists($key, $this->duplicatedObjects ?? [])) { array_unshift($this->duplicatedObjects[$key], $object); return; @@ -123,7 +123,7 @@ protected function getDuplicatedPageKey(): ?string { $pages = $this->duplicatedPages; - if (count($pages) === 0) { + if (count($pages ?? []) === 0) { return null; } @@ -148,7 +148,7 @@ protected function initDuplication(Page $original): void return; } - if (in_array($key, $this->duplicatedPages)) { + if (in_array($key, $this->duplicatedPages ?? [])) { // this should never happen as it would indicate a duplication loop return; } @@ -228,7 +228,7 @@ protected function writeDuplication(Page $original): void return; } - if (array_key_exists($key, $this->duplicatedObjects)) { + if (array_key_exists($key, $this->duplicatedObjects ?? [])) { $objects = $this->duplicatedObjects[$key]; /** @var DataObject|DataExtension $object */ diff --git a/tests/Behat/Context/FeatureContext.php b/tests/Behat/Context/FeatureContext.php index 7c65ae36..d5c048a8 100644 --- a/tests/Behat/Context/FeatureContext.php +++ b/tests/Behat/Context/FeatureContext.php @@ -201,7 +201,7 @@ public function stepIPressTheButtonInTheAddBlockPopover($text) { $popover = $this->getSession()->getPage()->find('css', '.popover-option-set'); - $blockType = strtolower($text); + $blockType = strtolower($text ?? ''); // Selector preferable not font-icon, but other class shared among all buttons $button = $popover->find('css', '.font-icon-block-'. $blockType); diff --git a/tests/Behat/Context/FixtureContext.php b/tests/Behat/Context/FixtureContext.php index 167f9c38..29cc0232 100644 --- a/tests/Behat/Context/FixtureContext.php +++ b/tests/Behat/Context/FixtureContext.php @@ -68,7 +68,7 @@ public function contentBlocksAreNotInLineEditable() $file = 'content-blocks-not-inline-editable.yml'; $path = $this->getDestinationConfigFolder($file); - file_put_contents($path, $config); + file_put_contents($path ?? '', $config); $this->activatedConfigFiles[] = $path; diff --git a/tests/Extensions/ElementalAreasExtensionTest.php b/tests/Extensions/ElementalAreasExtensionTest.php index ab47825d..8b7983c2 100644 --- a/tests/Extensions/ElementalAreasExtensionTest.php +++ b/tests/Extensions/ElementalAreasExtensionTest.php @@ -48,7 +48,7 @@ public function testGetElementalTypesSortsAlphabetically() $page = new SiteTree(); $types = $page->getElementalTypes(); - $this->assertContainsInOrder(['A test element', 'Content', 'Unused Element'], array_values($types)); + $this->assertContainsInOrder(['A test element', 'Content', 'Unused Element'], array_values($types ?? [])); } public function testGetElementalTypesAreNotSortedAlphabetically() @@ -59,7 +59,7 @@ public function testGetElementalTypesAreNotSortedAlphabetically() $page = new SiteTree(); $types = $page->getElementalTypes(); - $this->assertContainsInOrder(['Content', 'A test element', 'Unused Element'], array_values($types)); + $this->assertContainsInOrder(['Content', 'A test element', 'Unused Element'], array_values($types ?? [])); } /** @@ -71,7 +71,7 @@ public function testGetElementalTypesAreNotSortedAlphabetically() */ private function assertContainsInOrder(array $expected, array $actual) { - $matches = array_values(array_intersect($actual, $expected)); + $matches = array_values(array_intersect($actual ?? [], $expected)); $this->assertSame($expected, $matches); }