Skip to content

Commit

Permalink
Merge pull request #1264 from creative-commoners/pulls/1/php81
Browse files Browse the repository at this point in the history
ENH PHP 8.1 compatibility
  • Loading branch information
GuySartorelli authored Apr 22, 2022
2 parents b5f57ed + 5f4a01e commit 617464e
Show file tree
Hide file tree
Showing 18 changed files with 52 additions and 52 deletions.
14 changes: 7 additions & 7 deletions code/Controller/AssetAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ public function getClientConfig()
'filesizeBase' => 1024,
'acceptedFiles' => implode(',', array_map(function ($ext) {
return $ext[0] != '.' ? ".$ext" : $ext;
}, $validator->getAllowedExtensions()))
}, $validator->getAllowedExtensions() ?? []))
]
]);
}
Expand Down Expand Up @@ -369,7 +369,7 @@ public function apiUploadFile(HTTPRequest $request)
return null;
}
$tmpFile = $data['Upload'];
if (empty($data['ID']) || empty($tmpFile['name']) || !array_key_exists('Name', $data)) {
if (empty($data['ID']) || empty($tmpFile['name']) || !array_key_exists('Name', $data ?? [])) {
$this->jsonError(400, _t(__CLASS__.'.INVALID_REQUEST', 'Invalid request'));
return null;
}
Expand Down Expand Up @@ -419,7 +419,7 @@ public function apiUploadFile(HTTPRequest $request)
return null;
}

$tuple['Name'] = basename($tuple['Filename']);
$tuple['Name'] = basename($tuple['Filename'] ?? '');
return (new HTTPResponse(json_encode($tuple)))
->addHeader('Content-Type', 'application/json');
}
Expand Down Expand Up @@ -464,7 +464,7 @@ public function apiHistory(HTTPRequest $request)
// swap the order so we can get the version number to compare against.
// i.e version 3 needs to know version 2 is the previous version
$copy = $versions->map('Version', 'Version')->toArray();
foreach (array_reverse($copy) as $k => $v) {
foreach (array_reverse($copy ?? []) as $k => $v) {
if ($prev) {
$next[$v] = $prev;
}
Expand Down Expand Up @@ -1050,7 +1050,7 @@ protected function saveOrPublish($data, $form, $doPublish = false)
// File::class make sure to register the file extension and your class to config in
// File::class_for_file_extension
$currentClass = $record->getClassName();
if (!is_a($currentClass, $newClass, true) ||
if (!is_a($currentClass, $newClass ?? '', true) ||
($currentClass !== $newClass && $newClass === File::class)
) {
$record = $record->newClassInstance($newClass);
Expand Down Expand Up @@ -1316,7 +1316,7 @@ protected function getUpload()
$upload = Upload::create();
$upload->getValidator()->setAllowedExtensions(
// filter out '' since this would be a regex problem on JS end
array_filter(File::getAllowedExtensions())
array_filter(File::getAllowedExtensions() ?? [])
);
$upload->getValidator()->setAllowedMaxFileSize(
$this->config()->max_upload_size
Expand Down Expand Up @@ -1425,7 +1425,7 @@ public function canView($member = null)
// Since admin/assets is used as the endpoint for various other CMS modals,
// we need to permit most admin/assets actions
$asAjax = $this->getRequest()->isAjax()
|| in_array('application/json', $this->getRequest()->getAcceptMimetypes(false));
|| in_array('application/json', $this->getRequest()->getAcceptMimetypes(false) ?? []);
if ($asAjax && Permission::checkMember($member, 'CMS_ACCESS')) {
return true;
}
Expand Down
2 changes: 1 addition & 1 deletion code/Controller/AssetAdminFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public function humanizedChanges($from, $to)
$diff = new DataDifferencer($fromRecord, $toRecord);
$changes = $diff->changedFieldNames();

$k = array_search('LastEdited', $changes);
$k = array_search('LastEdited', $changes ?? []);

if ($k !== false) {
unset($changes[$k]);
Expand Down
2 changes: 1 addition & 1 deletion code/Forms/AssetFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ protected function getPopoverActions($record)
];

$this->invokeWithExtensions('updatePopoverActions', $actions, $record);
return array_filter($actions);
return array_filter($actions ?? []);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion code/Forms/FileFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ protected function getFormActions(RequestHandler $controller = null, $formName,
}

// Group all actions
if (count($actionItems) > 1) {
if (count($actionItems ?? []) > 1) {
$actionItems = [
FieldGroup::create($actionItems)
->setName('Actions')
Expand Down
22 changes: 11 additions & 11 deletions code/Forms/RemoteFileFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public function getForm(RequestHandler $controller = null, $name = self::DEFAULT
$form = Form::create($controller, $name, $fields, $actions, $validator);
$form->addExtraClass('form--fill-height');
$form->addExtraClass('form--no-dividers');
$form->addExtraClass('insert-embed-modal--'. strtolower($context['type']));
$form->addExtraClass('insert-embed-modal--'. strtolower($context['type'] ?? ''));

// Extend form
$this->invokeWithExtensions('updateForm', $form, $controller, $name, $context);
Expand Down Expand Up @@ -230,7 +230,7 @@ protected function getEditFormFields($context)
return $this->getCreateFormFields();
}

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

// Get embed
$this->validateUrl($url);
Expand Down Expand Up @@ -316,12 +316,12 @@ protected function getEditFormFields($context)
*/
protected function validateURLScheme($url)
{
$scheme = strtolower(parse_url($url, PHP_URL_SCHEME));
$scheme = strtolower(parse_url($url ?? '', PHP_URL_SCHEME) ?? '');
$allowedSchemes = self::config()->get('fileurl_scheme_whitelist');
$disallowedSchemes = self::config()->get('fileurl_scheme_blacklist');
if (!$scheme
|| ($allowedSchemes && !in_array($scheme, $allowedSchemes))
|| ($disallowedSchemes && in_array($scheme, $disallowedSchemes))
|| ($allowedSchemes && !in_array($scheme, $allowedSchemes ?? []))
|| ($disallowedSchemes && in_array($scheme, $disallowedSchemes ?? []))
) {
throw new InvalidRemoteUrlException(_t(
__CLASS__ . '.ERROR_SCHEME',
Expand All @@ -336,12 +336,12 @@ protected function validateURLScheme($url)
*/
protected function validateURLHost($url)
{
$domain = strtolower(parse_url($url, PHP_URL_HOST));
$domain = strtolower(parse_url($url ?? '', PHP_URL_HOST) ?? '');
$allowedDomains = self::config()->get('fileurl_domain_whitelist');
$disallowedDomains = self::config()->get('fileurl_domain_blacklist');
if (!$domain
|| ($allowedDomains && !in_array($domain, $allowedDomains))
|| ($disallowedDomains && in_array($domain, $disallowedDomains))
|| ($allowedDomains && !in_array($domain, $allowedDomains ?? []))
|| ($disallowedDomains && in_array($domain, $disallowedDomains ?? []))
) {
throw new InvalidRemoteUrlException(_t(
__CLASS__ . '.ERROR_HOSTNAME',
Expand All @@ -356,14 +356,14 @@ protected function validateURLHost($url)
*/
protected function validateURLPort($url)
{
$port = (int)parse_url($url, PHP_URL_PORT);
$port = (int)parse_url($url ?? '', PHP_URL_PORT);
if (!$port) {
return;
}
$allowedPorts = self::config()->get('fileurl_port_whitelist');
$disallowedPorts = self::config()->get('fileurl_port_blacklist');
if (($allowedPorts && !in_array($port, $allowedPorts))
|| ($disallowedPorts && in_array($port, $disallowedPorts))
if (($allowedPorts && !in_array($port, $allowedPorts ?? []))
|| ($disallowedPorts && in_array($port, $disallowedPorts ?? []))
) {
throw new InvalidRemoteUrlException(_t(
__CLASS__ . '.ERROR_PORT',
Expand Down
2 changes: 1 addition & 1 deletion code/Forms/UploadField.php
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ public function performDisabledTransformation()
public function validate($validator)
{
$maxFiles = $this->getAllowedMaxFileNumber();
$count = count($this->getItems());
$count = count($this->getItems() ?? []);

if ($maxFiles < 1 || $count <= $maxFiles) {
return true;
Expand Down
14 changes: 7 additions & 7 deletions code/GraphQL/Resolvers/AssetAdminResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ public static function resolveDeleteFiles($object, array $args, $context, Resolv

/** @var DataList $file */
$files = Versioned::get_by_stage(File::class, Versioned::DRAFT)->byIDs($idList);
if ($files->count() < count($idList)) {
if ($files->count() < count($idList ?? [])) {
// Find out which files count not be found
$missingIds = array_diff($idList, $files->column('ID'));
$missingIds = array_diff($idList ?? [], $files->column('ID'));
throw new InvalidArgumentException(sprintf(
'%s items %s are not found',
File::class,
Expand Down Expand Up @@ -193,7 +193,7 @@ public static function resolvePublicationNotice($value, array $args, array $cont
{
$fieldName = $info->fieldName;
$method = 'get'.$fieldName;
if (method_exists($value, $method)) {
if (method_exists($value, $method ?? '')) {
return $value->$method();
}

Expand Down Expand Up @@ -227,9 +227,9 @@ public static function resolveReadDescendantFileCounts($object, array $args, $co

/** @var DataList|File[] $files */
$files = Versioned::get_by_stage(File::class, Versioned::DRAFT)->byIDs($ids);
if ($files->count() < count($ids)) {
if ($files->count() < count($ids ?? [])) {
$class = File::class;
$missingIds = implode(', ', array_diff($ids, $files->column('ID')));
$missingIds = implode(', ', array_diff($ids ?? [], $files->column('ID')));
throw new \InvalidArgumentException("{$class} items {$missingIds} are not found");
}

Expand All @@ -255,9 +255,9 @@ public static function resolveReadFileUsage($object, array $args, $context, Reso

/** @var DataList|File[] $files */
$files = Versioned::get_by_stage(File::class, Versioned::DRAFT)->byIDs($idList);
if ($files->count() < count($idList)) {
if ($files->count() < count($idList ?? [])) {
// Find out which files count not be found
$missingIds = array_diff($idList, $files->column('ID'));
$missingIds = array_diff($idList ?? [], $files->column('ID'));
throw new InvalidArgumentException(sprintf(
'%s items %s are not found',
File::class,
Expand Down
2 changes: 1 addition & 1 deletion code/GraphQL/Resolvers/FolderTypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public static function resolveFolderChildren(
$canViewIDs = array_keys(array_filter($permissionChecker->canViewMultiple(
$ids,
$member
)));
) ?? []));
// Filter by visible IDs (or force empty set if none are visible)
// Remove the limit as it no longer applies. We've already filtered down to the exact
// IDs we need.
Expand Down
4 changes: 2 additions & 2 deletions code/GraphQL/Resolvers/PublicationResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ private static function resolvePublicationOperation(
->byIds($idList);

// If warning suppression is not on, bundle up all the warnings into a single exception
if (!$quiet && $files->count() < count($idList)) {
$missingIds = array_diff($idList, $files->column('ID'));
if (!$quiet && $files->count() < count($idList ?? [])) {
$missingIds = array_diff($idList ?? [], $files->column('ID'));
foreach ($missingIds as $id) {
$warningMessages[] = sprintf(
'File #%s either does not exist or is not on stage %s.',
Expand Down
4 changes: 2 additions & 2 deletions code/GraphQL/Schema/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ public static function updateSchema(Schema $schema): void
{
$categoryValues = array_map(function ($category) {
return ['value' => $category];
}, File::config()->get('app_categories'));
}, File::config()->get('app_categories') ?? []);

// Sanitise GraphQL Enum aliases (some contain slashes)
foreach ($categoryValues as $key => $v) {
unset($categoryValues[$key]);
$newKey = strtoupper(preg_replace('/[^[[:alnum:]]]*/', '', $key));
$newKey = strtoupper(preg_replace('/[^[[:alnum:]]]*/', '', $key ?? '') ?? '');
$categoryValues[$newKey] = $v;
}

Expand Down
2 changes: 1 addition & 1 deletion code/Helper/ImageThumbnailHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public function run()
}

$generated = $this->generateThumbnails($file);
if (count($generated) > 0) {
if (count($generated ?? []) > 0) {
$generatedCount++;
$this->logger->debug(sprintf('Generated thumbnail for %s', $file->Filename));
}
Expand Down
2 changes: 1 addition & 1 deletion code/Model/ThumbnailGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public function generateLink(AssetContainer $thumbnail = null)
return $thumbnail->getURL();
case self::INLINE:
// Generate inline content
$base64 = base64_encode($thumbnail->getString());
$base64 = base64_encode($thumbnail->getString() ?? '');
return sprintf(
'data:%s;base64,%s',
$thumbnail->getMimeType(),
Expand Down
10 changes: 5 additions & 5 deletions tests/behat/src/FixtureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ public function iAttachTheFileToDropzone($path, $name)
// Get path
$filesPath = $this->getFilesPath();
if ($filesPath) {
$fullPath = rtrim(realpath($filesPath), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$path;
if (is_file($fullPath)) {
$fullPath = rtrim(realpath($filesPath ?? '') ?? '', DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$path;
if (is_file($fullPath ?? '')) {
$path = $fullPath;
}
}
Expand Down Expand Up @@ -216,7 +216,7 @@ public function assertMessageBoxContainsText($text)
$mainContext = $this->getMainContext();
$mainContext
->assertSession()
->elementTextContains('css', '.message-box', str_replace('\\"', '"', $text));
->elementTextContains('css', '.message-box', str_replace('\\"', '"', $text ?? ''));
}

/**
Expand Down Expand Up @@ -404,7 +404,7 @@ public function iSelectTheImageInHtmlField($filename, $field)
{
$inputField = $this->getHtmlField($field);
$inputFieldId = $inputField->getAttribute('id');
$filename = addcslashes($filename, "'");
$filename = addcslashes($filename ?? '', "'");
$js = <<<JS
var editor = jQuery('#$inputFieldId').entwine('ss').getEditor(),
doc = editor.getInstance().getDoc(),
Expand Down Expand Up @@ -434,7 +434,7 @@ public function iSelectTheImageInHtmlField($filename, $field)
*/
protected function getHtmlField($locator)
{
$locator = str_replace('\\"', '"', $locator);
$locator = str_replace('\\"', '"', $locator ?? '');
$page = $this->getMainContext()->getSession()->getPage();
$element = $page->find('css', 'textarea.htmleditor[name=\'' . $locator . '\']');
if ($element) {
Expand Down
12 changes: 6 additions & 6 deletions tests/php/Controller/AssetAdminTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public function testApiHistory()

$this->assertFalse($response->isError());

$body = json_decode($response->getBody(), true);
$body = json_decode($response->getBody() ?? '', true);

$this->assertArrayHasKey('summary', $body[0]);
$this->assertArrayHasKey('versionid', $body[0]);
Expand Down Expand Up @@ -121,7 +121,7 @@ public function testItCreatesFile()
'POST'
);
$this->assertFalse($response->isError());
$responseData = json_decode($response->getBody(), true);
$responseData = json_decode($response->getBody() ?? '', true);
$newFile = File::get()->byID($responseData[0]['id']);
$this->assertNotNull($newFile);
$this->assertEquals($folder1->ID, $newFile->ParentID);
Expand All @@ -135,7 +135,7 @@ public function testItCreatesFile()
'POST'
);
$this->assertFalse($response->isError());
$responseData = json_decode($response->getBody(), true);
$responseData = json_decode($response->getBody() ?? '', true);
$newFile2 = File::get()->byID($responseData[0]['id']);
$this->assertNotNull($newFile2);
$this->assertEquals($folder1->ID, $newFile2->ParentID);
Expand Down Expand Up @@ -212,7 +212,7 @@ public function testItRestrictsCreateFileOnExtension()
);
$this->assertTrue($response->isError());
$this->assertEquals(400, $response->getStatusCode());
$responseData = json_decode($response->getBody(), true);
$responseData = json_decode($response->getBody() ?? '', true);
$this->assertEquals(
[
'type' => 'error',
Expand Down Expand Up @@ -276,13 +276,13 @@ protected function getUploadFile($paramName, $tmpFileName = 'AssetAdminTest.txt'
for ($i = 0; $i < 10000; $i++) {
$tmpFileContent .= '0';
}
file_put_contents($tmpFilePath, $tmpFileContent);
file_put_contents($tmpFilePath ?? '', $tmpFileContent);

// emulates the $_FILES array
return array(
'name' => $tmpFileName,
'type' => 'text/plaintext',
'size' => filesize($tmpFilePath),
'size' => filesize($tmpFilePath ?? ''),
'tmp_name' => $tmpFilePath,
'error' => UPLOAD_ERR_OK,
);
Expand Down
4 changes: 2 additions & 2 deletions tests/php/Forms/UploadFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public function testGetAttributes()
$this->assertSame('Form_MyForm_MyField', $attributes['id']);

// Check schema / state are encoded in this field
$this->assertEquals($schema, json_decode($attributes['data-schema'], true));
$this->assertEquals($state, json_decode($attributes['data-state'], true));
$this->assertEquals($schema, json_decode($attributes['data-schema'] ?? '', true));
$this->assertEquals($state, json_decode($attributes['data-state'] ?? '', true));
}
}
2 changes: 1 addition & 1 deletion tests/php/Forms/UsedOnTableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ protected function setUp(): void
parent::setUp();
TestAssetStore::activate('UsedOnTableTest');
$path = dirname(__DIR__) . '/Forms/fixtures/testfile.txt';
$content = file_get_contents($path);
$content = file_get_contents($path ?? '');
$file = File::get()->find('Name', 'testfile.txt');
$file->setFromString($content, $file->generateFilename());
}
Expand Down
2 changes: 1 addition & 1 deletion tests/php/GraphQL/FolderTypeCreatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public function testItShowsParents()
],
array_map(function ($folder) {
return $folder->Name;
}, $parents)
}, $parents ?? [])
);
}

Expand Down
2 changes: 1 addition & 1 deletion tests/php/GraphQL/Legacy/FolderTypeCreatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ public function testItShowsParents()
],
array_map(function ($folder) {
return $folder->Name;
}, $parents)
}, $parents ?? [])
);
}

Expand Down

0 comments on commit 617464e

Please sign in to comment.