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 bd71554 commit 7eb8085
Show file tree
Hide file tree
Showing 54 changed files with 368 additions and 363 deletions.
2 changes: 1 addition & 1 deletion src/AssetControlExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ protected function findAssets(DataObject $record)
}

// De-dupe
return array_map("unserialize", array_unique(array_map("serialize", $files)));
return array_map("unserialize", array_unique(array_map("serialize", $files ?? [])));
}

/**
Expand Down
12 changes: 6 additions & 6 deletions src/Dev/Tasks/FileMigrationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -358,20 +358,20 @@ protected function migrateFile($base, File $file, $legacyFilename)
private function findNativeFile($base, File $file, $legacyFilename)
{
$path = $base . DIRECTORY_SEPARATOR . $legacyFilename;
if (file_exists($path)) {
if (file_exists($path ?? '')) {
return true;
}

$strippedLegacyFilename = $this->stripAssetsDir($legacyFilename);

// Try to find an alternative file
$legacyFilenameGlob = preg_replace_callback('/[a-z]/i', function ($matches) {
return sprintf('[%s%s]', strtolower($matches[0]), strtoupper($matches[0]));
}, $strippedLegacyFilename);
return sprintf('[%s%s]', strtolower($matches[0] ?? ''), strtoupper($matches[0] ?? ''));
}, $strippedLegacyFilename ?? '');

$files = glob($base . DIRECTORY_SEPARATOR . ASSETS_DIR . DIRECTORY_SEPARATOR . $legacyFilenameGlob);

switch (sizeof($files)) {
switch (sizeof($files ?? [])) {
case 0:
$this->logger->error(sprintf(
'%s could not be migrated because no matching file was found.',
Expand Down Expand Up @@ -433,7 +433,7 @@ private function stripAssetsDir($path, $base = '')
DIRECTORY_SEPARATOR
),
'',
$path
$path ?? ''
);
}

Expand Down Expand Up @@ -577,7 +577,7 @@ private function handleInvalidFile($file, $messages, $legacyFilename)
if ($this->logger) {
$logMessages = implode("\n\n", array_map(function ($msg) {
return $msg['message'];
}, $messages));
}, $messages ?? []));
$this->logger->warning(
sprintf(
" %s was not migrated because the file is not valid. More information: %s",
Expand Down
4 changes: 2 additions & 2 deletions src/Dev/Tasks/LegacyThumbnailMigrationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ protected function migrateFolder(FlysystemAssetStore $store, Folder $folder)
$moved = [];

// Get normalised store relative path
$folderPath = preg_replace('#^/#', '', $folder->getFilename());
$folderPath = preg_replace('#^/#', '', $folder->getFilename() ?? '');
$resampledFolderPath = $folderPath . '_resampled';

// Legacy thumbnails couldn't have been stored in a protected filesystem
Expand Down Expand Up @@ -190,7 +190,7 @@ protected function migrateFolder(FlysystemAssetStore $store, Folder $folder)
// get migrated leave the folder where it is.
if (!$foundError) {
$files = array_filter(
$filesystem->listContents($resampledFolderPath, true),
$filesystem->listContents($resampledFolderPath, true) ?? [],
function ($file) {
return $file['type'] === 'file';
}
Expand Down
58 changes: 29 additions & 29 deletions src/Dev/Tasks/NormaliseAccessMigrationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,18 +162,18 @@ public function run()
} else {
$this->warning(sprintf(
'Could not find any files with incorrect access permission, but %d errors were found.',
sizeof($this->errors)
sizeof($this->errors ?? [])
));
}

return [
'total' => 0,
'success' => 0,
'fail' => sizeof($this->errors)
'fail' => sizeof($this->errors ?? [])
];
}

$this->notice(sprintf('%d files with bad access permission have been found.', sizeof($badFiles)));
$this->notice(sprintf('%d files with bad access permission have been found.', sizeof($badFiles ?? [])));

$step++;

Expand All @@ -185,12 +185,12 @@ public function run()

// Step 3 - Move files to their correct spots
$this->notice(sprintf('Step %d/%d: Correct files with bad access permission', $step, $totalStep));
$badFileIDs = array_keys($badFiles);
$badFileIDs = array_keys($badFiles ?? []);
unset($badFiles);

$success = 0;
$fail = 0;
$count = sizeof($badFileIDs);
$count = sizeof($badFileIDs ?? []);
foreach ($this->loopBadFiles($badFileIDs) as $file) {
try {
if ($this->fix($file)) {
Expand All @@ -210,7 +210,7 @@ public function run()

// Print out some summary info
if ($this->errors) {
$this->warning(sprintf('Completed with %d errors', sizeof($this->errors)));
$this->warning(sprintf('Completed with %d errors', sizeof($this->errors ?? [])));
foreach ($this->errors as $error) {
$this->warning($error);
}
Expand All @@ -221,7 +221,7 @@ public function run()
return [
'total' => $count,
'success' => $success,
'fail' => sizeof($this->errors)
'fail' => sizeof($this->errors ?? [])
];
}

Expand Down Expand Up @@ -276,12 +276,12 @@ private function cleanup()

// Sort list of folders so that the deeper ones are processed first
usort($this->public_folders_to_truncate, function ($a, $b) {
$aCrumbs = explode('/', $a);
$bCrumbs = explode('/', $b);
if (sizeof($aCrumbs) > sizeof($bCrumbs)) {
$aCrumbs = explode('/', $a ?? '');
$bCrumbs = explode('/', $b ?? '');
if (sizeof($aCrumbs ?? []) > sizeof($bCrumbs ?? [])) {
return -1;
}
if (sizeof($aCrumbs) < sizeof($bCrumbs)) {
if (sizeof($aCrumbs ?? []) < sizeof($bCrumbs ?? [])) {
return 1;
}
return 0;
Expand All @@ -297,7 +297,7 @@ private function cleanup()

foreach ($truncatedPaths as $path) {
// For each folder that we've deleted, recursively check if we can now delete its parent.
$this->recursiveTruncate(dirname($path), $fs);
$this->recursiveTruncate(dirname($path ?? ''), $fs);
}

// Restore initial config
Expand Down Expand Up @@ -345,11 +345,11 @@ private function canBeTruncated($path, FilesystemInterface $fs)
*/
private function recursiveTruncate($path, FilesystemInterface $fs)
{
if ($path && ltrim($path, '.') && empty($fs->listContents($path))
if ($path && ltrim($path ?? '', '.') && empty($fs->listContents($path))
) {
$this->info(sprintf('Deleting empty folder %s', $path));
$fs->deleteDir($path);
$this->recursiveTruncate(dirname($path), $fs);
$this->recursiveTruncate(dirname($path ?? ''), $fs);
}
}

Expand All @@ -366,22 +366,22 @@ private function markFolderForTruncating(File $file)

$url = $file->getSourceURL(false);

if ($this->basePath && strpos($url, $this->basePath) === 0) {
if ($this->basePath && strpos($url ?? '', $this->basePath ?? '') === 0) {
// This bit is only relevant for unit test because our URL will be prefixied with the TestAssetStore path
$url = substr($url, strlen($this->basePath));
$url = substr($url ?? '', strlen($this->basePath ?? ''));
}

$url = trim($url, '/');
$url = trim($url ?? '', '/');

if (strpos($url, ASSETS_DIR . '/') === 0) {
if (strpos($url ?? '', ASSETS_DIR . '/') === 0) {
// Remove the assets prefix
$url = substr($url, strlen(ASSETS_DIR . '/'));
$url = substr($url ?? '', strlen(ASSETS_DIR . '/'));
}

$folderPath = trim(dirname($url), '/');
$folderPath = trim(dirname($url ?? ''), '/');


if (!in_array($folderPath, $this->public_folders_to_truncate)) {
if (!in_array($folderPath, $this->public_folders_to_truncate ?? [])) {
$this->public_folders_to_truncate[] = $folderPath;
}
}
Expand All @@ -408,13 +408,13 @@ public function findBadFiles()
}

foreach ($operations as &$ops) {
$ops = array_filter($ops, function ($storeToMove) {
$ops = array_filter($ops ?? [], function ($storeToMove) {
// We only keep operation that involvs protecting files for now.
return $storeToMove === AssetStore::VISIBILITY_PROTECTED;
});
}

return array_filter($operations, function ($ops) {
return array_filter($operations ?? [], function ($ops) {
return !empty($ops);
});
}
Expand Down Expand Up @@ -584,7 +584,7 @@ public function needToMove(File $draftFile)
$moveOperations[Versioned::DRAFT] = $this->needToMoveVersion($draftFile);
}

return array_filter($moveOperations);
return array_filter($moveOperations ?? []);
}

/**
Expand Down Expand Up @@ -621,7 +621,7 @@ private function needToMoveVersion(File $file)
*/
private function validateInputFile(File $file)
{
if (in_array($file->ClassName, $this->folderClasses)) {
if (in_array($file->ClassName, $this->folderClasses ?? [])) {
throw new InvalidArgumentException(sprintf(
'%s::%s(): Provided File can not be a Folder',
__CLASS__,
Expand All @@ -639,7 +639,7 @@ private function validateInputFile(File $file)
private function validateVisibility(File $file, $visibility)
{
$validVisibilities = [AssetStore::VISIBILITY_PROTECTED, AssetStore::VISIBILITY_PUBLIC];
if (!in_array($visibility, $validVisibilities)) {
if (!in_array($visibility, $validVisibilities ?? [])) {
throw new LogicException(sprintf(
'%s::%s(): File %s visibility of "%s" is invalid',
__CLASS__,
Expand All @@ -659,9 +659,9 @@ private function loopBadFiles(array $IDs)
{
$limit = 100;
$yieldCount = 0;
$total = sizeof($IDs);
$total = sizeof($IDs ?? []);

$chunks = array_chunk($IDs, $limit);
$chunks = array_chunk($IDs ?? [], $limit ?? 0);
unset($IDs);

foreach ($chunks as $chunk) {
Expand All @@ -670,7 +670,7 @@ private function loopBadFiles(array $IDs)
foreach (File::get()->filter('ID', $chunk) as $file) {
yield $file;
}
$yieldCount += sizeof($chunk);
$yieldCount += sizeof($chunk ?? []);
$this->notice(sprintf('Processed %d files out of %d', $yieldCount, $total));
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Dev/Tasks/SecureAssetsMigrationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,14 @@ public function setLogger(LoggerInterface $logger)
public function htaccessMatch($content)
{
$regexes = $this->htaccessRegexes;
$lines = explode("\n", $content);
$lines = explode("\n", $content ?? '');

if (count($lines) != count($regexes)) {
if (count($lines ?? []) != count($regexes ?? [])) {
return false;
}

foreach ($lines as $i => $line) {
if (!preg_match($regexes[$i], $line)) {
if (!preg_match($regexes[$i] ?? '', $line ?? '')) {
return false;
}
}
Expand Down
24 changes: 12 additions & 12 deletions src/Dev/Tasks/TagsToShortcodeHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public function __construct($baseClass = null, $includeBaseClass = false)
$this->baseClass = $baseClass ?: DataObject::class;
$this->includeBaseClass = $includeBaseClass;

$this->validTagsPattern = implode('|', array_keys(static::VALID_TAGS));
$this->validTagsPattern = implode('|', array_keys(static::VALID_TAGS ?? []));
$this->validAttributesPattern = implode('|', static::VALID_ATTRIBUTES);
}

Expand Down Expand Up @@ -152,7 +152,7 @@ private function updateTable($table, $field)
{
$sqlSelect = SQLSelect::create(['"ID"', "\"$field\""], "\"$table\"");
$whereAnys = [];
foreach (array_keys(static::VALID_TAGS) as $tag) {
foreach (array_keys(static::VALID_TAGS ?? []) as $tag) {
$whereAnys[]= "\"$table\".\"$field\" LIKE '%<$tag%'";
$whereAnys[]= "\"$table\".\"$field\" LIKE '%[$tag%'";
}
Expand Down Expand Up @@ -194,7 +194,7 @@ public function getNewContent($content)
$tags = $this->getTagsInContent($content);
foreach ($tags as $tag) {
if ($newTag = $this->getNewTag($tag)) {
$content = str_replace($tag, $newTag, $content);
$content = str_replace($tag ?? '', $newTag ?? '', $content ?? '');
}
}

Expand All @@ -211,7 +211,7 @@ private function getTagsInContent($content)
$resultTags = [];

$regex = '/<('.$this->validTagsPattern.')\s[^>]*?('.$this->validAttributesPattern.')\s*=.*?>/i';
preg_match_all($regex, $content, $matches, PREG_SET_ORDER);
preg_match_all($regex ?? '', $content ?? '', $matches, PREG_SET_ORDER);
if ($matches) {
foreach ($matches as $match) {
$resultTags []= $match[0];
Expand All @@ -232,7 +232,7 @@ private function getTagTuple($tag)
$this->validTagsPattern,
$this->validAttributesPattern
);
preg_match($pattern, $tag, $matches);
preg_match($pattern ?? '', $tag ?? '', $matches);
return $matches;
}

Expand All @@ -253,7 +253,7 @@ private function getParsedFileIDFromSrc($src)

// set fileID to the filepath relative to assets dir
$pattern = sprintf('#^/?(%s/?)?#', ASSETS_DIR);
$fileID = preg_replace($pattern, '', $src);
$fileID = preg_replace($pattern ?? '', '', $src ?? '');

// Our file reference might be using invalid file name that will have been cleaned up by the migration task.
$fileID = $defaultFileIDHelper->cleanFilename($fileID);
Expand Down Expand Up @@ -288,7 +288,7 @@ private function getNewTag($tag)
if (!isset($tuple['tagType']) || !isset($tuple['src'])) {
return null;
}
$tagType = strtolower($tuple['tagType']);
$tagType = strtolower($tuple['tagType'] ?? '');
$src = $tuple['src'] ?: $tuple['href'];

// Search for a File object containing this filename
Expand Down Expand Up @@ -322,12 +322,12 @@ private function getNewTag($tag)
"",
" id=\"{$file->ID}\"]",
];
$shortcode = preg_replace($find, $replace, $tag);
$shortcode = preg_replace($find ?? '', $replace ?? '', $tag ?? '');
} elseif ($tagType == 'a') {
$attribute = 'href';
$find = "/$attribute\s*=\s*(?:\"|').*?(?:\"|')/i";
$replace = "$attribute=\"[file_link,id={$file->ID}]\"";
$shortcode = preg_replace($find, $replace, $tag);
$shortcode = preg_replace($find ?? '', $replace ?? '', $tag ?? '');
} else {
return null;
}
Expand Down Expand Up @@ -382,16 +382,16 @@ private function getFieldMap($baseClass, $includeBaseClass, $fieldNames)
$fields = $schema->fieldSpecs($class, DataObjectSchema::DB_ONLY|DataObjectSchema::UNINHERITED);

foreach ($fields as $field => $type) {
$type = preg_replace('/\(.*\)$/', '', $type);
if (in_array($type, $fieldNames)) {
$type = preg_replace('/\(.*\)$/', '', $type ?? '');
if (in_array($type, $fieldNames ?? [])) {
$table = $schema->tableForField($class, $field);
if (!isset($mapping[$class])) {
$mapping[$class] = [];
}
if (!isset($mapping[$class][$table])) {
$mapping[$class][$table] = [];
}
if (!in_array($field, $mapping[$class][$table])) {
if (!in_array($field, $mapping[$class][$table] ?? [])) {
$mapping[$class][$table][] = $field;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Dev/TestAssetStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public static function reset()
// Remove all files in this store
if (self::$basedir) {
$path = self::base_path();
if (file_exists($path)) {
if (file_exists($path ?? '')) {
SSFilesystem::removeFolder($path);
}
}
Expand Down

0 comments on commit 7eb8085

Please sign in to comment.