From 62800c6d042a9b399938afb47af82e3092424df3 Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Mon, 11 Apr 2022 16:57:44 +1200 Subject: [PATCH] ENH PHP 8.1 compatibility --- code/Controller/AssetAdmin.php | 8 ++++---- code/Controller/AssetAdminFile.php | 2 +- code/Forms/AssetFormFactory.php | 2 +- code/Forms/FileFormFactory.php | 2 +- code/Forms/RemoteFileFormFactory.php | 20 +++++++++---------- code/Forms/UploadField.php | 2 +- code/GraphQL/Resolvers/AssetAdminResolver.php | 14 ++++++------- code/GraphQL/Resolvers/FolderTypeResolver.php | 2 +- .../GraphQL/Resolvers/PublicationResolver.php | 4 ++-- code/GraphQL/Schema/Builder.php | 4 ++-- code/Helper/ImageThumbnailHelper.php | 2 +- tests/behat/src/FixtureContext.php | 8 ++++---- tests/php/Controller/AssetAdminTest.php | 10 +++++----- tests/php/Forms/UsedOnTableTest.php | 2 +- 14 files changed, 41 insertions(+), 41 deletions(-) diff --git a/code/Controller/AssetAdmin.php b/code/Controller/AssetAdmin.php index 3f823cd10..ee8384ffa 100644 --- a/code/Controller/AssetAdmin.php +++ b/code/Controller/AssetAdmin.php @@ -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; } @@ -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; } @@ -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); @@ -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; } diff --git a/code/Controller/AssetAdminFile.php b/code/Controller/AssetAdminFile.php index 9ec1910d7..052398f40 100644 --- a/code/Controller/AssetAdminFile.php +++ b/code/Controller/AssetAdminFile.php @@ -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]); diff --git a/code/Forms/AssetFormFactory.php b/code/Forms/AssetFormFactory.php index 10b5fb74b..3ac460e44 100644 --- a/code/Forms/AssetFormFactory.php +++ b/code/Forms/AssetFormFactory.php @@ -282,7 +282,7 @@ protected function getPopoverActions($record) ]; $this->invokeWithExtensions('updatePopoverActions', $actions, $record); - return array_filter($actions); + return array_filter($actions ?? []); } /** diff --git a/code/Forms/FileFormFactory.php b/code/Forms/FileFormFactory.php index 9b89e8c66..2e4222343 100644 --- a/code/Forms/FileFormFactory.php +++ b/code/Forms/FileFormFactory.php @@ -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') diff --git a/code/Forms/RemoteFileFormFactory.php b/code/Forms/RemoteFileFormFactory.php index 25efddd9e..3ebdb2d8b 100644 --- a/code/Forms/RemoteFileFormFactory.php +++ b/code/Forms/RemoteFileFormFactory.php @@ -230,7 +230,7 @@ protected function getEditFormFields($context) return $this->getCreateFormFields(); } - $url = trim($url); + $url = trim($url ?? ''); // Get embed $this->validateUrl($url); @@ -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', @@ -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', @@ -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', diff --git a/code/Forms/UploadField.php b/code/Forms/UploadField.php index cccca6faa..ec0c247df 100644 --- a/code/Forms/UploadField.php +++ b/code/Forms/UploadField.php @@ -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; diff --git a/code/GraphQL/Resolvers/AssetAdminResolver.php b/code/GraphQL/Resolvers/AssetAdminResolver.php index 12d2fda63..721932442 100644 --- a/code/GraphQL/Resolvers/AssetAdminResolver.php +++ b/code/GraphQL/Resolvers/AssetAdminResolver.php @@ -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, @@ -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(); } @@ -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"); } @@ -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, diff --git a/code/GraphQL/Resolvers/FolderTypeResolver.php b/code/GraphQL/Resolvers/FolderTypeResolver.php index 631bcb742..16216a220 100644 --- a/code/GraphQL/Resolvers/FolderTypeResolver.php +++ b/code/GraphQL/Resolvers/FolderTypeResolver.php @@ -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. diff --git a/code/GraphQL/Resolvers/PublicationResolver.php b/code/GraphQL/Resolvers/PublicationResolver.php index a64d55829..5454a894d 100644 --- a/code/GraphQL/Resolvers/PublicationResolver.php +++ b/code/GraphQL/Resolvers/PublicationResolver.php @@ -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.', diff --git a/code/GraphQL/Schema/Builder.php b/code/GraphQL/Schema/Builder.php index b67e0b72a..023ce348e 100644 --- a/code/GraphQL/Schema/Builder.php +++ b/code/GraphQL/Schema/Builder.php @@ -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; } diff --git a/code/Helper/ImageThumbnailHelper.php b/code/Helper/ImageThumbnailHelper.php index b4071699c..15c102c99 100644 --- a/code/Helper/ImageThumbnailHelper.php +++ b/code/Helper/ImageThumbnailHelper.php @@ -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)); } diff --git a/tests/behat/src/FixtureContext.php b/tests/behat/src/FixtureContext.php index c90cb37a2..89dffbe8d 100644 --- a/tests/behat/src/FixtureContext.php +++ b/tests/behat/src/FixtureContext.php @@ -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; } } @@ -404,7 +404,7 @@ public function iSelectTheImageInHtmlField($filename, $field) { $inputField = $this->getHtmlField($field); $inputFieldId = $inputField->getAttribute('id'); - $filename = addcslashes($filename, "'"); + $filename = addcslashes($filename ?? '', "'"); $js = <<getMainContext()->getSession()->getPage(); $element = $page->find('css', 'textarea.htmleditor[name=\'' . $locator . '\']'); if ($element) { diff --git a/tests/php/Controller/AssetAdminTest.php b/tests/php/Controller/AssetAdminTest.php index fe682da7e..5742d6308 100644 --- a/tests/php/Controller/AssetAdminTest.php +++ b/tests/php/Controller/AssetAdminTest.php @@ -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]); @@ -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); @@ -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); @@ -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', @@ -276,7 +276,7 @@ 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( diff --git a/tests/php/Forms/UsedOnTableTest.php b/tests/php/Forms/UsedOnTableTest.php index 844f6cb25..6832d1642 100644 --- a/tests/php/Forms/UsedOnTableTest.php +++ b/tests/php/Forms/UsedOnTableTest.php @@ -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()); }