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 7, 2022
1 parent a850ecc commit f249b7a
Show file tree
Hide file tree
Showing 48 changed files with 284 additions and 275 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
10 changes: 5 additions & 5 deletions src/Dev/Tasks/FileMigrationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ 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;
}

Expand All @@ -367,11 +367,11 @@ private function findNativeFile($base, File $file, $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);
}, $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
44 changes: 22 additions & 22 deletions src/Dev/Tasks/NormaliseAccessMigrationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 Down Expand Up @@ -345,7 +345,7 @@ 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);
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
20 changes: 10 additions & 10 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 @@ -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,8 +382,8 @@ 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] = [];
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
10 changes: 5 additions & 5 deletions src/Dev/VersionedFilesMigrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,10 @@ private function doProtect()
{
foreach ($this->getVersionDirectories() as $path) {
$htaccessPath = Path::join($path, '.htaccess');
if (!file_exists($htaccessPath)) {
if (!file_exists($htaccessPath ?? '')) {
$content = "Require all denied";
@file_put_contents($htaccessPath, $content);
if (file_exists($htaccessPath)) {
@file_put_contents($htaccessPath ?? '', $content);
if (file_exists($htaccessPath ?? '')) {
$this->output("Added .htaccess file to $htaccessPath");
} else {
$this->output("Failed to add .htaccess file to $htaccessPath");
Expand All @@ -110,13 +110,13 @@ private function doProtect()
private function doDelete()
{
foreach ($this->getVersionDirectories() as $path) {
if (!is_dir($path)) {
if (!is_dir($path ?? '')) {
continue;
}

Filesystem::removeFolder($path);

if (!is_dir($path)) {
if (!is_dir($path ?? '')) {
$this->output("Deleted $path");
} else {
$this->output("Failed to delete $path");
Expand Down

0 comments on commit f249b7a

Please sign in to comment.