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 54daa19 commit 36a86c7
Show file tree
Hide file tree
Showing 15 changed files with 44 additions and 44 deletions.
2 changes: 1 addition & 1 deletion src/Control/LocaleAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
]
Expand Down
6 changes: 3 additions & 3 deletions src/Extension/FluentDirectorExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}
Expand Down
36 changes: 18 additions & 18 deletions src/Extension/FluentExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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]);
Expand All @@ -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
Expand Down Expand Up @@ -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']);

Expand Down Expand Up @@ -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('/^(?<field>\w+)ID$/', $translatedField, $matches)) {
if (!$field && preg_match('/^(?<field>\w+)ID$/', $translatedField ?? '', $matches)) {
$field = $fields->dataFieldByName($matches['field']);
}
if (!$field || $field->hasClass('fluent__localised-field')) {
Expand Down Expand Up @@ -985,24 +985,24 @@ protected function requireSavedInLocale()
protected function detectLocalisedTableField($tables, $sql)
{
// Check explicit "table"."field" within the fragment
if (preg_match('/"(?<table>[\w\\\\]+)"\."(?<field>\w+)"/i', $sql, $matches)) {
if (preg_match('/"(?<table>[\w\\\\]+)"\."(?<field>\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('/(?<![.])"(?<field>\w+)"(?![.])/i', $sql, $matches)) {
if (preg_match('/(?<![.])"(?<field>\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];
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Extension/FluentFilteredExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
2 changes: 1 addition & 1 deletion src/Extension/FluentSiteTreeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Extension/FluentVersionedExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? [])
);
}

Expand Down Expand Up @@ -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;
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Middleware/InitStateMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Model/CachableModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions src/Model/Locale.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public function getDefaultLocale()
*/
public function getLocaleSuffix()
{
$bits = explode('_', $this->Locale);
$bits = explode('_', $this->Locale ?? '');
return array_pop($bits);
}

Expand Down Expand Up @@ -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;
}

/**
Expand Down
8 changes: 4 additions & 4 deletions src/Search/FluentSearchForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? ''
);
}

Expand All @@ -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()
Expand Down
6 changes: 3 additions & 3 deletions src/State/BrowserLocaleDetector.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ public function detectLocale(HTTPRequest $request)
// break up string into pieces (languages and q factors)
preg_match_all(
'/(?<code>[a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(?<priority>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) {
Expand Down
2 changes: 1 addition & 1 deletion src/Task/ConvertTranslatableTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public function fluentClasses()
}
}
}
return array_unique($classes);
return array_unique($classes ?? []);
}

public function run($request)
Expand Down
4 changes: 2 additions & 2 deletions tests/php/Extension/FluentDirectorExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' => [
Expand All @@ -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');
}
Expand Down
2 changes: 1 addition & 1 deletion tests/php/Extension/FluentSiteTreeExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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() ?? ''));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion tests/php/Middleware/Stub/DetectLocaleMiddlewareSpy.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down

0 comments on commit 36a86c7

Please sign in to comment.