From 36a86c709612008955a9a2f57e63d82e5b976d03 Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Wed, 13 Apr 2022 14:09:46 +1200 Subject: [PATCH] ENH PHP 8.1 compatibility --- src/Control/LocaleAdmin.php | 2 +- src/Extension/FluentDirectorExtension.php | 6 ++-- src/Extension/FluentExtension.php | 36 +++++++++---------- src/Extension/FluentFilteredExtension.php | 4 +-- src/Extension/FluentSiteTreeExtension.php | 2 +- src/Extension/FluentVersionedExtension.php | 4 +-- src/Middleware/InitStateMiddleware.php | 4 +-- src/Model/CachableModel.php | 2 +- src/Model/Locale.php | 4 +-- src/Search/FluentSearchForm.php | 8 ++--- src/State/BrowserLocaleDetector.php | 6 ++-- src/Task/ConvertTranslatableTask.php | 2 +- .../Extension/FluentDirectorExtensionTest.php | 4 +-- .../Extension/FluentSiteTreeExtensionTest.php | 2 +- .../Stub/DetectLocaleMiddlewareSpy.php | 2 +- 15 files changed, 44 insertions(+), 44 deletions(-) diff --git a/src/Control/LocaleAdmin.php b/src/Control/LocaleAdmin.php index 152923a1..87a358a9 100644 --- a/src/Control/LocaleAdmin.php +++ b/src/Control/LocaleAdmin.php @@ -44,7 +44,7 @@ public function getClientConfig() 'code' => $locale->getLocale(), 'title' => $locale->getTitle(), ]; - }, Locale::getCached()->toArray()), + }, Locale::getCached()->toArray() ?? []), 'locale' => FluentState::singleton()->getLocale(), 'param' => FluentDirectorExtension::config()->get('query_param'), ] diff --git a/src/Extension/FluentDirectorExtension.php b/src/Extension/FluentDirectorExtension.php index 6ebf1d66..adb480f8 100644 --- a/src/Extension/FluentDirectorExtension.php +++ b/src/Extension/FluentDirectorExtension.php @@ -123,7 +123,7 @@ protected function getExplicitRoutes($originalRules) $url = $localeObj->getURLSegment(); // apply encode so we could route urls that contain multi-byte charaters - $url = urlencode($url); + $url = urlencode($url ?? ''); // Apply to nested page url $controller = $this->getRuleController($originalRules['$URLSegment//$Action/$ID/$OtherID'], $localeObj); @@ -166,9 +166,9 @@ protected function getRuleController($existingRule, $localeObj) */ protected function insertRuleBefore(array $rules, $key, array $rule, $prependIfMissing = true) { - $i = array_search($key, array_keys($rules)); + $i = array_search($key, array_keys($rules ?? [])); if ($i !== false) { - return array_slice($rules, 0, $i, true) + $rule + array_slice($rules, $i, null, true); + return array_slice($rules ?? [], 0, $i, true) + $rule + array_slice($rules ?? [], $i ?? 0, null, true); } elseif ($prependIfMissing) { $rules = $rule + $rules; } diff --git a/src/Extension/FluentExtension.php b/src/Extension/FluentExtension.php index 07ff148f..86d205dc 100644 --- a/src/Extension/FluentExtension.php +++ b/src/Extension/FluentExtension.php @@ -199,7 +199,7 @@ protected function isFieldLocalised($field, $type, $class) return false; } if ($filter && is_array($filter)) { - return in_array($field, $filter); + return in_array($field, $filter ?? []); } // Named blacklist @@ -249,7 +249,7 @@ public function getLocalisedTables() // Mark this table as translatable $table = DataObject::getSchema()->tableName($class); - $includedTables[$table] = array_keys($translatedFields); + $includedTables[$table] = array_keys($translatedFields ?? []); } return $includedTables; } @@ -265,11 +265,11 @@ public function getLocalisedTables() protected function anyMatch($value, $patterns) { // Test both explicit value, as well as the value stripped of any trailing parameters - $valueBase = preg_replace('/\(.*/', '', $value); + $valueBase = preg_replace('/\(.*/', '', $value ?? ''); foreach ($patterns as $pattern) { - if (strpos($pattern, '/') === 0) { + if (strpos($pattern ?? '', '/') === 0) { // Assume value prefaced with '/' are regexp - if (preg_match($pattern, $value) || preg_match($pattern, $valueBase)) { + if (preg_match($pattern ?? '', $value ?? '') || preg_match($pattern ?? '', $valueBase ?? '')) { return true; } } else { @@ -352,7 +352,7 @@ protected function validateChildConfig() 'extensions', Config::EXCLUDE_EXTRA_SOURCES | Config::UNINHERITED ) ?: []; - $extensions = array_filter(array_values($extensions)); + $extensions = array_filter(array_values($extensions ?? [])); foreach ($extensions as $extension) { $extensionClass = Extension::get_classname_without_arguments($extension); if (is_a($extensionClass, self::class, true)) { @@ -460,11 +460,11 @@ public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null) $localisedColumn = str_replace( "\"{$field}\"", "\"{$table}\".\"{$field}\"", - $localisedColumn + $localisedColumn ?? '' ); } // Apply substitutions - $localisedColumn = str_replace($conditionSearch, $conditionReplace, $localisedColumn); + $localisedColumn = str_replace($conditionSearch ?? '', $conditionReplace ?? '', $localisedColumn ?? ''); if ($column !== $localisedColumn) { // Wrap sort in group to prevent dataquery messing it up unset($order[$column]); @@ -488,12 +488,12 @@ public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null) $parameters = array(); $predicate = $condition->conditionSQL($parameters); } else { - $parameters = array_values(reset($condition)); - $predicate = key($condition); + $parameters = array_values(reset($condition) ?? []); + $predicate = key($condition ?? []); } // Apply substitutions - $localisedPredicate = str_replace($conditionSearch, $conditionReplace, $predicate); + $localisedPredicate = str_replace($conditionSearch ?? '', $conditionReplace ?? '', $predicate ?? ''); $where[$index] = [ $localisedPredicate => $parameters @@ -581,8 +581,8 @@ protected function localiseManipulationTable(&$manipulation, $table, $localeTabl // Filter fields by localised fields $localisedUpdate['fields'] = array_intersect_key( - $updates['fields'], - array_combine($localisedFields, $localisedFields) + $updates['fields'] ?? [], + array_combine($localisedFields ?? [], $localisedFields ?? []) ); unset($localisedUpdate['fields']['id']); @@ -938,7 +938,7 @@ public function updateCMSFields(FieldList $fields) // If the translated field has an ID suffix also check for the non-suffixed version // E.g. UploadField() $field = $fields->dataFieldByName($translatedField); - if (!$field && preg_match('/^(?\w+)ID$/', $translatedField, $matches)) { + if (!$field && preg_match('/^(?\w+)ID$/', $translatedField ?? '', $matches)) { $field = $fields->dataFieldByName($matches['field']); } if (!$field || $field->hasClass('fluent__localised-field')) { @@ -985,24 +985,24 @@ protected function requireSavedInLocale() protected function detectLocalisedTableField($tables, $sql) { // Check explicit "table"."field" within the fragment - if (preg_match('/"(?[\w\\\\]+)"\."(?\w+)"/i', $sql, $matches)) { + if (preg_match('/"(?
[\w\\\\]+)"\."(?\w+)"/i', $sql ?? '', $matches)) { $table = $matches['table']; $field = $matches['field']; // Ensure both table and this field are valid - if (empty($tables[$table]) || !in_array($field, $tables[$table])) { + if (empty($tables[$table]) || !in_array($field, $tables[$table] ?? [])) { return [null, null, false]; } return [$table, $field, true]; } // Check sole "field" without table specifier ("name" without leading or trailing '.') - if (preg_match('/(?\w+)"(?![.])/i', $sql, $matches)) { + if (preg_match('/(?\w+)"(?![.])/i', $sql ?? '', $matches)) { $field = $matches['field']; // Check if this field is in any of the tables, and just pick any that match foreach ($tables as $table => $fields) { - if (in_array($field, $fields)) { + if (in_array($field, $fields ?? [])) { return [$table, $field, false]; } } diff --git a/src/Extension/FluentFilteredExtension.php b/src/Extension/FluentFilteredExtension.php index f074e2dc..dabbd3e8 100644 --- a/src/Extension/FluentFilteredExtension.php +++ b/src/Extension/FluentFilteredExtension.php @@ -167,10 +167,10 @@ protected function getModeIsStage() $readingMode = Versioned::get_reading_mode(); $draft = Versioned::DRAFT; - if (strlen($readingMode) === 0) { + if (strlen($readingMode ?? '') === 0) { $readingMode = Versioned::DEFAULT_MODE; } - return substr_compare($readingMode, $draft, strlen($readingMode) - strlen($draft), strlen($draft)) === 0; + return substr_compare($readingMode ?? '', $draft ?? '', strlen($readingMode ?? '') - strlen($draft ?? ''), strlen($draft ?? '')) === 0; } } diff --git a/src/Extension/FluentSiteTreeExtension.php b/src/Extension/FluentSiteTreeExtension.php index 2fabca6f..e87c7a89 100644 --- a/src/Extension/FluentSiteTreeExtension.php +++ b/src/Extension/FluentSiteTreeExtension.php @@ -61,7 +61,7 @@ public function updateRelativeLink(&$base, &$action) if (!$this->owner->exists()) { $base = Controller::join_links( $base, - '?' . FluentDirectorExtension::config()->get('query_param') . '=' . urlencode($localeObj->Locale) + '?' . FluentDirectorExtension::config()->get('query_param') . '=' . urlencode($localeObj->Locale ?? '') ); return; } diff --git a/src/Extension/FluentVersionedExtension.php b/src/Extension/FluentVersionedExtension.php index a9f436bb..f4b71153 100644 --- a/src/Extension/FluentVersionedExtension.php +++ b/src/Extension/FluentVersionedExtension.php @@ -231,7 +231,7 @@ public function augmentWrite(&$manipulation) if ($suffix === self::SUFFIX_VERSIONS) { $localisedVersionFields = array_merge( $localisedVersionFields, - array_keys($this->defaultVersionsFields) + array_keys($this->defaultVersionsFields ?? []) ); } @@ -428,7 +428,7 @@ public static function prepoulateIdsInLocale($locale, $dataObjectClass, $populat $ids = $result->column('RecordID'); // We need to execute ourselves as the param is lost from the subSelect - self::$idsInLocaleCache[$locale][$table] = array_combine($ids, $ids); + self::$idsInLocaleCache[$locale][$table] = array_combine($ids ?? [], $ids ?? []); self::$idsInLocaleCache[$locale][$table]['_complete'] = true; } } diff --git a/src/Middleware/InitStateMiddleware.php b/src/Middleware/InitStateMiddleware.php index f29bea61..c0cb38f6 100644 --- a/src/Middleware/InitStateMiddleware.php +++ b/src/Middleware/InitStateMiddleware.php @@ -63,10 +63,10 @@ public function getIsFrontend(HTTPRequest $request) { $adminPaths = static::config()->get('admin_url_paths'); $adminPaths[] = AdminRootController::config()->get('url_base') . '/'; - $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 false; } } diff --git a/src/Model/CachableModel.php b/src/Model/CachableModel.php index 9ee835dc..fe29576c 100644 --- a/src/Model/CachableModel.php +++ b/src/Model/CachableModel.php @@ -84,7 +84,7 @@ protected static function databaseIsReady() } $objFields = $object->getSchema()->databaseFields($object, false); - $missingFields = array_diff_key($objFields, $dbFields); + $missingFields = array_diff_key($objFields ?? [], $dbFields); if ($missingFields) { return false; diff --git a/src/Model/Locale.php b/src/Model/Locale.php index 0c9cd244..643ffa2d 100644 --- a/src/Model/Locale.php +++ b/src/Model/Locale.php @@ -153,7 +153,7 @@ public function getDefaultLocale() */ public function getLocaleSuffix() { - $bits = explode('_', $this->Locale); + $bits = explode('_', $this->Locale ?? ''); return array_pop($bits); } @@ -350,7 +350,7 @@ public static function getByLocale($locale) */ public function isLocale($locale) { - return stripos(i18n::convert_rfc1766($locale), i18n::convert_rfc1766($this->Locale)) === 0; + return stripos(i18n::convert_rfc1766($locale) ?? '', i18n::convert_rfc1766($this->Locale) ?? '') === 0; } /** diff --git a/src/Search/FluentSearchForm.php b/src/Search/FluentSearchForm.php index bd697345..7c59a7b2 100644 --- a/src/Search/FluentSearchForm.php +++ b/src/Search/FluentSearchForm.php @@ -51,9 +51,9 @@ public function getResults() ]; foreach ($keyword_patterns as $k_p) { $keywords = preg_replace_callback( - $k_p['patterns'], + $k_p['patterns'] ?? '', $k_p['callback'], - $keywords + $keywords ?? '' ); } @@ -70,10 +70,10 @@ public function getResults() ORDER BY Relevance DESC SQL; $params = [ - str_replace(['*', '+', '-'], '', $keywords), + str_replace(['*', '+', '-'], '', $keywords ?? ''), $current_locale, $keywords, - htmlentities($keywords, ENT_NOQUOTES, 'UTF-8') + htmlentities($keywords ?? '', ENT_NOQUOTES, 'UTF-8') ]; // Generate results list $sitetree_objects = SiteTree::get() diff --git a/src/State/BrowserLocaleDetector.php b/src/State/BrowserLocaleDetector.php index 06aa32af..b5e440ed 100644 --- a/src/State/BrowserLocaleDetector.php +++ b/src/State/BrowserLocaleDetector.php @@ -38,14 +38,14 @@ public function detectLocale(HTTPRequest $request) // break up string into pieces (languages and q factors) preg_match_all( '/(?[a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(?1|0\.[0-9]+))?/i', - $inputLocales, + $inputLocales ?? '', $parsedLocales ); $prioritisedLocales = []; - if (count($parsedLocales['code'])) { + if (count($parsedLocales['code'] ?? [])) { // create a list like "en" => 0.8 - $parsedLocales = array_combine($parsedLocales['code'], $parsedLocales['priority']); + $parsedLocales = array_combine($parsedLocales['code'] ?? [], $parsedLocales['priority'] ?? []); // Generate nested list of priorities => [locales] foreach ($parsedLocales as $locale => $priority) { diff --git a/src/Task/ConvertTranslatableTask.php b/src/Task/ConvertTranslatableTask.php index 217ed5d1..cec80a69 100644 --- a/src/Task/ConvertTranslatableTask.php +++ b/src/Task/ConvertTranslatableTask.php @@ -80,7 +80,7 @@ public function fluentClasses() } } } - return array_unique($classes); + return array_unique($classes ?? []); } public function run($request) diff --git a/tests/php/Extension/FluentDirectorExtensionTest.php b/tests/php/Extension/FluentDirectorExtensionTest.php index 424a0bce..982c89d4 100644 --- a/tests/php/Extension/FluentDirectorExtensionTest.php +++ b/tests/php/Extension/FluentDirectorExtensionTest.php @@ -94,7 +94,7 @@ protected function setUpRoutes() $rules = Director::config()->rules; // Modify the rule for our test controller to include the locale parameter - $i = array_search('admin', array_keys($rules)); + $i = array_search('admin', array_keys($rules ?? [])); if ($i !== false) { $rule = [ 'nouvelle-z%C3%A9lande/TestController//$Action/$ID/$OtherID' => [ @@ -103,7 +103,7 @@ protected function setUpRoutes() ] ]; - $rules = array_slice($rules, 0, $i, true) + $rule + array_slice($rules, $i, null, true); + $rules = array_slice($rules ?? [], 0, $i, true) + $rule + array_slice($rules ?? [], $i ?? 0, null, true); } else { throw new \Exception('Could not find "admin" url rule'); } diff --git a/tests/php/Extension/FluentSiteTreeExtensionTest.php b/tests/php/Extension/FluentSiteTreeExtensionTest.php index ef91578f..19f7bfc0 100644 --- a/tests/php/Extension/FluentSiteTreeExtensionTest.php +++ b/tests/php/Extension/FluentSiteTreeExtensionTest.php @@ -295,7 +295,7 @@ public function testUpdateCMSActionsDrafted() $this->assertEquals('Saved', $actionSave->Title()); // The default value changed between SS 4.0 and 4.1 - assert it contains Publish instead of exact matching - $this->assertStringContainsString('publish', strtolower($actionPublish->Title())); + $this->assertStringContainsString('publish', strtolower($actionPublish->Title() ?? '')); } /** diff --git a/tests/php/Middleware/Stub/DetectLocaleMiddlewareSpy.php b/tests/php/Middleware/Stub/DetectLocaleMiddlewareSpy.php index ff00173d..ce52cdd5 100644 --- a/tests/php/Middleware/Stub/DetectLocaleMiddlewareSpy.php +++ b/tests/php/Middleware/Stub/DetectLocaleMiddlewareSpy.php @@ -17,7 +17,7 @@ class DetectLocaleMiddlewareSpy extends DetectLocaleMiddleware implements TestOn { public function __call($method, $arguments) { - if (method_exists($this, $method)) { + if (method_exists($this, $method ?? '')) { return $this->$method(...$arguments); } }