From 83c0f184b0ad8b189ace97997a333a57b036b32f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Wed, 11 Oct 2023 16:08:11 +0200 Subject: [PATCH 1/2] feat: add rector --- composer.json | 4 +- composer.lock | 120 +++++++++++++++++++++++++++++++++++++++++++++++++- rector.php | 25 +++++++++++ 3 files changed, 147 insertions(+), 2 deletions(-) create mode 100644 rector.php diff --git a/composer.json b/composer.json index 78fb861248a4..34341c6b0c1d 100644 --- a/composer.json +++ b/composer.json @@ -36,6 +36,7 @@ "bamarni/composer-bin-plugin": "^1.8", "mikey179/vfsstream": "^1.6", "phpunit/phpunit": "^9.5", + "rector/rector": "^0.18.5", "roave/security-advisories": "dev-latest" }, "require": { @@ -109,7 +110,8 @@ "bin-links": false }, "cleaner-ignore": { - "phpunit/phpunit": true + "phpunit/phpunit": true, + "rector/rector": true }, "google/apiclient-services": [ "Drive" diff --git a/composer.lock b/composer.lock index f1131972f7cb..55566f469186 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "a05f0ad17290b0a59773026392b39fa7", + "content-hash": "15c3688c9a19d60502319c727bae2dba", "packages": [ { "name": "bantu/ini-get-wrapper", @@ -5077,6 +5077,68 @@ }, "time": "2022-02-21T01:04:05+00:00" }, + { + "name": "phpstan/phpstan", + "version": "1.10.38", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan.git", + "reference": "5302bb402c57f00fb3c2c015bac86e0827e4b691" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/5302bb402c57f00fb3c2c015bac86e0827e4b691", + "reference": "5302bb402c57f00fb3c2c015bac86e0827e4b691", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "docs": "https://phpstan.org/user-guide/getting-started", + "forum": "https://github.com/phpstan/phpstan/discussions", + "issues": "https://github.com/phpstan/phpstan/issues", + "security": "https://github.com/phpstan/phpstan/security/policy", + "source": "https://github.com/phpstan/phpstan-src" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan", + "type": "tidelift" + } + ], + "time": "2023-10-06T14:19:14+00:00" + }, { "name": "phpunit/php-code-coverage", "version": "9.2.29", @@ -5499,6 +5561,62 @@ ], "time": "2023-09-19T05:39:22+00:00" }, + { + "name": "rector/rector", + "version": "0.18.5", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "2a3b82f317e431fc142d21f3303891a4e64c96eb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/2a3b82f317e431fc142d21f3303891a4e64c96eb", + "reference": "2a3b82f317e431fc142d21f3303891a4e64c96eb", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0", + "phpstan/phpstan": "^1.10.35" + }, + "conflict": { + "rector/rector-doctrine": "*", + "rector/rector-downgrade-php": "*", + "rector/rector-phpunit": "*", + "rector/rector-symfony": "*" + }, + "bin": [ + "bin/rector" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/0.18.5" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "time": "2023-10-05T11:25:40+00:00" + }, { "name": "roave/security-advisories", "version": "dev-latest", diff --git a/rector.php b/rector.php new file mode 100644 index 000000000000..43c6d093ea3b --- /dev/null +++ b/rector.php @@ -0,0 +1,25 @@ +sets([LevelSetList::UP_TO_PHP_74]); + + $rectorConfig->paths([ + __DIR__ . '/apps', + __DIR__ . '/core', + __DIR__ . '/lib', + __DIR__ . '/ocm-provider', + __DIR__ . '/ocs', + __DIR__ . '/ocs-provider', + __DIR__ . '/settings', + __DIR__ . '/tests', + ]); + $rectorConfig->skip([ + __DIR__ . '/*/templates/*', + __DIR__ . '/lib/composer/*', + ]); +}; From 7f86d95c4940a6faf00d848398752bd99cff9af8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Wed, 11 Oct 2023 16:10:00 +0200 Subject: [PATCH 2/2] chore: migrate code base to php7.4 standard using rector --- apps/comments/appinfo/app.php | 4 +- apps/comments/lib/Dav/CommentNode.php | 4 +- apps/comments/lib/Dav/CommentsPlugin.php | 5 +- apps/comments/lib/Dav/EntityCollection.php | 4 +- apps/comments/lib/Dav/RootCollection.php | 2 +- .../tests/unit/ActivityListenerTest.php | 13 +- .../tests/unit/Dav/CommentsNodeTest.php | 30 +- .../tests/unit/Dav/CommentsPluginTest.php | 81 ++- .../tests/unit/Dav/EntityCollectionTest.php | 2 +- .../unit/Dav/EntityTypeCollectionTest.php | 6 +- .../tests/unit/Dav/RootCollectionTest.php | 14 +- .../Migrations/Version20170202213905.php | 5 +- .../Migrations/Version20190823065724.php | 3 +- apps/dav/appinfo/app.php | 4 +- apps/dav/appinfo/v1/publicwebdav.php | 4 +- apps/dav/appinfo/v1/webdav.php | 5 +- apps/dav/lib/AppInfo/PluginManager.php | 26 +- apps/dav/lib/Avatars/AvatarHome.php | 13 +- .../dav/lib/BackgroundJob/CleanProperties.php | 10 +- apps/dav/lib/CalDAV/BirthdayService.php | 9 +- apps/dav/lib/CalDAV/CalDavBackend.php | 26 +- apps/dav/lib/CalDAV/Calendar.php | 13 +- apps/dav/lib/CalDAV/CalendarObject.php | 2 +- apps/dav/lib/CalDAV/Plugin.php | 6 +- .../lib/CalDAV/Publishing/PublishPlugin.php | 4 +- apps/dav/lib/CalDAV/Schedule/IMipPlugin.php | 9 +- apps/dav/lib/Capabilities.php | 3 +- apps/dav/lib/CardDAV/AddressBook.php | 9 +- apps/dav/lib/CardDAV/AddressBookImpl.php | 12 +- apps/dav/lib/CardDAV/CardDavBackend.php | 30 +- apps/dav/lib/CardDAV/ContactsManager.php | 3 +- apps/dav/lib/CardDAV/ImageExportPlugin.php | 7 +- apps/dav/lib/CardDAV/Plugin.php | 10 +- apps/dav/lib/CardDAV/SyncService.php | 9 +- apps/dav/lib/Command/CreateAddressBook.php | 6 +- apps/dav/lib/Command/CreateCalendar.php | 3 +- apps/dav/lib/Command/SyncBirthdayCalendar.php | 6 +- .../dav/lib/Command/SyncSystemAddressBook.php | 3 +- apps/dav/lib/Connector/LegacyDAVACL.php | 2 +- apps/dav/lib/Connector/PublicAuth.php | 9 +- .../lib/Connector/Sabre/AppEnabledPlugin.php | 13 +- apps/dav/lib/Connector/Sabre/Auth.php | 20 +- .../lib/Connector/Sabre/AutorenamePlugin.php | 10 +- apps/dav/lib/Connector/Sabre/ChecksumList.php | 2 +- .../Sabre/CommentPropertiesPlugin.php | 18 +- .../Connector/Sabre/CopyEtagHeaderPlugin.php | 3 +- apps/dav/lib/Connector/Sabre/CorsPlugin.php | 24 +- apps/dav/lib/Connector/Sabre/DavAclPlugin.php | 2 +- apps/dav/lib/Connector/Sabre/Directory.php | 27 +- .../Connector/Sabre/ExceptionLoggerPlugin.php | 18 +- apps/dav/lib/Connector/Sabre/File.php | 24 +- apps/dav/lib/Connector/Sabre/FilesPlugin.php | 69 +-- .../lib/Connector/Sabre/FilesReportPlugin.php | 51 +- .../Sabre/FilesSearchReportPlugin.php | 11 +- apps/dav/lib/Connector/Sabre/LockPlugin.php | 22 +- .../lib/Connector/Sabre/MaintenancePlugin.php | 8 +- apps/dav/lib/Connector/Sabre/Node.php | 6 +- apps/dav/lib/Connector/Sabre/ObjectTree.php | 6 +- apps/dav/lib/Connector/Sabre/Principal.php | 25 +- apps/dav/lib/Connector/Sabre/QuotaPlugin.php | 10 +- .../dav/lib/Connector/Sabre/ServerFactory.php | 28 +- apps/dav/lib/Connector/Sabre/SharesPlugin.php | 20 +- apps/dav/lib/Connector/Sabre/TagList.php | 8 +- apps/dav/lib/Connector/Sabre/TagsPlugin.php | 24 +- .../Connector/Sabre/ValidateRequestPlugin.php | 8 +- .../DAV/AbstractCustomPropertiesBackend.php | 4 +- apps/dav/lib/DAV/CopyPlugin.php | 3 +- apps/dav/lib/DAV/GroupPrincipalBackend.php | 7 +- apps/dav/lib/DAV/LazyOpsPlugin.php | 29 +- apps/dav/lib/DAV/PublicAuth.php | 4 +- apps/dav/lib/DAV/Sharing/Backend.php | 11 +- apps/dav/lib/DAV/Sharing/Plugin.php | 18 +- apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php | 8 +- apps/dav/lib/DAV/SystemPrincipalBackend.php | 2 +- apps/dav/lib/DAV/ViewOnlyPlugin.php | 8 +- apps/dav/lib/Files/BrowserErrorPagePlugin.php | 3 +- apps/dav/lib/Files/FileLocksBackend.php | 2 +- apps/dav/lib/Files/FilesHome.php | 2 +- apps/dav/lib/Files/PreviewPlugin.php | 6 +- .../Files/PublicFiles/PublicFilesPlugin.php | 37 +- .../Files/PublicFiles/PublicShareSigner.php | 6 +- .../PublicFiles/PublicSharedRootNode.php | 18 +- .../Files/PublicFiles/PublicSharingAuth.php | 6 +- .../lib/Files/PublicFiles/RootCollection.php | 4 +- apps/dav/lib/Files/PublicFiles/SharedFile.php | 3 +- .../lib/Files/PublicFiles/SharedFolder.php | 13 +- apps/dav/lib/Files/RootCollection.php | 2 +- .../Files/Sharing/PublicLinkEventsPlugin.php | 6 +- apps/dav/lib/HookManager.php | 17 +- apps/dav/lib/JobStatus/Home.php | 5 +- apps/dav/lib/JobStatus/JobStatus.php | 3 +- apps/dav/lib/Meta/MetaFile.php | 3 +- apps/dav/lib/Meta/MetaFolder.php | 7 +- apps/dav/lib/Meta/MetaPlugin.php | 34 +- apps/dav/lib/Meta/RootCollection.php | 3 +- apps/dav/lib/Repair/RemoveInvalidShares.php | 9 +- apps/dav/lib/Server.php | 3 +- .../lib/SystemTag/SystemTagMappingNode.php | 5 +- apps/dav/lib/SystemTag/SystemTagPlugin.php | 44 +- .../SystemTag/SystemTagsByIdCollection.php | 19 +- .../SystemTagsObjectMappingCollection.php | 26 +- .../SystemTagsObjectTypeCollection.php | 20 +- apps/dav/lib/TrashBin/RootCollection.php | 2 +- apps/dav/lib/TrashBin/TrashBinFolder.php | 4 +- apps/dav/lib/TrashBin/TrashBinHome.php | 6 +- apps/dav/lib/TrashBin/TrashBinManager.php | 4 +- apps/dav/lib/TrashBin/TrashBinPlugin.php | 19 +- apps/dav/lib/Upload/AssemblyStream.php | 14 +- apps/dav/lib/Upload/ChunkLocationProvider.php | 3 +- apps/dav/lib/Upload/ChunkingPlugin.php | 3 +- apps/dav/lib/Upload/FutureFile.php | 10 +- apps/dav/lib/Upload/UploadFolder.php | 2 +- apps/dav/lib/Upload/UploadHome.php | 4 +- .../tests/unit/AppInfo/ApplicationTest.php | 8 +- .../Migrations/Version20170202213905Test.php | 4 +- .../Migrations/Version20210714123001Test.php | 2 +- .../dav/tests/unit/Avatars/AvatarHomeTest.php | 5 +- .../BackgroundJob/CleanPropertiesTest.php | 3 +- .../tests/unit/CalDAV/CalDavBackendTest.php | 12 +- apps/dav/tests/unit/CalDAV/CalendarTest.php | 6 +- apps/dav/tests/unit/CalDAV/PluginTest.php | 3 +- .../unit/CalDAV/PublicCalendarRootTest.php | 14 +- .../unit/CalDAV/Publishing/PublishingTest.php | 18 +- .../unit/CardDAV/AddressBookImplTest.php | 15 +- .../tests/unit/CardDAV/AddressBookTest.php | 8 +- .../unit/CardDAV/BirthdayServiceTest.php | 11 +- .../tests/unit/CardDAV/CardDavBackendTest.php | 24 +- .../unit/CardDAV/ContactsManagerTest.php | 6 +- apps/dav/tests/unit/CardDAV/ConverterTest.php | 2 +- .../unit/CardDAV/ImageExportPluginTest.php | 26 +- .../tests/unit/CardDAV/Sharing/PluginTest.php | 14 +- .../tests/unit/CardDAV/SyncServiceTest.php | 26 +- .../tests/unit/Command/CleanupChunksTest.php | 5 +- .../tests/unit/Connector/PublicAuthTest.php | 27 +- .../tests/unit/Connector/Sabre/AuthTest.php | 15 +- .../Sabre/BlockLegacyClientPluginTest.php | 13 +- .../Sabre/CommentsPropertiesPluginTest.php | 34 +- .../Sabre/CopyEtagHeaderPluginTest.php | 6 +- .../unit/Connector/Sabre/CorsPluginTest.php | 14 +- .../unit/Connector/Sabre/DirectoryTest.php | 28 +- .../Sabre/DummyGetResponsePluginTest.php | 9 +- .../Sabre/Exception/ForbiddenTest.php | 2 +- .../Sabre/Exception/InvalidPathTest.php | 2 +- .../Sabre/ExceptionLoggerPluginTest.php | 8 +- .../tests/unit/Connector/Sabre/FileTest.php | 46 +- .../unit/Connector/Sabre/FilesPluginTest.php | 13 +- .../Connector/Sabre/FilesReportPluginTest.php | 83 ++- .../Sabre/FilesSearchReportPluginTest.php | 30 +- .../Connector/Sabre/MaintenancePluginTest.php | 7 +- .../tests/unit/Connector/Sabre/NodeTest.php | 16 +- .../unit/Connector/Sabre/ObjectTreeTest.php | 26 +- .../unit/Connector/Sabre/PrincipalTest.php | 27 +- .../Sabre/PublicDavLocksPluginTest.php | 5 +- .../unit/Connector/Sabre/QuotaPluginTest.php | 4 +- .../Sabre/RequestTest/DeleteTest.php | 2 +- .../Sabre/RequestTest/RequestTest.php | 4 +- .../unit/Connector/Sabre/RequestTest/Sapi.php | 10 +- .../Sabre/RequestTest/UploadTest.php | 10 +- .../unit/Connector/Sabre/SharesPluginTest.php | 30 +- .../unit/Connector/Sabre/TagsPluginTest.php | 36 +- .../Sabre/ValidateRequestPluginTest.php | 6 +- .../unit/DAV/BrowserErrorPagePluginTest.php | 6 +- apps/dav/tests/unit/DAV/CopyPluginTest.php | 13 +- .../DAV/FileCustomPropertiesBackendTest.php | 32 +- .../dav/tests/unit/DAV/GroupPrincipalTest.php | 5 +- apps/dav/tests/unit/DAV/HookManagerTest.php | 8 +- apps/dav/tests/unit/DAV/LazyOpsPluginTest.php | 13 +- apps/dav/tests/unit/DAV/LockPluginTest.php | 15 +- .../DAV/MiscCustomPropertiesBackendTest.php | 19 +- .../dav/tests/unit/DAV/Sharing/PluginTest.php | 14 +- .../dav/tests/unit/DAV/ViewOnlyPluginTest.php | 7 +- .../tests/unit/Files/FileLocksBackendTest.php | 11 +- apps/dav/tests/unit/Files/FilesHomeTest.php | 7 +- .../tests/unit/Files/PreviewPluginTest.php | 15 +- .../PublicFiles/PublicSharingAuthTest.php | 4 +- .../Sharing/PublicLinkEventsPluginTest.php | 7 +- .../JobStatus/Entity/JobStatusMapperTest.php | 6 +- .../tests/unit/JobStatus/JobStatusTest.php | 8 +- apps/dav/tests/unit/Meta/MetaPluginTest.php | 9 +- apps/dav/tests/unit/ServerTest.php | 2 +- .../SystemTag/SystemTagMappingNodeTest.php | 16 +- .../unit/SystemTag/SystemTagNodeTest.php | 24 +- .../unit/SystemTag/SystemTagPluginTest.php | 80 ++- .../SystemTagsByIdCollectionTest.php | 35 +- .../SystemTagsObjectMappingCollectionTest.php | 26 +- .../SystemTagsObjectTypeCollectionTest.php | 27 +- .../tests/unit/TrashBin/TrashBinFileTest.php | 7 +- .../unit/TrashBin/TrashBinFolderTest.php | 19 +- .../tests/unit/TrashBin/TrashBinHomeTest.php | 7 +- apps/dav/tests/unit/TreeTest.php | 4 +- .../tests/unit/Upload/AssemblyStreamTest.php | 4 +- .../unit/Upload/ChunkLocationProviderTest.php | 8 +- .../tests/unit/Upload/ChunkingPluginTest.php | 29 +- apps/dav/tests/unit/Upload/FutureFileTest.php | 8 +- apps/dav/tests/unit/bootstrap.php | 2 +- apps/federatedfilesharing/appinfo/app.php | 8 +- .../lib/AddressHandler.php | 6 +- .../lib/AppInfo/Application.php | 122 ++--- .../lib/BackgroundJob/RetryJob.php | 11 +- .../lib/Command/PollIncomingShares.php | 18 +- .../lib/Controller/OcmController.php | 8 +- .../Controller/RequestHandlerController.php | 12 +- .../SharingPersonalSettingsController.php | 10 +- .../lib/DiscoveryManager.php | 14 +- .../lib/FedShareManager.php | 41 +- .../lib/FederatedShareProvider.php | 54 +- .../lib/Middleware/OcmMiddleware.php | 4 +- .../lib/Notifications.php | 33 +- .../lib/Panels/SharingPersonalPanel.php | 6 +- .../federatedfilesharing/lib/TokenHandler.php | 3 +- .../tests/AddressHandlerTest.php | 13 +- .../tests/Command/PollIncomingSharesTest.php | 13 +- .../tests/Controller/OcmControllerTest.php | 28 +- .../tests/Controller/RequestHandlerTest.php | 10 +- .../SharingPersonalSettingsControllerTest.php | 9 +- .../tests/DiscoveryManagerTest.php | 33 +- .../tests/External/ManagerTest.php | 15 +- .../tests/FedShareManagerTest.php | 18 +- .../tests/FederatedShareProviderTest.php | 4 +- .../tests/Middleware/OcmMiddlewareTest.php | 15 +- .../tests/NotificationsTest.php | 18 +- .../tests/Panels/AdminPanelTest.php | 7 +- .../tests/Panels/GeneralPersonalPanelTest.php | 13 +- .../tests/Panels/SharingPersonalPanelTest.php | 7 +- apps/federatedfilesharing/tests/TestCase.php | 2 +- .../tests/TokenHandlerTest.php | 10 +- .../tests/appinfo/ApplicationTest.php | 8 +- .../Migrations/Version20190410160725Test.php | 2 +- apps/federation/lib/AppInfo/Application.php | 24 +- .../lib/BackgroundJob/GetSharedSecret.php | 20 +- .../lib/BackgroundJob/RequestSharedSecret.php | 16 +- .../Command/SyncFederationAddressBooks.php | 3 +- .../lib/Command/TrustedServerAdd.php | 3 +- .../lib/Command/TrustedServerList.php | 3 +- .../lib/Command/TrustedServerRemove.php | 3 +- .../lib/Controller/OCSAuthAPIController.php | 19 +- .../lib/Controller/SettingsController.php | 6 +- apps/federation/lib/DAV/FedAuth.php | 3 +- apps/federation/lib/DbHandler.php | 9 +- apps/federation/lib/Hooks.php | 3 +- .../lib/SyncFederationAddressBooks.php | 3 +- apps/federation/lib/TrustedServers.php | 24 +- apps/federation/tests/API/OCSAuthAPITest.php | 19 +- .../BackgroundJob/GetSharedSecretTest.php | 33 +- .../BackgroundJob/RequestSharedSecretTest.php | 29 +- .../tests/Command/TrustedServerAddTest.php | 4 +- .../tests/Command/TrustedServerListTest.php | 4 +- .../tests/Command/TrustedServerRemoveTest.php | 4 +- .../Controller/SettingsControllerTest.php | 15 +- apps/federation/tests/DAV/FedAuthTest.php | 2 +- apps/federation/tests/DbHandlerTest.php | 10 +- apps/federation/tests/HooksTest.php | 7 +- .../Middleware/AddServerMiddlewareTest.php | 19 +- apps/federation/tests/PanelTest.php | 19 +- .../tests/SyncFederationAddressbooksTest.php | 11 +- apps/federation/tests/TrustedServersTest.php | 50 +- apps/files/ajax/download.php | 10 +- apps/files/ajax/list.php | 6 +- apps/files/appinfo/app.php | 26 +- apps/files/lib/App.php | 5 +- apps/files/lib/AppInfo/Application.php | 70 ++- .../CleanupPersistentFileLocks.php | 3 +- apps/files/lib/Command/CheckCache.php | 3 +- apps/files/lib/Command/RemoveStorageCache.php | 3 +- apps/files/lib/Command/Scan.php | 42 +- apps/files/lib/Command/TransferOwnership.php | 31 +- .../Command/TroubleshootTransferOwnership.php | 6 +- apps/files/lib/Command/VerifyChecksums.php | 12 +- apps/files/lib/Controller/ApiController.php | 18 +- apps/files/lib/Controller/ViewController.php | 4 +- apps/files/lib/Helper.php | 2 +- apps/files/lib/Service/TagService.php | 15 +- apps/files/tests/ActivityHelperTest.php | 9 +- apps/files/tests/ActivityTest.php | 30 +- .../tests/BackgroundJob/ScanFilesTest.php | 14 +- apps/files/tests/Command/CheckCacheTest.php | 7 +- .../tests/Command/DeleteOrphanedFilesTest.php | 9 +- apps/files/tests/Command/ScanTest.php | 13 +- .../tests/Command/TransferOwnershipTest.php | 14 +- .../TroubleshootTransferOwnershipTest.php | 5 +- .../tests/Command/VerifyChecksumsTest.php | 22 +- .../tests/Controller/ApiControllerTest.php | 32 +- .../tests/Controller/ViewControllerTest.php | 66 ++- apps/files/tests/HelperTest.php | 4 +- apps/files/tests/Service/TagServiceTest.php | 7 +- apps/files_external/ajax/oauth2.php | 2 +- .../Migrations/Version20210511082903.php | 12 +- .../Migrations/Version20220329110116.php | 9 +- apps/files_external/appinfo/app.php | 2 +- apps/files_external/appinfo/routes.php | 2 +- .../lib/AppInfo/Application.php | 46 +- .../files_external/lib/Command/Applicable.php | 10 +- apps/files_external/lib/Command/Backends.php | 15 +- apps/files_external/lib/Command/Config.php | 4 +- apps/files_external/lib/Command/Create.php | 23 +- apps/files_external/lib/Command/Import.php | 33 +- .../lib/Command/ListCommand.php | 14 +- apps/files_external/lib/Command/Option.php | 4 +- apps/files_external/lib/Command/Verify.php | 4 +- .../lib/Controller/AjaxController.php | 3 +- .../lib/Controller/StoragesController.php | 2 +- .../UserGlobalStoragesController.php | 5 +- .../lib/Controller/UserStoragesController.php | 5 +- apps/files_external/lib/Lib/Backend/DAV.php | 4 +- .../files_external/lib/Lib/Backend/Google.php | 2 +- apps/files_external/lib/Lib/Backend/Local.php | 4 +- .../lib/Lib/Backend/OwnCloud.php | 2 +- apps/files_external/lib/Lib/Backend/SFTP.php | 2 +- .../lib/Lib/Backend/SFTP_Key.php | 2 +- apps/files_external/lib/Lib/Backend/SMB.php | 2 +- apps/files_external/lib/Lib/Backend/SMB2.php | 2 +- .../files_external/lib/Lib/Backend/SMB_OC.php | 2 +- .../lib/Lib/Cache/SmbCacheWrapper.php | 13 +- apps/files_external/lib/Lib/RSAStore.php | 12 +- .../files_external/lib/Lib/Storage/Google.php | 18 +- apps/files_external/lib/Lib/Storage/SMB.php | 25 +- apps/files_external/lib/Lib/Storage/SMB2.php | 5 +- apps/files_external/lib/config.php | 4 +- .../tests/Command/ApplicableTest.php | 8 +- .../tests/Command/CommandTest.php | 2 +- .../tests/Command/ListCommandTest.php | 46 +- .../GlobalStoragesControllerTest.php | 8 +- .../Controller/StoragesControllerTest.php | 26 +- .../Controller/UserStoragesControllerTest.php | 14 +- .../LegacyDependencyCheckPolyfillTest.php | 4 +- .../files_external/tests/Panels/AdminTest.php | 11 +- .../tests/Panels/PersonalTest.php | 11 +- apps/files_external/tests/RSAStoreTest.php | 7 +- apps/files_sharing/ajax/shareinfo.php | 4 +- apps/files_sharing/appinfo/app.php | 18 +- .../files_sharing/lib/AppInfo/Application.php | 136 +++-- apps/files_sharing/lib/Cache.php | 12 +- apps/files_sharing/lib/Capabilities.php | 26 +- .../lib/Controller/NotificationController.php | 25 +- .../Controller/PersonalSettingsController.php | 10 +- .../lib/Controller/RemoteOcsController.php | 8 +- .../lib/Controller/Share20OcsController.php | 51 +- .../lib/Controller/ShareesController.php | 10 +- .../Controllers/ExternalSharesController.php | 16 +- .../lib/Controllers/ShareController.php | 4 +- apps/files_sharing/lib/ExpireSharesJob.php | 20 +- apps/files_sharing/lib/External/Cache.php | 4 +- apps/files_sharing/lib/External/Manager.php | 29 +- .../lib/External/MountProvider.php | 5 +- .../lib/External/ScanExternalSharesJob.php | 3 +- apps/files_sharing/lib/External/Storage.php | 15 +- apps/files_sharing/lib/Helper.php | 8 +- apps/files_sharing/lib/Hooks.php | 41 +- apps/files_sharing/lib/Migration.php | 6 +- apps/files_sharing/lib/MountProvider.php | 8 +- .../lib/Panels/Admin/SettingsPanel.php | 6 +- .../lib/Panels/Personal/PersonalPanel.php | 9 +- apps/files_sharing/lib/Scanner.php | 10 +- .../lib/Service/NotificationPublisher.php | 12 +- .../files_sharing/lib/ShareBackend/Folder.php | 4 +- apps/files_sharing/lib/SharedMount.php | 7 +- apps/files_sharing/lib/SharedPropagator.php | 2 +- apps/files_sharing/lib/SharedStorage.php | 19 +- apps/files_sharing/lib/SharingAllowlist.php | 12 +- apps/files_sharing/lib/SharingBlacklist.php | 9 +- apps/files_sharing/lib/Updater.php | 2 +- apps/files_sharing/lib/ViewOnly.php | 3 +- apps/files_sharing/public.php | 2 +- apps/files_sharing/tests/API/ShareesTest.php | 20 +- apps/files_sharing/tests/ActivityTest.php | 11 +- apps/files_sharing/tests/ApiTest.php | 20 +- apps/files_sharing/tests/CacheTest.php | 21 +- apps/files_sharing/tests/CapabilitiesTest.php | 10 +- .../Command/CleanupRemoteStoragesTest.php | 11 +- .../Controller/NotificationControllerTest.php | 17 +- .../PersonalSettingsControllerTest.php | 9 +- .../Controller/Share20OcsControllerTest.php | 455 ++++++++-------- .../ExternalShareControllerTest.php | 24 +- .../tests/Controllers/ShareControllerTest.php | 62 ++- .../tests/DeleteOrphanedSharesJobTest.php | 7 +- .../tests/EtagPropagationTest.php | 18 +- .../tests/ExpireSharesJobTest.php | 9 +- .../tests/External/CacheTest.php | 9 +- .../tests/External/ManagerTest.php | 35 +- .../tests/External/MountProviderTest.php | 5 +- .../External/ScanExternalSharesJobTest.php | 4 +- apps/files_sharing/tests/HooksTest.php | 21 +- .../Middleware/SharingCheckMiddlewareTest.php | 25 +- apps/files_sharing/tests/MigrationTest.php | 5 +- .../files_sharing/tests/MountProviderTest.php | 67 +-- apps/files_sharing/tests/NotifierTest.php | 15 +- .../tests/Panels/Admin/SettingsPanelTest.php | 6 +- .../Panels/Personal/PersonalPanelTest.php | 9 +- .../tests/Panels/Personal/SectionTest.php | 5 +- apps/files_sharing/tests/PermissionsTest.php | 9 +- .../tests/PropagationTestCase.php | 2 +- .../Service/NotificationPublisherTest.php | 15 +- apps/files_sharing/tests/SharedMountTest.php | 2 +- .../files_sharing/tests/SharedStorageTest.php | 14 +- .../tests/SharingAllowlistTest.php | 6 +- .../tests/SharingBlacklistTest.php | 6 +- .../tests/SizePropagationTest.php | 2 +- apps/files_sharing/tests/TestCase.php | 4 +- .../tests/UnshareChildrenTest.php | 2 +- apps/files_sharing/tests/WatcherTest.php | 4 +- apps/files_trashbin/ajax/delete.php | 4 +- apps/files_trashbin/ajax/undelete.php | 2 +- apps/files_trashbin/appinfo/app.php | 2 +- .../lib/AppInfo/Application.php | 34 +- .../lib/BackgroundJob/ExpireTrash.php | 10 +- .../lib/Command/ExpireTrash.php | 10 +- apps/files_trashbin/lib/Expiration.php | 12 +- apps/files_trashbin/lib/Storage.php | 28 +- .../files_trashbin/lib/TrashExpiryManager.php | 6 +- apps/files_trashbin/lib/Trashbin.php | 61 +-- .../lib/TrashbinSkipChecker.php | 10 +- .../tests/BackgroundJob/ExpireTrashTest.php | 8 +- .../tests/Command/CleanUpTest.php | 16 +- .../tests/Command/ExpireTrashTest.php | 7 +- apps/files_trashbin/tests/ExpirationTest.php | 6 +- apps/files_trashbin/tests/QuotaTest.php | 2 +- apps/files_trashbin/tests/StorageTest.php | 44 +- apps/files_trashbin/tests/TestCase.php | 4 +- .../tests/TrashbinExpiryManagerTest.php | 11 +- apps/files_trashbin/tests/TrashbinTest.php | 10 +- .../lib/AppInfo/Application.php | 26 +- .../lib/Command/ExpireVersions.php | 10 +- .../lib/Controller/VersionController.php | 3 +- apps/files_versions/lib/Expiration.php | 12 +- apps/files_versions/lib/FileHelper.php | 2 +- apps/files_versions/lib/Hooks.php | 18 +- apps/files_versions/lib/MetaStorage.php | 10 +- apps/files_versions/lib/Storage.php | 56 +- .../tests/Command/CleanupTest.php | 16 +- .../tests/Command/ExpireVersionsTest.php | 7 +- apps/files_versions/tests/ExpirationTest.php | 4 +- apps/files_versions/tests/VersioningTest.php | 252 +++++---- apps/provisioning_api/lib/Apps.php | 5 +- apps/provisioning_api/lib/Groups.php | 23 +- apps/provisioning_api/lib/Users.php | 34 +- apps/provisioning_api/tests/AppsTest.php | 3 +- apps/provisioning_api/tests/GroupsTest.php | 14 +- apps/provisioning_api/tests/UsersTest.php | 2 +- apps/systemtags/appinfo/app.php | 8 +- .../tests/unit/activity/ExtensionTest.php | 7 +- .../tests/unit/activity/ListenerTest.php | 14 +- apps/updatenotification/appinfo/app.php | 10 +- .../lib/Controller/AdminController.php | 25 +- .../lib/Notification/BackgroundJob.php | 2 +- apps/updatenotification/lib/UpdateChecker.php | 7 +- .../tests/Controller/AdminControllerTest.php | 37 +- .../tests/Notification/BackgroundJobTest.php | 26 +- .../tests/Notification/NotifierTest.php | 8 +- .../tests/ResetTokenBackgroundJobTest.php | 17 +- .../tests/UpdateCheckerTest.php | 7 +- core/Application.php | 218 +++----- core/Command/App/CheckCode.php | 16 +- core/Command/Background/Queue/Delete.php | 3 +- core/Command/Background/Queue/Status.php | 5 +- core/Command/Base.php | 10 +- core/Command/Check.php | 9 +- core/Command/Config/Import.php | 2 +- core/Command/Config/System/SetConfig.php | 2 +- core/Command/Db/ConvertMysqlToMB4.php | 9 +- core/Command/Db/ConvertType.php | 4 +- core/Command/Db/Migrations/ExecuteCommand.php | 3 +- .../Command/Db/Migrations/GenerateCommand.php | 9 +- core/Command/Db/Migrations/MigrateCommand.php | 3 +- core/Command/Db/Migrations/StatusCommand.php | 3 +- core/Command/Db/RestoreDefaultRowFormat.php | 6 +- core/Command/Group/AddMember.php | 3 +- core/Command/Group/ListGroups.php | 7 +- core/Command/Group/RemoveMember.php | 3 +- core/Command/Integrity/CheckApp.php | 5 +- core/Command/Integrity/CheckCore.php | 5 +- core/Command/Integrity/SignApp.php | 9 +- core/Command/Integrity/SignCore.php | 6 +- core/Command/L10n/CreateJs.php | 4 +- core/Command/Maintenance/DataFingerprint.php | 9 +- core/Command/Maintenance/Install.php | 5 +- core/Command/Maintenance/Repair.php | 12 +- core/Command/Previews/Cleanup.php | 5 +- core/Command/Security/CreateSignKey.php | 15 +- core/Command/Security/ListCertificates.php | 14 +- core/Command/Security/ListRoutes.php | 10 +- core/Command/System/Cron.php | 12 +- core/Command/TwoFactorAuth/Disable.php | 6 +- core/Command/TwoFactorAuth/Enable.php | 6 +- core/Command/Upgrade.php | 49 +- core/Command/User/Delete.php | 3 +- core/Command/User/Modify.php | 9 +- core/Command/User/MoveHome.php | 5 +- core/Command/User/Report.php | 2 +- core/Command/User/ResetPassword.php | 16 +- core/Command/User/SyncBackend.php | 6 +- core/Controller/AppRegistryController.php | 2 +- core/Controller/CloudController.php | 2 +- core/Controller/CronController.php | 9 +- core/Controller/LicenseController.php | 3 +- core/Controller/LoginController.php | 23 +- core/Controller/LostController.php | 5 +- core/Controller/OccController.php | 12 +- core/Controller/OcsController.php | 9 +- core/Controller/RolesController.php | 10 +- core/Controller/SetupController.php | 3 +- core/Controller/TokenController.php | 12 +- .../TwoFactorChallengeController.php | 12 +- core/Controller/UserSyncController.php | 10 +- core/Middleware/AccountModuleMiddleware.php | 12 +- core/Middleware/TwoFactorMiddleware.php | 15 +- core/ajax/appconfig.php | 2 +- core/ajax/share.php | 10 +- core/ajax/update.php | 37 +- core/js/config.php | 32 +- lib/kernel.php | 43 +- lib/private/Activity/Manager.php | 10 +- lib/private/AllConfig.php | 6 +- lib/private/App/AppManager.php | 52 +- lib/private/App/CodeChecker/CodeChecker.php | 7 +- .../App/CodeChecker/DeprecationCheck.php | 12 +- lib/private/App/CodeChecker/InfoChecker.php | 14 +- lib/private/App/DependencyAnalyzer.php | 24 +- lib/private/App/Platform.php | 3 +- lib/private/App/PlatformRepository.php | 11 +- lib/private/AppConfig.php | 14 +- lib/private/AppFramework/App.php | 16 +- .../DependencyInjection/DIContainer.php | 321 ++++-------- lib/private/AppFramework/Http/Dispatcher.php | 8 +- lib/private/AppFramework/Http/Output.php | 2 +- lib/private/AppFramework/Http/Request.php | 40 +- .../Middleware/MiddlewareDispatcher.php | 4 +- .../Middleware/Security/CORSMiddleware.php | 20 +- .../Security/SecurityMiddleware.php | 23 +- .../Middleware/SessionMiddleware.php | 9 +- .../Routing/RouteActionHandler.php | 2 +- .../AppFramework/Routing/RouteConfig.php | 22 +- .../AppFramework/Utility/SimpleContainer.php | 8 +- lib/private/Archive/TAR.php | 4 +- lib/private/Archive/ZIP.php | 4 +- .../Authentication/AccountModule/Manager.php | 11 +- .../LoginPolicies/GroupLoginPolicy.php | 9 +- .../LoginPolicies/LoginPolicyManager.php | 11 +- .../Token/DefaultTokenCleanupJob.php | 2 +- .../Token/DefaultTokenMapper.php | 4 +- .../Token/DefaultTokenProvider.php | 15 +- .../Authentication/TwoFactorAuth/Manager.php | 29 +- lib/private/Autoloader.php | 5 +- lib/private/Avatar.php | 12 +- lib/private/AvatarManager.php | 12 +- lib/private/BackgroundJob/JobList.php | 8 +- lib/private/Cache/CappedMemoryCache.php | 7 +- lib/private/CapabilitiesManager.php | 2 +- lib/private/Command/AsyncBus.php | 8 +- lib/private/Command/QueueBus.php | 2 +- lib/private/Comments/Manager.php | 4 +- lib/private/Comments/ManagerFactory.php | 8 +- lib/private/Config.php | 8 +- lib/private/Console/Application.php | 14 +- lib/private/Console/TimestampFormatter.php | 3 +- lib/private/ContactsManager.php | 2 +- lib/private/DB/ConnectionFactory.php | 21 +- lib/private/DB/MigrationService.php | 15 +- lib/private/DB/Migrator.php | 9 +- lib/private/DB/OracleMigrator.php | 100 ++-- lib/private/DB/PgSqlTools.php | 3 +- lib/private/DB/QueryBuilder/QueryBuilder.php | 12 +- lib/private/DB/QueryBuilder/QuoteHelper.php | 2 +- lib/private/Diagnostics/EventLogger.php | 4 +- lib/private/Diagnostics/QueryLogger.php | 2 +- lib/private/Encryption/DecryptAll.php | 6 +- lib/private/Encryption/EncryptionWrapper.php | 13 +- lib/private/Encryption/File.php | 2 +- lib/private/Encryption/HookManager.php | 5 +- lib/private/Encryption/Keys/Storage.php | 19 +- lib/private/Encryption/Update.php | 6 +- lib/private/Encryption/Util.php | 10 +- lib/private/Files/Cache/Cache.php | 36 +- lib/private/Files/Cache/HomeCache.php | 2 +- lib/private/Files/Cache/HomePropagator.php | 2 +- lib/private/Files/Cache/Propagator.php | 11 +- lib/private/Files/Cache/Scanner.php | 26 +- lib/private/Files/Cache/Storage.php | 4 +- .../Wrapper/ReadOnlyCachePermissionsMask.php | 9 +- .../Files/Config/LazyStorageMountInfo.php | 3 +- .../Files/Config/MountProviderCollection.php | 22 +- lib/private/Files/Config/UserMountCache.php | 26 +- .../Files/Config/UserMountCacheListener.php | 5 +- .../Auth/CoreAuthMechanismProvider.php | 9 +- .../Auth/Password/SessionCredentials.php | 4 +- lib/private/Files/External/ConfigAdapter.php | 14 +- lib/private/Files/External/LegacyUtil.php | 11 +- .../External/Service/DBConfigService.php | 40 +- .../Service/GlobalStoragesService.php | 8 +- .../Service/LegacyStoragesService.php | 5 +- .../External/Service/StoragesService.php | 26 +- lib/private/Files/External/StorageConfig.php | 58 +-- .../Files/External/StoragesBackendService.php | 27 +- lib/private/Files/FileInfo.php | 8 +- lib/private/Files/Filesystem.php | 25 +- lib/private/Files/Meta/MetaFileIdNode.php | 9 +- .../Files/Meta/MetaFileVersionNode.php | 19 +- lib/private/Files/Meta/MetaRootNode.php | 10 +- .../Files/Meta/MetaVersionCollection.php | 6 +- .../Files/Mount/CacheMountProvider.php | 7 +- .../Files/Mount/LocalHomeMountProvider.php | 2 +- lib/private/Files/Mount/Manager.php | 2 +- lib/private/Files/Mount/MountPoint.php | 12 +- .../Files/Mount/ObjectHomeMountProvider.php | 7 +- .../Files/Mount/PreviewsMountProvider.php | 7 +- lib/private/Files/Node/Folder.php | 4 +- lib/private/Files/Node/HookConnector.php | 12 +- lib/private/Files/Node/LazyRoot.php | 3 +- lib/private/Files/Node/Node.php | 4 +- lib/private/Files/Node/Root.php | 7 +- lib/private/Files/ObjectStore/Mapper.php | 3 +- .../Files/ObjectStore/ObjectStoreStorage.php | 9 +- .../Files/Storage/CacheableFlysystem.php | 4 +- lib/private/Files/Storage/Common.php | 18 +- lib/private/Files/Storage/CommonTest.php | 7 +- lib/private/Files/Storage/DAV.php | 8 +- lib/private/Files/Storage/Flysystem.php | 4 +- lib/private/Files/Storage/Local.php | 4 +- lib/private/Files/Storage/StorageFactory.php | 10 +- .../Files/Storage/Wrapper/Checksum.php | 3 +- lib/private/Files/Storage/Wrapper/DirMask.php | 2 +- .../Files/Storage/Wrapper/Encryption.php | 32 +- lib/private/Files/Storage/Wrapper/Quota.php | 2 +- lib/private/Files/Storage/Wrapper/Wrapper.php | 2 +- lib/private/Files/Stream/Checksum.php | 11 +- lib/private/Files/Stream/Close.php | 8 +- lib/private/Files/Stream/Dir.php | 6 +- lib/private/Files/Stream/Encryption.php | 2 +- lib/private/Files/Stream/Quota.php | 2 +- lib/private/Files/Type/Detection.php | 17 +- lib/private/Files/Type/Loader.php | 3 +- lib/private/Files/Utils/Scanner.php | 42 +- lib/private/Files/View.php | 52 +- lib/private/Group/Database.php | 2 +- lib/private/Group/Group.php | 10 +- lib/private/Group/Manager.php | 31 +- lib/private/HTTPHelper.php | 6 +- lib/private/Helper/LocaleHelper.php | 8 +- lib/private/HintException.php | 2 +- lib/private/Hooks/ForwardingEmitter.php | 4 +- lib/private/Http/Client/Client.php | 12 +- lib/private/Http/Client/ClientService.php | 6 +- lib/private/Http/Client/Response.php | 3 +- .../Http/Client/WebDavClientService.php | 6 +- lib/private/Image/BmpToResource.php | 12 +- lib/private/Installer.php | 6 +- lib/private/IntegrityCheck/Checker.php | 34 +- .../ExcludeFileByNameFilterIterator.php | 36 +- .../ExcludeFoldersByPathFilterIterator.php | 2 +- lib/private/L10N/Factory.php | 2 +- lib/private/License/BasicLicense.php | 10 +- lib/private/License/LicenseFetcher.php | 6 +- lib/private/License/LicenseManager.php | 23 +- lib/private/License/MessageService.php | 3 +- lib/private/Lock/AbstractLockingProvider.php | 2 +- lib/private/Lock/DBLockingProvider.php | 19 +- lib/private/Lock/MemcacheLockingProvider.php | 5 +- lib/private/Lock/Persistent/LockManager.php | 14 +- lib/private/Lock/Persistent/LockMapper.php | 3 +- lib/private/Log.php | 14 +- lib/private/Log/CommandLogger.php | 7 +- lib/private/Log/ErrorHandler.php | 3 +- lib/private/Log/Owncloud.php | 4 +- lib/private/Log/Rotate.php | 2 +- lib/private/Log/Syslog.php | 2 +- lib/private/Mail/Mailer.php | 15 +- lib/private/Mail/Message.php | 7 +- lib/private/Memcache/Factory.php | 5 +- lib/private/Memcache/Memcached.php | 5 +- lib/private/Memcache/Redis.php | 10 +- lib/private/Migration/BackgroundRepair.php | 6 +- lib/private/Migration/ConsoleOutput.php | 6 +- lib/private/Migration/SimpleOutput.php | 3 +- lib/private/NaturalSort.php | 4 +- lib/private/NavigationManager.php | 23 +- .../Events/RegisterConsumerEventImpl.php | 3 +- .../Events/RegisterNotifierEventImpl.php | 3 +- lib/private/OCS/Exception.php | 3 +- lib/private/OCS/Provider.php | 3 +- lib/private/OCS/Result.php | 3 +- lib/private/Preview.php | 27 +- lib/private/Preview/Bitmap.php | 2 +- lib/private/Preview/MP3.php | 2 +- lib/private/Preview/Movie.php | 9 +- lib/private/Preview/TXT.php | 2 +- lib/private/PreviewCleanup.php | 5 +- lib/private/PreviewManager.php | 86 ++-- lib/private/RedisFactory.php | 3 +- lib/private/Repair.php | 17 +- lib/private/Repair/Apps.php | 27 +- lib/private/Repair/DisableExtraThemes.php | 4 +- .../Repair/MoveAvatarIntoSubFolder.php | 18 +- lib/private/Repair/MoveAvatarOutsideHome.php | 18 +- lib/private/Repair/RepairOrphanedSubshare.php | 3 +- lib/private/Repair/RepairSubShares.php | 7 +- lib/private/Repair/RepairUnmergedShares.php | 4 +- lib/private/Repair/SharePropagation.php | 3 +- lib/private/Route/CachingRouter.php | 2 +- lib/private/Route/Router.php | 4 +- lib/private/Search.php | 4 +- lib/private/Search/Result/Audio.php | 2 +- lib/private/Search/Result/Image.php | 2 +- .../CSP/ContentSecurityPolicyManager.php | 2 +- .../Security/CSRF/CsrfTokenGenerator.php | 3 +- .../Security/CSRF/CsrfTokenManager.php | 6 +- .../CSRF/TokenStorage/SessionStorage.php | 3 +- lib/private/Security/Certificate.php | 8 +- lib/private/Security/CertificateManager.php | 4 +- lib/private/Security/CredentialsManager.php | 4 +- lib/private/Security/Crypto.php | 16 +- lib/private/Security/Hasher.php | 7 +- lib/private/Security/SignedUrl/Verifier.php | 14 +- lib/private/Security/TrustedDomainHelper.php | 3 +- lib/private/Server.php | 486 +++++++----------- lib/private/ServerContainer.php | 6 +- lib/private/Session/CryptoSessionData.php | 12 +- lib/private/Session/CryptoWrapper.php | 8 +- lib/private/Session/Internal.php | 2 +- lib/private/Settings/SettingsManager.php | 9 +- lib/private/Setup.php | 2 +- lib/private/Setup/AbstractDatabase.php | 2 +- lib/private/Setup/MySQL.php | 2 +- lib/private/Setup/PostgreSQL.php | 4 +- lib/private/Share/Helper.php | 5 +- lib/private/Share/MailNotifications.php | 36 +- lib/private/Share/SearchResultSorter.php | 4 +- lib/private/Share/Share.php | 148 +++--- lib/private/Share20/DefaultShareProvider.php | 26 +- lib/private/Share20/Manager.php | 94 ++-- lib/private/Share20/ProviderFactory.php | 6 +- lib/private/Share20/Share.php | 33 +- lib/private/Shutdown/ShutDownManager.php | 2 +- lib/private/Streamer.php | 2 +- lib/private/SubAdmin.php | 13 +- lib/private/SystemConfig.php | 3 +- lib/private/SystemTag/ManagerFactory.php | 8 +- .../SystemTag/SystemTagObjectMapper.php | 4 +- lib/private/TagManager.php | 16 +- lib/private/Tagging/TagMapper.php | 2 +- lib/private/Tags.php | 36 +- lib/private/Template/ResourceLocator.php | 4 +- lib/private/TemplateLayout.php | 2 +- lib/private/Theme/ThemeService.php | 10 +- lib/private/URLGenerator.php | 12 +- lib/private/Updater.php | 50 +- lib/private/Updater/VersionCheck.php | 10 +- lib/private/User/Account.php | 4 +- lib/private/User/Backend.php | 6 +- lib/private/User/BasicAuthModule.php | 19 +- lib/private/User/DeletedUser.php | 8 +- lib/private/User/Manager.php | 41 +- lib/private/User/Session.php | 30 +- .../User/Sync/BackendUsersIterator.php | 11 +- lib/private/User/Sync/SeenUsersIterator.php | 5 +- lib/private/User/SyncService.php | 17 +- lib/private/User/TokenAuthModule.php | 9 +- lib/private/User/User.php | 23 +- lib/private/Utf8Analyzer.php | 4 +- lib/private/legacy/api.php | 6 +- lib/private/legacy/app.php | 21 +- lib/private/legacy/db.php | 2 +- lib/private/legacy/db/statementwrapper.php | 4 +- lib/private/legacy/defaults.php | 27 +- lib/private/legacy/eventsource.php | 15 +- lib/private/legacy/files.php | 22 +- lib/private/legacy/helper.php | 6 +- lib/private/legacy/image.php | 5 +- lib/private/legacy/response.php | 2 +- lib/private/legacy/template.php | 9 +- lib/private/legacy/user.php | 4 +- lib/private/legacy/util.php | 26 +- lib/public/App/ManagerEvent.php | 7 +- lib/public/AppFramework/ApiController.php | 2 +- lib/public/AppFramework/App.php | 2 +- lib/public/AppFramework/Http/Response.php | 16 +- lib/public/AppFramework/OCSController.php | 10 +- .../Exceptions/AccountCheckException.php | 5 +- lib/public/BackgroundJob.php | 4 +- lib/public/Defaults.php | 2 +- lib/public/Files.php | 2 +- lib/public/Files/External/Backend/Backend.php | 2 +- .../Files/External/Backend/InvalidBackend.php | 2 +- .../Files/External/DefinitionParameter.php | 4 +- lib/public/Files/LockNotAcquiredException.php | 2 +- lib/public/ITags.php | 2 +- lib/public/Roles/AddRolesEvent.php | 2 +- .../User/UserExtendedAttributesEvent.php | 6 +- lib/public/Util.php | 2 +- rector.php | 2 + settings/Application.php | 338 +++++------- settings/ChangePassword/Controller.php | 8 +- settings/Controller/AppConfigController.php | 3 +- settings/Controller/AppSettingsController.php | 29 +- .../Controller/AuthSettingsController.php | 16 +- settings/Controller/CertificateController.php | 12 +- settings/Controller/CheckSetupController.php | 20 +- settings/Controller/CorsController.php | 22 +- settings/Controller/GroupsController.php | 11 +- .../Controller/LegalSettingsController.php | 10 +- settings/Controller/LogSettingsController.php | 10 +- .../Controller/MailSettingsController.php | 15 +- settings/Controller/UsersController.php | 40 +- settings/Panels/Admin/Enforce2fa.php | 2 +- settings/Panels/Admin/FileSharing.php | 10 +- settings/Panels/Admin/License.php | 3 +- settings/Panels/Admin/PersistentLocking.php | 5 +- settings/Panels/Personal/Cors.php | 5 +- settings/Panels/Personal/Legacy.php | 3 +- settings/Panels/Personal/Profile.php | 7 +- settings/ajax/togglegroups.php | 4 +- settings/routes.php | 4 +- settings/users.php | 2 +- tests/Core/Command/Apps/AppsDisableTest.php | 3 +- tests/Core/Command/Apps/AppsEnableTest.php | 3 +- tests/Core/Command/Apps/AppsGetPathTest.php | 3 +- tests/Core/Command/Apps/AppsListTest.php | 3 +- tests/Core/Command/Apps/CheckCodeTest.php | 3 +- .../Command/Background/Queue/DeleteTest.php | 9 +- .../Command/Background/Queue/ExecuteTest.php | 7 +- .../Command/Background/Queue/StatusTest.php | 5 +- .../Command/Config/App/DeleteConfigTest.php | 6 +- .../Core/Command/Config/App/GetConfigTest.php | 8 +- .../Core/Command/Config/App/SetConfigTest.php | 6 +- tests/Core/Command/Config/ImportTest.php | 6 +- tests/Core/Command/Config/ListConfigsTest.php | 8 +- .../Config/System/DeleteConfigTest.php | 6 +- .../Command/Config/System/GetConfigTest.php | 12 +- .../Command/Config/System/SetConfigTest.php | 6 +- tests/Core/Command/Db/ConvertTypeTest.php | 9 +- .../Db/RestoreDefaultRowFormatTest.php | 9 +- .../Encryption/ChangeKeyStorageRootTest.php | 26 +- .../Command/Encryption/DecryptAllTest.php | 14 +- tests/Core/Command/Encryption/EnableTest.php | 10 +- .../Command/Encryption/EncryptAllTest.php | 14 +- .../Encryption/SetDefaultModuleTest.php | 6 +- tests/Core/Command/Group/AddMemberTest.php | 3 +- tests/Core/Command/Group/AddTest.php | 3 +- tests/Core/Command/Group/DeleteTest.php | 8 +- .../Command/Group/ListGroupMembersTest.php | 3 +- tests/Core/Command/Group/ListGroupsTest.php | 3 +- tests/Core/Command/Group/RemoveMemberTest.php | 3 +- tests/Core/Command/Log/ManageTest.php | 6 +- tests/Core/Command/Log/OwnCloudTest.php | 6 +- .../Maintenance/DataFingerprintTest.php | 11 +- .../Maintenance/Mimetype/UpdateDBTest.php | 8 +- tests/Core/Command/Maintenance/RepairTest.php | 5 +- .../Command/Maintenance/SingleUserTest.php | 6 +- .../Security/ImportCertificateTest.php | 8 +- .../Security/RemoveCertificateTest.php | 8 +- tests/Core/Command/System/CronTest.php | 11 +- .../Command/TwoFactorAuth/DisableTest.php | 3 +- .../Core/Command/TwoFactorAuth/EnableTest.php | 3 +- tests/Core/Command/User/AddTest.php | 3 +- tests/Core/Command/User/DeleteTest.php | 9 +- tests/Core/Command/User/DisableTest.php | 3 +- tests/Core/Command/User/EnableTest.php | 3 +- tests/Core/Command/User/HomeListDirsTest.php | 9 +- tests/Core/Command/User/HomeListUsersTest.php | 13 +- tests/Core/Command/User/InactiveTest.php | 10 +- tests/Core/Command/User/LastSeenTest.php | 8 +- .../Core/Command/User/ListUserGroupsTest.php | 3 +- tests/Core/Command/User/ListUsersTest.php | 3 +- tests/Core/Command/User/MoveHomeTest.php | 10 +- tests/Core/Command/User/ReportTest.php | 17 +- tests/Core/Command/User/ResetPasswordTest.php | 13 +- tests/Core/Command/User/SettingTest.php | 12 +- .../Controller/AppRegistryControllerTest.php | 10 +- .../Core/Controller/AvatarControllerTest.php | 36 +- tests/Core/Controller/CronControllerTest.php | 11 +- .../Core/Controller/LicenseControllerTest.php | 23 +- tests/Core/Controller/LoginControllerTest.php | 16 +- tests/Core/Controller/LostControllerTest.php | 75 ++- tests/Core/Controller/OccControllerTest.php | 18 +- tests/Core/Controller/OcsControllerTest.php | 10 +- tests/Core/Controller/TokenControllerTest.php | 26 +- .../TwoFactorChallengeControllerTest.php | 12 +- .../Controller/UserSyncControllerTest.php | 9 +- .../AccountModuleMiddlewareTest.php | 11 +- .../Middleware/TwoFactorMiddlewareTest.php | 22 +- .../Controller/AppConfigControllerTest.php | 5 +- .../Controller/AppSettingsControllerTest.php | 11 +- .../Controller/AuthSettingsControllerTest.php | 33 +- .../Controller/CertificateControllerTest.php | 30 +- .../Controller/CheckSetupControllerTest.php | 60 ++- .../Controller/CorsControllerTest.php | 35 +- .../Controller/GroupsControllerTest.php | 40 +- .../Controller/LogSettingsControllerTest.php | 4 +- .../Controller/MailSettingsControllerTest.php | 10 +- .../Controller/UsersControllerTest.php | 62 ++- .../Middleware/SubadminMiddlewareTest.php | 14 +- tests/Settings/Panels/Admin/AppsTest.php | 5 +- .../Panels/Admin/BackgroundJobsTest.php | 5 +- .../Panels/Admin/CertificatesTest.php | 9 +- .../Settings/Panels/Admin/EncryptionTest.php | 3 +- .../Settings/Panels/Admin/Enforce2faTest.php | 5 +- .../Settings/Panels/Admin/FileSharingTest.php | 7 +- tests/Settings/Panels/Admin/LegacyTest.php | 5 +- tests/Settings/Panels/Admin/LegalTest.php | 5 +- tests/Settings/Panels/Admin/LicenseTest.php | 5 +- tests/Settings/Panels/Admin/LoggingTest.php | 9 +- tests/Settings/Panels/Admin/MailTest.php | 11 +- .../Panels/Admin/PersistentLockingTest.php | 7 +- .../Panels/Admin/SecurityWarningTest.php | 13 +- tests/Settings/Panels/Admin/TipsTest.php | 3 +- .../Settings/Panels/Personal/ClientsTest.php | 7 +- tests/Settings/Panels/Personal/LegacyTest.php | 5 +- .../Settings/Panels/Personal/ProfileTest.php | 11 +- tests/Settings/Panels/Personal/QuotaTest.php | 5 +- tests/Settings/Panels/Personal/TokensTest.php | 3 +- .../Settings/Panels/Personal/VersionTest.php | 3 +- tests/TestHelpers/AppConfigHelper.php | 4 +- tests/TestHelpers/EmailHelper.php | 4 +- tests/TestHelpers/SetupHelper.php | 13 +- tests/TestHelpers/TagsHelper.php | 2 +- tests/TestHelpers/Unit/DeleteHelperTest.php | 2 +- tests/TestHelpers/UploadHelper.php | 2 +- tests/TestHelpers/WebDavHelper.php | 4 +- .../bootstrap/AppManagementContext.php | 12 +- .../features/bootstrap/AuthContext.php | 7 +- .../features/bootstrap/CorsContext.php | 6 +- .../features/bootstrap/FeatureContext.php | 97 ++-- .../features/bootstrap/LoggingContext.php | 8 +- .../bootstrap/NotificationsCoreContext.php | 6 +- .../features/bootstrap/OCSContext.php | 4 +- .../bootstrap/OccAppManagementContext.php | 8 +- .../features/bootstrap/OccContext.php | 36 +- .../bootstrap/OccUsersGroupsContext.php | 8 +- .../features/bootstrap/Provisioning.php | 28 +- .../bootstrap/PublicWebDavContext.php | 3 +- .../features/bootstrap/ShareesContext.php | 2 +- .../acceptance/features/bootstrap/Sharing.php | 19 +- .../features/bootstrap/TUSContext.php | 2 +- .../features/bootstrap/TagsContext.php | 5 +- .../bootstrap/TransferOwnershipContext.php | 2 +- .../features/bootstrap/TrashbinContext.php | 22 +- .../acceptance/features/bootstrap/WebDav.php | 6 +- .../bootstrap/WebDavLockingContext.php | 2 +- .../WebUIAdminStorageSettingsContext.php | 3 +- .../WebUIPersonalSecuritySettingsContext.php | 2 +- .../features/bootstrap/bootstrap.php | 2 +- .../lib/AdminEncryptionSettingsPage.php | 8 +- tests/acceptance/features/lib/FilesPage.php | 2 +- .../lib/FilesPageElement/ConflictDialog.php | 4 +- .../lib/FilesPageElement/DetailsDialog.php | 52 +- .../lib/FilesPageElement/SharingDialog.php | 69 ++- .../EditPublicLinkPopup.php | 26 +- .../SharingDialogElement/PublicLinkTab.php | 14 +- .../acceptance/features/lib/Notification.php | 4 +- .../features/lib/NotificationsAppDialog.php | 8 +- .../lib/NotificationsEnabledOwncloudPage.php | 2 +- .../acceptance/features/lib/OwncloudPage.php | 2 +- .../lib/OwncloudPageElement/SettingsMenu.php | 2 +- .../lib/PersonalEncryptionSettingsPage.php | 4 +- .../lib/PersonalSecuritySettingsPage.php | 2 +- tests/acceptance/features/lib/TagsPage.php | 4 +- tests/lib/APITest.php | 2 +- tests/lib/Activity/ManagerTest.php | 55 +- .../lib/Activity/NullSession/ManagerTest.php | 45 +- tests/lib/AllConfigTest.php | 8 +- .../App/CodeChecker/DeprecationCheckTest.php | 4 +- tests/lib/App/CodeChecker/InfoCheckerTest.php | 4 +- tests/lib/App/CodeChecker/Mock/TestList.php | 2 +- tests/lib/App/CodeChecker/NodeVisitorTest.php | 4 +- tests/lib/App/DependencyAnalyzerTest.php | 17 +- tests/lib/App/InfoParserTest.php | 7 +- tests/lib/App/ManagerTest.php | 22 +- tests/lib/AppConfigTest.php | 4 +- tests/lib/AppFramework/AppTest.php | 24 +- .../Controller/ApiControllerTest.php | 4 +- .../Controller/ControllerTest.php | 13 +- tests/lib/AppFramework/Db/MapperTest.php | 10 +- .../lib/AppFramework/Db/MapperTestUtility.php | 6 +- .../DependencyInjection/DIContainerTest.php | 10 +- .../Http/ContentSecurityPolicyTest.php | 3 +- .../AppFramework/Http/DataResponseTest.php | 5 +- .../lib/AppFramework/Http/DispatcherTest.php | 68 ++- .../Http/EmptyContentSecurityPolicyTest.php | 3 +- tests/lib/AppFramework/Http/HttpTest.php | 7 +- .../AppFramework/Http/JSONResponseTest.php | 5 +- tests/lib/AppFramework/Http/RequestTest.php | 20 +- tests/lib/AppFramework/Http/ResponseTest.php | 5 +- .../AppFramework/Http/StreamResponseTest.php | 4 +- .../Http/TemplateResponseTest.php | 7 +- .../Middleware/MiddlewareDispatcherTest.php | 27 +- .../Middleware/MiddlewareTest.php | 25 +- .../Security/CORSMiddlewareTest.php | 9 +- .../Security/SecurityMiddlewareTest.php | 50 +- .../Middleware/SessionMiddlewareTest.php | 16 +- .../lib/AppFramework/Routing/RoutingTest.php | 8 +- .../Utility/ControllerMethodReflectorTest.php | 22 +- .../Utility/SimpleContainerTest.php | 55 +- tests/lib/AppTest.php | 50 +- .../AccountModule/ManagerTest.php | 15 +- .../LoginPolicies/GroupLoginPolicyTest.php | 21 +- .../LoginPolicies/LoginPolicyManagerTest.php | 9 +- .../Token/DefaultTokenCleanupJobTest.php | 11 +- .../Token/DefaultTokenMapperTest.php | 13 +- .../Token/DefaultTokenProviderTest.php | 35 +- .../TwoFactorAuth/ManagerTest.php | 38 +- tests/lib/AutoLoaderTest.php | 2 +- tests/lib/AvatarManagerTest.php | 15 +- tests/lib/AvatarTest.php | 7 +- tests/lib/BackgroundJob/DummyJobList.php | 2 +- tests/lib/BackgroundJob/JobListTest.php | 36 +- tests/lib/BackgroundJob/JobTest.php | 4 +- tests/lib/BackgroundJob/QueuedJobTest.php | 9 +- tests/lib/BackgroundJob/TimedJobTest.php | 9 +- tests/lib/Cache/FileCacheTest.php | 7 +- tests/lib/CapabilitiesManagerTest.php | 28 +- tests/lib/Command/AsyncBusTest.php | 8 +- tests/lib/Command/Integrity/SignAppTest.php | 39 +- tests/lib/Command/Integrity/SignCoreTest.php | 31 +- tests/lib/Command/User/SyncBackendTest.php | 17 +- tests/lib/Comments/ManagerTest.php | 8 +- tests/lib/ConfigTest.php | 9 +- tests/lib/ContactsManagerTest.php | 23 +- tests/lib/DB/LegacyDBTest.php | 30 +- tests/lib/DB/MDB2SchemaReaderTest.php | 8 +- tests/lib/DB/MigrationsTest.php | 2 +- tests/lib/DB/MigratorTest.php | 13 +- tests/lib/DB/MySqlToolsTest.php | 2 +- .../DB/QueryBuilder/ExpressionBuilderTest.php | 50 +- tests/lib/DB/QueryBuilder/QuoteHelperTest.php | 2 +- tests/lib/DB/SchemaDiffTest.php | 6 +- tests/lib/DateTimeFormatterTest.php | 12 +- tests/lib/Diagnostics/EventLoggerTest.php | 3 +- tests/lib/Diagnostics/QueryLoggerTest.php | 3 +- tests/lib/Encryption/DecryptAllTest.php | 14 +- .../lib/Encryption/EncryptionWrapperTest.php | 35 +- tests/lib/Encryption/Keys/StorageTest.php | 10 +- tests/lib/Encryption/ManagerTest.php | 44 +- tests/lib/Encryption/UpdateTest.php | 32 +- tests/lib/Encryption/UtilTest.php | 18 +- tests/lib/Events/EventEmitterTraitTest.php | 4 +- tests/lib/FileChunkingTest.php | 2 +- tests/lib/Files/Cache/CacheTest.php | 14 +- tests/lib/Files/Cache/HomeCacheTest.php | 7 +- tests/lib/Files/Cache/PropagatorTest.php | 6 +- tests/lib/Files/Cache/ScannerTest.php | 10 +- tests/lib/Files/Cache/UpdaterLegacyTest.php | 4 +- tests/lib/Files/Cache/UpdaterTest.php | 2 +- tests/lib/Files/Cache/WatcherTest.php | 2 +- tests/lib/Files/Config/UserMountCacheTest.php | 17 +- tests/lib/Files/EtagTest.php | 4 +- .../Files/External/Auth/AuthMechanismTest.php | 8 +- .../Auth/Password/SessionCredentialsTest.php | 10 +- .../Files/External/Backend/BackendTest.php | 6 +- .../Files/External/Backend/DummyBackend.php | 4 +- .../lib/Files/External/ConfigAdapterTest.php | 15 +- .../External/FrontendDefinitionTraitTest.php | 16 +- .../lib/Files/External/PersonalMountTest.php | 4 +- .../External/Service/CleaningDBConfig.php | 2 +- .../External/Service/DBConfigServiceTest.php | 11 +- .../GlobalStoragesServiceDeleteUserTest.php | 8 +- .../External/Service/StoragesServiceTest.php | 53 +- .../Service/UserGlobalStoragesServiceTest.php | 4 +- .../Service/UserStoragesServiceTest.php | 10 +- .../lib/Files/External/StorageConfigTest.php | 6 +- .../External/StoragesBackendServiceTest.php | 20 +- tests/lib/Files/FilesystemTest.php | 40 +- tests/lib/Files/MetaVersionCollectionTest.php | 23 +- .../Files/Mount/CacheMountProviderTest.php | 2 +- tests/lib/Files/Mount/ManagerTest.php | 5 +- tests/lib/Files/Mount/MountPointTest.php | 18 +- tests/lib/Files/Mount/MountTest.php | 14 +- .../Mount/ObjectHomeMountProviderTest.php | 40 +- .../Files/Mount/PreviewsMountProviderTest.php | 2 +- tests/lib/Files/Node/FolderTest.php | 142 ++--- tests/lib/Files/Node/HookConnectorTest.php | 10 +- tests/lib/Files/Node/IntegrationTest.php | 18 +- tests/lib/Files/Node/NodeTest.php | 120 ++--- tests/lib/Files/Node/RootTest.php | 16 +- tests/lib/Files/ObjectStore/MapperTest.php | 2 +- .../lib/Files/ObjectStore/NoopScannerTest.php | 5 +- .../lib/Files/ObjectStore/ObjectStoreTest.php | 8 +- tests/lib/Files/PathVerificationTest.php | 5 +- tests/lib/Files/Storage/DavTest.php | 44 +- .../Files/Storage/HomeStorageQuotaTest.php | 6 +- tests/lib/Files/Storage/HomeTest.php | 4 +- tests/lib/Files/Storage/LockingTests.php | 2 +- tests/lib/Files/Storage/Storage.php | 4 +- .../lib/Files/Storage/StorageFactoryTest.php | 30 +- .../Storage/Wrapper/AvailabilityTest.php | 14 +- .../Files/Storage/Wrapper/ChecksumTest.php | 12 +- .../lib/Files/Storage/Wrapper/DirMaskTest.php | 3 +- .../Files/Storage/Wrapper/EncodingTest.php | 5 +- .../Files/Storage/Wrapper/EncryptionTest.php | 73 +-- tests/lib/Files/Storage/Wrapper/JailTest.php | 5 +- .../Storage/Wrapper/PermissionsMaskTest.php | 5 +- tests/lib/Files/Storage/Wrapper/QuotaTest.php | 20 +- .../Storage/Wrapper/ReadOnlyJailTest.php | 6 +- .../lib/Files/Storage/Wrapper/WrapperTest.php | 2 +- tests/lib/Files/Stream/ChecksumTest.php | 2 +- tests/lib/Files/Stream/EncryptionTest.php | 36 +- tests/lib/Files/Stream/StaticStreamTest.php | 2 +- tests/lib/Files/Type/DetectionTest.php | 19 +- tests/lib/Files/Utils/ScannerTest.php | 10 +- tests/lib/Files/ViewTest.php | 38 +- tests/lib/Group/DatabaseTest.php | 2 +- tests/lib/Group/GroupTest.php | 56 +- tests/lib/Group/ManagerTest.php | 8 +- tests/lib/Group/MetaDataTest.php | 18 +- tests/lib/HTTPHelperTest.php | 18 +- tests/lib/Helper/EnvironmentHelperTest.php | 2 +- tests/lib/Helper/LocaleHelperTest.php | 6 +- tests/lib/HelperStorageTest.php | 5 +- tests/lib/HookHelper.php | 12 +- tests/lib/Hooks/BasicEmitterTest.php | 2 +- tests/lib/Hooks/LegacyEmitterTest.php | 6 +- tests/lib/Http/Client/ClientServiceTest.php | 4 +- tests/lib/Http/Client/ClientTest.php | 11 +- tests/lib/Http/Client/ResponseTest.php | 6 +- tests/lib/Image/BmpToResourceTest.php | 2 +- tests/lib/ImageTest.php | 8 +- tests/lib/InstallerTest.php | 2 +- tests/lib/IntegrityCheck/CheckerTest.php | 40 +- .../IntegrityCheck/Helpers/AppLocatorTest.php | 3 +- .../Helpers/EnvironmentHelperTest.php | 3 +- .../Helpers/FileAccessHelperTest.php | 3 +- tests/lib/L10N/L10nTest.php | 20 +- tests/lib/LargeFileHelperTest.php | 2 +- tests/lib/LegacyHelperTest.php | 30 +- tests/lib/License/LicenseFetcherTest.php | 15 +- tests/lib/License/LicenseManagerTest.php | 401 +++++++-------- tests/lib/License/MessageServiceTest.php | 12 +- tests/lib/Lock/DBLockingProviderTest.php | 10 +- .../lib/Lock/MemcacheLockingProviderTest.php | 5 +- tests/lib/Lock/Persistent/LockManagerTest.php | 13 +- tests/lib/Lock/Persistent/LockMapperTest.php | 72 ++- tests/lib/Log/OwncloudTest.php | 2 +- tests/lib/LoggerTest.php | 10 +- tests/lib/LoggerWithoutWriteExtraTest.php | 8 +- tests/lib/Mail/MailerTest.php | 6 +- tests/lib/Mail/MessageTest.php | 5 +- tests/lib/Memcache/CasTraitTest.php | 18 +- tests/lib/Memcache/FactoryTest.php | 4 +- tests/lib/Migration/BackgroundRepairTest.php | 16 +- tests/lib/NavigationManagerTest.php | 8 +- tests/lib/Notification/ManagerTest.php | 104 +--- tests/lib/Notification/NotificationTest.php | 20 +- tests/lib/OCS/ProviderTest.php | 11 +- tests/lib/PreviewManagerTest.php | 7 +- tests/lib/PreviewTest.php | 60 ++- tests/lib/PublicNamespace/ContactsTest.php | 8 +- tests/lib/PublicNamespace/UtilTest.php | 2 +- tests/lib/Repair/AppsTest.php | 6 +- tests/lib/Repair/CleanTagsTest.php | 8 +- tests/lib/Repair/DropOldJobsTest.php | 2 +- tests/lib/Repair/DropOldTablesTest.php | 2 +- .../Repair/OldGroupMembershipSharesTest.php | 4 +- tests/lib/Repair/RemoveGetETagEntriesTest.php | 2 +- tests/lib/Repair/RemoveRootSharesTest.php | 4 +- tests/lib/Repair/RepairCollationTest.php | 7 +- tests/lib/Repair/RepairInnoDBTest.php | 4 +- tests/lib/Repair/RepairInvalidSharesTest.php | 12 +- tests/lib/Repair/RepairMimeTypesTest.php | 9 +- .../RepairMismatchFileCachePathTest.php | 4 +- .../lib/Repair/RepairOrphanedSubshareTest.php | 8 +- .../lib/Repair/RepairSharePropagationTest.php | 4 +- .../Repair/RepairSqliteAutoincrementTest.php | 7 +- tests/lib/Repair/RepairSubSharesTest.php | 8 +- tests/lib/Repair/RepairUnmergedSharesTest.php | 19 +- tests/lib/RepairStepTest.php | 5 +- tests/lib/Route/RouterTest.php | 2 +- .../CSP/ContentSecurityPolicyManagerTest.php | 3 +- .../Security/CSRF/CsrfTokenGeneratorTest.php | 7 +- .../Security/CSRF/CsrfTokenManagerTest.php | 11 +- .../CSRF/TokenStorage/SessionStorageTest.php | 7 +- tests/lib/Security/CertificateManagerTest.php | 5 +- tests/lib/Security/CredentialsManagerTest.php | 8 +- tests/lib/Security/HasherTest.php | 2 +- .../lib/Security/TrustedDomainHelperTest.php | 2 +- tests/lib/Session/CryptoSessionDataTest.php | 10 +- tests/lib/Session/CryptoWrappingTest.php | 16 +- tests/lib/Settings/ManagerTest.php | 52 +- tests/lib/SetupTest.php | 16 +- tests/lib/Share/Backend.php | 6 +- tests/lib/Share/HelperTest.php | 18 +- tests/lib/Share/MailNotificationsTest.php | 27 +- tests/lib/Share/ShareTest.php | 76 ++- .../lib/Share20/DefaultShareProviderTest.php | 28 +- tests/lib/Share20/ManagerTest.php | 276 +++++----- tests/lib/Share20/ShareTest.php | 4 +- tests/lib/SubAdminTest.php | 4 +- tests/lib/SystemConfigTest.php | 9 +- tests/lib/SystemTag/SystemTagManagerTest.php | 14 +- .../SystemTag/SystemTagObjectMapperTest.php | 16 +- tests/lib/TagsTest.php | 6 +- tests/lib/Template/ResourceLocatorTest.php | 6 +- tests/lib/TemplateFunctionsTest.php | 30 +- tests/lib/TestCase.php | 41 +- tests/lib/Theme/ThemeServiceTest.php | 4 +- tests/lib/Theme/ThemeTest.php | 5 +- tests/lib/Traits/MountProviderTrait.php | 6 +- tests/lib/Updater/VersionCheckTest.php | 10 +- tests/lib/UpdaterTest.php | 9 +- tests/lib/UrlGeneratorTest.php | 6 +- tests/lib/User/BackendTestCase.php | 2 +- tests/lib/User/BasicAuthModuleTest.php | 14 +- tests/lib/User/DeletedUserTest.php | 9 +- tests/lib/User/ManagerTest.php | 4 +- tests/lib/User/RemoteUserTest.php | 3 +- tests/lib/User/SessionTest.php | 16 +- .../User/Sync/BackendUsersIteratorTest.php | 4 +- tests/lib/User/Sync/SeenUsersIteratorTest.php | 4 +- tests/lib/User/SyncServiceTest.php | 14 +- tests/lib/User/TokenAuthModuleTest.php | 10 +- .../User/UserExtendedAttributesEventTest.php | 4 +- tests/lib/User/UserTest.php | 35 +- tests/lib/Utf8AnalyzerTest.php | 3 +- tests/lib/Util/Group/Dummy.php | 2 +- tests/lib/Util/User/Dummy.php | 6 +- tests/lib/Util/User/MemoryAccountMapper.php | 16 +- tests/lib/UtilCheckServerTest.php | 6 +- tests/lib/UtilTest.php | 20 +- 1214 files changed, 7507 insertions(+), 10839 deletions(-) diff --git a/apps/comments/appinfo/app.php b/apps/comments/appinfo/app.php index bbc292dc4a1f..21cd283b6701 100644 --- a/apps/comments/appinfo/app.php +++ b/apps/comments/appinfo/app.php @@ -39,14 +39,14 @@ function () { $activityManager->registerExtension(function () { $application = new \OCP\AppFramework\App('comments'); /** @var \OCA\Comments\Activity\Extension $extension */ - $extension = $application->getContainer()->query('OCA\Comments\Activity\Extension'); + $extension = $application->getContainer()->query(\OCA\Comments\Activity\Extension::class); return $extension; }); $managerListener = function (\OCP\Comments\CommentsEvent $event) { $application = new \OCP\AppFramework\App('comments'); /** @var \OCA\Comments\Activity\Listener $listener */ - $listener = $application->getContainer()->query('OCA\Comments\Activity\Listener'); + $listener = $application->getContainer()->query(\OCA\Comments\Activity\Listener::class); $listener->commentEvent($event); }; diff --git a/apps/comments/lib/Dav/CommentNode.php b/apps/comments/lib/Dav/CommentNode.php index f90e47153bfa..643dd4ee48f8 100644 --- a/apps/comments/lib/Dav/CommentNode.php +++ b/apps/comments/lib/Dav/CommentNode.php @@ -79,9 +79,7 @@ public function __construct( $this->logger = $logger; $methods = \get_class_methods($this->comment); - $methods = \array_filter($methods, function ($name) { - return \strpos($name, 'get') === 0; - }); + $methods = \array_filter($methods, fn ($name) => \strpos($name, 'get') === 0); foreach ($methods as $getter) { $name = '{'.self::NS_OWNCLOUD.'}' . \lcfirst(\substr($getter, 3)); $this->properties[$name] = $getter; diff --git a/apps/comments/lib/Dav/CommentsPlugin.php b/apps/comments/lib/Dav/CommentsPlugin.php index fee316a39a3b..a15fcffdf623 100644 --- a/apps/comments/lib/Dav/CommentsPlugin.php +++ b/apps/comments/lib/Dav/CommentsPlugin.php @@ -53,8 +53,7 @@ class CommentsPlugin extends ServerPlugin { /** @var ICommentsManager */ protected $commentsManager; - /** @var \Sabre\DAV\Server $server */ - private $server; + private ?\Sabre\DAV\Server $server = null; /** @var \OCP\IUserSession */ protected $userSession; @@ -222,7 +221,7 @@ public function onReport($reportName, $report, $uri) { */ private function createComment($objectType, $objectId, $data, $contentType = 'application/json') { if (\explode(';', $contentType)[0] === 'application/json') { - $data = \json_decode($data, true); + $data = \json_decode($data, true, 512, JSON_THROW_ON_ERROR); } else { throw new UnsupportedMediaType(); } diff --git a/apps/comments/lib/Dav/EntityCollection.php b/apps/comments/lib/Dav/EntityCollection.php index 5db5e15fe339..fffdd58cb360 100644 --- a/apps/comments/lib/Dav/EntityCollection.php +++ b/apps/comments/lib/Dav/EntityCollection.php @@ -67,8 +67,8 @@ public function __construct( ) { parent::__construct($commentsManager, $userManager, $userSession, $dispatcher, $logger); foreach (['id', 'name'] as $property) { - $$property = \trim($$property); - if (empty($$property) || !\is_string($$property)) { + ${$property} = \trim(${$property}); + if (empty(${$property}) || !\is_string(${$property})) { throw new \InvalidArgumentException('"' . $property . '" parameter must be non-empty string'); } } diff --git a/apps/comments/lib/Dav/RootCollection.php b/apps/comments/lib/Dav/RootCollection.php index 774516d327dd..75321ff49153 100644 --- a/apps/comments/lib/Dav/RootCollection.php +++ b/apps/comments/lib/Dav/RootCollection.php @@ -36,7 +36,7 @@ class RootCollection implements ICollection { /** @var EntityTypeCollection[]|null */ - private $entityTypeCollections; + private ?array $entityTypeCollections = null; /** @var ICommentsManager */ protected $commentsManager; diff --git a/apps/comments/tests/unit/ActivityListenerTest.php b/apps/comments/tests/unit/ActivityListenerTest.php index fe06d4c0d3bd..f19ba9ffef2b 100644 --- a/apps/comments/tests/unit/ActivityListenerTest.php +++ b/apps/comments/tests/unit/ActivityListenerTest.php @@ -45,30 +45,27 @@ class ActivityListenerTest extends \Test\TestCase { use UserTrait; - /** - * @var Listener - */ - private $listener; + private \OCA\Comments\Activity\Listener $listener; /** * @var IUserMountCache */ - private $userMountCache; + private \PHPUnit\Framework\MockObject\MockObject $userMountCache; /** * @var IRootFolder */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; /** * @var IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** * @var IManager */ - private $activityManager; + private \PHPUnit\Framework\MockObject\MockObject $activityManager; protected function setUp(): void { parent::setUp(); diff --git a/apps/comments/tests/unit/Dav/CommentsNodeTest.php b/apps/comments/tests/unit/Dav/CommentsNodeTest.php index 37a25f9c24aa..012a8dbbff51 100644 --- a/apps/comments/tests/unit/Dav/CommentsNodeTest.php +++ b/apps/comments/tests/unit/Dav/CommentsNodeTest.php @@ -38,11 +38,11 @@ class CommentsNodeTest extends \Test\TestCase { public function setUp(): void { parent::setUp(); - $this->commentsManager = $this->createMock('\OCP\Comments\ICommentsManager'); - $this->comment = $this->createMock('\OCP\Comments\IComment'); - $this->userManager = $this->createMock('\OCP\IUserManager'); - $this->userSession = $this->createMock('\OCP\IUserSession'); - $this->logger = $this->createMock('\OCP\ILogger'); + $this->commentsManager = $this->createMock('\\' . \OCP\Comments\ICommentsManager::class); + $this->comment = $this->createMock('\\' . \OCP\Comments\IComment::class); + $this->userManager = $this->createMock('\\' . \OCP\IUserManager::class); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); + $this->logger = $this->createMock('\\' . \OCP\ILogger::class); $this->node = new CommentNode( $this->commentsManager, @@ -54,7 +54,7 @@ public function setUp(): void { } public function testDelete() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') @@ -88,7 +88,7 @@ public function testDelete() { public function testDeleteForbidden() { $this->expectException(\Sabre\DAV\Exception\Forbidden::class); - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') @@ -139,7 +139,7 @@ public function testGetLastModified() { public function testUpdateComment() { $msg = 'Hello Earth'; - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') @@ -176,7 +176,7 @@ public function testUpdateCommentLogException() { $msg = null; - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') @@ -214,7 +214,7 @@ public function testUpdateCommentMessageTooLongException() { $this->expectException(\Sabre\DAV\Exception\BadRequest::class); $this->expectExceptionMessage('Message exceeds allowed character limit of'); - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') @@ -253,7 +253,7 @@ public function testUpdateForbiddenByUser() { $msg = 'HaXX0r'; - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') @@ -287,7 +287,7 @@ public function testUpdateForbiddenByType() { $msg = 'HaXX0r'; - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->never()) ->method('getUID'); @@ -334,7 +334,7 @@ public function testUpdateForbiddenByNotLoggedIn() { } public function testPropPatch() { - $propPatch = $this->getMockBuilder('Sabre\DAV\PropPatch') + $propPatch = $this->getMockBuilder(\Sabre\DAV\PropPatch::class) ->disableOriginalConstructor() ->getMock(); @@ -412,7 +412,7 @@ public function testGetProperties() { ->method('getObjectId') ->will($this->returnValue($expected[$ns . 'objectId'])); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor() ->getMock(); $user->expects($this->once()) @@ -463,7 +463,7 @@ public function testGetPropertiesUnreadProperty($creationDT, $readDT, $expected) $this->userSession->expects($this->once()) ->method('getUser') - ->will($this->returnValue($this->createMock('\OCP\IUser'))); + ->will($this->returnValue($this->createMock('\\' . \OCP\IUser::class))); $properties = $this->node->getProperties(null); diff --git a/apps/comments/tests/unit/Dav/CommentsPluginTest.php b/apps/comments/tests/unit/Dav/CommentsPluginTest.php index 400720e4523a..e7b49c082b41 100644 --- a/apps/comments/tests/unit/Dav/CommentsPluginTest.php +++ b/apps/comments/tests/unit/Dav/CommentsPluginTest.php @@ -30,33 +30,32 @@ class CommentsPluginTest extends \Test\TestCase { /** @var \Sabre\DAV\Server */ - private $server; + private \PHPUnit\Framework\MockObject\MockObject $server; /** @var \Sabre\DAV\Tree */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** @var \OCP\Comments\ICommentsManager */ - private $commentsManager; + private \PHPUnit\Framework\MockObject\MockObject $commentsManager; /** @var \OCP\IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; - /** @var CommentsPluginImplementation */ - private $plugin; + private \OCA\Comments\Dav\CommentsPlugin $plugin; public function setUp(): void { parent::setUp(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + $this->tree = $this->getMockBuilder('\\' . \Sabre\DAV\Tree::class) ->disableOriginalConstructor() ->getMock(); - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + $this->server = $this->getMockBuilder('\\' . \Sabre\DAV\Server::class) ->setConstructorArgs([$this->tree]) ->setMethods(['getRequestUri']) ->getMock(); - $this->commentsManager = $this->createMock('\OCP\Comments\ICommentsManager'); - $this->userSession = $this->createMock('\OCP\IUserSession'); + $this->commentsManager = $this->createMock('\\' . \OCP\Comments\ICommentsManager::class); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); $this->plugin = new CommentsPluginImplementation($this->commentsManager, $this->userSession); } @@ -80,12 +79,12 @@ public function testCreateComment() { $requestData = \json_encode($commentData); - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->once()) ->method('getUID') ->will($this->returnValue('alice')); - $node = $this->getMockBuilder('\OCA\Comments\Dav\EntityCollection') + $node = $this->getMockBuilder('\\' . \OCA\Comments\Dav\EntityCollection::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->once()) @@ -117,11 +116,11 @@ public function testCreateComment() { ->with('/' . $path) ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -175,11 +174,11 @@ public function testCreateCommentInvalidObject() { $path = 'comments/files/666'; - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->never()) ->method('getUID'); - $node = $this->getMockBuilder('\OCA\Comments\Dav\EntityCollection') + $node = $this->getMockBuilder('\\' . \OCA\Comments\Dav\EntityCollection::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->never()) @@ -202,11 +201,11 @@ public function testCreateCommentInvalidObject() { ->with('/' . $path) ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -258,11 +257,11 @@ public function testCreateCommentInvalidActor() { $requestData = \json_encode($commentData); - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->never()) ->method('getUID'); - $node = $this->getMockBuilder('\OCA\Comments\Dav\EntityCollection') + $node = $this->getMockBuilder('\\' . \OCA\Comments\Dav\EntityCollection::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->once()) @@ -287,11 +286,11 @@ public function testCreateCommentInvalidActor() { ->with('/' . $path) ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -345,11 +344,11 @@ public function testCreateCommentUnsupportedMediaType() { $requestData = \json_encode($commentData); - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->never()) ->method('getUID'); - $node = $this->getMockBuilder('\OCA\Comments\Dav\EntityCollection') + $node = $this->getMockBuilder('\\' . \OCA\Comments\Dav\EntityCollection::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->once()) @@ -374,11 +373,11 @@ public function testCreateCommentUnsupportedMediaType() { ->with('/' . $path) ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -434,12 +433,12 @@ public function testCreateCommentInvalidPayload() { $requestData = \json_encode($commentData); - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->once()) ->method('getUID') ->will($this->returnValue('alice')); - $node = $this->getMockBuilder('\OCA\Comments\Dav\EntityCollection') + $node = $this->getMockBuilder('\\' . \OCA\Comments\Dav\EntityCollection::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->once()) @@ -467,11 +466,11 @@ public function testCreateCommentInvalidPayload() { ->with('/' . $path) ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -525,14 +524,14 @@ public function testCreateCommentMessageTooLong() { $path = 'comments/files/42'; - $requestData = \json_encode($commentData); + $requestData = \json_encode($commentData, JSON_THROW_ON_ERROR); - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->once()) ->method('getUID') ->will($this->returnValue('alice')); - $node = $this->getMockBuilder('\OCA\Comments\Dav\EntityCollection') + $node = $this->getMockBuilder('\\' . \OCA\Comments\Dav\EntityCollection::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->once()) @@ -563,11 +562,11 @@ public function testCreateCommentMessageTooLong() { ->with('/' . $path) ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -605,7 +604,7 @@ public function testOnReportInvalidNode() { $this->tree->expects($this->any()) ->method('getNodeForPath') ->with('/' . $path) - ->will($this->returnValue($this->createMock('\Sabre\DAV\INode'))); + ->will($this->returnValue($this->createMock('\\' . \Sabre\DAV\INode::class))); $this->server->expects($this->any()) ->method('getRequestUri') @@ -625,7 +624,7 @@ public function testOnReportInvalidReportName() { $this->tree->expects($this->any()) ->method('getNodeForPath') ->with('/' . $path) - ->will($this->returnValue($this->createMock('\Sabre\DAV\INode'))); + ->will($this->returnValue($this->createMock('\\' . \Sabre\DAV\INode::class))); $this->server->expects($this->any()) ->method('getRequestUri') @@ -653,7 +652,7 @@ public function testOnReportDateTimeEmpty() { ] ]; - $node = $this->getMockBuilder('\OCA\Comments\Dav\EntityCollection') + $node = $this->getMockBuilder('\\' . \OCA\Comments\Dav\EntityCollection::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->once()) @@ -661,7 +660,7 @@ public function testOnReportDateTimeEmpty() { ->with(5, 10, null) ->will($this->returnValue([])); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -708,7 +707,7 @@ public function testOnReport() { ] ]; - $node = $this->getMockBuilder('\OCA\Comments\Dav\EntityCollection') + $node = $this->getMockBuilder('\\' . \OCA\Comments\Dav\EntityCollection::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->once()) @@ -716,7 +715,7 @@ public function testOnReport() { ->with(5, 10, new \DateTime($parameters[2]['value'])) ->will($this->returnValue([])); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); diff --git a/apps/comments/tests/unit/Dav/EntityCollectionTest.php b/apps/comments/tests/unit/Dav/EntityCollectionTest.php index 4a890c3a9304..1fda9ce7b6ae 100644 --- a/apps/comments/tests/unit/Dav/EntityCollectionTest.php +++ b/apps/comments/tests/unit/Dav/EntityCollectionTest.php @@ -43,7 +43,7 @@ class EntityCollectionTest extends \Test\TestCase { /** @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject */ protected $userSession; /** @var EventDispatcherInterface | \PHPUnit_Framework_MockObject_MockObject */ - private $dispatcher; + private \PHPUnit\Framework\MockObject\MockObject $dispatcher; public function setUp(): void { parent::setUp(); diff --git a/apps/comments/tests/unit/Dav/EntityTypeCollectionTest.php b/apps/comments/tests/unit/Dav/EntityTypeCollectionTest.php index e6fb13d065e8..96a9ed706884 100644 --- a/apps/comments/tests/unit/Dav/EntityTypeCollectionTest.php +++ b/apps/comments/tests/unit/Dav/EntityTypeCollectionTest.php @@ -45,7 +45,7 @@ class EntityTypeCollectionTest extends \Test\TestCase { protected $childMap = []; /** @var EventDispatcherInterface | \PHPUnit_Framework_MockObject_MockObject */ - private $dispatcher; + private \PHPUnit\Framework\MockObject\MockObject $dispatcher; public function setUp(): void { parent::setUp(); @@ -65,9 +65,7 @@ public function setUp(): void { $this->userSession, $this->dispatcher, $this->logger, - function ($child) use ($instance) { - return !empty($instance->childMap[$child]); - } + fn ($child) => !empty($instance->childMap[$child]) ); } diff --git a/apps/comments/tests/unit/Dav/RootCollectionTest.php b/apps/comments/tests/unit/Dav/RootCollectionTest.php index 32f1b067cccc..5a5378c89873 100644 --- a/apps/comments/tests/unit/Dav/RootCollectionTest.php +++ b/apps/comments/tests/unit/Dav/RootCollectionTest.php @@ -47,13 +47,13 @@ class RootCollectionTest extends \Test\TestCase { public function setUp(): void { parent::setUp(); - $this->user = $this->createMock('\OCP\IUser'); + $this->user = $this->createMock('\\' . \OCP\IUser::class); - $this->commentsManager = $this->createMock('\OCP\Comments\ICommentsManager'); - $this->userManager = $this->createMock('\OCP\IUserManager'); - $this->userSession = $this->createMock('\OCP\IUserSession'); + $this->commentsManager = $this->createMock('\\' . \OCP\Comments\ICommentsManager::class); + $this->userManager = $this->createMock('\\' . \OCP\IUserManager::class); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); $this->dispatcher = new EventDispatcher(); - $this->logger = $this->createMock('\OCP\ILogger'); + $this->logger = $this->createMock('\\' . \OCP\ILogger::class); $this->collection = new \OCA\Comments\Dav\RootCollection( $this->commentsManager, @@ -74,9 +74,7 @@ protected function prepareForInitCollections() { ->will($this->returnValue($this->user)); $this->dispatcher->addListener(CommentsEntityEvent::EVENT_ENTITY, function (CommentsEntityEvent $event) { - $event->addEntityCollection('files', function () { - return true; - }); + $event->addEntityCollection('files', fn () => true); }); } diff --git a/apps/dav/appinfo/Migrations/Version20170202213905.php b/apps/dav/appinfo/Migrations/Version20170202213905.php index 82d98c916b16..b2ccfd980290 100644 --- a/apps/dav/appinfo/Migrations/Version20170202213905.php +++ b/apps/dav/appinfo/Migrations/Version20170202213905.php @@ -34,11 +34,10 @@ * Drop all entries that can't be resolved */ class Version20170202213905 implements ISqlMigration { - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; /** @var string[] */ - private $statements = []; + private array $statements = []; public function __construct(IUserManager $userManager) { $this->userManager = $userManager; diff --git a/apps/dav/appinfo/Migrations/Version20190823065724.php b/apps/dav/appinfo/Migrations/Version20190823065724.php index 97f201f45e4d..9ebdebcbeba2 100644 --- a/apps/dav/appinfo/Migrations/Version20190823065724.php +++ b/apps/dav/appinfo/Migrations/Version20190823065724.php @@ -30,8 +30,7 @@ * The fileid column should not accept null values in the properties table. */ class Version20190823065724 implements ISchemaMigration { - /** @var IDBConnection */ - private $dbConnection; + private \OCP\IDBConnection $dbConnection; public function __construct(IDBConnection $dbConnection) { $this->dbConnection = $dbConnection; diff --git a/apps/dav/appinfo/app.php b/apps/dav/appinfo/app.php index 625bc0349215..55b4843c837b 100644 --- a/apps/dav/appinfo/app.php +++ b/apps/dav/appinfo/app.php @@ -29,9 +29,7 @@ $app = new Application(); $app->registerHooks(); -\OC::$server->registerService('CardDAVSyncService', function () use ($app) { - return $app->getSyncService(); -}); +\OC::$server->registerService('CardDAVSyncService', fn () => $app->getSyncService()); $eventDispatcher = \OC::$server->getEventDispatcher(); diff --git a/apps/dav/appinfo/v1/publicwebdav.php b/apps/dav/appinfo/v1/publicwebdav.php index efe56bb62bb5..890e4cbf0117 100644 --- a/apps/dav/appinfo/v1/publicwebdav.php +++ b/apps/dav/appinfo/v1/publicwebdav.php @@ -84,9 +84,7 @@ // FIXME: should not add storage wrappers outside of preSetup, need to find a better way $previousLog = Filesystem::logWarningWhenAddingStorageWrapper(false); - Filesystem::addStorageWrapper('sharePermissions', function ($mountPoint, $storage) use ($share) { - return new PermissionsMask(['storage' => $storage, 'mask' => $share->getPermissions() | Constants::PERMISSION_SHARE]); - }); + Filesystem::addStorageWrapper('sharePermissions', fn ($mountPoint, $storage) => new PermissionsMask(['storage' => $storage, 'mask' => $share->getPermissions() | Constants::PERMISSION_SHARE])); Filesystem::logWarningWhenAddingStorageWrapper($previousLog); # in case any fs is already mounted: tear it down diff --git a/apps/dav/appinfo/v1/webdav.php b/apps/dav/appinfo/v1/webdav.php index 5b8e23abcd31..bd707c84e838 100644 --- a/apps/dav/appinfo/v1/webdav.php +++ b/apps/dav/appinfo/v1/webdav.php @@ -53,10 +53,9 @@ ); $requestUri = \OC::$server->getRequest()->getRequestUri(); -$server = $serverFactory->createServer($baseuri, $requestUri, $authBackend, function () { +$server = $serverFactory->createServer($baseuri, $requestUri, $authBackend, fn () => // use the view for the logged in user - return \OC\Files\Filesystem::getView(); -}); + \OC\Files\Filesystem::getView()); // allow setup of additional auth backends $event = new \OCP\SabrePluginEvent($server); diff --git a/apps/dav/lib/AppInfo/PluginManager.php b/apps/dav/lib/AppInfo/PluginManager.php index 627930d953e7..142f8909b6ed 100644 --- a/apps/dav/lib/AppInfo/PluginManager.php +++ b/apps/dav/lib/AppInfo/PluginManager.php @@ -29,29 +29,19 @@ * to the Sabre server. */ class PluginManager { - /** - * @var ServerContainer - */ - private $container; + private \OC\ServerContainer $container; - /** - * @var IAppManager - */ - private $appManager; + private \OCP\App\IAppManager $appManager; /** - * App plugins - * - * @var array - */ - private $plugins = null; + * App plugins + */ + private ?array $plugins = null; /** - * App collections - * - * @var array - */ - private $collections = null; + * App collections + */ + private ?array $collections = null; /** * Construct a PluginManager diff --git a/apps/dav/lib/Avatars/AvatarHome.php b/apps/dav/lib/Avatars/AvatarHome.php index c83d74d1cc3a..5ff909f8661a 100644 --- a/apps/dav/lib/Avatars/AvatarHome.php +++ b/apps/dav/lib/Avatars/AvatarHome.php @@ -30,8 +30,7 @@ class AvatarHome implements ICollection { /** @var array */ private $principalInfo; - /** @var IAvatarManager */ - private $avatarManager; + private \OCP\IAvatarManager $avatarManager; /** * AvatarHome constructor. @@ -53,8 +52,8 @@ public function createDirectory($name) { public function getChild($name) { $elements = \pathinfo($name); - $ext = isset($elements['extension']) ? $elements['extension'] : ''; - $size = \intval(isset($elements['filename']) ? $elements['filename'] : '64'); + $ext = $elements['extension'] ?? ''; + $size = \intval($elements['filename'] ?? '64'); if (!\in_array($ext, ['jpeg', 'png'])) { throw new MethodNotAllowed('File format not allowed'); } @@ -82,9 +81,7 @@ public function childExists($name) { try { $ret = $this->getChild($name); return $ret !== null; - } catch (NotFound $ex) { - return false; - } catch (MethodNotAllowed $ex) { + } catch (NotFound|MethodNotAllowed $ex) { return false; } } @@ -94,7 +91,7 @@ public function delete() { } public function getName() { - list(, $name) = \Sabre\Uri\split($this->principalInfo['uri']); + [, $name] = \Sabre\Uri\split($this->principalInfo['uri']); return $name; } diff --git a/apps/dav/lib/BackgroundJob/CleanProperties.php b/apps/dav/lib/BackgroundJob/CleanProperties.php index 14956e887692..347ed7b1419f 100644 --- a/apps/dav/lib/BackgroundJob/CleanProperties.php +++ b/apps/dav/lib/BackgroundJob/CleanProperties.php @@ -34,10 +34,8 @@ class CleanProperties extends TimedJob { public const CHUNK_SIZE = 200; - /** @var IDBConnection */ - private $connection; - /** @var ILogger */ - private $logger; + private \OCP\IDBConnection $connection; + private \OCP\ILogger $logger; /** * CleanProperties constructor. @@ -90,9 +88,7 @@ private function processProperties() { ->setMaxResults(self::CHUNK_SIZE); while ($rows = $qb->execute()->fetchAll()) { - $fileIds = \array_map(function ($row) { - return (int) $row['fileid']; - }, $rows); + $fileIds = \array_map(fn ($row) => (int) $row['fileid'], $rows); if (!empty($fileIds)) { $this->deleteOrphan($fileIds); diff --git a/apps/dav/lib/CalDAV/BirthdayService.php b/apps/dav/lib/CalDAV/BirthdayService.php index 967db74aaa88..583b628f9c44 100644 --- a/apps/dav/lib/CalDAV/BirthdayService.php +++ b/apps/dav/lib/CalDAV/BirthdayService.php @@ -37,14 +37,11 @@ class BirthdayService { public const BIRTHDAY_CALENDAR_URI = 'contact_birthdays'; - /** @var GroupPrincipalBackend */ - private $principalBackend; + private \OCA\DAV\DAV\GroupPrincipalBackend $principalBackend; - /** @var CardDavBackend */ - private $cardDavBackEnd; + private \OCA\DAV\CardDAV\CardDavBackend $cardDavBackEnd; - /** @var CalDavBackend */ - private $calDavBackEnd; + private \OCA\DAV\CalDAV\CalDavBackend $calDavBackEnd; /** * BirthdayService constructor. diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 905cbcf7b63b..fd2b23699ff4 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -101,17 +101,13 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments', ]; - /** @var IDBConnection */ - private $db; + private \OCP\IDBConnection $db; - /** @var Backend */ - private $sharingBackend; + private \OCA\DAV\DAV\Sharing\Backend $sharingBackend; - /** @var Principal */ - private $principalBackend; + private \OCA\DAV\Connector\Sabre\Principal $principalBackend; - /** @var ISecureRandom */ - private $random; + private \OCP\Security\ISecureRandom $random; /** @var bool */ private $legacyMode; @@ -234,7 +230,7 @@ public function getCalendarsForUser($principalUri) { ->execute(); while ($row = $result->fetch()) { - list(, $name) = \Sabre\Uri\split($row['principaluri']); + [, $name] = \Sabre\Uri\split($row['principaluri']); $uri = $row['uri'] . '_shared_by_' . $name; $row['displayname'] .= " ($name)"; $components = []; @@ -337,7 +333,7 @@ public function getPublicCalendars() { ->execute(); while ($row = $result->fetch()) { - list(, $name) = \Sabre\Uri\split($row['principaluri']); + [, $name] = \Sabre\Uri\split($row['principaluri']); $row['displayname'] .= "($name)"; $components = []; if ($row['components']) { @@ -401,7 +397,7 @@ public function getPublicCalendar($uri) { throw new NotFound('Node with name \'' . $uri . '\' could not be found'); } - list(, $name) = \Sabre\Uri\split($row['principaluri']); + [, $name] = \Sabre\Uri\split($row['principaluri']); $row['displayname'] = $row['displayname'] . ' ' . "($name)"; $components = []; if ($row['components']) { @@ -788,9 +784,7 @@ public function getMultipleCalendarObjects($calendarId, array $uris) { return $result; } $chunks = \array_chunk($uris, $chunkSize); - $results = \array_map(function ($chunk) use ($calendarId) { - return $this->getMultipleCalendarObjects($calendarId, $chunk); - }, $chunks); + $results = \array_map(fn ($chunk) => $this->getMultipleCalendarObjects($calendarId, $chunk), $chunks); return \array_merge(...$results); } @@ -1659,8 +1653,8 @@ public function applyShareAcl($resourceId, $acl) { private function convertPrincipal($principalUri, $toV2 = null) { if ($this->principalBackend->getPrincipalPrefix() === 'principals') { - list(, $name) = \Sabre\Uri\split($principalUri); - $toV2 = $toV2 === null ? !$this->legacyMode : $toV2; + [, $name] = \Sabre\Uri\split($principalUri); + $toV2 ??= !$this->legacyMode; if ($toV2) { return "principals/users/$name"; } diff --git a/apps/dav/lib/CalDAV/Calendar.php b/apps/dav/lib/CalDAV/Calendar.php index 0140d62bac01..06bbc84a191a 100644 --- a/apps/dav/lib/CalDAV/Calendar.php +++ b/apps/dav/lib/CalDAV/Calendar.php @@ -150,19 +150,14 @@ public function getChildACL() { } public function getOwner() { - if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) { - return $this->calendarInfo['{http://owncloud.org/ns}owner-principal']; - } - return parent::getOwner(); + return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] ?? parent::getOwner(); } public function delete() { if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) { $principal = 'principal:' . parent::getOwner(); $shares = $this->getShares(); - $shares = \array_filter($shares, function ($share) use ($principal) { - return $share['href'] === $principal; - }); + $shares = \array_filter($shares, fn ($share) => $share['href'] === $principal); if (empty($shares)) { throw new Forbidden(); } @@ -244,9 +239,7 @@ public function childExists($name) { public function calendarQuery(array $filters) { $uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters); if ($this->isShared()) { - return \array_filter($uris, function ($uri) { - return $this->childExists($uri); - }); + return \array_filter($uris, fn ($uri) => $this->childExists($uri)); } return $uris; diff --git a/apps/dav/lib/CalDAV/CalendarObject.php b/apps/dav/lib/CalDAV/CalendarObject.php index ef2490608ea1..a5a2134ccd01 100644 --- a/apps/dav/lib/CalDAV/CalendarObject.php +++ b/apps/dav/lib/CalDAV/CalendarObject.php @@ -32,7 +32,7 @@ class CalendarObject extends \Sabre\CalDAV\CalendarObject { public function get() { $data = parent::get(); if ($this->isShared() && $this->objectData['classification'] === CalDavBackend::CLASSIFICATION_CONFIDENTIAL) { - return $this->createConfidentialObject($data); + return self::createConfidentialObject($data); } return $data; } diff --git a/apps/dav/lib/CalDAV/Plugin.php b/apps/dav/lib/CalDAV/Plugin.php index ad46660312b0..b644317a225d 100644 --- a/apps/dav/lib/CalDAV/Plugin.php +++ b/apps/dav/lib/CalDAV/Plugin.php @@ -33,9 +33,7 @@ public function propFind(DAV\PropFind $propFind, DAV\INode $node) { parent::propFind($propFind, $node); if ($node instanceof Calendar && $node->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) { - $propFind->handle('{DAV:}share-access', function () { - return new ShareAccess(DAV\Sharing\Plugin::ACCESS_NOACCESS); - }); + $propFind->handle('{DAV:}share-access', fn () => new ShareAccess(DAV\Sharing\Plugin::ACCESS_NOACCESS)); } } @@ -44,7 +42,7 @@ public function propFind(DAV\PropFind $propFind, DAV\INode $node) { */ public function getCalendarHomeForPrincipal($principalUrl) { if (\strrpos($principalUrl, 'principals/users', -\strlen($principalUrl)) !== false) { - list(, $principalId) = \Sabre\Uri\split($principalUrl); + [, $principalId] = \Sabre\Uri\split($principalUrl); return self::CALENDAR_ROOT .'/' . $principalId; } diff --git a/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php b/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php index 2a3aee2699bf..43f571d66066 100644 --- a/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php +++ b/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php @@ -123,9 +123,7 @@ public function propFind(PropFind $propFind, INode $node) { } }); - $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function () use ($node) { - return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription()); - }); + $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', fn () => new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription())); } } diff --git a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php index ffe6930fdb4a..54531347e4c7 100644 --- a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php +++ b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php @@ -41,14 +41,11 @@ * @license http://sabre.io/license/ Modified BSD License */ class IMipPlugin extends SabreIMipPlugin { - /** @var IMailer */ - private $mailer; + private \OCP\Mail\IMailer $mailer; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var IRequest */ - private $request; + private \OCP\IRequest $request; /** * Creates the email handler. diff --git a/apps/dav/lib/Capabilities.php b/apps/dav/lib/Capabilities.php index 51518cb44d33..b258fa5931a9 100644 --- a/apps/dav/lib/Capabilities.php +++ b/apps/dav/lib/Capabilities.php @@ -25,8 +25,7 @@ use OCP\IConfig; class Capabilities implements ICapability { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** * Capabilities constructor. diff --git a/apps/dav/lib/CardDAV/AddressBook.php b/apps/dav/lib/CardDAV/AddressBook.php index 75967e3724f4..e25091468965 100644 --- a/apps/dav/lib/CardDAV/AddressBook.php +++ b/apps/dav/lib/CardDAV/AddressBook.php @@ -132,19 +132,14 @@ public function getResourceId() { } public function getOwner() { - if (isset($this->addressBookInfo['{http://owncloud.org/ns}owner-principal'])) { - return $this->addressBookInfo['{http://owncloud.org/ns}owner-principal']; - } - return parent::getOwner(); + return $this->addressBookInfo['{http://owncloud.org/ns}owner-principal'] ?? parent::getOwner(); } public function delete() { if (isset($this->addressBookInfo['{http://owncloud.org/ns}owner-principal'])) { $principal = 'principal:' . parent::getOwner(); $shares = $this->getShares(); - $shares = \array_filter($shares, function ($share) use ($principal) { - return $share['href'] === $principal; - }); + $shares = \array_filter($shares, fn ($share) => $share['href'] === $principal); if (empty($shares)) { throw new Forbidden(); } diff --git a/apps/dav/lib/CardDAV/AddressBookImpl.php b/apps/dav/lib/CardDAV/AddressBookImpl.php index 512b77b90c02..c16ea597167b 100644 --- a/apps/dav/lib/CardDAV/AddressBookImpl.php +++ b/apps/dav/lib/CardDAV/AddressBookImpl.php @@ -31,17 +31,13 @@ use Sabre\VObject\UUIDUtil; class AddressBookImpl implements IAddressBook { - /** @var CardDavBackend */ - private $backend; + private \OCA\DAV\CardDAV\CardDavBackend $backend; - /** @var array */ - private $addressBookInfo; + private array $addressBookInfo; - /** @var AddressBook */ - private $addressBook; + private \OCA\DAV\CardDAV\AddressBook $addressBook; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; /** * AddressBookImpl constructor. diff --git a/apps/dav/lib/CardDAV/CardDavBackend.php b/apps/dav/lib/CardDAV/CardDavBackend.php index 58422bece507..509f681eadd4 100644 --- a/apps/dav/lib/CardDAV/CardDavBackend.php +++ b/apps/dav/lib/CardDAV/CardDavBackend.php @@ -44,31 +44,25 @@ use Symfony\Component\EventDispatcher\GenericEvent; class CardDavBackend implements BackendInterface, SyncSupport { - /** @var Principal */ - private $principalBackend; + private \OCA\DAV\Connector\Sabre\Principal $principalBackend; - /** @var string */ - private $dbCardsTable = 'cards'; + private string $dbCardsTable = 'cards'; - /** @var string */ - private $dbCardsPropertiesTable = 'cards_properties'; + private string $dbCardsPropertiesTable = 'cards_properties'; - /** @var IDBConnection */ - private $db; + private \OCP\IDBConnection $db; - /** @var Backend */ - private $sharingBackend; + private \OCA\DAV\DAV\Sharing\Backend $sharingBackend; /** @var CappedMemoryCache Cache of card URI to db row ids */ - private $idCache; + private \OC\Cache\CappedMemoryCache $idCache; /** @var array properties to index */ public static $indexProperties = [ 'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME', 'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD']; - /** @var EventDispatcherInterface */ - private $dispatcher; + private ?\Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher = null; /** @var bool */ private $legacyMode; @@ -181,7 +175,7 @@ public function getAddressBooksForUser($principalUri) { ->execute(); while ($row = $result->fetch()) { - list(, $name) = \Sabre\Uri\split($row['principaluri']); + [, $name] = \Sabre\Uri\split($row['principaluri']); $uri = $row['uri'] . '_shared_by_' . $name; $displayName = $row['displayname'] . " ($name)"; if (!isset($addressBooks[$row['id']])) { @@ -496,9 +490,7 @@ public function getMultipleCards($addressBookId, array $uris) { return $cards; } $chunks = \array_chunk($uris, $chunkSize); - $results = \array_map(function ($chunk) use ($addressBookId) { - return $this->getMultipleCards($addressBookId, $chunk); - }, $chunks); + $results = \array_map(fn ($chunk) => $this->getMultipleCards($addressBookId, $chunk), $chunks); return \array_merge(...$results); } @@ -1080,8 +1072,8 @@ public function applyShareAcl($addressBookId, $acl) { private function convertPrincipal($principalUri, $toV2 = null) { if ($this->principalBackend->getPrincipalPrefix() === 'principals') { - list(, $name) = \Sabre\Uri\split($principalUri); - $toV2 = $toV2 === null ? !$this->legacyMode : $toV2; + [, $name] = \Sabre\Uri\split($principalUri); + $toV2 ??= !$this->legacyMode; if ($toV2) { return "principals/users/$name"; } diff --git a/apps/dav/lib/CardDAV/ContactsManager.php b/apps/dav/lib/CardDAV/ContactsManager.php index 17ac75eb9d06..5a8a9946ca93 100644 --- a/apps/dav/lib/CardDAV/ContactsManager.php +++ b/apps/dav/lib/CardDAV/ContactsManager.php @@ -26,8 +26,7 @@ use OCP\IURLGenerator; class ContactsManager { - /** @var CardDavBackend */ - private $backend; + private \OCA\DAV\CardDAV\CardDavBackend $backend; /** * ContactsManager constructor. diff --git a/apps/dav/lib/CardDAV/ImageExportPlugin.php b/apps/dav/lib/CardDAV/ImageExportPlugin.php index 49ee98f92baf..5112e039de34 100644 --- a/apps/dav/lib/CardDAV/ImageExportPlugin.php +++ b/apps/dav/lib/CardDAV/ImageExportPlugin.php @@ -35,8 +35,7 @@ class ImageExportPlugin extends ServerPlugin { /** @var Server */ protected $server; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; public function __construct(ILogger $logger) { $this->logger = $logger; @@ -116,7 +115,7 @@ public function getPhoto(Card $node) { return false; } if (\substr_count($parsed['path'], ';') === 1) { - list($type, ) = \explode(';', $parsed['path']); + [$type, ] = \explode(';', $parsed['path']); } $val = \file_get_contents($val); } @@ -147,7 +146,7 @@ private function getType($photo) { $params = $photo->parameters(); if (isset($params['TYPE']) || isset($params['MEDIATYPE'])) { /** @var Parameter $typeParam */ - $typeParam = isset($params['TYPE']) ? $params['TYPE'] : $params['MEDIATYPE']; + $typeParam = $params['TYPE'] ?? $params['MEDIATYPE']; $type = $typeParam->getValue(); if (\strpos($type, 'image/') === 0) { diff --git a/apps/dav/lib/CardDAV/Plugin.php b/apps/dav/lib/CardDAV/Plugin.php index cf1de737f2e7..2afe218d779e 100644 --- a/apps/dav/lib/CardDAV/Plugin.php +++ b/apps/dav/lib/CardDAV/Plugin.php @@ -40,15 +40,15 @@ public function initialize(Server $server) { */ protected function getAddressbookHomeForPrincipal($principal) { if (\strrpos($principal, 'principals/users', -\strlen($principal)) !== false) { - list(, $principalId) = \Sabre\Uri\split($principal); + [, $principalId] = \Sabre\Uri\split($principal); return self::ADDRESSBOOK_ROOT . '/users/' . $principalId; } if (\strrpos($principal, 'principals/groups', -\strlen($principal)) !== false) { - list(, $principalId) = \Sabre\Uri\split($principal); + [, $principalId] = \Sabre\Uri\split($principal); return self::ADDRESSBOOK_ROOT . '/groups/' . $principalId; } if (\strrpos($principal, 'principals/system', -\strlen($principal)) !== false) { - list(, $principalId) = \Sabre\Uri\split($principal); + [, $principalId] = \Sabre\Uri\split($principal); return self::ADDRESSBOOK_ROOT . '/system/' . $principalId; } @@ -66,9 +66,7 @@ public function propFind(PropFind $propFind, INode $node) { $ns = '{http://owncloud.org/ns}'; if ($node instanceof AddressBook) { - $propFind->handle($ns . 'groups', function () use ($node) { - return new Groups($node->getContactsGroups()); - }); + $propFind->handle($ns . 'groups', fn () => new Groups($node->getContactsGroups())); } } } diff --git a/apps/dav/lib/CardDAV/SyncService.php b/apps/dav/lib/CardDAV/SyncService.php index 112e1d7769e3..998c4f317902 100644 --- a/apps/dav/lib/CardDAV/SyncService.php +++ b/apps/dav/lib/CardDAV/SyncService.php @@ -34,14 +34,11 @@ use Sabre\VObject\Reader; class SyncService { - /** @var CardDavBackend */ - private $backend; + private \OCA\DAV\CardDAV\CardDavBackend $backend; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; /** @var array */ private $localSystemAddressBook; diff --git a/apps/dav/lib/Command/CreateAddressBook.php b/apps/dav/lib/Command/CreateAddressBook.php index a9bd3a83f72f..9c249a21dff2 100644 --- a/apps/dav/lib/Command/CreateAddressBook.php +++ b/apps/dav/lib/Command/CreateAddressBook.php @@ -29,11 +29,9 @@ use Symfony\Component\Console\Output\OutputInterface; class CreateAddressBook extends Command { - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var CardDavBackend */ - private $cardDavBackend; + private \OCA\DAV\CardDAV\CardDavBackend $cardDavBackend; /** * @param IUserManager $userManager diff --git a/apps/dav/lib/Command/CreateCalendar.php b/apps/dav/lib/Command/CreateCalendar.php index 0becd3a3a3bf..606768da8426 100644 --- a/apps/dav/lib/Command/CreateCalendar.php +++ b/apps/dav/lib/Command/CreateCalendar.php @@ -36,8 +36,7 @@ class CreateCalendar extends Command { /** @var IUserManager */ protected $userManager; - /** @var IGroupManager $groupManager */ - private $groupManager; + private \OCP\IGroupManager $groupManager; /** @var \OCP\IDBConnection */ protected $dbConnection; diff --git a/apps/dav/lib/Command/SyncBirthdayCalendar.php b/apps/dav/lib/Command/SyncBirthdayCalendar.php index aac0c0f1013e..a991a3ed2bbf 100644 --- a/apps/dav/lib/Command/SyncBirthdayCalendar.php +++ b/apps/dav/lib/Command/SyncBirthdayCalendar.php @@ -31,11 +31,9 @@ use Symfony\Component\Console\Output\OutputInterface; class SyncBirthdayCalendar extends Command { - /** @var BirthdayService */ - private $birthdayService; + private \OCA\DAV\CalDAV\BirthdayService $birthdayService; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; /** * @param IUserManager $userManager diff --git a/apps/dav/lib/Command/SyncSystemAddressBook.php b/apps/dav/lib/Command/SyncSystemAddressBook.php index 8ebf40efbc61..4900b5e89287 100644 --- a/apps/dav/lib/Command/SyncSystemAddressBook.php +++ b/apps/dav/lib/Command/SyncSystemAddressBook.php @@ -27,8 +27,7 @@ use Symfony\Component\Console\Output\OutputInterface; class SyncSystemAddressBook extends Command { - /** @var SyncService */ - private $syncService; + private \OCA\DAV\CardDAV\SyncService $syncService; /** * @param SyncService $syncService diff --git a/apps/dav/lib/Connector/LegacyDAVACL.php b/apps/dav/lib/Connector/LegacyDAVACL.php index 7f4434318b84..efb79220fce2 100644 --- a/apps/dav/lib/Connector/LegacyDAVACL.php +++ b/apps/dav/lib/Connector/LegacyDAVACL.php @@ -50,7 +50,7 @@ public function getCurrentUserPrincipals() { } private function convertPrincipal($principal, $toV2) { - list(, $name) = \Sabre\Uri\split($principal); + [, $name] = \Sabre\Uri\split($principal); if ($toV2) { return "principals/users/$name"; } diff --git a/apps/dav/lib/Connector/PublicAuth.php b/apps/dav/lib/Connector/PublicAuth.php index ae3f85502467..ee9f765df8ae 100644 --- a/apps/dav/lib/Connector/PublicAuth.php +++ b/apps/dav/lib/Connector/PublicAuth.php @@ -42,14 +42,11 @@ class PublicAuth extends AbstractBasic { /** @var \OCP\Share\IShare */ private $share; - /** @var IManager */ - private $shareManager; + private \OCP\Share\IManager $shareManager; - /** @var ISession */ - private $session; + private \OCP\ISession $session; - /** @var IRequest */ - private $request; + private \OCP\IRequest $request; /** * @param IRequest $request diff --git a/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php b/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php index 83f3c58494d4..ed7603d8da28 100644 --- a/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php +++ b/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php @@ -32,21 +32,16 @@ */ class AppEnabledPlugin extends ServerPlugin { /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; /** * @var string */ private $app; - /** - * @var \OCP\App\IAppManager - */ - private $appManager; + private \OCP\App\IAppManager $appManager; /** * @param string $app diff --git a/apps/dav/lib/Connector/Sabre/Auth.php b/apps/dav/lib/Connector/Sabre/Auth.php index 97526430fd24..dfc0b23cbcef 100644 --- a/apps/dav/lib/Connector/Sabre/Auth.php +++ b/apps/dav/lib/Connector/Sabre/Auth.php @@ -50,20 +50,12 @@ class Auth extends AbstractBasic { public const DAV_AUTHENTICATED = 'AUTHENTICATED_TO_DAV_BACKEND'; - /** @var ISession */ - private $session; - /** @var Session */ - private $userSession; - /** @var IRequest */ - private $request; - /** @var Manager */ - private $twoFactorManager; - /** @var AccountModuleManager */ - private $accountModuleManager; - /** - * @var IConfig - */ - private $config; + private \OCP\ISession $session; + private \OC\User\Session $userSession; + private \OCP\IRequest $request; + private \OC\Authentication\TwoFactorAuth\Manager $twoFactorManager; + private \OC\Authentication\AccountModule\Manager $accountModuleManager; + private \OCP\IConfig $config; /** * @param ISession $session diff --git a/apps/dav/lib/Connector/Sabre/AutorenamePlugin.php b/apps/dav/lib/Connector/Sabre/AutorenamePlugin.php index 10952375dfbc..0db0cf2c37b8 100644 --- a/apps/dav/lib/Connector/Sabre/AutorenamePlugin.php +++ b/apps/dav/lib/Connector/Sabre/AutorenamePlugin.php @@ -33,11 +33,9 @@ */ class AutorenamePlugin extends ServerPlugin { /** - * Reference to main server object - * - * @var Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; /** * This initializes the plugin. @@ -96,7 +94,7 @@ public function handlePut(RequestInterface $request, ResponseInterface $response '@phan-var ObjectTree $this->server->tree'; $view = $this->server->tree->getView(); - list($nodePath, $nodeName) = \Sabre\Uri\split($node->getPath()); + [$nodePath, $nodeName] = \Sabre\Uri\split($node->getPath()); $newName = \OC_Helper::buildNotExistingFileNameForView($nodePath, $nodeName, $view); $body = $request->getBodyAsStream(); diff --git a/apps/dav/lib/Connector/Sabre/ChecksumList.php b/apps/dav/lib/Connector/Sabre/ChecksumList.php index 4af2f6015a5e..5c8262ee0e75 100644 --- a/apps/dav/lib/Connector/Sabre/ChecksumList.php +++ b/apps/dav/lib/Connector/Sabre/ChecksumList.php @@ -33,7 +33,7 @@ class ChecksumList implements XmlSerializable { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; /** @var string[] of TYPE:CHECKSUM */ - private $checksums; + private array $checksums; /** * @param string $checksum diff --git a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php index d7eb44cf50a8..d5cd3cbf940e 100644 --- a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php @@ -36,11 +36,9 @@ class CommentPropertiesPlugin extends ServerPlugin { /** @var \Sabre\DAV\Server */ protected $server; - /** @var ICommentsManager */ - private $commentsManager; + private \OCP\Comments\ICommentsManager $commentsManager; - /** @var IUserSession */ - private $userSession; + private \OCP\IUserSession $userSession; /** * @var int[] @@ -125,17 +123,11 @@ public function handleGetProperties( } } - $propFind->handle(self::PROPERTY_NAME_COUNT, function () use ($node) { - return $this->commentsManager->getNumberOfCommentsForObject('files', \strval($node->getId())); - }); + $propFind->handle(self::PROPERTY_NAME_COUNT, fn () => $this->commentsManager->getNumberOfCommentsForObject('files', \strval($node->getId()))); - $propFind->handle(self::PROPERTY_NAME_HREF, function () use ($node) { - return $this->getCommentsLink($node); - }); + $propFind->handle(self::PROPERTY_NAME_HREF, fn () => $this->getCommentsLink($node)); - $propFind->handle(self::PROPERTY_NAME_UNREAD, function () use ($node) { - return $this->getUnreadCount($node); - }); + $propFind->handle(self::PROPERTY_NAME_UNREAD, fn () => $this->getUnreadCount($node)); } /** diff --git a/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php b/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php index 6ef64118b58e..955d588c8007 100644 --- a/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php @@ -32,8 +32,7 @@ * or mangle Etag headers. */ class CopyEtagHeaderPlugin extends \Sabre\DAV\ServerPlugin { - /** @var \Sabre\DAV\Server */ - private $server; + private ?\Sabre\DAV\Server $server = null; /** * This initializes the plugin. * diff --git a/apps/dav/lib/Connector/Sabre/CorsPlugin.php b/apps/dav/lib/Connector/Sabre/CorsPlugin.php index 3e64cc87957b..0349786c8449 100644 --- a/apps/dav/lib/Connector/Sabre/CorsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CorsPlugin.php @@ -32,25 +32,17 @@ */ class CorsPlugin extends ServerPlugin { /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; /** - * Reference to logged in user's session - * - * @var IUserSession - */ - private $userSession; + * Reference to logged in user's session + */ + private \OCP\IUserSession $userSession; - /** @var array */ - private $extraHeaders; - /** - * @var bool - */ - private $alreadyExecuted = false; + private ?array $extraHeaders = null; + private bool $alreadyExecuted = false; /** * @param IUserSession $userSession diff --git a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php index 6aa82e2fe8aa..b0c057dba243 100644 --- a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php +++ b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php @@ -54,7 +54,7 @@ public function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $node = $this->server->tree->getNodeForPath($uri); switch (\get_class($node)) { - case 'OCA\DAV\CardDAV\AddressBook': + case \OCA\DAV\CardDAV\AddressBook::class: $type = 'Addressbook'; break; default: diff --git a/apps/dav/lib/Connector/Sabre/Directory.php b/apps/dav/lib/Connector/Sabre/Directory.php index 762d9932df7e..a806905ccc72 100644 --- a/apps/dav/lib/Connector/Sabre/Directory.php +++ b/apps/dav/lib/Connector/Sabre/Directory.php @@ -62,19 +62,14 @@ class Directory extends Node implements ICollection, IQuota, IMoveTarget { * * @var INode[] */ - private $dirContent; + private ?array $dirContent = null; /** - * Cached quota info - * - * @var array - */ - private $quotaInfo; + * Cached quota info + */ + private ?array $quotaInfo = null; - /** - * @var ObjectTree|null - */ - private $tree; + private ?\OCA\DAV\Connector\Sabre\ObjectTree $tree = null; /** * Sets up the node, expects a full path name @@ -215,13 +210,13 @@ public function createDirectory($name) { } $absolutePath = Filesystem::normalizePath($this->fileView->getAbsolutePath($name)); - list($targetStorage, $targetInternalPath) = Filesystem::resolvePath($absolutePath); + [$targetStorage, $targetInternalPath] = Filesystem::resolvePath($absolutePath); // We are using == instead of === as the computerFileSize method which is // used to get the quota may return a float type. Note that the same // has been observed for the disk_free_space function in local storage - list($used, $free) = $this->getQuotaInfo(); - if ($free == 0 && ($targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage') === true)) { + [$used, $free] = $this->getQuotaInfo(); + if ($free == 0 && ($targetStorage->instanceOfStorage('\\' . \OCP\Files\IHomeStorage::class) === true)) { throw new SabreInsufficientStorage('Creation of empty directories is forbidden in case of no available quota'); } @@ -455,7 +450,7 @@ public function moveInto($targetName, $fullSourcePath, INode $sourceNode) { throw new SabreForbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists'); } - list($sourceDir, ) = \Sabre\Uri\split($sourceNode->getPath()); + [$sourceDir, ] = \Sabre\Uri\split($sourceNode->getPath()); $destinationDir = $this->getPath(); $sourcePath = $sourceNode->getPath(); @@ -499,8 +494,8 @@ public function moveInto($targetName, $fullSourcePath, INode $sourceNode) { $renameOkay = $this->fileView->rename($sourcePath, $destinationPath); if (!$renameOkay) { - list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($destinationPath); - if ($isMovableMount === true && $targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage') !== true) { + [$targetStorage, $targetInternalPath] = \OC\Files\Filesystem::resolvePath($destinationPath); + if ($isMovableMount === true && $targetStorage->instanceOfStorage('\\' . \OCP\Files\IHomeStorage::class) !== true) { throw new SabreForbidden('It is not allowed to move one mount point into another one'); } diff --git a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php index 0a49b3b62bc5..333e8d5ce466 100644 --- a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php @@ -33,28 +33,28 @@ class ExceptionLoggerPlugin extends \Sabre\DAV\ServerPlugin { protected $nonFatalExceptions = [ - 'Sabre\DAV\Exception\NotAuthenticated' => true, + \Sabre\DAV\Exception\NotAuthenticated::class => true, // the sync client uses this to find out whether files exist, // so it is not always an error, log it as debug - 'Sabre\DAV\Exception\NotFound' => true, + \Sabre\DAV\Exception\NotFound::class => true, // this one mostly happens when the same file is uploaded at // exactly the same time from two clients, only one client // wins, the second one gets "Precondition failed" - 'Sabre\DAV\Exception\PreconditionFailed' => true, + \Sabre\DAV\Exception\PreconditionFailed::class => true, // forbidden can be expected when trying to upload to // read-only folders for example - 'Sabre\DAV\Exception\Forbidden' => true, + \Sabre\DAV\Exception\Forbidden::class => true, // Custom exception similar to NotAuthenticated - 'OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden' => true, + \OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden::class => true, // Happens when an external storage or federated share is temporarily // not available 'Sabre\DAV\Exception\StorageNotAvailableException' => true, - 'OCP\Files\StorageNotAvailableException' => true, + \OCP\Files\StorageNotAvailableException::class => true, // Locked exceptions could be fine if the file is truly locked - 'Sabre\DAV\Exception\Locked' => true, - 'OCA\DAV\Connector\Sabre\Exception\FileLocked' => true, // thrown by the LockPlugin + \Sabre\DAV\Exception\Locked::class => true, + \OCA\DAV\Connector\Sabre\Exception\FileLocked::class => true, // thrown by the LockPlugin //If the exception is InsufficientStorage, then log a debug message - 'Sabre\DAV\Exception\InsufficientStorage' => true + \Sabre\DAV\Exception\InsufficientStorage::class => true ]; /** @var string */ diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index b491680b205a..f84afaf77ada 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -167,12 +167,12 @@ public function put($data) { \OC::$server->getEventDispatcher()->dispatch($beforeEvent, 'file.beforeupdate'); } - list($partStorage) = $this->fileView->resolvePath($this->path); + [$partStorage] = $this->fileView->resolvePath($this->path); $usePartFile = $this->usePartFile($partStorage) && (\strlen($this->path) > 1); if ($usePartFile) { // mark file as partial while uploading (ignored by the scanner) - $partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . \rand() . '.part'; + $partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . random_int(0, mt_getrandmax()) . '.part'; } else { // upload file directly as the final path $partFilePath = $this->path; @@ -180,9 +180,9 @@ public function put($data) { // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share) /** @var \OC\Files\Storage\Storage $partStorage */ - list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath); + [$partStorage, $internalPartPath] = $this->fileView->resolvePath($partFilePath); /** @var \OC\Files\Storage\Storage $storage */ - list($storage, $internalPath) = $this->fileView->resolvePath($this->path); + [$storage, $internalPath] = $this->fileView->resolvePath($this->path); try { try { $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE); @@ -203,7 +203,7 @@ public function put($data) { throw new Exception('Could not write file contents'); } - list($count, $result) = \OC_Helper::streamCopy($data, $target); + [$count, $result] = \OC_Helper::streamCopy($data, $target); \fclose($target); try { @@ -489,7 +489,7 @@ public function getDirectDownload() { return []; } /** @var \OCP\Files\Storage $storage */ - list($storage, $internalPath) = $this->fileView->resolvePath($this->path); + [$storage, $internalPath] = $this->fileView->resolvePath($this->path); if ($storage === null) { return []; } @@ -506,7 +506,7 @@ public function getDirectDownload() { * @throws ServiceUnavailable */ private function createFileChunked($data) { - list($path, $name) = \Sabre\Uri\split($this->path); + [$path, $name] = \Sabre\Uri\split($this->path); $info = \OC_FileChunking::decodeName($name); if (empty($info)) { @@ -530,7 +530,7 @@ private function createFileChunked($data) { } if ($chunk_handler->isComplete()) { - list($storage, ) = $this->fileView->resolvePath($path); + [$storage, ] = $this->fileView->resolvePath($path); $usePartFile = $this->usePartFile($storage); $partFile = null; @@ -546,7 +546,7 @@ private function createFileChunked($data) { } /** @var \OC\Files\Storage\Storage $targetStorage */ - list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath); + [$targetStorage, $targetInternalPath] = $this->fileView->resolvePath($targetPath); $exists = $this->fileView->file_exists($targetPath); @@ -556,13 +556,13 @@ private function createFileChunked($data) { $this->emitPreHooks($exists, $targetPath); $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE); /** @var \OC\Files\Storage\Storage $targetStorage */ - list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath); + [$targetStorage, $targetInternalPath] = $this->fileView->resolvePath($targetPath); if ($usePartFile) { // we first assembly the target file as a part file $partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part'; /** @var \OC\Files\Storage\Storage $targetStorage */ - list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile); + [$partStorage, $partInternalPath] = $this->fileView->resolvePath($partFile); $chunk_handler->file_assemble($partStorage, $partInternalPath); @@ -605,7 +605,7 @@ private function createFileChunked($data) { } else { $metadata = $targetStorage->getMetaData($targetInternalPath); } - $checksums = (isset($metadata['checksum'])) ? $metadata['checksum'] : null; + $checksums = $metadata['checksum'] ?? null; $this->fileView->putFileInfo( $targetPath, diff --git a/apps/dav/lib/Connector/Sabre/FilesPlugin.php b/apps/dav/lib/Connector/Sabre/FilesPlugin.php index d30c27a220cc..4cce088856de 100644 --- a/apps/dav/lib/Connector/Sabre/FilesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesPlugin.php @@ -66,16 +66,11 @@ class FilesPlugin extends ServerPlugin { public const PRIVATE_LINK_PROPERTYNAME = '{http://owncloud.org/ns}privatelink'; /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; - /** - * @var Tree - */ - private $tree; + private \Sabre\DAV\Tree $tree; /** * Whether this is public webdav. @@ -90,15 +85,9 @@ class FilesPlugin extends ServerPlugin { */ private $downloadAttachment; - /** - * @var IConfig - */ - private $config; + private \OCP\IConfig $config; - /** - * @var IRequest - */ - private $request; + private \OCP\IRequest $request; /** * @param Tree $tree @@ -184,9 +173,9 @@ public function checkPropFind($request) { /** @var Node $node */ '@phan-var Node $node'; $fileInfo = $node->getFileInfo(); - list($storage, ) = Filesystem::resolvePath($fileInfo->getPath()); + [$storage, ] = Filesystem::resolvePath($fileInfo->getPath()); - if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) { + if ($storage->instanceOfStorage('\\' . \OCA\Files_Sharing\SharedStorage::class)) { /** @var \OCA\Files_Sharing\SharedStorage $storage */ '@phan-var \OCA\Files_Sharing\SharedStorage $storage'; $hasReadPermission = ($storage->getShare()->getPermissions() & \OCP\Constants::PERMISSION_READ) > 0; @@ -229,8 +218,8 @@ public function checkMove($source, $destination) { if (!$sourceNode instanceof Node) { return; } - list($sourceDir, ) = \Sabre\Uri\split($source); - list($destinationDir, ) = \Sabre\Uri\split($destination); + [$sourceDir, ] = \Sabre\Uri\split($source); + [$destinationDir, ] = \Sabre\Uri\split($destination); if ($sourceDir !== $destinationDir) { $sourceNodeFileInfo = $sourceNode->getFileInfo(); @@ -340,13 +329,9 @@ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) throw new NotFound(); } - $propFind->handle(self::FILEID_PROPERTYNAME, function () use ($node) { - return $node->getFileId(); - }); + $propFind->handle(self::FILEID_PROPERTYNAME, fn () => $node->getFileId()); - $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function () use ($node) { - return $node->getInternalFileId(); - }); + $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, fn () => $node->getInternalFileId()); $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function () use ($node) { $perms = $node->getDavPermissions(); @@ -367,9 +352,7 @@ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) } }); - $propFind->handle(self::GETETAG_PROPERTYNAME, function () use ($node) { - return $node->getETag(); - }); + $propFind->handle(self::GETETAG_PROPERTYNAME, fn () => $node->getETag()); $propFind->handle(self::OWNER_ID_PROPERTYNAME, function () use ($node) { $owner = $node->getOwner(); @@ -380,20 +363,14 @@ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) $displayName = $owner->getDisplayName(); return $displayName; }); - $propFind->handle(self::SIZE_PROPERTYNAME, function () use ($node) { - return $node->getSize(); - }); + $propFind->handle(self::SIZE_PROPERTYNAME, fn () => $node->getSize()); - $propFind->handle(self::PRIVATE_LINK_PROPERTYNAME, function () use ($node) { - return \OC::$server->getURLGenerator() - ->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileId' => $node->getInternalFileId()]); - }); + $propFind->handle(self::PRIVATE_LINK_PROPERTYNAME, fn () => \OC::$server->getURLGenerator() + ->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileId' => $node->getInternalFileId()])); } if ($node instanceof \OCA\DAV\Connector\Sabre\Node) { - $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function () { - return $this->config->getSystemValue('data-fingerprint', ''); - }); + $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, fn () => $this->config->getSystemValue('data-fingerprint', '')); } if ($node instanceof \OCA\DAV\Connector\Sabre\File) { @@ -404,9 +381,7 @@ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) if (isset($directDownloadUrl['url'])) { return $directDownloadUrl['url']; } - } catch (StorageNotAvailableException $e) { - return false; - } catch (ForbiddenException $e) { + } catch (StorageNotAvailableException|ForbiddenException $e) { return false; } return false; @@ -423,9 +398,7 @@ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) } if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) { - $propFind->handle(self::SIZE_PROPERTYNAME, function () use ($node) { - return $node->getSize(); - }); + $propFind->handle(self::SIZE_PROPERTYNAME, fn () => $node->getSize()); } } @@ -469,7 +442,7 @@ public function handleUpdateProperties($path, PropPatch $propPatch) { public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) { // chunked upload handling if (\OC_FileChunking::isWebdavChunk()) { - list($path, $name) = \Sabre\Uri\split($filePath); + [$path, $name] = \Sabre\Uri\split($filePath); $info = \OC_FileChunking::decodeName($name); if (!empty($info)) { $filePath = $path . '/' . $info['name']; @@ -500,7 +473,7 @@ private function setSecretCookie($secretName, $secretToken) { if ($secretToken === '-1' || (!isset($secretToken[32]) && \preg_match('!^[a-zA-Z0-9]+$!', $secretToken) === 1)) { // FIXME: use $response->setHeader() instead - \setcookie($secretName, $secretToken, \time() + 20, '/'); + \setcookie($secretName, $secretToken, ['expires' => \time() + 20, 'path' => '/']); } } } diff --git a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php index 5dd609ac6627..84fb34b96a90 100644 --- a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php @@ -46,53 +46,28 @@ class FilesReportPlugin extends ServerPlugin { public const SYSTEMTAG_PROPERTYNAME = '{http://owncloud.org/ns}systemtag'; /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; - /** - * @var Tree - */ - private $tree; + private \Sabre\DAV\Tree $tree; - /** - * @var View - */ - private $fileView; + private \OC\Files\View $fileView; - /** - * @var ISystemTagManager - */ - private $tagManager; + private \OCP\SystemTag\ISystemTagManager $tagManager; - /** - * @var ISystemTagObjectMapper - */ - private $tagMapper; + private \OCP\SystemTag\ISystemTagObjectMapper $tagMapper; /** - * Manager for private tags - * - * @var ITagManager - */ - private $fileTagger; + * Manager for private tags + */ + private \OCP\ITagManager $fileTagger; - /** - * @var IUserSession - */ - private $userSession; + private \OCP\IUserSession $userSession; - /** - * @var IGroupManager - */ - private $groupManager; + private \OCP\IGroupManager $groupManager; - /** - * @var Folder - */ - private $userFolder; + private \OCP\Files\Folder $userFolder; /** * @param Tree $tree diff --git a/apps/dav/lib/Connector/Sabre/FilesSearchReportPlugin.php b/apps/dav/lib/Connector/Sabre/FilesSearchReportPlugin.php index b7d524906bbb..870dad2c2e4a 100644 --- a/apps/dav/lib/Connector/Sabre/FilesSearchReportPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesSearchReportPlugin.php @@ -38,14 +38,11 @@ class FilesSearchReportPlugin extends ServerPlugin { public const REPORT_SCORE = '{http://owncloud.org/ns}search-score'; /** - * Reference to main server object - * - * @var DavServer - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; - /** @var ISearch */ - private $searchService; + private \OCP\ISearch $searchService; public function __construct(ISearch $searchService) { $this->searchService = $searchService; diff --git a/apps/dav/lib/Connector/Sabre/LockPlugin.php b/apps/dav/lib/Connector/Sabre/LockPlugin.php index a641520b9538..755ed3ff461e 100644 --- a/apps/dav/lib/Connector/Sabre/LockPlugin.php +++ b/apps/dav/lib/Connector/Sabre/LockPlugin.php @@ -39,26 +39,18 @@ class LockPlugin extends ServerPlugin { /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; - /** - * @var IConfig - */ - private $config; - /** - * @var IGroupManager - */ - private $groupManager; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; + private \OCP\IConfig $config; + private \OCP\IGroupManager $groupManager; public function __construct(IConfig $config, IGroupManager $groupManager) { $this->config = $config; $this->groupManager = $groupManager; } - private $missedLocks = []; + private array $missedLocks = []; /** * {@inheritdoc} @@ -155,7 +147,7 @@ public function beforeUnlock($uri, LockInfo $lock) { private function userIsALockBreaker(IUser $currentUser): bool { $lockBreakerGroups = $this->config->getAppValue('core', 'lock-breaker-groups', '[]'); - $lockBreakerGroups = \json_decode($lockBreakerGroups) ?? []; + $lockBreakerGroups = \json_decode($lockBreakerGroups, null, 512, JSON_THROW_ON_ERROR) ?? []; foreach ($lockBreakerGroups as $lockBreakerGroup) { if ($this->groupManager->isInGroup($currentUser->getUID(), $lockBreakerGroup)) { diff --git a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php index 31e2db598585..e50bba04cf2e 100644 --- a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php +++ b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php @@ -34,11 +34,9 @@ class MaintenancePlugin extends ServerPlugin { private $config; /** - * Reference to main server object - * - * @var Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; /** * @param IConfig $config diff --git a/apps/dav/lib/Connector/Sabre/Node.php b/apps/dav/lib/Connector/Sabre/Node.php index 16b96c48f477..82d0ba03fdcd 100644 --- a/apps/dav/lib/Connector/Sabre/Node.php +++ b/apps/dav/lib/Connector/Sabre/Node.php @@ -130,8 +130,8 @@ public function setName($name) { // verify path of the source $this->verifyPath(); - list($parentPath, ) = \Sabre\Uri\split($this->path); - list(, $newName) = \Sabre\Uri\split($name); + [$parentPath, ] = \Sabre\Uri\split($this->path); + [, $newName] = \Sabre\Uri\split($name); // verify path of target if (\OC\Files\Filesystem::isForbiddenFileOrDir($parentPath . '/' . $newName)) { @@ -279,7 +279,7 @@ public function getSharePermissions($user) { $path = $this->info->getInternalPath(); - if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) { + if ($storage->instanceOfStorage('\\' . \OCA\Files_Sharing\SharedStorage::class)) { /** @var \OCA\Files_Sharing\SharedStorage $storage */ '@phan-var \OCA\Files_Sharing\SharedStorage $storage'; $permissions = (int)$storage->getShare()->getPermissions(); diff --git a/apps/dav/lib/Connector/Sabre/ObjectTree.php b/apps/dav/lib/Connector/Sabre/ObjectTree.php index ee2993674220..63a14d044e02 100644 --- a/apps/dav/lib/Connector/Sabre/ObjectTree.php +++ b/apps/dav/lib/Connector/Sabre/ObjectTree.php @@ -76,7 +76,7 @@ public function init(\Sabre\DAV\INode $rootNode, \OC\Files\View $view, \OCP\File private function resolveChunkFile($path) { if (\OC_FileChunking::isWebdavChunk()) { // resolve to real file name to find the proper node - list($dir, $name) = \Sabre\Uri\split($path); + [$dir, $name] = \Sabre\Uri\split($path); if ($dir == '/' || $dir == '.') { $dir = ''; } @@ -227,7 +227,7 @@ public function copy($source, $destination) { // with that we have covered both source and destination $this->getNodeForPath($source); - list($destinationDir, $destinationName) = \Sabre\Uri\split($destination); + [$destinationDir, $destinationName] = \Sabre\Uri\split($destination); try { $this->fileView->verifyPath($destinationDir, $destinationName); } catch (\OCP\Files\InvalidPathException $ex) { @@ -254,7 +254,7 @@ public function copy($source, $destination) { throw new FileLocked($e->getMessage(), $e->getCode(), $e); } - list($destinationDir, ) = \Sabre\Uri\split($destination); + [$destinationDir, ] = \Sabre\Uri\split($destination); $this->markDirty($destinationDir); } diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index c9022719a894..9695b06441fd 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -38,17 +38,13 @@ use Sabre\DAVACL\PrincipalBackend\BackendInterface; class Principal implements BackendInterface { - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IGroupManager */ - private $groupManager; + private \OCP\IGroupManager $groupManager; - /** @var string */ - private $principalPrefix; + private string $principalPrefix; - /** @var bool */ - private $hasGroups; + private bool $hasGroups; /** * @param IUserManager $userManager @@ -100,7 +96,7 @@ public function getPrincipalsByPrefix($prefixPath) { * @return array */ public function getPrincipalByPath($path) { - list($prefix, $name) = \Sabre\Uri\split($path); + [$prefix, $name] = \Sabre\Uri\split($path); if ($prefix === $this->principalPrefix) { $user = $this->userManager->get($name); @@ -138,7 +134,7 @@ public function getGroupMemberSet($principal) { * @throws Exception */ public function getGroupMembership($principal, $needGroups = false) { - list($prefix, $name) = \Sabre\Uri\split($principal); + [$prefix, $name] = \Sabre\Uri\split($principal); if ($prefix === $this->principalPrefix) { $user = $this->userManager->get($name); @@ -148,10 +144,9 @@ public function getGroupMembership($principal, $needGroups = false) { if ($this->hasGroups || $needGroups) { $groups = $this->groupManager->getUserGroups($user, 'sharing'); - $groups = \array_map(function ($group) { - /** @var IGroup $group */ - return 'principals/groups/' . $group->getGID(); - }, $groups); + $groups = \array_map(fn ($group) => + /** @var IGroup $group */ + 'principals/groups/' . $group->getGID(), $groups); return $groups; } @@ -224,7 +219,7 @@ protected function userToPrincipal($user) { $displayName = $user->getDisplayName(); $principal = [ 'uri' => $this->principalPrefix . '/' . $userId, - '{DAV:}displayname' => $displayName === null ? $userId : $displayName, + '{DAV:}displayname' => $displayName ?? $userId, ]; $email = $user->getEMailAddress(); diff --git a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php index 8e347190a541..2eaea0b1194b 100644 --- a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php +++ b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php @@ -44,11 +44,9 @@ class QuotaPlugin extends \Sabre\DAV\ServerPlugin { private $view; /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; /** * @param \OC\Files\View $view @@ -189,7 +187,7 @@ public function checkQuota($path, $length = null, $extraSpace = 0) { $length = $this->getLength(); } if ($length !== null) { - list($parentPath, $newName) = \Sabre\Uri\split($path); + [$parentPath, $newName] = \Sabre\Uri\split($path); if ($parentPath === null) { $parentPath = ''; } diff --git a/apps/dav/lib/Connector/Sabre/ServerFactory.php b/apps/dav/lib/Connector/Sabre/ServerFactory.php index 90f53498d5ef..9ec757392ef8 100644 --- a/apps/dav/lib/Connector/Sabre/ServerFactory.php +++ b/apps/dav/lib/Connector/Sabre/ServerFactory.php @@ -46,22 +46,14 @@ use Sabre\HTTP\Request; class ServerFactory { - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; - /** @var IDBConnection */ - private $databaseConnection; - /** @var IUserSession */ - private $userSession; - /** @var IMountManager */ - private $mountManager; - /** @var ITagManager */ - private $tagManager; - /** @var IRequest */ - private $request; - /** @var ITimeFactory */ - private $timeFactory; + private \OCP\IConfig $config; + private \OCP\ILogger $logger; + private \OCP\IDBConnection $databaseConnection; + private \OCP\IUserSession $userSession; + private \OCP\Files\Mount\IMountManager $mountManager; + private \OCP\ITagManager $tagManager; + private \OCP\IRequest $request; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; /** * @param IConfig $config @@ -127,9 +119,7 @@ public function createServer( $server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin($this->config, \OC::$server->getGroupManager())); $fileLocksBackend = new FileLocksBackend($server->tree, true, $this->timeFactory, $isPublicAccess); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\PublicDavLocksPlugin($fileLocksBackend, function ($uri) use ($isPublicAccess) { - return $isPublicAccess; - })); + $server->addPlugin(new \OCA\DAV\Connector\Sabre\PublicDavLocksPlugin($fileLocksBackend, fn ($uri) => $isPublicAccess)); if (BrowserErrorPagePlugin::isBrowserRequest($this->request)) { $server->addPlugin(new BrowserErrorPagePlugin()); diff --git a/apps/dav/lib/Connector/Sabre/SharesPlugin.php b/apps/dav/lib/Connector/Sabre/SharesPlugin.php index 86f6e6e8a14f..65994c4661ee 100644 --- a/apps/dav/lib/Connector/Sabre/SharesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/SharesPlugin.php @@ -33,21 +33,13 @@ class SharesPlugin extends \Sabre\DAV\ServerPlugin { public const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types'; /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; - /** - * @var \OCP\Share\IManager - */ - private $shareManager; + private \OCP\Share\IManager $shareManager; - /** - * @var \Sabre\DAV\Tree - */ - private $tree; + private \Sabre\DAV\Tree $tree; /** * @var string @@ -93,7 +85,7 @@ public function __construct( */ public function initialize(\Sabre\DAV\Server $server) { $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc'; - $server->xml->elementMap[self::SHARETYPES_PROPERTYNAME] = 'OCA\\DAV\\Connector\\Sabre\\ShareTypeList'; + $server->xml->elementMap[self::SHARETYPES_PROPERTYNAME] = \OCA\DAV\Connector\Sabre\ShareTypeList::class; $server->protectedProperties[] = self::SHARETYPES_PROPERTYNAME; $this->server = $server; diff --git a/apps/dav/lib/Connector/Sabre/TagList.php b/apps/dav/lib/Connector/Sabre/TagList.php index f42fc27d82e6..341d8eeedf71 100644 --- a/apps/dav/lib/Connector/Sabre/TagList.php +++ b/apps/dav/lib/Connector/Sabre/TagList.php @@ -36,11 +36,9 @@ class TagList implements Element { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; /** - * tags - * - * @var array - */ - private $tags; + * tags + */ + private array $tags; /** * @param array $tags diff --git a/apps/dav/lib/Connector/Sabre/TagsPlugin.php b/apps/dav/lib/Connector/Sabre/TagsPlugin.php index 8877836c091b..65d2c9024aa4 100644 --- a/apps/dav/lib/Connector/Sabre/TagsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/TagsPlugin.php @@ -54,16 +54,11 @@ class TagsPlugin extends \Sabre\DAV\ServerPlugin { public const TAG_FAVORITE = '_$!!$_'; /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; - /** - * @var \OCP\ITagManager - */ - private $tagManager; + private \OCP\ITagManager $tagManager; /** * @var \OCP\ITags @@ -78,10 +73,7 @@ class TagsPlugin extends \Sabre\DAV\ServerPlugin { */ private $cachedTags; - /** - * @var \Sabre\DAV\Tree - */ - private $tree; + private \Sabre\DAV\Tree $tree; /** * @param \Sabre\DAV\Tree $tree tree @@ -107,7 +99,7 @@ public function __construct(\Sabre\DAV\Tree $tree, \OCP\ITagManager $tagManager) */ public function initialize(\Sabre\DAV\Server $server) { $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc'; - $server->xml->elementMap[self::TAGS_PROPERTYNAME] = 'OCA\\DAV\\Connector\\Sabre\\TagList'; + $server->xml->elementMap[self::TAGS_PROPERTYNAME] = \OCA\DAV\Connector\Sabre\TagList::class; $this->server = $server; $this->server->on('propFind', [$this, 'handleGetProperties']); @@ -241,13 +233,13 @@ public function handleGetProperties( $isFav = null; $propFind->handle(self::TAGS_PROPERTYNAME, function () use ($tags, &$isFav, $node) { - list($tags, $isFav) = $this->getTagsAndFav($node->getId()); + [$tags, $isFav] = $this->getTagsAndFav($node->getId()); return new TagList($tags); }); $propFind->handle(self::FAVORITE_PROPERTYNAME, function () use ($isFav, $node) { if ($isFav === null) { - list(, $isFav) = $this->getTagsAndFav($node->getId()); + [, $isFav] = $this->getTagsAndFav($node->getId()); } if ($isFav) { return 1; diff --git a/apps/dav/lib/Connector/Sabre/ValidateRequestPlugin.php b/apps/dav/lib/Connector/Sabre/ValidateRequestPlugin.php index 142731fbd407..03a4c19ee0c6 100644 --- a/apps/dav/lib/Connector/Sabre/ValidateRequestPlugin.php +++ b/apps/dav/lib/Connector/Sabre/ValidateRequestPlugin.php @@ -34,11 +34,9 @@ */ class ValidateRequestPlugin extends ServerPlugin { /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; /** * Service type as decided by resolveService($service) in remote.php diff --git a/apps/dav/lib/DAV/AbstractCustomPropertiesBackend.php b/apps/dav/lib/DAV/AbstractCustomPropertiesBackend.php index d1c217605734..099b6e57c59b 100644 --- a/apps/dav/lib/DAV/AbstractCustomPropertiesBackend.php +++ b/apps/dav/lib/DAV/AbstractCustomPropertiesBackend.php @@ -226,9 +226,7 @@ public function propPatch($path, PropPatch $propPatch) { return; } - $propPatch->handleRemaining(function ($changedProps) use ($path, $node) { - return $this->updateProperties($path, $node, $changedProps); - }); + $propPatch->handleRemaining(fn ($changedProps) => $this->updateProperties($path, $node, $changedProps)); } /** diff --git a/apps/dav/lib/DAV/CopyPlugin.php b/apps/dav/lib/DAV/CopyPlugin.php index 35735a7dcbf4..486cc208b96d 100644 --- a/apps/dav/lib/DAV/CopyPlugin.php +++ b/apps/dav/lib/DAV/CopyPlugin.php @@ -44,8 +44,7 @@ * @package OCA\DAV\DAV */ class CopyPlugin extends ServerPlugin { - /** @var Server */ - private $server; + private ?\Sabre\DAV\Server $server = null; /** * @param Server $server diff --git a/apps/dav/lib/DAV/GroupPrincipalBackend.php b/apps/dav/lib/DAV/GroupPrincipalBackend.php index be3962737ac4..bb1d45e92004 100644 --- a/apps/dav/lib/DAV/GroupPrincipalBackend.php +++ b/apps/dav/lib/DAV/GroupPrincipalBackend.php @@ -30,8 +30,7 @@ class GroupPrincipalBackend implements BackendInterface { public const PRINCIPAL_PREFIX = 'principals/groups'; - /** @var IGroupManager */ - private $groupManager; + private \OCP\IGroupManager $groupManager; /** * @param IGroupManager $IGroupManager @@ -112,9 +111,7 @@ public function getGroupMemberSet($principal) { return []; } - return \array_map(function ($user) { - return $this->userToPrincipal($user); - }, $group->getUsers()); + return \array_map(fn ($user) => $this->userToPrincipal($user), $group->getUsers()); } /** diff --git a/apps/dav/lib/DAV/LazyOpsPlugin.php b/apps/dav/lib/DAV/LazyOpsPlugin.php index ba84db27e73b..f66583d055a3 100644 --- a/apps/dav/lib/DAV/LazyOpsPlugin.php +++ b/apps/dav/lib/DAV/LazyOpsPlugin.php @@ -41,22 +41,15 @@ * @package OCA\DAV\DAV */ class LazyOpsPlugin extends ServerPlugin { - /** @var Server */ - private $server; + private ?\Sabre\DAV\Server $server = null; /** @var string */ private $jobId; - /** @var JobStatus */ - private $entity; - /** @var IUserSession */ - private $userSession; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var IShutdownManager */ - private $shutdownManager; - /** @var ILogger */ - private $logger; - /** @var JobStatusMapper */ - private $mapper; + private ?\OCA\DAV\JobStatus\Entity\JobStatus $entity = null; + private \OCP\IUserSession $userSession; + private \OCP\IURLGenerator $urlGenerator; + private \OCP\Shutdown\IShutdownManager $shutdownManager; + private \OCP\ILogger $logger; + private \OCA\DAV\JobStatus\Entity\JobStatusMapper $mapper; public function __construct( IUserSession $userSession, @@ -103,9 +96,7 @@ public function httpMove(RequestInterface $request, ResponseInterface $response) $response->setHeader('Connection', 'close'); $response->setHeader('OC-JobStatus-Location', $location); - $this->shutdownManager->register(function () use ($request, $response) { - return $this->afterResponse($request, $response); - }, IShutdownManager::HIGH); + $this->shutdownManager->register(fn () => $this->afterResponse($request, $response), IShutdownManager::HIGH); return false; } @@ -146,12 +137,12 @@ private function setJobStatus(array $status) { $userId = $this->getUserId(); $this->entity = new JobStatus(); - $this->entity->setStatusInfo(\json_encode($status)); + $this->entity->setStatusInfo(\json_encode($status, JSON_THROW_ON_ERROR)); $this->entity->setUserId($userId); $this->entity->setUuid($this->jobId); $this->mapper->insert($this->entity); } else { - $this->entity->setStatusInfo(\json_encode($status)); + $this->entity->setStatusInfo(\json_encode($status, JSON_THROW_ON_ERROR)); $this->mapper->update($this->entity); } } diff --git a/apps/dav/lib/DAV/PublicAuth.php b/apps/dav/lib/DAV/PublicAuth.php index ff9484032ab9..198b66146d33 100644 --- a/apps/dav/lib/DAV/PublicAuth.php +++ b/apps/dav/lib/DAV/PublicAuth.php @@ -82,9 +82,7 @@ public function challenge(RequestInterface $request, ResponseInterface $response */ private function isRequestPublic(RequestInterface $request) { $url = $request->getPath(); - $matchingUrls = \array_filter($this->publicURLs, function ($publicUrl) use ($url) { - return \strpos($url, $publicUrl, 0) === 0; - }); + $matchingUrls = \array_filter($this->publicURLs, fn ($publicUrl) => \strpos($url, (string) $publicUrl, 0) === 0); return !empty($matchingUrls); } } diff --git a/apps/dav/lib/DAV/Sharing/Backend.php b/apps/dav/lib/DAV/Sharing/Backend.php index 4893579a7447..ad57627d0477 100644 --- a/apps/dav/lib/DAV/Sharing/Backend.php +++ b/apps/dav/lib/DAV/Sharing/Backend.php @@ -29,12 +29,9 @@ use OCP\IDBConnection; class Backend { - /** @var IDBConnection */ - private $db; - /** @var Principal */ - private $principalBackend; - /** @var GroupPrincipalBackend */ - private $groupPrincipalBackend; + private \OCP\IDBConnection $db; + private \OCA\DAV\Connector\Sabre\Principal $principalBackend; + private \OCA\DAV\DAV\GroupPrincipalBackend $groupPrincipalBackend; /** @var string */ private $resourceType; @@ -186,7 +183,7 @@ public function getShares($resourceId) { $p = $this->principalBackend->getPrincipalByPath($row['principaluri']); $shares[]= [ 'href' => "principal:{$row['principaluri']}", - 'commonName' => isset($p['{DAV:}displayname']) ? $p['{DAV:}displayname'] : '', + 'commonName' => $p['{DAV:}displayname'] ?? '', 'status' => 1, 'readOnly' => $row['access'] == self::ACCESS_READ, '{http://owncloud.org/ns}principal' => $row['principaluri'], diff --git a/apps/dav/lib/DAV/Sharing/Plugin.php b/apps/dav/lib/DAV/Sharing/Plugin.php index 9324534374e9..aa0d2cdd380c 100644 --- a/apps/dav/lib/DAV/Sharing/Plugin.php +++ b/apps/dav/lib/DAV/Sharing/Plugin.php @@ -35,11 +35,9 @@ class Plugin extends ServerPlugin { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; - /** @var Auth */ - private $auth; + private \OCA\DAV\Connector\Sabre\Auth $auth; - /** @var IRequest */ - private $request; + private \OCP\IRequest $request; /** * Plugin constructor. @@ -96,8 +94,8 @@ public function getPluginName() { */ public function initialize(Server $server) { $this->server = $server; - $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}share'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\ShareRequest'; - $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = 'OCA\\DAV\\DAV\\Sharing\\Xml\\Invite'; + $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}share'] = \OCA\DAV\DAV\Sharing\Xml\ShareRequest::class; + $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = \OCA\DAV\DAV\Sharing\Xml\Invite::class; $this->server->on('method:POST', [$this, 'httpPost']); $this->server->on('propFind', [$this, 'propFind']); @@ -185,11 +183,9 @@ public function httpPost(RequestInterface $request, ResponseInterface $response) */ public function propFind(PropFind $propFind, INode $node) { if ($node instanceof IShareable) { - $propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', function () use ($node) { - return new Invite( - $node->getShares() - ); - }); + $propFind->handle('{' . Plugin::NS_OWNCLOUD . '}invite', fn () => new Invite( + $node->getShares() + )); } } } diff --git a/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php b/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php index 25ef36d8328f..fa70a24ccf62 100644 --- a/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php +++ b/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php @@ -42,8 +42,8 @@ public function __construct(array $set, array $remove) { public static function xmlDeserialize(Reader $reader) { $elements = $reader->parseInnerTree([ - '{' . Plugin::NS_OWNCLOUD. '}set' => 'Sabre\\Xml\\Element\\KeyValue', - '{' . Plugin::NS_OWNCLOUD . '}remove' => 'Sabre\\Xml\\Element\\KeyValue', + '{' . Plugin::NS_OWNCLOUD. '}set' => \Sabre\Xml\Element\KeyValue::class, + '{' . Plugin::NS_OWNCLOUD . '}remove' => \Sabre\Xml\Element\KeyValue::class, ]); $set = []; @@ -59,8 +59,8 @@ public static function xmlDeserialize(Reader $reader) { $set[] = [ 'href' => $sharee['{DAV:}href'], - 'commonName' => isset($sharee[$commonName]) ? $sharee[$commonName] : null, - 'summary' => isset($sharee[$sumElem]) ? $sharee[$sumElem] : null, + 'commonName' => $sharee[$commonName] ?? null, + 'summary' => $sharee[$sumElem] ?? null, 'readOnly' => !\array_key_exists('{' . Plugin::NS_OWNCLOUD . '}read-write', $sharee), ]; break; diff --git a/apps/dav/lib/DAV/SystemPrincipalBackend.php b/apps/dav/lib/DAV/SystemPrincipalBackend.php index 43759da2c41a..5b2bcbf92f30 100644 --- a/apps/dav/lib/DAV/SystemPrincipalBackend.php +++ b/apps/dav/lib/DAV/SystemPrincipalBackend.php @@ -160,7 +160,7 @@ public function getGroupMemberSet($principal) { * @return array */ public function getGroupMembership($principal) { - list($prefix, $name) = \Sabre\Uri\split($principal); + [$prefix, $name] = \Sabre\Uri\split($principal); if ($prefix === 'principals/system') { $principal = $this->getPrincipalByPath($principal); diff --git a/apps/dav/lib/DAV/ViewOnlyPlugin.php b/apps/dav/lib/DAV/ViewOnlyPlugin.php index 2adfed1fa980..1eb6f4effb9d 100644 --- a/apps/dav/lib/DAV/ViewOnlyPlugin.php +++ b/apps/dav/lib/DAV/ViewOnlyPlugin.php @@ -36,11 +36,9 @@ * Sabre plugin for restricting file share receiver download: */ class ViewOnlyPlugin extends ServerPlugin { - /** @var Server $server */ - private $server; + private ?\Sabre\DAV\Server $server = null; - /** @var ILogger $logger */ - private $logger; + private \OCP\ILogger $logger; /** * @param ILogger $logger @@ -94,7 +92,7 @@ public function checkViewOnly( $storage = $node->getStorage(); // using string as we have no guarantee that "files_sharing" app is loaded - if (!$storage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')) { + if (!$storage->instanceOfStorage(\OCA\Files_Sharing\SharedStorage::class)) { return true; } // Extract extra permissions diff --git a/apps/dav/lib/Files/BrowserErrorPagePlugin.php b/apps/dav/lib/Files/BrowserErrorPagePlugin.php index a822c7fa0052..bcce63ecbce0 100644 --- a/apps/dav/lib/Files/BrowserErrorPagePlugin.php +++ b/apps/dav/lib/Files/BrowserErrorPagePlugin.php @@ -30,8 +30,7 @@ use Sabre\DAV\ServerPlugin; class BrowserErrorPagePlugin extends ServerPlugin { - /** @var Server */ - private $server; + private ?\Sabre\DAV\Server $server = null; /** * This initializes the plugin. diff --git a/apps/dav/lib/Files/FileLocksBackend.php b/apps/dav/lib/Files/FileLocksBackend.php index 5309e34a6219..de72b3ccd901 100644 --- a/apps/dav/lib/Files/FileLocksBackend.php +++ b/apps/dav/lib/Files/FileLocksBackend.php @@ -97,7 +97,7 @@ public function getLocks($uri, $returnChildLocks) { } // get parent storage and check for locks on the target path - list($parentPath, $childPath) = \Sabre\Uri\split($uri); + [$parentPath, $childPath] = \Sabre\Uri\split($uri); try { $node = $this->tree->getNodeForPath($parentPath); diff --git a/apps/dav/lib/Files/FilesHome.php b/apps/dav/lib/Files/FilesHome.php index 428d876f91c1..8e9dd69bbd0a 100644 --- a/apps/dav/lib/Files/FilesHome.php +++ b/apps/dav/lib/Files/FilesHome.php @@ -78,7 +78,7 @@ public function delete($path = null) { } public function getName() { - list(, $name) = \Sabre\Uri\split($this->principalInfo['uri']); + [, $name] = \Sabre\Uri\split($this->principalInfo['uri']); return $name; } diff --git a/apps/dav/lib/Files/PreviewPlugin.php b/apps/dav/lib/Files/PreviewPlugin.php index afad5efc3d23..130f055824a6 100644 --- a/apps/dav/lib/Files/PreviewPlugin.php +++ b/apps/dav/lib/Files/PreviewPlugin.php @@ -42,10 +42,8 @@ class PreviewPlugin extends ServerPlugin { /** @var Server */ protected $server; - /** @var ITimeFactory */ - private $timeFactory; - /** @var IPreview */ - private $previewManager; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; + private \OCP\IPreview $previewManager; /** * PreviewPlugin constructor. diff --git a/apps/dav/lib/Files/PublicFiles/PublicFilesPlugin.php b/apps/dav/lib/Files/PublicFiles/PublicFilesPlugin.php index f01942c1216e..5ec7a81c879d 100644 --- a/apps/dav/lib/Files/PublicFiles/PublicFilesPlugin.php +++ b/apps/dav/lib/Files/PublicFiles/PublicFilesPlugin.php @@ -48,8 +48,7 @@ class PublicFilesPlugin extends ServerPlugin { public const PUBLIC_LINK_SHARE_DATETIME = '{http://owncloud.org/ns}public-link-share-datetime'; public const PUBLIC_LINK_SHARE_OWNER = '{http://owncloud.org/ns}public-link-share-owner'; - /** @var Server */ - private $server; + private ?\Sabre\DAV\Server $server = null; public function initialize(Server $server) { $this->server = $server; @@ -65,7 +64,7 @@ public function beforePut(RequestInterface $request, ResponseInterface $response if (!$this->server->tree->nodeExists($path)) { return; } - list($parentPath, ) = \Sabre\Uri\split($path); + [$parentPath, ] = \Sabre\Uri\split($path); $parent = $this->server->tree->getNodeForPath($parentPath); // only in share roots of file drop folders auto renaming will be applied @@ -97,13 +96,9 @@ private function newFileName($path) { public function propFind(PropFind $propFind, INode $node) { // properties about the share if ($node instanceof PublicSharedRootNode) { - $propFind->handle(self::PUBLIC_LINK_ITEM_TYPE, static function () use ($node) { - return $node->getShare()->getNodeType(); - }); + $propFind->handle(self::PUBLIC_LINK_ITEM_TYPE, static fn () => $node->getShare()->getNodeType()); - $propFind->handle(self::PUBLIC_LINK_PERMISSION, static function () use ($node) { - return $node->getShare()->getPermissions(); - }); + $propFind->handle(self::PUBLIC_LINK_PERMISSION, static fn () => $node->getShare()->getPermissions()); $propFind->handle(self::PUBLIC_LINK_EXPIRATION, static function () use ($node) { $expire = $node->getShare()->getExpirationDate(); @@ -113,28 +108,18 @@ public function propFind(PropFind $propFind, INode $node) { return null; }); - $propFind->handle(self::PUBLIC_LINK_SHARE_DATETIME, static function () use ($node) { - return new GetLastModified($node->getShare()->getShareTime()); - }); + $propFind->handle(self::PUBLIC_LINK_SHARE_DATETIME, static fn () => new GetLastModified($node->getShare()->getShareTime())); - $propFind->handle(self::PUBLIC_LINK_SHARE_OWNER, static function () use ($node) { - return $node->getShare()->getShareOwner(); - }); + $propFind->handle(self::PUBLIC_LINK_SHARE_OWNER, static fn () => $node->getShare()->getShareOwner()); - $propFind->handle(FilesPlugin::PERMISSIONS_PROPERTYNAME, static function () use ($node) { - return $node->getPermissions(); - }); + $propFind->handle(FilesPlugin::PERMISSIONS_PROPERTYNAME, static fn () => $node->getPermissions()); } // properties about the resources within the public link if ($node instanceof IPublicSharedNode) { - $propFind->handle(FilesPlugin::INTERNAL_FILEID_PROPERTYNAME, static function () use ($node) { - return $node->getNode()->getId(); - }); + $propFind->handle(FilesPlugin::INTERNAL_FILEID_PROPERTYNAME, static fn () => $node->getNode()->getId()); - $propFind->handle(FilesPlugin::PERMISSIONS_PROPERTYNAME, static function () use ($node) { - return $node->getDavPermissions(); - }); + $propFind->handle(FilesPlugin::PERMISSIONS_PROPERTYNAME, static fn () => $node->getDavPermissions()); $propFind->handle(FilesPlugin::OWNER_ID_PROPERTYNAME, static function () use ($node) { $owner = $node->getNode()->getOwner(); @@ -144,9 +129,7 @@ public function propFind(PropFind $propFind, INode $node) { $owner = $node->getNode()->getOwner(); return $owner->getDisplayName(); }); - $propFind->handle(FilesPlugin::SIZE_PROPERTYNAME, static function () use ($node) { - return $node->getNode()->getSize(); - }); + $propFind->handle(FilesPlugin::SIZE_PROPERTYNAME, static fn () => $node->getNode()->getSize()); if ($node->getNode()->getType() === FileInfo::TYPE_FILE) { $server = $this->server; $propFind->handle(FilesPlugin::DOWNLOADURL_PROPERTYNAME, static function () use ($node, $server) { diff --git a/apps/dav/lib/Files/PublicFiles/PublicShareSigner.php b/apps/dav/lib/Files/PublicFiles/PublicShareSigner.php index ae33333cbc0e..02befe12f508 100644 --- a/apps/dav/lib/Files/PublicFiles/PublicShareSigner.php +++ b/apps/dav/lib/Files/PublicFiles/PublicShareSigner.php @@ -22,10 +22,10 @@ namespace OCA\DAV\Files\PublicFiles; class PublicShareSigner { - private $token; - private $fileName; + private string $token; + private string $fileName; private $validUntil; - private $signingKey; + private string $signingKey; public function __construct(String $token, String $fileName, \DateTime $validUntil, String $signingKey) { $this->token = $token; diff --git a/apps/dav/lib/Files/PublicFiles/PublicSharedRootNode.php b/apps/dav/lib/Files/PublicFiles/PublicSharedRootNode.php index 20e202318efb..a7571756868c 100644 --- a/apps/dav/lib/Files/PublicFiles/PublicSharedRootNode.php +++ b/apps/dav/lib/Files/PublicFiles/PublicSharedRootNode.php @@ -43,12 +43,8 @@ class PublicSharedRootNode extends Collection implements IACL { use NodeFactoryTrait, ACLTrait; - /** @var IShare */ - private $share; - /** - * @var IRequest - */ - private $request; + private \OCP\Share\IShare $share; + private \OCP\IRequest $request; /** * PublicSharedRootNode constructor. @@ -81,9 +77,7 @@ public function getChildren() { } else { $nodes = [$this->share->getNode()]; } - return \array_map(function (Node $node) { - return $this->nodeFactory($node, $this->share); - }, $nodes); + return \array_map(fn (Node $node) => $this->nodeFactory($node, $this->share), $nodes); } catch (NotFoundException $ex) { throw new NotFound(); } @@ -119,11 +113,7 @@ public function createFile($name, $data = null) { // all operations have been successful - no need to cleanup the pending file in finally block $pendingFile = null; return '"' . $etag . '"'; - } catch (NotPermittedException $ex) { - throw new Forbidden('Permission denied to create file'); - } catch (InvalidPathException $ex) { - throw new Forbidden('Permission denied to create file'); - } catch (NotFoundException $ex) { + } catch (NotPermittedException|InvalidPathException|NotFoundException $ex) { throw new Forbidden('Permission denied to create file'); } finally { // in case of an exception we need to delete the pending file diff --git a/apps/dav/lib/Files/PublicFiles/PublicSharingAuth.php b/apps/dav/lib/Files/PublicFiles/PublicSharingAuth.php index fed2ac26b912..881d1532005a 100644 --- a/apps/dav/lib/Files/PublicFiles/PublicSharingAuth.php +++ b/apps/dav/lib/Files/PublicFiles/PublicSharingAuth.php @@ -38,12 +38,10 @@ * @package OCA\DAV\Files\PublicFiles */ class PublicSharingAuth extends AbstractBasic { - /** @var Server */ - private $server; + private \Sabre\DAV\Server $server; /** @var IShare */ private $share; - /** @var IManager */ - private $shareManager; + private \OCP\Share\IManager $shareManager; /** * PublicSharingAuth constructor. diff --git a/apps/dav/lib/Files/PublicFiles/RootCollection.php b/apps/dav/lib/Files/PublicFiles/RootCollection.php index 5a56f956c297..ca72e490fa95 100644 --- a/apps/dav/lib/Files/PublicFiles/RootCollection.php +++ b/apps/dav/lib/Files/PublicFiles/RootCollection.php @@ -88,8 +88,6 @@ public function getChildren() { } $shares = $this->shareManager->getAllSharedWith(null, [Constants::SHARE_TYPE_LINK]); - return \array_map(function (IShare $share) { - return new PublicSharedRootNode($share, $this->request); - }, $shares); + return \array_map(fn (IShare $share) => new PublicSharedRootNode($share, $this->request), $shares); } } diff --git a/apps/dav/lib/Files/PublicFiles/SharedFile.php b/apps/dav/lib/Files/PublicFiles/SharedFile.php index 8334d839d58d..14dd3d0c5b78 100644 --- a/apps/dav/lib/Files/PublicFiles/SharedFile.php +++ b/apps/dav/lib/Files/PublicFiles/SharedFile.php @@ -36,8 +36,7 @@ class SharedFile extends File implements IACL, IFileNode, IPublicSharedNode { use SharedNodeTrait; - /** @var \OCP\Files\File */ - private $file; + private \OCP\Files\File $file; /** * MetaFolder constructor. diff --git a/apps/dav/lib/Files/PublicFiles/SharedFolder.php b/apps/dav/lib/Files/PublicFiles/SharedFolder.php index 7a33f1a2a7f4..35ba9b18fcfb 100644 --- a/apps/dav/lib/Files/PublicFiles/SharedFolder.php +++ b/apps/dav/lib/Files/PublicFiles/SharedFolder.php @@ -39,8 +39,7 @@ class SharedFolder extends Collection implements IACL, IPublicSharedNode { use SharedNodeTrait, NodeFactoryTrait; - /** @var Folder */ - private $folder; + private \OCP\Files\Folder $folder; /** * SharedFolder constructor. @@ -59,9 +58,7 @@ public function __construct(Folder $folder, IShare $share) { */ public function getChildren() { $nodes = $this->folder->getDirectoryListing(); - return \array_map(function ($node) { - return $this->nodeFactory($node, $this->share); - }, $nodes); + return \array_map(fn ($node) => $this->nodeFactory($node, $this->share), $nodes); } public function createDirectory($name) { @@ -77,11 +74,7 @@ public function createFile($name, $data = null) { $file = $this->folder->newFile($name); $file->putContent($data); return '"' . $file->getEtag() . '"'; - } catch (NotPermittedException $ex) { - throw new Forbidden('Permission denied to create file'); - } catch (InvalidPathException $ex) { - throw new Forbidden('Permission denied to create file'); - } catch (NotFoundException $ex) { + } catch (NotPermittedException|InvalidPathException|NotFoundException $ex) { throw new Forbidden('Permission denied to create file'); } } diff --git a/apps/dav/lib/Files/RootCollection.php b/apps/dav/lib/Files/RootCollection.php index dba4745cd387..fb19bfc926b6 100644 --- a/apps/dav/lib/Files/RootCollection.php +++ b/apps/dav/lib/Files/RootCollection.php @@ -41,7 +41,7 @@ class RootCollection extends AbstractPrincipalCollection { * @return INode */ public function getChildForPrincipal(array $principalInfo) { - list(, $name) = \Sabre\Uri\split($principalInfo['uri']); + [, $name] = \Sabre\Uri\split($principalInfo['uri']); $user = \OC::$server->getUserSession()->getUser(); $uid = ''; diff --git a/apps/dav/lib/Files/Sharing/PublicLinkEventsPlugin.php b/apps/dav/lib/Files/Sharing/PublicLinkEventsPlugin.php index 3da90b6f13b5..6c0b7741c27f 100644 --- a/apps/dav/lib/Files/Sharing/PublicLinkEventsPlugin.php +++ b/apps/dav/lib/Files/Sharing/PublicLinkEventsPlugin.php @@ -29,10 +29,8 @@ use Symfony\Component\EventDispatcher\GenericEvent; class PublicLinkEventsPlugin extends ServerPlugin { - /** @var EventDispatcherInterface */ - private $dispatcher; - /** @var Server */ - private $server; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher; + private ?\Sabre\DAV\Server $server = null; public function __construct(EventDispatcherInterface $dispatcher) { $this->dispatcher = $dispatcher; diff --git a/apps/dav/lib/HookManager.php b/apps/dav/lib/HookManager.php index d9b1b4953247..98c437ddf161 100644 --- a/apps/dav/lib/HookManager.php +++ b/apps/dav/lib/HookManager.php @@ -31,23 +31,18 @@ use OCP\Util; class HookManager { - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var SyncService */ - private $syncService; + private \OCA\DAV\CardDAV\SyncService $syncService; /** @var IUser[] */ - private $usersToDelete; + private ?array $usersToDelete = null; - /** @var CalDavBackend */ - private $calDav; + private \OCA\DAV\CalDAV\CalDavBackend $calDav; - /** @var CardDavBackend */ - private $cardDav; + private \OCA\DAV\CardDAV\CardDavBackend $cardDav; - /** @var IL10N */ - private $l10n; + private \OCP\IL10N $l10n; /** @var array */ private $calendarsToDelete; diff --git a/apps/dav/lib/JobStatus/Home.php b/apps/dav/lib/JobStatus/Home.php index 684e28d1b997..ff9cd6028d3e 100644 --- a/apps/dav/lib/JobStatus/Home.php +++ b/apps/dav/lib/JobStatus/Home.php @@ -29,8 +29,7 @@ class Home extends Collection { /** @var array */ private $principalInfo; - /** @var JobStatusMapper */ - private $mapper; + private \OCA\DAV\JobStatus\Entity\JobStatusMapper $mapper; /** * Home constructor. @@ -58,7 +57,7 @@ public function getChildren() { } public function getName() { - list(, $name) = \Sabre\Uri\split($this->principalInfo['uri']); + [, $name] = \Sabre\Uri\split($this->principalInfo['uri']); return $name; } } diff --git a/apps/dav/lib/JobStatus/JobStatus.php b/apps/dav/lib/JobStatus/JobStatus.php index 70d9141ae717..1b1ca155ce34 100644 --- a/apps/dav/lib/JobStatus/JobStatus.php +++ b/apps/dav/lib/JobStatus/JobStatus.php @@ -31,8 +31,7 @@ class JobStatus extends File { private $userId; /** @var string */ private $data; - /** @var JobStatusMapper */ - private $mapper; + private \OCA\DAV\JobStatus\Entity\JobStatusMapper $mapper; /** @var JobStatusEntity */ private $entity; diff --git a/apps/dav/lib/Meta/MetaFile.php b/apps/dav/lib/Meta/MetaFile.php index 845777c702c2..716595d2c1b2 100644 --- a/apps/dav/lib/Meta/MetaFile.php +++ b/apps/dav/lib/Meta/MetaFile.php @@ -37,8 +37,7 @@ * @package OCA\DAV\Meta */ class MetaFile extends File implements ICopySource, IFileNode, IProvidesAdditionalHeaders { - /** @var \OCP\Files\File */ - private $file; + private \OCP\Files\File $file; /** * MetaFolder constructor. diff --git a/apps/dav/lib/Meta/MetaFolder.php b/apps/dav/lib/Meta/MetaFolder.php index 9a129943e61e..c39cbe2263d7 100644 --- a/apps/dav/lib/Meta/MetaFolder.php +++ b/apps/dav/lib/Meta/MetaFolder.php @@ -35,8 +35,7 @@ * @package OCA\DAV\Meta */ class MetaFolder extends Collection { - /** @var Folder */ - private $folder; + private \OCP\Files\Folder $folder; /** * MetaFolder constructor. @@ -52,9 +51,7 @@ public function __construct(Folder $folder) { */ public function getChildren() { $nodes = $this->folder->getDirectoryListing(); - return \array_map(function ($node) { - return $this->nodeFactory($node); - }, $nodes); + return \array_map(fn ($node) => $this->nodeFactory($node), $nodes); } /** diff --git a/apps/dav/lib/Meta/MetaPlugin.php b/apps/dav/lib/Meta/MetaPlugin.php index 760492b2b747..5e5d3d62836a 100644 --- a/apps/dav/lib/Meta/MetaPlugin.php +++ b/apps/dav/lib/Meta/MetaPlugin.php @@ -39,19 +39,11 @@ class MetaPlugin extends ServerPlugin { public const VERSION_TAG_PROPERTYNAME = '{http://owncloud.org/ns}meta-version-tag'; /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; - /** - * @var IUserSession - */ - private $userSession; - /** - * @var IRootFolder - */ - private $rootFolder; + * Reference to main server object + */ + private ?\Sabre\DAV\Server $server = null; + private \OCP\IUserSession $userSession; + private \OCP\Files\IRootFolder $rootFolder; public function __construct( IUserSession $userSession, @@ -102,9 +94,7 @@ public function handleGetProperties(PropFind $propFind, INode $node) { $file = \current($files); return $baseFolder->getRelativePath($file->getPath()); }); - $propFind->handle(self::VERSION_EDITED_BY_PROPERTYNAME, function () use ($node) { - return $node->getVersionEditedBy(); - }); + $propFind->handle(self::VERSION_EDITED_BY_PROPERTYNAME, fn () => $node->getVersionEditedBy()); $propFind->handle(self::VERSION_EDITED_BY_NAME_PROPERTYNAME, function () use ($node) { $versionEditedBy = $node->getVersionEditedBy(); if (!$versionEditedBy) { @@ -114,13 +104,9 @@ public function handleGetProperties(PropFind $propFind, INode $node) { $user = $manager->get($versionEditedBy); return $user !== null ? $user->getDisplayName() : ''; }); - $propFind->handle(self::VERSION_TAG_PROPERTYNAME, function () use ($node) { - return $node->getVersionTag(); - }); + $propFind->handle(self::VERSION_TAG_PROPERTYNAME, fn () => $node->getVersionTag()); } elseif ($node instanceof MetaFile) { - $propFind->handle(self::VERSION_EDITED_BY_PROPERTYNAME, function () use ($node) { - return $node->getVersionEditedBy(); - }); + $propFind->handle(self::VERSION_EDITED_BY_PROPERTYNAME, fn () => $node->getVersionEditedBy()); $propFind->handle(self::VERSION_EDITED_BY_NAME_PROPERTYNAME, function () use ($node) { $versionEditedBy = $node->getVersionEditedBy(); if (!$versionEditedBy) { @@ -130,9 +116,7 @@ public function handleGetProperties(PropFind $propFind, INode $node) { $user = $manager->get($versionEditedBy); return $user !== null ? $user->getDisplayName() : ''; }); - $propFind->handle(self::VERSION_TAG_PROPERTYNAME, function () use ($node) { - return $node->getVersionTag(); - }); + $propFind->handle(self::VERSION_TAG_PROPERTYNAME, fn () => $node->getVersionTag()); } } } diff --git a/apps/dav/lib/Meta/RootCollection.php b/apps/dav/lib/Meta/RootCollection.php index 327a74610486..9e25f30147b6 100644 --- a/apps/dav/lib/Meta/RootCollection.php +++ b/apps/dav/lib/Meta/RootCollection.php @@ -29,8 +29,7 @@ use Sabre\DAV\Exception\NotFound; class RootCollection extends Collection { - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; /** * RootCollection constructor. diff --git a/apps/dav/lib/Repair/RemoveInvalidShares.php b/apps/dav/lib/Repair/RemoveInvalidShares.php index f6cdc7c48bc1..7ae05a4fc6be 100644 --- a/apps/dav/lib/Repair/RemoveInvalidShares.php +++ b/apps/dav/lib/Repair/RemoveInvalidShares.php @@ -34,12 +34,9 @@ * @package OCA\DAV\Repair */ class RemoveInvalidShares implements IRepairStep { - /** @var IDBConnection */ - private $connection; - /** @var Principal */ - private $principalBackend; - /** @var GroupPrincipalBackend */ - private $groupPrincipalBackend; + private \OCP\IDBConnection $connection; + private \OCA\DAV\Connector\Sabre\Principal $principalBackend; + private \OCA\DAV\DAV\GroupPrincipalBackend $groupPrincipalBackend; /** * RemoveInvalidShares constructor. diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index 338be6e7816c..3ed1404677a6 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -81,8 +81,7 @@ class Server { /** @var string */ private $baseUri; - /** @var IRequest */ - private $request; + private \OCP\IRequest $request; /** * Server constructor. diff --git a/apps/dav/lib/SystemTag/SystemTagMappingNode.php b/apps/dav/lib/SystemTag/SystemTagMappingNode.php index 41f77999db3c..618fd5281b8f 100644 --- a/apps/dav/lib/SystemTag/SystemTagMappingNode.php +++ b/apps/dav/lib/SystemTag/SystemTagMappingNode.php @@ -62,10 +62,7 @@ class SystemTagMappingNode implements \Sabre\DAV\INode { */ protected $tagManager; - /** - * @var ISystemTagObjectMapper - */ - private $tagMapper; + private \OCP\SystemTag\ISystemTagObjectMapper $tagMapper; /** * Sets up the node, expects a full path name diff --git a/apps/dav/lib/SystemTag/SystemTagPlugin.php b/apps/dav/lib/SystemTag/SystemTagPlugin.php index d47cb09205af..9fdb4b094a70 100644 --- a/apps/dav/lib/SystemTag/SystemTagPlugin.php +++ b/apps/dav/lib/SystemTag/SystemTagPlugin.php @@ -55,10 +55,7 @@ class SystemTagPlugin extends \Sabre\DAV\ServerPlugin { public const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign'; public const WHITELISTEDINGROUP = '{http://owncloud.org/ns}editable-in-group'; - /** - * @var \Sabre\DAV\Server $server - */ - private $server; + private ?\Sabre\DAV\Server $server = null; /** * @var ISystemTagManager @@ -163,7 +160,7 @@ public function httpPost(RequestInterface $request, ResponseInterface $response) */ private function createTag($data, $contentType = 'application/json'): ISystemTag { if (\explode(';', $contentType)[0] === 'application/json') { - $data = \json_decode($data, true); + $data = \json_decode($data, true, 512, JSON_THROW_ON_ERROR); } else { throw new UnsupportedMediaType(); } @@ -231,32 +228,23 @@ public function handleGetProperties( return; } - $propFind->handle(self::ID_PROPERTYNAME, function () use ($node) { - return $node->getSystemTag()->getId(); - }); + $propFind->handle(self::ID_PROPERTYNAME, fn () => $node->getSystemTag()->getId()); - $propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function () use ($node) { - return $node->getSystemTag()->getName(); - }); + $propFind->handle(self::DISPLAYNAME_PROPERTYNAME, fn () => $node->getSystemTag()->getName()); - $propFind->handle(self::USERVISIBLE_PROPERTYNAME, function () use ($node) { - return $node->getSystemTag()->isUserVisible() ? 'true' : 'false'; - }); + $propFind->handle(self::USERVISIBLE_PROPERTYNAME, fn () => $node->getSystemTag()->isUserVisible() ? 'true' : 'false'); - $propFind->handle(self::USEREDITABLE_PROPERTYNAME, function () use ($node) { - // this is the tag's inherent property "is user editable" - return $node->getSystemTag()->isUserEditable() ? 'true' : 'false'; - }); + $propFind->handle(self::USEREDITABLE_PROPERTYNAME, fn () => + // this is the tag's inherent property "is user editable" + $node->getSystemTag()->isUserEditable() ? 'true' : 'false'); - $propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, function () use ($node) { - // this is the tag's inherent property "is user assignable" - return $node->getSystemTag()->isUserAssignable() ? 'true' : 'false'; - }); + $propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, fn () => + // this is the tag's inherent property "is user assignable" + $node->getSystemTag()->isUserAssignable() ? 'true' : 'false'); - $propFind->handle(self::CANASSIGN_PROPERTYNAME, function () use ($node) { - // this is the effective permission for the current user - return $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false'; - }); + $propFind->handle(self::CANASSIGN_PROPERTYNAME, fn () => + // this is the effective permission for the current user + $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false'); $propFind->handle(self::GROUPS_PROPERTYNAME, function () use ($node) { if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) { @@ -276,9 +264,7 @@ public function handleGetProperties( return \implode('|', $groups); }); - $propFind->handle(self::WHITELISTEDINGROUP, function () use ($node) { - return $this->tagManager->canUserUseStaticTagInGroup($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false'; - }); + $propFind->handle(self::WHITELISTEDINGROUP, fn () => $this->tagManager->canUserUseStaticTagInGroup($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false'); } /** diff --git a/apps/dav/lib/SystemTag/SystemTagsByIdCollection.php b/apps/dav/lib/SystemTag/SystemTagsByIdCollection.php index 61bfe5cb6a6c..2d101bed6ba0 100644 --- a/apps/dav/lib/SystemTag/SystemTagsByIdCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsByIdCollection.php @@ -33,20 +33,11 @@ use Sabre\DAV\ICollection; class SystemTagsByIdCollection implements ICollection { - /** - * @var ISystemTagManager - */ - private $tagManager; + private \OCP\SystemTag\ISystemTagManager $tagManager; - /** - * @var IGroupManager - */ - private $groupManager; + private \OCP\IGroupManager $groupManager; - /** - * @var IUserSession - */ - private $userSession; + private \OCP\IUserSession $userSession; /** * SystemTagsByIdCollection constructor. @@ -133,9 +124,7 @@ public function getChildren() { return true; }); - return \array_map(function ($tag) { - return $this->makeNode($tag); - }, $tags); + return \array_map(fn ($tag) => $this->makeNode($tag), $tags); } /** diff --git a/apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php b/apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php index 1d66fa578a7d..b93db857fd3d 100644 --- a/apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php @@ -46,22 +46,14 @@ class SystemTagsObjectMappingCollection implements ICollection { */ private $objectType; - /** - * @var ISystemTagManager - */ - private $tagManager; + private \OCP\SystemTag\ISystemTagManager $tagManager; - /** - * @var ISystemTagObjectMapper - */ - private $tagMapper; + private \OCP\SystemTag\ISystemTagObjectMapper $tagMapper; /** - * User - * - * @var IUser - */ - private $user; + * User + */ + private \OCP\IUser $user; /** * Constructor @@ -140,13 +132,9 @@ public function getChildren() { $tags = $this->tagManager->getTagsByIds($tagIds); // filter out non-visible tags - $tags = \array_filter($tags, function ($tag) { - return $this->tagManager->canUserSeeTag($tag, $this->user); - }); + $tags = \array_filter($tags, fn ($tag) => $this->tagManager->canUserSeeTag($tag, $this->user)); - return \array_values(\array_map(function ($tag) { - return $this->makeNode($tag); - }, $tags)); + return \array_values(\array_map(fn ($tag) => $this->makeNode($tag), $tags)); } public function childExists($tagId) { diff --git a/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php b/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php index 371666734e44..1efe11c8d858 100644 --- a/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php @@ -41,25 +41,13 @@ class SystemTagsObjectTypeCollection implements ICollection { */ private $objectType; - /** - * @var ISystemTagManager - */ - private $tagManager; + private \OCP\SystemTag\ISystemTagManager $tagManager; - /** - * @var ISystemTagObjectMapper - */ - private $tagMapper; + private \OCP\SystemTag\ISystemTagObjectMapper $tagMapper; - /** - * @var IGroupManager - */ - private $groupManager; + private \OCP\IGroupManager $groupManager; - /** - * @var IUserSession - */ - private $userSession; + private \OCP\IUserSession $userSession; /** * @var IRootFolder diff --git a/apps/dav/lib/TrashBin/RootCollection.php b/apps/dav/lib/TrashBin/RootCollection.php index 61f4e76625ec..b22d59a7de9e 100644 --- a/apps/dav/lib/TrashBin/RootCollection.php +++ b/apps/dav/lib/TrashBin/RootCollection.php @@ -62,7 +62,7 @@ public function __construct(BackendInterface $principalBackend, IUserSession $us * @throws NotAuthenticated */ public function getChildForPrincipal(array $principalInfo) { - list(, $name) = \Sabre\Uri\split($principalInfo['uri']); + [, $name] = \Sabre\Uri\split($principalInfo['uri']); $sessionUser = $this->userSession->getUser(); if ($sessionUser === null || $name !== $sessionUser->getUID()) { throw new NotAuthenticated(); diff --git a/apps/dav/lib/TrashBin/TrashBinFolder.php b/apps/dav/lib/TrashBin/TrashBinFolder.php index 44adb64d5c25..042dbd69be20 100644 --- a/apps/dav/lib/TrashBin/TrashBinFolder.php +++ b/apps/dav/lib/TrashBin/TrashBinFolder.php @@ -47,9 +47,7 @@ public function childExists($name) { try { $ret = $this->getChild($name); return $ret !== null; - } catch (NotFound $ex) { - return false; - } catch (MethodNotAllowed $ex) { + } catch (NotFound|MethodNotAllowed $ex) { return false; } } diff --git a/apps/dav/lib/TrashBin/TrashBinHome.php b/apps/dav/lib/TrashBin/TrashBinHome.php index 8bdeb7150d79..660e9a686195 100644 --- a/apps/dav/lib/TrashBin/TrashBinHome.php +++ b/apps/dav/lib/TrashBin/TrashBinHome.php @@ -25,10 +25,8 @@ use Sabre\DAV\Exception\Forbidden; class TrashBinHome extends Collection { - /** @var TrashBinManager */ - private $trashBinManager; - /** @var string */ - private $user; + private \OCA\DAV\TrashBin\TrashBinManager $trashBinManager; + private string $user; /** * TrashBinHome constructor. diff --git a/apps/dav/lib/TrashBin/TrashBinManager.php b/apps/dav/lib/TrashBin/TrashBinManager.php index 5d33ab4f7efa..380bcf53ea97 100644 --- a/apps/dav/lib/TrashBin/TrashBinManager.php +++ b/apps/dav/lib/TrashBin/TrashBinManager.php @@ -64,9 +64,7 @@ public function getChildren(string $user, string $fileId = null) { throw new InvalidResourceType(); } $files = $view->getDirectoryContent($path); - return \array_map(function ($fileInfo) use ($user) { - return $this->nodeFactory($user, $fileInfo); - }, $files); + return \array_map(fn ($fileInfo) => $this->nodeFactory($user, $fileInfo), $files); } catch (\Exception $exception) { return []; } diff --git a/apps/dav/lib/TrashBin/TrashBinPlugin.php b/apps/dav/lib/TrashBin/TrashBinPlugin.php index aa39de03d67a..1c5ca90662f8 100644 --- a/apps/dav/lib/TrashBin/TrashBinPlugin.php +++ b/apps/dav/lib/TrashBin/TrashBinPlugin.php @@ -33,8 +33,7 @@ class TrashBinPlugin extends ServerPlugin { public const TRASHBIN_DELETE_TIMESTAMP = '{http://owncloud.org/ns}trashbin-delete-timestamp'; public const TRASHBIN_DELETE_DATETIME = '{http://owncloud.org/ns}trashbin-delete-datetime'; - /** @var Server */ - private $server; + private ?\Sabre\DAV\Server $server = null; public function initialize(Server $server) { $this->server = $server; @@ -47,20 +46,12 @@ public function propFind(PropFind $propFind, INode $node) { return; } - $propFind->handle(self::TRASHBIN_ORIGINAL_FILENAME, static function () use ($node) { - return $node->getOriginalFileName(); - }); + $propFind->handle(self::TRASHBIN_ORIGINAL_FILENAME, static fn () => $node->getOriginalFileName()); - $propFind->handle(self::TRASHBIN_ORIGINAL_LOCATION, static function () use ($node) { - return $node->getOriginalLocation(); - }); + $propFind->handle(self::TRASHBIN_ORIGINAL_LOCATION, static fn () => $node->getOriginalLocation()); - $propFind->handle(self::TRASHBIN_DELETE_TIMESTAMP, static function () use ($node) { - return $node->getDeleteTimestamp(); - }); + $propFind->handle(self::TRASHBIN_DELETE_TIMESTAMP, static fn () => $node->getDeleteTimestamp()); - $propFind->handle(self::TRASHBIN_DELETE_DATETIME, static function () use ($node) { - return new GetLastModified($node->getDeleteTimestamp()); - }); + $propFind->handle(self::TRASHBIN_DELETE_DATETIME, static fn () => new GetLastModified($node->getDeleteTimestamp())); } } diff --git a/apps/dav/lib/Upload/AssemblyStream.php b/apps/dav/lib/Upload/AssemblyStream.php index 2f408f5b876a..a6d194791993 100644 --- a/apps/dav/lib/Upload/AssemblyStream.php +++ b/apps/dav/lib/Upload/AssemblyStream.php @@ -42,11 +42,9 @@ class AssemblyStream implements \Icewind\Streams\File { /** @var IFile[] */ private $nodes; - /** @var int */ - private $pos = 0; + private int $pos = 0; - /** @var array */ - private $sortedNodes; + private ?array $sortedNodes = null; /** @var int */ private $size; @@ -70,9 +68,7 @@ public function stream_open($path, $mode, $options, &$opened_path) { // sort the nodes $nodes = $this->nodes; // http://stackoverflow.com/a/10985500 - @\usort($nodes, function (IFile $a, IFile $b) { - return \strnatcmp($a->getName(), $b->getName()); - }); + @\usort($nodes, fn (IFile $a, IFile $b) => \strnatcmp($a->getName(), $b->getName())); $this->nodes = $nodes; // build additional information @@ -113,7 +109,7 @@ public function stream_read($count) { $lastNode = null; do { if ($this->currentStream === null) { - list($node, $posInNode) = $this->getNodeForPosition($this->pos); + [$node, $posInNode] = $this->getNodeForPosition($this->pos); if ($node === null) { // reached last node, no more data return ''; @@ -248,7 +244,7 @@ public static function wrap(array $nodes) { 'assembly' => [ 'nodes' => $nodes] ]); - \stream_wrapper_register('assembly', '\OCA\DAV\Upload\AssemblyStream'); + \stream_wrapper_register('assembly', '\\' . \OCA\DAV\Upload\AssemblyStream::class); try { $wrapped = \fopen('assembly://', 'r', null, $context); } catch (\BadMethodCallException $e) { diff --git a/apps/dav/lib/Upload/ChunkLocationProvider.php b/apps/dav/lib/Upload/ChunkLocationProvider.php index 3a8bb19ec8e6..87b3fd46c37d 100644 --- a/apps/dav/lib/Upload/ChunkLocationProvider.php +++ b/apps/dav/lib/Upload/ChunkLocationProvider.php @@ -40,8 +40,7 @@ * @package OCA\DAV\Upload */ class ChunkLocationProvider implements IMountProvider { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** * ChunkLocationProvider constructor. diff --git a/apps/dav/lib/Upload/ChunkingPlugin.php b/apps/dav/lib/Upload/ChunkingPlugin.php index 6dfcaff2fa28..baa83066d099 100644 --- a/apps/dav/lib/Upload/ChunkingPlugin.php +++ b/apps/dav/lib/Upload/ChunkingPlugin.php @@ -26,8 +26,7 @@ use Sabre\DAV\ServerPlugin; class ChunkingPlugin extends ServerPlugin { - /** @var Server */ - private $server; + private ?\Sabre\DAV\Server $server = null; /** @var FutureFile */ private $sourceNode; diff --git a/apps/dav/lib/Upload/FutureFile.php b/apps/dav/lib/Upload/FutureFile.php index 2024291e044e..e9e9d70d34e6 100644 --- a/apps/dav/lib/Upload/FutureFile.php +++ b/apps/dav/lib/Upload/FutureFile.php @@ -34,8 +34,7 @@ * @package OCA\DAV\Upload */ class FutureFile implements \Sabre\DAV\IFile { - /** @var Directory */ - private $root; + private \OCA\DAV\Connector\Sabre\Directory $root; /** @var string */ private $name; @@ -99,10 +98,9 @@ public function getETag() { */ public function getSize() { $children = $this->root->getChildren(); - $sizes = \array_map(function ($node) { - /** @var IFile $node */ - return $node->getSize(); - }, $children); + $sizes = \array_map(fn ($node) => + /** @var IFile $node */ + $node->getSize(), $children); return \array_sum($sizes); } diff --git a/apps/dav/lib/Upload/UploadFolder.php b/apps/dav/lib/Upload/UploadFolder.php index 774a84b56ab9..b75706918a3f 100644 --- a/apps/dav/lib/Upload/UploadFolder.php +++ b/apps/dav/lib/Upload/UploadFolder.php @@ -26,7 +26,7 @@ use Sabre\DAV\ICollection; class UploadFolder implements ICollection { - private $node; + private \OCA\DAV\Connector\Sabre\Directory $node; public function __construct(Directory $node) { $this->node = $node; diff --git a/apps/dav/lib/Upload/UploadHome.php b/apps/dav/lib/Upload/UploadHome.php index e96159f55b8d..7b50b0e66a18 100644 --- a/apps/dav/lib/Upload/UploadHome.php +++ b/apps/dav/lib/Upload/UploadHome.php @@ -53,9 +53,7 @@ public function getChild($name) { } public function getChildren() { - return \array_map(function ($node) { - return new UploadFolder($node); - }, $this->impl()->getChildren()); + return \array_map(fn ($node) => new UploadFolder($node), $this->impl()->getChildren()); } public function childExists($name) { diff --git a/apps/dav/tests/unit/AppInfo/ApplicationTest.php b/apps/dav/tests/unit/AppInfo/ApplicationTest.php index 91a4d849b116..b957b4c3e336 100644 --- a/apps/dav/tests/unit/AppInfo/ApplicationTest.php +++ b/apps/dav/tests/unit/AppInfo/ApplicationTest.php @@ -42,23 +42,23 @@ public function test() { // assert service instances in the container are properly setup $s = $c->query(ContactsManager::class); - $this->assertInstanceOf('OCA\DAV\CardDAV\ContactsManager', $s); + $this->assertInstanceOf(\OCA\DAV\CardDAV\ContactsManager::class, $s); $s = $c->query(CardDavBackend::class); - $this->assertInstanceOf('OCA\DAV\CardDAV\CardDavBackend', $s); + $this->assertInstanceOf(\OCA\DAV\CardDAV\CardDavBackend::class, $s); } public function testContactsManagerSetup() { $app = new Application(); $c = $app->getContainer(); $c->registerService(CardDavBackend::class, function ($c) { - $service = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $service = $this->getMockBuilder(\OCA\DAV\CardDAV\CardDavBackend::class)->disableOriginalConstructor()->getMock(); $service->method('getAddressBooksForUser')->willReturn([]); return $service; }); // assert setupContactsProvider() is proper /** @var IManager | \PHPUnit\Framework\MockObject\MockObject $cm */ - $cm = $this->getMockBuilder('OCP\Contacts\IManager')->disableOriginalConstructor()->getMock(); + $cm = $this->getMockBuilder(\OCP\Contacts\IManager::class)->disableOriginalConstructor()->getMock(); $app->setupContactsProvider($cm, 'xxx'); $this->assertTrue(true); } diff --git a/apps/dav/tests/unit/AppInfo/Migrations/Version20170202213905Test.php b/apps/dav/tests/unit/AppInfo/Migrations/Version20170202213905Test.php index 81a1799f2fe7..9d9892d569f4 100644 --- a/apps/dav/tests/unit/AppInfo/Migrations/Version20170202213905Test.php +++ b/apps/dav/tests/unit/AppInfo/Migrations/Version20170202213905Test.php @@ -33,9 +33,7 @@ public function testGetRepairQuery() { $expressionBuilder = $this->createMock(IExpressionBuilder::class); $expressionBuilder->expects($this->any())->method('eq')->will($this->returnArgument(1)); $expressionBuilder->expects($this->any())->method('literal')->will( - $this->returnCallback(function ($arg) { - return \sprintf("'%s'", $arg); - }) + $this->returnCallback(fn ($arg) => \sprintf("'%s'", $arg)) ); $queryBuilder = $this->createMock(IQueryBuilder::class); diff --git a/apps/dav/tests/unit/AppInfo/Migrations/Version20210714123001Test.php b/apps/dav/tests/unit/AppInfo/Migrations/Version20210714123001Test.php index 52c0fe44c6f0..52c5b02fc61e 100644 --- a/apps/dav/tests/unit/AppInfo/Migrations/Version20210714123001Test.php +++ b/apps/dav/tests/unit/AppInfo/Migrations/Version20210714123001Test.php @@ -31,7 +31,7 @@ class Version20210714123001Test extends TestCase { /** @var ISchemaMigration */ - private $migration; + private \OCA\DAV\Migrations\Version20210714123001 $migration; protected function setUp(): void { $this->migration = new Version20210714123001(); diff --git a/apps/dav/tests/unit/Avatars/AvatarHomeTest.php b/apps/dav/tests/unit/Avatars/AvatarHomeTest.php index 6d5233e710e6..c5afd9c9ad43 100644 --- a/apps/dav/tests/unit/Avatars/AvatarHomeTest.php +++ b/apps/dav/tests/unit/Avatars/AvatarHomeTest.php @@ -30,11 +30,10 @@ use Test\TestCase; class AvatarHomeTest extends TestCase { - /** @var AvatarHome */ - private $home; + private \OCA\DAV\Avatars\AvatarHome $home; /** @var IAvatarManager | \PHPUnit\Framework\MockObject\MockObject */ - private $avatarManager; + private \PHPUnit\Framework\MockObject\MockObject $avatarManager; public function setUp(): void { $this->avatarManager = $this->createMock(IAvatarManager::class); diff --git a/apps/dav/tests/unit/BackgroundJob/CleanPropertiesTest.php b/apps/dav/tests/unit/BackgroundJob/CleanPropertiesTest.php index 237127bd848e..ff15fac4925e 100644 --- a/apps/dav/tests/unit/BackgroundJob/CleanPropertiesTest.php +++ b/apps/dav/tests/unit/BackgroundJob/CleanPropertiesTest.php @@ -39,8 +39,7 @@ class CleanPropertiesTest extends TestCase { private $connection; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ private $logger; - /** @var CleanProperties */ - private $cleanProperties; + private \OCA\DAV\BackgroundJob\CleanProperties $cleanProperties; /** @var string */ private $username; diff --git a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php index 585aee4f2011..1964244ad084 100644 --- a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php @@ -102,9 +102,7 @@ public function testCalendarSharing($userCanRead, $userCanWrite, $groupCanRead, $l10n ->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $calendarId = $this->createTestCalendar(); $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); @@ -380,9 +378,7 @@ public function testCalendarQuery($expectedEventsInResult, $propFilters, $compFi 'comp-filters' => $compFilter ]); - $expectedEventsInResult = \array_map(function ($index) use ($events) { - return $events[$index]; - }, $expectedEventsInResult); + $expectedEventsInResult = \array_map(fn ($index) => $events[$index], $expectedEventsInResult); $this->assertEqualsCanonicalizing($expectedEventsInResult, $result); } @@ -610,9 +606,7 @@ public function providesCalDataForGetDenormalizedData() { */ public function testHugeMultiGet() { $calendarId = $this->createTestCalendar(); - $urls = \array_map(function ($number) { - return "url-$number"; - }, \range(0, 2000)); + $urls = \array_map(fn ($number) => "url-$number", \range(0, 2000)); $calendarObjects = $this->backend->getMultipleCalendarObjects($calendarId, $urls); $this->assertEquals([], $calendarObjects); } diff --git a/apps/dav/tests/unit/CalDAV/CalendarTest.php b/apps/dav/tests/unit/CalDAV/CalendarTest.php index 4cdbfe8a517f..8e10c9741e7e 100644 --- a/apps/dav/tests/unit/CalDAV/CalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/CalendarTest.php @@ -33,7 +33,7 @@ class CalendarTest extends TestCase { /** @var IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; public function setUp(): void { parent::setUp(); @@ -42,9 +42,7 @@ public function setUp(): void { $this->l10n ->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); } public function testDelete() { diff --git a/apps/dav/tests/unit/CalDAV/PluginTest.php b/apps/dav/tests/unit/CalDAV/PluginTest.php index 23494384ed6d..abad0ddc6781 100644 --- a/apps/dav/tests/unit/CalDAV/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/PluginTest.php @@ -10,8 +10,7 @@ use Test\TestCase; class PluginTest extends TestCase { - /** @var Plugin */ - private $plugin; + private \OCA\DAV\CalDAV\Plugin $plugin; protected function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php index 7bc54a40a47d..2e0288a94252 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php @@ -40,23 +40,21 @@ class PublicCalendarRootTest extends TestCase { public const UNIT_TEST_USER = 'principals/users/caldav-unit-test'; - /** @var CalDavBackend */ - private $backend; + private \OCA\DAV\CalDAV\CalDavBackend $backend; - /** @var PublicCalendarRoot */ - private $publicCalendarRoot; + private \OCA\DAV\CalDAV\PublicCalendarRoot $publicCalendarRoot; /** @var IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** var IConfig */ protected $config; /** @var Principal */ - private $principal; + private \PHPUnit\Framework\MockObject\MockObject $principal; /** @var GroupPrincipalBackend */ - private $groupPrincipal; + private \PHPUnit\Framework\MockObject\MockObject $groupPrincipal; /** @var ISecureRandom */ private $random; @@ -77,7 +75,7 @@ public function setUp(): void { $this->publicCalendarRoot = new PublicCalendarRoot($this->backend); - $this->l10n = $this->getMockBuilder('\OCP\IL10N') + $this->l10n = $this->getMockBuilder('\\' . \OCP\IL10N::class) ->disableOriginalConstructor()->getMock(); } diff --git a/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php b/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php index 4f7c998ab55c..bf929a770e0e 100644 --- a/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php +++ b/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php @@ -32,28 +32,26 @@ use Test\TestCase; class PluginTest extends TestCase { - /** @var PublishPlugin */ - private $plugin; - /** @var Server */ - private $server; + private \OCA\DAV\CalDAV\Publishing\PublishPlugin $plugin; + private \Sabre\DAV\Server $server; /** @var Calendar | \PHPUnit\Framework\MockObject\MockObject */ - private $book; + private \PHPUnit\Framework\MockObject\MockObject $book; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; public function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder('\OCP\IConfig')-> + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class)-> disableOriginalConstructor()-> getMock(); $this->config->expects($this->any())->method('getSystemValue') ->with($this->equalTo('secret')) ->willReturn('mysecret'); - $this->urlGenerator = $this->getMockBuilder('OCP\IURLGenerator')-> + $this->urlGenerator = $this->getMockBuilder(\OCP\IURLGenerator::class)-> disableOriginalConstructor()-> getMock(); @@ -63,7 +61,7 @@ public function setUp(): void { $root = new SimpleCollection('calendars'); $this->server = new Server($root); /** @var SimpleCollection $node */ - $this->book = $this->getMockBuilder('OCA\DAV\CalDAV\Calendar')-> + $this->book = $this->getMockBuilder(\OCA\DAV\CalDAV\Calendar::class)-> disableOriginalConstructor()-> getMock(); $this->book->method('getName')->willReturn('cal1'); diff --git a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php index c862d8664b9f..35375a0b1480 100644 --- a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php +++ b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php @@ -33,23 +33,22 @@ use Test\TestCase; class AddressBookImplTest extends TestCase { - /** @var AddressBookImpl */ - private $addressBookImpl; + private \OCA\DAV\CardDAV\AddressBookImpl $addressBookImpl; /** @var array */ private $addressBookInfo; /** @var AddressBook | \PHPUnit\Framework\MockObject\MockObject */ - private $addressBook; + private \PHPUnit\Framework\MockObject\MockObject $addressBook; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject */ - private $backend; + private \PHPUnit\Framework\MockObject\MockObject $backend; /** @var VCard | \PHPUnit\Framework\MockObject\MockObject */ - private $vCard; + private \PHPUnit\Framework\MockObject\MockObject $vCard; public function setUp(): void { parent::setUp(); @@ -282,9 +281,7 @@ public function testCreateUid() { // simulate that 'uid0' already exists, so the second uid will be returned $this->backend->expects($this->exactly(2))->method('getContact') ->willReturnCallback( - function ($id, $uid) { - return ($uid === 'uid0.vcf'); - } + fn ($id, $uid) => $uid === 'uid0.vcf' ); $this->assertSame( diff --git a/apps/dav/tests/unit/CardDAV/AddressBookTest.php b/apps/dav/tests/unit/CardDAV/AddressBookTest.php index e89412ea8cb0..8f0662ef1b8b 100644 --- a/apps/dav/tests/unit/CardDAV/AddressBookTest.php +++ b/apps/dav/tests/unit/CardDAV/AddressBookTest.php @@ -30,7 +30,7 @@ class AddressBookTest extends TestCase { public function testDelete() { /** @var \PHPUnit\Framework\MockObject\MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backend = $this->getMockBuilder(\OCA\DAV\CardDAV\CardDavBackend::class)->disableOriginalConstructor()->getMock(); $backend->expects($this->once())->method('updateShares'); $backend->expects($this->any())->method('getShares')->willReturn([ ['href' => 'principal:user2'] @@ -50,7 +50,7 @@ public function testDeleteFromGroup() { $this->expectException(\Sabre\DAV\Exception\Forbidden::class); /** @var \PHPUnit\Framework\MockObject\MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backend = $this->getMockBuilder(\OCA\DAV\CardDAV\CardDavBackend::class)->disableOriginalConstructor()->getMock(); $backend->expects($this->never())->method('updateShares'); $backend->expects($this->any())->method('getShares')->willReturn([ ['href' => 'principal:group2'] @@ -70,7 +70,7 @@ public function testPropPatch() { $this->expectException(\Sabre\DAV\Exception\Forbidden::class); /** @var \PHPUnit\Framework\MockObject\MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backend = $this->getMockBuilder(\OCA\DAV\CardDAV\CardDavBackend::class)->disableOriginalConstructor()->getMock(); $calendarInfo = [ '{http://owncloud.org/ns}owner-principal' => 'user1', 'principaluri' => 'user2', @@ -85,7 +85,7 @@ public function testPropPatch() { */ public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet) { /** @var \PHPUnit\Framework\MockObject\MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backend = $this->getMockBuilder(\OCA\DAV\CardDAV\CardDavBackend::class)->disableOriginalConstructor()->getMock(); $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1); $calendarInfo = [ 'principaluri' => 'user2', diff --git a/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php b/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php index ce17fadf6819..3381503d9fdb 100644 --- a/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php +++ b/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php @@ -31,14 +31,13 @@ use Test\TestCase; class BirthdayServiceTest extends TestCase { - /** @var BirthdayService */ - private $service; + private \OCA\DAV\CalDAV\BirthdayService $service; /** @var CalDavBackend | \PHPUnit\Framework\MockObject\MockObject */ - private $calDav; + private \PHPUnit\Framework\MockObject\MockObject $calDav; /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject */ - private $cardDav; + private \PHPUnit\Framework\MockObject\MockObject $cardDav; /** @var GroupPrincipalBackend | \PHPUnit\Framework\MockObject\MockObject */ - private $groupPrincipalBackend; + private \PHPUnit\Framework\MockObject\MockObject $groupPrincipalBackend; public function setUp(): void { parent::setUp(); @@ -60,7 +59,7 @@ public function testBuildBirthdayFromContact($expectedSummary, $data) { if ($expectedSummary === null) { $this->assertNull($cal); } else { - $this->assertInstanceOf('Sabre\VObject\Component\VCalendar', $cal); + $this->assertInstanceOf(\Sabre\VObject\Component\VCalendar::class, $cal); $this->assertTrue(isset($cal->VEVENT)); $this->assertEquals('FREQ=YEARLY', $cal->VEVENT->RRULE->getValue()); $this->assertEquals($expectedSummary, $cal->VEVENT->SUMMARY->getValue()); diff --git a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php index ab25755ac786..c2bf85933f28 100644 --- a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php +++ b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php @@ -48,19 +48,17 @@ class CardDavBackendTest extends TestCase { private $backend; /** @var Principal | \PHPUnit\Framework\MockObject\MockObject */ - private $principal; + private \PHPUnit\Framework\MockObject\MockObject $principal; /** @var GroupPrincipalBackend | \PHPUnit\Framework\MockObject\MockObject */ - private $groupPrincipal; + private \PHPUnit\Framework\MockObject\MockObject $groupPrincipal; /** @var IDBConnection */ private $db; - /** @var string */ - private $dbCardsTable = 'cards'; + private string $dbCardsTable = 'cards'; - /** @var string */ - private $dbCardsPropertiesTable = 'cards_properties'; + private string $dbCardsPropertiesTable = 'cards_properties'; public const UNIT_TEST_USER = 'principals/users/carddav-unit-test'; public const UNIT_TEST_USER1 = 'principals/users/carddav-unit-test1'; @@ -461,7 +459,7 @@ public function testGetCardId() { 'addressbookid' => $query->createNamedParameter(1), 'carddata' => $query->createNamedParameter(''), 'uri' => $query->createNamedParameter('uri'), - 'lastmodified' => $query->createNamedParameter(4738743), + 'lastmodified' => $query->createNamedParameter(4_738_743), 'etag' => $query->createNamedParameter('etag'), 'size' => $query->createNamedParameter(120) ] @@ -569,7 +567,7 @@ public function testSearch($pattern, $properties, $matchModes, $expected, $limit $found = []; foreach ($result as $r) { foreach ($expected as $exp) { - if ($r['uri'] === $exp[0] && \strpos($r['carddata'], $exp[1]) > 0) { + if ($r['uri'] === $exp[0] && \strpos($r['carddata'], (string) $exp[1]) > 0) { $found[$exp[1]] = true; break; } @@ -613,7 +611,7 @@ public function testGetCardUri() { 'addressbookid' => $query->createNamedParameter(1), 'carddata' => $query->createNamedParameter('carddata', IQueryBuilder::PARAM_LOB), 'uri' => $query->createNamedParameter('uri'), - 'lastmodified' => $query->createNamedParameter(5489543), + 'lastmodified' => $query->createNamedParameter(5_489_543), 'etag' => $query->createNamedParameter('etag'), 'size' => $query->createNamedParameter(120), ] @@ -642,7 +640,7 @@ public function testGetContact() { 'addressbookid' => $query->createNamedParameter($i), 'carddata' => $query->createNamedParameter('carddata' . $i, IQueryBuilder::PARAM_LOB), 'uri' => $query->createNamedParameter('uri' . $i), - 'lastmodified' => $query->createNamedParameter(5489543), + 'lastmodified' => $query->createNamedParameter(5_489_543), 'etag' => $query->createNamedParameter('etag' . $i), 'size' => $query->createNamedParameter(120), ] @@ -654,7 +652,7 @@ public function testGetContact() { $this->assertCount(7, $result); $this->assertSame(0, (int)$result['addressbookid']); $this->assertSame('uri0', $result['uri']); - $this->assertSame(5489543, (int)$result['lastmodified']); + $this->assertSame(5_489_543, (int)$result['lastmodified']); $this->assertSame('etag0', $result['etag']); $this->assertSame(120, (int)$result['size']); @@ -687,9 +685,7 @@ public function testCollectCardProperties() { public function testHugeMultiGet() { $bookId = 1; - $urls = \array_map(function ($number) { - return "url-$number"; - }, \range(0, 2000)); + $urls = \array_map(fn ($number) => "url-$number", \range(0, 2000)); $multipleCards = $this->backend->getMultipleCards($bookId, $urls); $this->assertEquals([], $multipleCards); } diff --git a/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php b/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php index c5cb450bce4e..471b3a0cc856 100644 --- a/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php +++ b/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php @@ -31,11 +31,11 @@ class ContactsManagerTest extends TestCase { public function test() { /** @var IManager | \PHPUnit\Framework\MockObject\MockObject $cm */ - $cm = $this->getMockBuilder('OCP\Contacts\IManager')->disableOriginalConstructor()->getMock(); + $cm = $this->getMockBuilder(\OCP\Contacts\IManager::class)->disableOriginalConstructor()->getMock(); $cm->expects($this->exactly(2))->method('registerAddressBook'); - $urlGenerator = $this->getMockBuilder('OCP\IUrlGenerator')->disableOriginalConstructor()->getMock(); + $urlGenerator = $this->getMockBuilder(\OCP\IUrlGenerator::class)->disableOriginalConstructor()->getMock(); /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject $backEnd */ - $backEnd = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backEnd = $this->getMockBuilder(\OCA\DAV\CardDAV\CardDavBackend::class)->disableOriginalConstructor()->getMock(); $backEnd->method('getAddressBooksForUser')->willReturn([ [] ]); diff --git a/apps/dav/tests/unit/CardDAV/ConverterTest.php b/apps/dav/tests/unit/CardDAV/ConverterTest.php index 93178afbf8b9..846a0e8f6187 100644 --- a/apps/dav/tests/unit/CardDAV/ConverterTest.php +++ b/apps/dav/tests/unit/CardDAV/ConverterTest.php @@ -74,7 +74,7 @@ public function testUpdateOfRemovedElement($expectedVCard, $displayName = null, $converter = new Converter(); $vCard = $converter->createCardFromUser($user); - $user1 = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); + $user1 = $this->getMockBuilder(\OCP\IUser::class)->disableOriginalConstructor()->getMock(); $user1->method('getUID')->willReturn('12345'); $user1->method('getDisplayName')->willReturn(null); $user1->method('getEMailAddress')->willReturn(null); diff --git a/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php b/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php index 1b0d29526eb2..e4977d4f52ca 100644 --- a/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php +++ b/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php @@ -33,29 +33,29 @@ class ImageExportPluginTest extends TestCase { /** @var ResponseInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; /** @var RequestInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var ImageExportPlugin | \PHPUnit\Framework\MockObject\MockObject */ private $plugin; /** @var Server */ - private $server; + private \PHPUnit\Framework\MockObject\MockObject $server; /** @var Tree | \PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; public function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder('Sabre\HTTP\RequestInterface')->getMock(); - $this->response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface')->getMock(); - $this->server = $this->getMockBuilder('Sabre\DAV\Server')->getMock(); - $this->tree = $this->getMockBuilder('Sabre\DAV\Tree')->disableOriginalConstructor()->getMock(); + $this->request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class)->getMock(); + $this->response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class)->getMock(); + $this->server = $this->getMockBuilder(\Sabre\DAV\Server::class)->getMock(); + $this->tree = $this->getMockBuilder(\Sabre\DAV\Tree::class)->disableOriginalConstructor()->getMock(); $this->server->tree = $this->tree; - $this->logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); + $this->logger = $this->getMockBuilder('\\' . \OCP\ILogger::class)->getMock(); - $this->plugin = $this->getMockBuilder('OCA\DAV\CardDAV\ImageExportPlugin') + $this->plugin = $this->getMockBuilder(\OCA\DAV\CardDAV\ImageExportPlugin::class) ->setMethods(['getPhoto']) ->setConstructorArgs([$this->logger]) ->getMock(); @@ -97,7 +97,7 @@ public function testCardWithOrWithoutPhoto($expectedContentType, $getPhotoResult $this->request->expects($this->once())->method('getQueryParameters')->willReturn(['photo' => true]); $this->request->expects($this->once())->method('getPath')->willReturn('/files/welcome.txt'); - $card = $this->getMockBuilder('Sabre\CardDAV\Card')->disableOriginalConstructor()->getMock(); + $card = $this->getMockBuilder(\Sabre\CardDAV\Card::class)->disableOriginalConstructor()->getMock(); $this->tree->expects($this->once())->method('getNodeForPath')->with('/files/welcome.txt')->willReturn($card); $this->plugin->expects($this->once())->method('getPhoto')->willReturn($getPhotoResult); @@ -129,7 +129,7 @@ public function providesCardWithOrWithoutPhoto() { */ public function testGetPhoto($expected, $cardData) { /** @var Card | \PHPUnit\Framework\MockObject\MockObject $card */ - $card = $this->getMockBuilder('Sabre\CardDAV\Card')->disableOriginalConstructor()->getMock(); + $card = $this->getMockBuilder(\Sabre\CardDAV\Card::class)->disableOriginalConstructor()->getMock(); $card->expects($this->once())->method('get')->willReturn($cardData); $this->plugin = new ImageExportPlugin($this->logger); diff --git a/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php b/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php index 5441b43c36b9..d777cd3a2bc2 100644 --- a/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php +++ b/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php @@ -33,28 +33,26 @@ use Test\TestCase; class PluginTest extends TestCase { - /** @var Plugin */ - private $plugin; - /** @var Server */ - private $server; + private \OCA\DAV\DAV\Sharing\Plugin $plugin; + private \Sabre\DAV\Server $server; /** @var IShareable | \PHPUnit\Framework\MockObject\MockObject */ - private $book; + private \PHPUnit\Framework\MockObject\MockObject $book; public function setUp(): void { parent::setUp(); /** @var Auth | \PHPUnit\Framework\MockObject\MockObject $authBackend */ - $authBackend = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Auth')->disableOriginalConstructor()->getMock(); + $authBackend = $this->getMockBuilder(\OCA\DAV\Connector\Sabre\Auth::class)->disableOriginalConstructor()->getMock(); $authBackend->method('isDavAuthenticated')->willReturn(true); /** @var IRequest $request */ - $request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder(\OCP\IRequest::class)->disableOriginalConstructor()->getMock(); $this->plugin = new Plugin($authBackend, $request); $root = new SimpleCollection('root'); $this->server = new \Sabre\DAV\Server($root); /** @var SimpleCollection $node */ - $this->book = $this->getMockBuilder('OCA\DAV\DAV\Sharing\IShareable')->disableOriginalConstructor()->getMock(); + $this->book = $this->getMockBuilder(\OCA\DAV\DAV\Sharing\IShareable::class)->disableOriginalConstructor()->getMock(); $this->book->method('getName')->willReturn('addressbook1.vcf'); $root->addChild($this->book); $this->plugin->initialize($this->server); diff --git a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php index f06e28cf0ada..08772d3994d6 100644 --- a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php +++ b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php @@ -74,8 +74,8 @@ public function testEnsureSystemAddressBookExists() { ->willReturnOnConsecutiveCalls(null, []); /** @var IUserManager $userManager */ - $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); + $userManager = $this->getMockBuilder(\OCP\IUserManager::class)->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder(\OCP\ILogger::class)->disableOriginalConstructor()->getMock(); $ss = new SyncService($backend, $userManager, $logger); $book = $ss->ensureSystemAddressBookExists('principals/users/adam', 'contacts', []); } @@ -83,7 +83,7 @@ public function testEnsureSystemAddressBookExists() { public function testUpdateAndDeleteUser() { /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject $backend */ $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder(\OCP\ILogger::class)->disableOriginalConstructor()->getMock(); $backend->expects($this->once())->method('createCard'); $backend->expects($this->once())->method('updateCard'); @@ -103,10 +103,10 @@ public function testUpdateAndDeleteUser() { ]); /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject $userManager */ - $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); + $userManager = $this->getMockBuilder(\OCP\IUserManager::class)->disableOriginalConstructor()->getMock(); /** @var IUser | \PHPUnit\Framework\MockObject\MockObject $user */ - $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); + $user = $this->getMockBuilder(\OCP\IUser::class)->disableOriginalConstructor()->getMock(); $user->method('getBackendClassName')->willReturn('unittest'); $user->method('getUID')->willReturn('test-user'); @@ -121,8 +121,8 @@ public function testUpdateAndDeleteUser() { } public function testDeleteUserByUidIfUnique() { - $logger = $this->createMock('OCP\ILogger'); - $userManager = $this->createMock('OCP\IUserManager'); + $logger = $this->createMock(\OCP\ILogger::class); + $userManager = $this->createMock(\OCP\IUserManager::class); $backend = $this->createMock(CardDavBackend::class); $backend->method('getAddressBooksByUri')->willReturn([ @@ -149,8 +149,8 @@ public function testDeleteUserByUidIfUnique() { } public function testDeleteUserByUidIfUniqueNoData() { - $logger = $this->createMock('OCP\ILogger'); - $userManager = $this->createMock('OCP\IUserManager'); + $logger = $this->createMock(\OCP\ILogger::class); + $userManager = $this->createMock(\OCP\IUserManager::class); $backend = $this->createMock(CardDavBackend::class); $backend->method('getAddressBooksByUri')->willReturn([ @@ -171,8 +171,8 @@ public function testDeleteUserByUidIfUniqueNoData() { } public function testDeleteUserByUidIfUniqueMultiple() { - $logger = $this->createMock('OCP\ILogger'); - $userManager = $this->createMock('OCP\IUserManager'); + $logger = $this->createMock(\OCP\ILogger::class); + $userManager = $this->createMock(\OCP\IUserManager::class); $backend = $this->createMock(CardDavBackend::class); $backend->method('getAddressBooksByUri')->willReturn([ @@ -223,8 +223,8 @@ private function getBackendMock($createCount, $updateCount, $deleteCount) { * @return SyncService|\PHPUnit\Framework\MockObject\MockObject */ private function getSyncServiceMock($backend, $response) { - $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); + $userManager = $this->getMockBuilder(\OCP\IUserManager::class)->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder(\OCP\ILogger::class)->disableOriginalConstructor()->getMock(); /** @var SyncService | \PHPUnit\Framework\MockObject\MockObject $ss */ $ss = $this->getMockBuilder(SyncService::class) ->setMethods(['ensureSystemAddressBookExists', 'requestSyncReport', 'download']) diff --git a/apps/dav/tests/unit/Command/CleanupChunksTest.php b/apps/dav/tests/unit/Command/CleanupChunksTest.php index ed01aed7189d..4aaf8b9e925e 100644 --- a/apps/dav/tests/unit/Command/CleanupChunksTest.php +++ b/apps/dav/tests/unit/Command/CleanupChunksTest.php @@ -37,8 +37,7 @@ class CleanupChunksTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; public function setUp(): void { parent::setUp(); @@ -98,7 +97,7 @@ public function testCommandWithOptionLocal() { $path = $view->getAbsolutePath('/' . $user->getUID( ) . '/uploads/'. $uploadId); - list($storage) = Filesystem::resolvePath($path); + [$storage] = Filesystem::resolvePath($path); if (!$storage->isLocal()) { $this->markTestSkipped('Test only relevant on local storage'); diff --git a/apps/dav/tests/unit/Connector/PublicAuthTest.php b/apps/dav/tests/unit/Connector/PublicAuthTest.php index b7612a3187d5..87768bd89c82 100644 --- a/apps/dav/tests/unit/Connector/PublicAuthTest.php +++ b/apps/dav/tests/unit/Connector/PublicAuthTest.php @@ -37,13 +37,12 @@ */ class PublicAuthTest extends \Test\TestCase { /** @var ISession|\PHPUnit\Framework\MockObject\MockObject */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $shareManager; - /** @var \OCA\DAV\Connector\PublicAuth */ - private $auth; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; + private \OCA\DAV\Connector\PublicAuth $auth; /** @var string */ private $oldUser; @@ -51,9 +50,9 @@ class PublicAuthTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->session = $this->createMock('\OCP\ISession'); - $this->request = $this->createMock('\OCP\IRequest'); - $this->shareManager = $this->createMock('\OCP\Share\IManager'); + $this->session = $this->createMock('\\' . \OCP\ISession::class); + $this->request = $this->createMock('\\' . \OCP\IRequest::class); + $this->shareManager = $this->createMock('\\' . \OCP\Share\IManager::class); $this->auth = new \OCA\DAV\Connector\PublicAuth( $this->request, @@ -86,7 +85,7 @@ public function testNoShare() { } public function testShareNoPassword() { - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getPassword')->willReturn(null); $this->shareManager->expects($this->once()) @@ -99,7 +98,7 @@ public function testShareNoPassword() { } public function testSharePasswordFancyShareType() { - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(42); @@ -113,7 +112,7 @@ public function testSharePasswordFancyShareType() { } public function testSharePasswordRemote() { - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_REMOTE); @@ -127,7 +126,7 @@ public function testSharePasswordRemote() { } public function testSharePasswordLinkValidPassword() { - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); @@ -147,7 +146,7 @@ public function testSharePasswordLinkValidPassword() { } public function testSharePasswordLinkValidSession() { - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); $share->method('getId')->willReturn('42'); @@ -171,7 +170,7 @@ public function testSharePasswordLinkValidSession() { } public function testSharePasswordLinkInvalidSession() { - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); $share->method('getId')->willReturn('42'); diff --git a/apps/dav/tests/unit/Connector/Sabre/AuthTest.php b/apps/dav/tests/unit/Connector/Sabre/AuthTest.php index 7431e519752d..6b3852e32bcd 100644 --- a/apps/dav/tests/unit/Connector/Sabre/AuthTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/AuthTest.php @@ -51,21 +51,20 @@ */ class AuthTest extends TestCase { /** @var ISession | MockObject */ - private $session; - /** @var Auth */ - private $auth; + private \PHPUnit\Framework\MockObject\MockObject $session; + private \OCA\DAV\Connector\Sabre\Auth $auth; /** @var Session | MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IRequest | MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var Manager | MockObject */ - private $twoFactorManager; + private \PHPUnit\Framework\MockObject\MockObject $twoFactorManager; /** @var AccountModuleManager | MockObject */ - private $accountModuleManager; + private \PHPUnit\Framework\MockObject\MockObject $accountModuleManager; /** * @var IConfig|MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php index 043a3e6d0529..37a57a3c7783 100644 --- a/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php @@ -34,14 +34,13 @@ */ class BlockLegacyClientPluginTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; - /** @var BlockLegacyClientPlugin */ - private $blockLegacyClientVersionPlugin; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin $blockLegacyClientVersionPlugin; public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('\OCP\IConfig'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); $this->blockLegacyClientVersionPlugin = new BlockLegacyClientPlugin($this->config); } @@ -67,7 +66,7 @@ public function testBeforeHandlerException($userAgent) { $this->expectExceptionMessage('Unsupported client version.'); /** @var \Sabre\HTTP\RequestInterface | PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock('\Sabre\HTTP\RequestInterface'); + $request = $this->createMock('\\' . \Sabre\HTTP\RequestInterface::class); $request ->expects($this->once()) ->method('getHeader') @@ -102,7 +101,7 @@ public function newAndAlternateDesktopClientProvider() { */ public function testBeforeHandlerSuccess($userAgent) { /** @var \Sabre\HTTP\RequestInterface | PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock('\Sabre\HTTP\RequestInterface'); + $request = $this->createMock('\\' . \Sabre\HTTP\RequestInterface::class); $request ->expects($this->once()) ->method('getHeader') @@ -120,7 +119,7 @@ public function testBeforeHandlerSuccess($userAgent) { public function testBeforeHandlerNoUserAgent() { /** @var \Sabre\HTTP\RequestInterface | PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock('\Sabre\HTTP\RequestInterface'); + $request = $this->createMock('\\' . \Sabre\HTTP\RequestInterface::class); $request ->expects($this->once()) ->method('getHeader') diff --git a/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php index c4ed5e82be83..9c0a995850e9 100644 --- a/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php @@ -36,12 +36,12 @@ class CommentsPropertiesPluginTest extends \Test\TestCase { public function setUp(): void { parent::setUp(); - $this->commentsManager = $this->createMock('\OCP\Comments\ICommentsManager'); - $this->userSession = $this->createMock('\OCP\IUserSession'); + $this->commentsManager = $this->createMock('\\' . \OCP\Comments\ICommentsManager::class); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); - $this->userFolder = $this->createMock('\OCP\Files\Folder'); + $this->userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + $this->server = $this->getMockBuilder('\\' . \Sabre\DAV\Server::class) ->disableOriginalConstructor() ->getMock(); @@ -50,7 +50,7 @@ public function setUp(): void { } public function testHandleGetPropertiesUser() { - $sabreNode1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $sabreNode1 = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $sabreNode1->expects($this->any()) @@ -58,7 +58,7 @@ public function testHandleGetPropertiesUser() { ->will($this->returnValue(111)); $sabreNode1->expects($this->never()) ->method('getPath'); - $sabreNode2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $sabreNode2 = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $sabreNode2->expects($this->any()) @@ -67,7 +67,7 @@ public function testHandleGetPropertiesUser() { $sabreNode2->expects($this->never()) ->method('getPath'); - $sabreNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + $sabreNode = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->getMock(); $sabreNode->expects($this->any()) @@ -108,7 +108,7 @@ public function testHandleGetPropertiesUser() { // Now test with user $this->userSession->expects($this->any()) ->method('getUser') - ->willReturn($this->createMock('\OCP\IUser')); + ->willReturn($this->createMock('\\' . \OCP\IUser::class)); $this->plugin->handleGetProperties( $propFindRoot, @@ -135,7 +135,7 @@ public function testHandleGetPropertiesUser() { } public function testHandleGetPropertiesUserLoggedOut() { - $sabreNode1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $sabreNode1 = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $sabreNode1->expects($this->any()) @@ -143,7 +143,7 @@ public function testHandleGetPropertiesUserLoggedOut() { ->will($this->returnValue(111)); $sabreNode1->expects($this->never()) ->method('getPath'); - $sabreNode2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $sabreNode2 = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $sabreNode2->expects($this->any()) @@ -152,7 +152,7 @@ public function testHandleGetPropertiesUserLoggedOut() { $sabreNode2->expects($this->never()) ->method('getPath'); - $sabreNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + $sabreNode = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->getMock(); $sabreNode->expects($this->any()) @@ -202,7 +202,7 @@ public function testHandleGetPropertiesUserLoggedOut() { public function nodeProvider() { $mocks = []; - foreach (['\OCA\DAV\Connector\Sabre\File', '\OCA\DAV\Connector\Sabre\Directory', '\Sabre\DAV\INode'] as $class) { + foreach (['\\' . \OCA\DAV\Connector\Sabre\File::class, '\\' . \OCA\DAV\Connector\Sabre\Directory::class, '\\' . \Sabre\DAV\INode::class] as $class) { $mocks[] = $this->getMockBuilder($class) ->disableOriginalConstructor() ->getMock(); @@ -221,7 +221,7 @@ public function nodeProvider() { * @param $expectedSuccessful */ public function testHandleGetPropertiesCorrectNode($node, $expectedSuccessful) { - $propFind = $this->getMockBuilder('\Sabre\DAV\PropFind') + $propFind = $this->getMockBuilder('\\' . \Sabre\DAV\PropFind::class) ->disableOriginalConstructor() ->getMock(); @@ -251,7 +251,7 @@ public function baseUriProvider() { * @param $expectedHref */ public function testGetCommentsLink($baseUri, $fid, $expectedHref) { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $node = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -268,7 +268,7 @@ public function testGetCommentsLink($baseUri, $fid, $expectedHref) { public function userProvider() { return [ - [$this->createMock('\OCP\IUser')], + [$this->createMock('\\' . \OCP\IUser::class)], [null] ]; } @@ -278,7 +278,7 @@ public function userProvider() { * @param $user */ public function testGetUnreadCount($user) { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $node = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -307,7 +307,7 @@ public function testGetUnreadCount($user) { * @param $user */ public function testGetUnreadCountWithZeroUnread($user) { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $node = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) diff --git a/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php index 6fef80722730..4fed59e70d7e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php @@ -35,11 +35,9 @@ * See the COPYING-README file. */ class CopyEtagHeaderPluginTest extends TestCase { - /** @var CopyEtagHeaderPlugin */ - private $plugin; + private \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin $plugin; - /** @var Server */ - private $server; + private \Sabre\DAV\Server $server; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/Connector/Sabre/CorsPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/CorsPluginTest.php index 48daf4fb8194..cf222328a6dd 100644 --- a/apps/dav/tests/unit/Connector/Sabre/CorsPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/CorsPluginTest.php @@ -29,25 +29,19 @@ use Test\TestCase; class CorsPluginTest extends TestCase { - /** - * @var Server - */ - private $server; + private \Sabre\DAV\Server $server; - /** - * @var CorsPlugin - */ - private $plugin; + private \OCA\DAV\Connector\Sabre\CorsPlugin $plugin; /** * @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** * @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php b/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php index f983d21b64c4..52859df85ff5 100644 --- a/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php @@ -70,15 +70,15 @@ public function getRelativePath($path) { */ class DirectoryTest extends \Test\TestCase { /** @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject */ - private $view; + private \PHPUnit\Framework\MockObject\MockObject $view; /** @var \OC\Files\FileInfo | \PHPUnit\Framework\MockObject\MockObject */ - private $info; + private \PHPUnit\Framework\MockObject\MockObject $info; protected function setUp(): void { parent::setUp(); - $this->view = $this->createMock('OC\Files\View', [], [], '', false); - $this->info = $this->createMock('OC\Files\FileInfo', [], [], '', false); + $this->view = $this->createMock(\OC\Files\View::class); + $this->info = $this->createMock(\OC\Files\FileInfo::class); $this->info->expects($this->any()) ->method('isReadable') ->will($this->returnValue(true)); @@ -231,10 +231,10 @@ public function testDeleteFolderThrowsWhenStorageNotAvailable() { } public function testGetChildren() { - $info1 = $this->getMockBuilder('OC\Files\FileInfo') + $info1 = $this->getMockBuilder(\OC\Files\FileInfo::class) ->disableOriginalConstructor() ->getMock(); - $info2 = $this->getMockBuilder('OC\Files\FileInfo') + $info2 = $this->getMockBuilder(\OC\Files\FileInfo::class) ->disableOriginalConstructor() ->getMock(); $info1->expects($this->any()) @@ -274,7 +274,7 @@ public function testGetChildren() { public function testGetChildrenNoPermission() { $this->expectException(\Sabre\DAV\Exception\Forbidden::class); - $info = $this->getMockBuilder('OC\Files\FileInfo') + $info = $this->getMockBuilder(\OC\Files\FileInfo::class) ->disableOriginalConstructor() ->getMock(); $info->expects($this->any()) @@ -290,7 +290,7 @@ public function testGetChildrenNoPermission() { public function testGetChildNoPermission() { $this->expectException(\Sabre\DAV\Exception\NotFound::class); - $info = $this->getMockBuilder('OC\Files\FileInfo') + $info = $this->getMockBuilder(\OC\Files\FileInfo::class) ->disableOriginalConstructor() ->getMock(); $info->expects($this->any()) @@ -330,15 +330,15 @@ public function testGetChildThrowInvalidPath() { } public function testGetQuotaInfoUnlimited() { - $storage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Quota') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Wrapper\Quota::class) ->disableOriginalConstructor() ->getMock(); $storage->expects($this->any()) ->method('instanceOfStorage') ->will($this->returnValueMap([ - '\OCA\Files_Sharing\SharedStorage' => false, - '\OC\Files\Storage\Wrapper\Quota' => false, + '\\' . \OCA\Files_Sharing\SharedStorage::class => false, + '\\' . \OC\Files\Storage\Wrapper\Quota::class => false, ])); $storage->expects($this->never()) @@ -361,15 +361,15 @@ public function testGetQuotaInfoUnlimited() { } public function testGetQuotaInfoSpecific() { - $storage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Quota') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Wrapper\Quota::class) ->disableOriginalConstructor() ->getMock(); $storage->expects($this->any()) ->method('instanceOfStorage') ->will($this->returnValueMap([ - ['\OCA\Files_Sharing\SharedStorage', false], - ['\OC\Files\Storage\Wrapper\Quota', true], + ['\\' . \OCA\Files_Sharing\SharedStorage::class, false], + ['\\' . \OC\Files\Storage\Wrapper\Quota::class, true], ])); $storage->expects($this->once()) diff --git a/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php b/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php index bbddea9db928..747718666019 100644 --- a/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php @@ -32,8 +32,7 @@ * @package OCA\DAV\Tests\unit\Connector\Sabre */ class DummyGetResponsePluginTest extends TestCase { - /** @var DummyGetResponsePlugin */ - private $dummyGetResponsePlugin; + private \OCA\DAV\Connector\Sabre\DummyGetResponsePlugin $dummyGetResponsePlugin; public function setUp(): void { parent::setUp(); @@ -43,7 +42,7 @@ public function setUp(): void { public function testInitialize() { /** @var \Sabre\DAV\Server $server */ - $server = $this->createMock('\Sabre\DAV\Server'); + $server = $this->createMock('\\' . \Sabre\DAV\Server::class); $server ->expects($this->once()) ->method('on') @@ -54,9 +53,9 @@ public function testInitialize() { public function testHttpGet() { /** @var \Sabre\HTTP\RequestInterface $request */ - $request = $this->createMock('\Sabre\HTTP\RequestInterface'); + $request = $this->createMock('\\' . \Sabre\HTTP\RequestInterface::class); /** @var \Sabre\HTTP\ResponseInterface $response */ - $response = $server = $this->createMock('\Sabre\HTTP\ResponseInterface'); + $response = $server = $this->createMock('\\' . \Sabre\HTTP\ResponseInterface::class); $response ->expects($this->once()) ->method('setBody'); diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php index 2b9bab321b15..b7ef2744628a 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php @@ -46,7 +46,7 @@ public function testSerialization() { EOD; $ex = new Forbidden($message, $retry); - $server = $this->createMock('Sabre\DAV\Server'); + $server = $this->createMock(\Sabre\DAV\Server::class); $ex->serialize($server, $error); // assert diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php index 2402e211b015..94b6b0e61b36 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php @@ -46,7 +46,7 @@ public function testSerialization() { EOD; $ex = new InvalidPath($message, $retry); - $server = $this->createMock('Sabre\DAV\Server'); + $server = $this->createMock(\Sabre\DAV\Server::class); $ex->serialize($server, $error); // assert diff --git a/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php index 234c6b32be20..bd5a00b2db69 100644 --- a/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php @@ -47,14 +47,12 @@ public function log($level, $message, array $context = []) { } class ExceptionLoggerPluginTest extends TestCase { - /** @var Server */ - private $server; + private ?\Sabre\DAV\Server $server = null; - /** @var PluginToTest */ - private $plugin; + private ?\OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin $plugin = null; /** @var TestLogger | PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private ?\OCA\DAV\Tests\unit\Connector\Sabre\TestLogger $logger = null; private function init() { $this->server = new Server(); diff --git a/apps/dav/tests/unit/Connector/Sabre/FileTest.php b/apps/dav/tests/unit/Connector/Sabre/FileTest.php index 20c7ec8cb72a..ea884036a817 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FileTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FileTest.php @@ -80,7 +80,7 @@ public function setUp(): void { self::loginAsUser($this->user); - $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class)->getMock(); } public function tearDown(): void { @@ -119,53 +119,53 @@ public function fopenFailuresProvider() { [ // return false null, - '\Sabre\Dav\Exception', + '\\' . \Sabre\Dav\Exception::class, false ], [ new NotPermittedException(), - 'Sabre\DAV\Exception\Forbidden' + \Sabre\DAV\Exception\Forbidden::class ], [ new EntityTooLargeException(), - 'OCA\DAV\Connector\Sabre\Exception\EntityTooLarge' + \OCA\DAV\Connector\Sabre\Exception\EntityTooLarge::class ], [ new InvalidContentException(), - 'OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType' + \OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType::class ], [ new InvalidPathException(), - 'Sabre\DAV\Exception\Forbidden' + \Sabre\DAV\Exception\Forbidden::class ], [ new ForbiddenException('', true), - 'OCA\DAV\Connector\Sabre\Exception\Forbidden' + \OCA\DAV\Connector\Sabre\Exception\Forbidden::class ], [ new LockNotAcquiredException('/test.txt', 1), - 'OCA\DAV\Connector\Sabre\Exception\FileLocked' + \OCA\DAV\Connector\Sabre\Exception\FileLocked::class ], [ new LockedException('/test.txt'), - 'OCA\DAV\Connector\Sabre\Exception\FileLocked' + \OCA\DAV\Connector\Sabre\Exception\FileLocked::class ], [ new GenericEncryptionException(), - 'Sabre\DAV\Exception\ServiceUnavailable' + \Sabre\DAV\Exception\ServiceUnavailable::class ], [ new StorageNotAvailableException(), - 'Sabre\DAV\Exception\ServiceUnavailable' + \Sabre\DAV\Exception\ServiceUnavailable::class ], [ new Exception('Generic sabre exception'), - 'Sabre\DAV\Exception', + \Sabre\DAV\Exception::class, false ], [ new \Exception('Generic exception'), - 'Sabre\DAV\Exception' + \Sabre\DAV\Exception::class ], ]; } @@ -188,9 +188,7 @@ public function testSimplePutFails($thrownException, $expectedException, $checkP $view->expects($this->atLeastOnce()) ->method('resolvePath') ->will($this->returnCallback( - function ($path) use ($storage) { - return [$storage, $path]; - } + fn ($path) => [$storage, $path] )); if ($thrownException !== null) { @@ -264,9 +262,7 @@ public function testFileContentNotAllowedConvertedToForbidden() { ->method('resolvePath') ->will( $this->returnCallback( - function ($path) use ($storage) { - return [$storage, $path]; - } + fn ($path) => [$storage, $path] ) ); @@ -346,13 +342,11 @@ public function testChunkedPutFails($thrownException, $expectedException, $check ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]]) ->getMock(); Filesystem::mount($storage, [], $this->user . '/'); - $view = $this->createMock(View::class, ['getRelativePath', 'resolvePath'], []); + $view = $this->createMock(View::class); $view->expects($this->atLeastOnce()) ->method('resolvePath') ->will($this->returnCallback( - function ($path) use ($storage) { - return [$storage, $path]; - } + fn ($path) => [$storage, $path] )); if ($thrownException !== null) { @@ -882,7 +876,7 @@ public function testPutSingleFileCancelPreHook() { Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_create, - '\Test\HookHelper', + '\\' . \Test\HookHelper::class, 'cancellingCallback' ); @@ -1405,7 +1399,7 @@ private function listPartFiles(View $userView = null, $path = '') { $userView = Filesystem::getView(); } $files = []; - list($storage, $internalPath) = $userView->resolvePath($path); + [$storage, $internalPath] = $userView->resolvePath($path); if ($storage instanceof Local) { $realPath = $storage->getSourcePath($internalPath); $dh = \opendir($realPath); @@ -1600,7 +1594,7 @@ public function testPutTooLongPartFileName() { ->setMethods(['header']) ->getMock(); - list($storage) = $view->resolvePath("/$path"); + [$storage] = $view->resolvePath("/$path"); $usePartFile = $storage->usePartFile(); if ($usePartFile) { diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php index 61b35a748307..0ed18dd210ad 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php @@ -74,27 +74,24 @@ class FilesPluginTest extends TestCase { /** * @var Server | \PHPUnit\Framework\MockObject\MockObject */ - private $server; + private \PHPUnit\Framework\MockObject\MockObject $server; /** * @var Tree | \PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; - /** - * @var FilesPlugin - */ - private $plugin; + private \OCA\DAV\Connector\Sabre\FilesPlugin $plugin; /** * @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** * @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php index 2dda24113852..f14e427f60dd 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php @@ -37,44 +37,43 @@ class FilesReportPluginTest extends \Test\TestCase { /** @var \Sabre\DAV\Server|\PHPUnit\Framework\MockObject\MockObject */ - private $server; + private \PHPUnit\Framework\MockObject\MockObject $server; /** @var \Sabre\DAV\Tree|\PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** @var ISystemTagObjectMapper|\PHPUnit\Framework\MockObject\MockObject */ - private $tagMapper; + private \PHPUnit\Framework\MockObject\MockObject $tagMapper; /** @var ISystemTagManager|\PHPUnit\Framework\MockObject\MockObject */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** @var ITags|\PHPUnit\Framework\MockObject\MockObject */ - private $privateTags; + private \PHPUnit\Framework\MockObject\MockObject $privateTags; /** @var \OCP\IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; - /** @var FilesReportPluginImplementation */ - private $plugin; + private \OCA\DAV\Connector\Sabre\FilesReportPlugin $plugin; /** @var View|\PHPUnit\Framework\MockObject\MockObject **/ - private $view; + private \OC\Files\View $view; /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject **/ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var Folder|\PHPUnit\Framework\MockObject\MockObject **/ - private $userFolder; + private \PHPUnit\Framework\MockObject\MockObject $userFolder; public function setUp(): void { parent::setUp(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + $this->tree = $this->getMockBuilder('\\' . \Sabre\DAV\Tree::class) ->disableOriginalConstructor() ->getMock(); $this->view = new View(); - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + $this->server = $this->getMockBuilder('\\' . \Sabre\DAV\Server::class) ->setConstructorArgs([$this->tree]) ->setMethods(['getRequestUri', 'getBaseUri', 'generateMultiStatus']) ->getMock(); @@ -83,25 +82,25 @@ public function setUp(): void { ->method('getBaseUri') ->will($this->returnValue('http://example.com/owncloud/remote.php/dav')); - $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') + $this->groupManager = $this->getMockBuilder('\\' . \OCP\IGroupManager::class) ->disableOriginalConstructor() ->getMock(); - $this->userFolder = $this->getMockBuilder('\OCP\Files\Folder') + $this->userFolder = $this->getMockBuilder('\\' . \OCP\Files\Folder::class) ->disableOriginalConstructor() ->getMock(); - $this->tagManager = $this->createMock('\OCP\SystemTag\ISystemTagManager'); - $this->tagMapper = $this->createMock('\OCP\SystemTag\ISystemTagObjectMapper'); - $this->userSession = $this->createMock('\OCP\IUserSession'); - $this->privateTags = $this->createMock('\OCP\ITags'); - $privateTagManager = $this->createMock('\OCP\ITagManager'); + $this->tagManager = $this->createMock('\\' . \OCP\SystemTag\ISystemTagManager::class); + $this->tagMapper = $this->createMock('\\' . \OCP\SystemTag\ISystemTagObjectMapper::class); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); + $this->privateTags = $this->createMock('\\' . \OCP\ITags::class); + $privateTagManager = $this->createMock('\\' . \OCP\ITagManager::class); $privateTagManager->expects($this->any()) ->method('load') ->with('files') ->will($this->returnValue($this->privateTags)); - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('testuser')); @@ -136,7 +135,7 @@ public function testOnReportInvalidNode() { $this->tree->expects($this->any()) ->method('getNodeForPath') ->with('/' . $path) - ->will($this->returnValue($this->createMock('\Sabre\DAV\INode'))); + ->will($this->returnValue($this->createMock('\\' . \Sabre\DAV\INode::class))); $this->server->expects($this->any()) ->method('getRequestUri') @@ -152,7 +151,7 @@ public function testOnReportInvalidReportName() { $this->tree->expects($this->any()) ->method('getNodeForPath') ->with('/' . $path) - ->will($this->returnValue($this->createMock('\Sabre\DAV\INode'))); + ->will($this->returnValue($this->createMock('\\' . \Sabre\DAV\INode::class))); $this->server->expects($this->any()) ->method('getRequestUri') @@ -262,14 +261,14 @@ public function testOnReport() { $props1 = $responses[0]; $this->assertEquals('111', $props1[200]['{http://owncloud.org/ns}fileid']); $this->assertNull($props1[404]['{DAV:}getcontentlength']); - $this->assertInstanceOf('\Sabre\DAV\Xml\Property\ResourceType', $props1[200]['{DAV:}resourcetype']); + $this->assertInstanceOf('\\' . \Sabre\DAV\Xml\Property\ResourceType::class, $props1[200]['{DAV:}resourcetype']); $resourceType1 = $props1[200]['{DAV:}resourcetype']->getValue(); $this->assertEquals('{DAV:}collection', $resourceType1[0]); $props2 = $responses[1]; $this->assertEquals('1024', $props2[200]['{DAV:}getcontentlength']); $this->assertEquals('222', $props2[200]['{http://owncloud.org/ns}fileid']); - $this->assertInstanceOf('\Sabre\DAV\Xml\Property\ResourceType', $props2[200]['{DAV:}resourcetype']); + $this->assertInstanceOf('\\' . \Sabre\DAV\Xml\Property\ResourceType::class, $props2[200]['{DAV:}resourcetype']); $this->assertCount(0, $props2[200]['{DAV:}resourcetype']->getValue()); } @@ -350,21 +349,21 @@ public function testOnReportPaginationFiltered() { } public function testFindNodesByFileIdsRoot() { - $filesNode1 = $this->getMockBuilder('\OCP\Files\Folder') + $filesNode1 = $this->getMockBuilder('\\' . \OCP\Files\Folder::class) ->disableOriginalConstructor() ->getMock(); $filesNode1->expects($this->once()) ->method('getName') ->will($this->returnValue('first node')); - $filesNode2 = $this->getMockBuilder('\OCP\Files\File') + $filesNode2 = $this->getMockBuilder('\\' . \OCP\Files\File::class) ->disableOriginalConstructor() ->getMock(); $filesNode2->expects($this->once()) ->method('getName') ->will($this->returnValue('second node')); - $reportTargetNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + $reportTargetNode = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->getMock(); $reportTargetNode->expects($this->any()) @@ -387,35 +386,35 @@ public function testFindNodesByFileIdsRoot() { $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); $this->assertCount(2, $result); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\Directory', $result[0]); + $this->assertInstanceOf('\\' . \OCA\DAV\Connector\Sabre\Directory::class, $result[0]); $this->assertEquals('first node', $result[0]->getName()); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\File', $result[1]); + $this->assertInstanceOf('\\' . \OCA\DAV\Connector\Sabre\File::class, $result[1]); $this->assertEquals('second node', $result[1]->getName()); } public function testFindNodesByFileIdsSubDir() { - $filesNode1 = $this->getMockBuilder('\OCP\Files\Folder') + $filesNode1 = $this->getMockBuilder('\\' . \OCP\Files\Folder::class) ->disableOriginalConstructor() ->getMock(); $filesNode1->expects($this->once()) ->method('getName') ->will($this->returnValue('first node')); - $filesNode2 = $this->getMockBuilder('\OCP\Files\File') + $filesNode2 = $this->getMockBuilder('\\' . \OCP\Files\File::class) ->disableOriginalConstructor() ->getMock(); $filesNode2->expects($this->once()) ->method('getName') ->will($this->returnValue('second node')); - $reportTargetNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + $reportTargetNode = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->getMock(); $reportTargetNode->expects($this->any()) ->method('getPath') ->will($this->returnValue('/sub1/sub2')); - $subNode = $this->getMockBuilder('\OCP\Files\Folder') + $subNode = $this->getMockBuilder('\\' . \OCP\Files\Folder::class) ->disableOriginalConstructor() ->getMock(); @@ -440,9 +439,9 @@ public function testFindNodesByFileIdsSubDir() { $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); $this->assertCount(2, $result); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\Directory', $result[0]); + $this->assertInstanceOf('\\' . \OCA\DAV\Connector\Sabre\Directory::class, $result[0]); $this->assertEquals('first node', $result[0]->getName()); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\File', $result[1]); + $this->assertInstanceOf('\\' . \OCA\DAV\Connector\Sabre\File::class, $result[1]); $this->assertEquals('second node', $result[1]->getName()); } @@ -571,7 +570,7 @@ public function testProcessFilterRulesInvisibleTagAsAdmin() { ->method('isAdmin') ->will($this->returnValue(true)); - $tag1 = $this->createMock('\OCP\SystemTag\ISystemTag'); + $tag1 = $this->createMock('\\' . \OCP\SystemTag\ISystemTag::class); $tag1->expects($this->any()) ->method('getId') ->will($this->returnValue('123')); @@ -579,7 +578,7 @@ public function testProcessFilterRulesInvisibleTagAsAdmin() { ->method('isUserVisible') ->will($this->returnValue(true)); - $tag2 = $this->createMock('\OCP\SystemTag\ISystemTag'); + $tag2 = $this->createMock('\\' . \OCP\SystemTag\ISystemTag::class); $tag2->expects($this->any()) ->method('getId') ->will($this->returnValue('123')); @@ -620,7 +619,7 @@ public function testProcessFilterRulesInvisibleTagAsUser() { ->method('isAdmin') ->will($this->returnValue(false)); - $tag1 = $this->createMock('\OCP\SystemTag\ISystemTag'); + $tag1 = $this->createMock('\\' . \OCP\SystemTag\ISystemTag::class); $tag1->expects($this->any()) ->method('getId') ->will($this->returnValue('123')); @@ -628,7 +627,7 @@ public function testProcessFilterRulesInvisibleTagAsUser() { ->method('isUserVisible') ->will($this->returnValue(true)); - $tag2 = $this->createMock('\OCP\SystemTag\ISystemTag'); + $tag2 = $this->createMock('\\' . \OCP\SystemTag\ISystemTag::class); $tag2->expects($this->any()) ->method('getId') ->will($this->returnValue('123')); @@ -654,7 +653,7 @@ public function testProcessFilterRulesVisibleTagAsUser() { ->method('isAdmin') ->will($this->returnValue(false)); - $tag1 = $this->createMock('\OCP\SystemTag\ISystemTag'); + $tag1 = $this->createMock('\\' . \OCP\SystemTag\ISystemTag::class); $tag1->expects($this->any()) ->method('getId') ->will($this->returnValue('123')); @@ -662,7 +661,7 @@ public function testProcessFilterRulesVisibleTagAsUser() { ->method('isUserVisible') ->will($this->returnValue(true)); - $tag2 = $this->createMock('\OCP\SystemTag\ISystemTag'); + $tag2 = $this->createMock('\\' . \OCP\SystemTag\ISystemTag::class); $tag2->expects($this->any()) ->method('getId') ->will($this->returnValue('123')); diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesSearchReportPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesSearchReportPluginTest.php index bce9f25d51e0..198bd7e662e8 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesSearchReportPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesSearchReportPluginTest.php @@ -34,16 +34,16 @@ class FilesSearchReportPluginTest extends \Test\TestCase { /** @var Server|\PHPUnit\Framework\MockObject\MockObject */ - private $server; + private \PHPUnit\Framework\MockObject\MockObject $server; /** @var Tree|\PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** @var ISearch|\PHPUnit\Framework\MockObject\MockObject */ - private $searchService; + private \PHPUnit\Framework\MockObject\MockObject $searchService; /** @var FilesSearchReportPlugin|\PHPUnit\Framework\MockObject\MockObject */ - private $plugin; + private \OCA\DAV\Connector\Sabre\FilesSearchReportPlugin $plugin; public function setUp(): void { parent::setUp(); @@ -183,25 +183,21 @@ public function testOnReport($properties, $searchInfo) { $node = $this->createMock(Directory::class); $node->method('getPath')->willReturn($nodePath); - $expectedLimit = (isset($searchInfo['limit'])) ? $searchInfo['limit'] : 30; + $expectedLimit = $searchInfo['limit'] ?? 30; $realLimit = \min($expectedLimit, 8); $searchList = $this->getSearchList($searchInfo['pattern'], $realLimit); - $searchListNodePaths = \array_map(function ($path) use ($base) { - return "{$base}{$path}"; - }, $searchList); + $searchListNodePaths = \array_map(fn ($path) => "{$base}{$path}", $searchList); $this->searchService->method('searchPaged') ->with($searchInfo['pattern'], ['files'], 1, $expectedLimit) - ->will($this->returnCallback(function ($pattern, $apps, $page, $limit) use ($searchList) { - return \array_map(function ($key, $value) { - $mock = $this->createMock(ResultFile::class); - $mock->path = $value; - $mock->highlights = ['test value' . $key]; - $mock->score = '3.' . $key; - return $mock; - }, \array_keys($searchList), $searchList); - })); + ->will($this->returnCallback(fn ($pattern, $apps, $page, $limit) => \array_map(function ($key, $value) { + $mock = $this->createMock(ResultFile::class); + $mock->path = $value; + $mock->highlights = ['test value' . $key]; + $mock->score = '3.' . $key; + return $mock; + }, \array_keys($searchList), $searchList))); $this->tree->method('getMultipleNodes') ->with($searchListNodePaths) diff --git a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php index 48fc418794ed..812ab3ab8984 100644 --- a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php @@ -33,14 +33,13 @@ */ class MaintenancePluginTest extends TestCase { /** @var IConfig */ - private $config; - /** @var MaintenancePlugin */ - private $maintenancePlugin; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OCA\DAV\Connector\Sabre\MaintenancePlugin $maintenancePlugin; public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('\OCP\IConfig'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); $this->maintenancePlugin = new MaintenancePlugin($this->config); } diff --git a/apps/dav/tests/unit/Connector/Sabre/NodeTest.php b/apps/dav/tests/unit/Connector/Sabre/NodeTest.php index 5df48573bf73..b73e8958b13e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/NodeTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/NodeTest.php @@ -50,7 +50,7 @@ public function davPermissionsProvider() { * @dataProvider davPermissionsProvider */ public function testDavPermissions($permissions, $type, $shared, $mounted, $expected) { - $info = $this->getMockBuilder('\OC\Files\FileInfo') + $info = $this->getMockBuilder('\\' . \OC\Files\FileInfo::class) ->disableOriginalConstructor() ->setMethods(['getPermissions', 'isShared', 'isMounted', 'getType']) ->getMock(); @@ -66,7 +66,7 @@ public function testDavPermissions($permissions, $type, $shared, $mounted, $expe $info->expects($this->any()) ->method('getType') ->will($this->returnValue($type)); - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); $node = new \OCA\DAV\Connector\Sabre\File($view, $info); $this->assertEquals($expected, $node->getDavPermissions()); @@ -116,13 +116,13 @@ public function sharePermissionsProvider() { * @dataProvider sharePermissionsProvider */ public function testSharePermissions($type, $user, $permissions, $expected) { - $storage = $this->createMock('\OCP\Files\Storage'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); $storage->method('getPermissions')->willReturn($permissions); - $mountpoint = $this->createMock('\OCP\Files\Mount\IMountPoint'); + $mountpoint = $this->createMock('\\' . \OCP\Files\Mount\IMountPoint::class); $mountpoint->method('getMountPoint')->willReturn('myPath'); - $shareManager = $this->getMockBuilder('OCP\Share\IManager')->disableOriginalConstructor()->getMock(); - $share = $this->getMockBuilder('OCP\Share\IShare')->disableOriginalConstructor()->getMock(); + $shareManager = $this->getMockBuilder(\OCP\Share\IManager::class)->disableOriginalConstructor()->getMock(); + $share = $this->getMockBuilder(\OCP\Share\IShare::class)->disableOriginalConstructor()->getMock(); if ($user === null) { $shareManager->expects($this->never())->method('getShareByToken'); @@ -133,7 +133,7 @@ public function testSharePermissions($type, $user, $permissions, $expected) { $share->expects($this->once())->method('getPermissions')->willReturn($permissions); } - $info = $this->getMockBuilder('\OC\Files\FileInfo') + $info = $this->getMockBuilder('\\' . \OC\Files\FileInfo::class) ->disableOriginalConstructor() ->setMethods(['getStorage', 'getType', 'getMountPoint']) ->getMock(); @@ -142,7 +142,7 @@ public function testSharePermissions($type, $user, $permissions, $expected) { $info->method('getType')->willReturn($type); $info->method('getMountPoint')->willReturn($mountpoint); - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); $node = new \OCA\DAV\Connector\Sabre\File($view, $info); self::invokePrivate($node, 'shareManager', [$shareManager]); diff --git a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php index 392dc8077176..daa024d75ad7 100644 --- a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php @@ -140,12 +140,12 @@ public function testGetNodeForPath( $_SERVER['HTTP_OC_CHUNKED'] = true; } - $rootNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + $rootNode = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->getMock(); - $mountManager = $this->createMock('\OC\Files\Mount\Manager'); - $view = $this->createMock('\OC\Files\View'); - $fileInfo = $this->createMock('\OCP\Files\FileInfo'); + $mountManager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); + $view = $this->createMock('\\' . \OC\Files\View::class); + $fileInfo = $this->createMock('\\' . \OCP\Files\FileInfo::class); $fileInfo->expects($this->once()) ->method('getType') ->will($this->returnValue($type)); @@ -258,14 +258,12 @@ public function testGetNodeForPathInvalidPath() { ->getMock(); $view->expects($this->once()) ->method('resolvePath') - ->will($this->returnCallback(function ($path) use ($storage) { - return [$storage, \ltrim($path, '/')]; - })); + ->will($this->returnCallback(fn ($path) => [$storage, \ltrim($path, '/')])); $rootNode = $this->getMockBuilder(Directory::class) ->disableOriginalConstructor() ->getMock(); - $mountManager = $this->createMock('\OC\Files\Mount\Manager'); + $mountManager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); $tree = new ObjectTree(); $tree->init($rootNode, $view, $mountManager); @@ -278,21 +276,19 @@ public function testGetNodeForPathRoot() { $storage = new Temporary([]); - $view = $this->createMock('\OC\Files\View', ['resolvePath']); + $view = $this->createMock('\\' . \OC\Files\View::class); $view->expects($this->any()) ->method('resolvePath') - ->will($this->returnCallback(function ($path) use ($storage) { - return [$storage, \ltrim($path, '/')]; - })); + ->will($this->returnCallback(fn ($path) => [$storage, \ltrim($path, '/')])); - $rootNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + $rootNode = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->getMock(); - $mountManager = $this->createMock('\OC\Files\Mount\Manager'); + $mountManager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); $tree->init($rootNode, $view, $mountManager); - $this->assertInstanceOf('\Sabre\DAV\INode', $tree->getNodeForPath($path)); + $this->assertInstanceOf('\\' . \Sabre\DAV\INode::class, $tree->getNodeForPath($path)); } } diff --git a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php index 7374792ac287..f5f363e57185 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php @@ -31,16 +31,15 @@ class PrincipalTest extends TestCase { /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - /** @var \OCA\DAV\Connector\Sabre\Principal */ - private $connector; + private \PHPUnit\Framework\MockObject\MockObject $userManager; + private \OCA\DAV\Connector\Sabre\Principal $connector; /** @var IGroupManager | \PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; public function setUp(): void { - $this->userManager = $this->getMockBuilder('\OCP\IUserManager') + $this->userManager = $this->getMockBuilder('\\' . \OCP\IUserManager::class) ->disableOriginalConstructor()->getMock(); - $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') + $this->groupManager = $this->getMockBuilder('\\' . \OCP\IGroupManager::class) ->disableOriginalConstructor()->getMock(); $this->connector = new \OCA\DAV\Connector\Sabre\Principal( @@ -56,7 +55,7 @@ public function testGetPrincipalsByPrefixWithoutPrefix() { } public function testGetPrincipalsByPrefixWithUsers() { - $fooUser = $this->getMockBuilder('\OC\User\User') + $fooUser = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); $fooUser ->expects($this->exactly(1)) @@ -70,7 +69,7 @@ public function testGetPrincipalsByPrefixWithUsers() { ->expects($this->exactly(1)) ->method('getEMailAddress') ->will($this->returnValue('')); - $barUser = $this->getMockBuilder('\OC\User\User') + $barUser = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); $barUser ->expects($this->exactly(1)) @@ -113,7 +112,7 @@ public function testGetPrincipalsByPrefixEmpty() { } public function testGetPrincipalsByPathWithoutMail() { - $fooUser = $this->getMockBuilder('\OC\User\User') + $fooUser = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); $fooUser ->expects($this->exactly(1)) @@ -134,7 +133,7 @@ public function testGetPrincipalsByPathWithoutMail() { } public function testGetPrincipalsByPathWithMail() { - $fooUser = $this->getMockBuilder('\OC\User\User') + $fooUser = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); $fooUser ->expects($this->exactly(1)) @@ -171,7 +170,7 @@ public function testGetPrincipalsByPathEmpty() { } public function testGetGroupMemberSet() { - $fooUser = $this->getMockBuilder('\OC\User\User') + $fooUser = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); $fooUser ->expects($this->exactly(1)) @@ -203,9 +202,9 @@ public function testGetGroupMemberSetEmpty() { } public function testGetGroupMembership() { - $fooUser = $this->getMockBuilder('\OC\User\User') + $fooUser = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); - $group = $this->getMockBuilder('\OCP\IGroup') + $group = $this->getMockBuilder('\\' . \OCP\IGroup::class) ->disableOriginalConstructor()->getMock(); $group->expects($this->once()) ->method('getGID') @@ -262,7 +261,7 @@ public function testSearchPrincipals() { } public function testFindByUri() { - $fooUser = $this->getMockBuilder('\OC\User\User') + $fooUser = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); $fooUser ->expects($this->exactly(1)) diff --git a/apps/dav/tests/unit/Connector/Sabre/PublicDavLocksPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/PublicDavLocksPluginTest.php index f48f7404c71a..bbe702e809c0 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PublicDavLocksPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PublicDavLocksPluginTest.php @@ -29,11 +29,10 @@ class PublicDavLocksPluginTest extends TestCase { /** @var BackendInterface */ - private $backendInterface; + private \PHPUnit\Framework\MockObject\MockObject $backendInterface; /** @var callable */ private $matcher; - /** @var PublicDavLocksPlugin */ - private $publicDavLocksPlugin; + private \OCA\DAV\Connector\Sabre\PublicDavLocksPlugin $publicDavLocksPlugin; protected function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php index 1462d5023607..526382ba6f8a 100644 --- a/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php @@ -44,10 +44,10 @@ */ class QuotaPluginTest extends TestCase { /** @var \Sabre\DAV\Server | \PHPUnit\Framework\MockObject\MockObject */ - private $server; + private ?\Sabre\DAV\Server $server = null; /** @var \OCA\DAV\Connector\Sabre\QuotaPlugin | \PHPUnit\Framework\MockObject\MockObject */ - private $plugin; + private ?\PHPUnit\Framework\MockObject\MockObject $plugin = null; private function init($quota, $checkedPath = '') { $view = $this->buildFileViewMock($quota, $checkedPath); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php index 0d0580e9e90f..e542e524ff35 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php @@ -43,7 +43,7 @@ public function testBasicUpload() { $mount->getStorage()->unlink($mount->getInternalPath($internalPath) . '/foo.txt'); // delete just the file // cache entry still exists - $this->assertInstanceOf('\OCP\Files\FileInfo', $view->getFileInfo('foo.txt')); + $this->assertInstanceOf('\\' . \OCP\Files\FileInfo::class, $view->getFileInfo('foo.txt')); $response = $this->request($view, $user, 'pass', 'DELETE', '/foo.txt'); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTest.php index de59c49a203b..768d4468b708 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTest.php @@ -137,9 +137,7 @@ protected function makeRequest(Server $server, Request $request) { protected function getSabreServer(View $view, $user, $password, ExceptionPlugin $exceptionPlugin) { $authBackend = new Auth($user, $password); - $server = $this->serverFactory->createServer('/', 'dummy', $authBackend, function () use ($view) { - return $view; - }); + $server = $this->serverFactory->createServer('/', 'dummy', $authBackend, fn () => $view); $server->addPlugin($exceptionPlugin); return $server; diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php index 568bf4afacc8..62f4bea2b9fa 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php @@ -26,15 +26,9 @@ use Sabre\HTTP\Response; class Sapi { - /** - * @var \Sabre\HTTP\Request - */ - private $request; + private \Sabre\HTTP\Request $request; - /** - * @var \Sabre\HTTP\Response - */ - private $response; + private ?\Sabre\HTTP\Response $response = null; /** * This static method will create a new Request object, based on the diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php index 4f478696e9ef..afa354b1595a 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php @@ -46,7 +46,7 @@ public function testBasicUpload() { $this->assertEquals('asd', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $info); $this->assertEquals(3, $info->getSize()); } @@ -62,7 +62,7 @@ public function testUploadOverWrite() { $this->assertEquals('asd', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $info); $this->assertEquals(3, $info->getSize()); } @@ -115,7 +115,7 @@ public function testChunkedUpload() { $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $info); $this->assertEquals(6, $info->getSize()); } @@ -136,7 +136,7 @@ public function testChunkedUploadOverWrite() { $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $info); $this->assertEquals(6, $info->getSize()); } @@ -158,7 +158,7 @@ public function testChunkedUploadOutOfOrder() { $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $info); $this->assertEquals(6, $info->getSize()); } diff --git a/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php index 25f631de9f6f..59b8b35c4aaf 100644 --- a/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php @@ -27,43 +27,37 @@ class SharesPluginTest extends \Test\TestCase { public const SHARETYPES_PROPERTYNAME = \OCA\DAV\Connector\Sabre\SharesPlugin::SHARETYPES_PROPERTYNAME; - /** - * @var \Sabre\DAV\Server - */ - private $server; + private \Sabre\DAV\Server $server; /** * @var \Sabre\DAV\Tree */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** * @var \OCP\Share\IManager */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** * @var \OCP\Files\Folder */ private $userFolder; - /** - * @var \OCA\DAV\Connector\Sabre\SharesPlugin - */ - private $plugin; + private \OCA\DAV\Connector\Sabre\SharesPlugin $plugin; public function setUp(): void { parent::setUp(); $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + $this->tree = $this->getMockBuilder('\\' . \Sabre\DAV\Tree::class) ->disableOriginalConstructor() ->getMock(); - $this->shareManager = $this->createMock('\OCP\Share\IManager'); - $user = $this->createMock('\OCP\IUser'); + $this->shareManager = $this->createMock('\\' . \OCP\Share\IManager::class); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') ->will($this->returnValue('user1')); - $userSession = $this->createMock('\OCP\IUserSession'); + $userSession = $this->createMock('\\' . \OCP\IUserSession::class); $userSession->expects($this->once()) ->method('getUser') ->will($this->returnValue($user)); @@ -80,7 +74,7 @@ public function setUp(): void { * @dataProvider sharesGetPropertiesDataProvider */ public function testGetProperties($shareTypes) { - $sabreNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + $sabreNode = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Node::class) ->disableOriginalConstructor() ->getMock(); $sabreNode->expects($this->any()) @@ -138,7 +132,7 @@ public function testGetProperties($shareTypes) { * @dataProvider sharesGetPropertiesDataProvider */ public function testPreloadThenGetProperties($shareTypes) { - $sabreNode1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $sabreNode1 = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $sabreNode1->expects($this->any()) @@ -146,7 +140,7 @@ public function testPreloadThenGetProperties($shareTypes) { ->will($this->returnValue(111)); $sabreNode1->expects($this->never()) ->method('getPath'); - $sabreNode2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $sabreNode2 = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $sabreNode2->expects($this->any()) @@ -155,7 +149,7 @@ public function testPreloadThenGetProperties($shareTypes) { $sabreNode2->expects($this->never()) ->method('getPath'); - $sabreNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + $sabreNode = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->getMock(); $sabreNode->expects($this->any()) diff --git a/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php index 606e2c3e3975..71efd1d7756e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php @@ -33,39 +33,33 @@ class TagsPluginTest extends \Test\TestCase { public const FAVORITE_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::FAVORITE_PROPERTYNAME; public const TAG_FAVORITE = \OCA\DAV\Connector\Sabre\TagsPlugin::TAG_FAVORITE; - /** - * @var \Sabre\DAV\Server - */ - private $server; + private \Sabre\DAV\Server $server; /** * @var \Sabre\DAV\Tree */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** * @var \OCP\ITagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var \OCP\ITags */ - private $tagger; + private \PHPUnit\Framework\MockObject\MockObject $tagger; - /** - * @var \OCA\DAV\Connector\Sabre\TagsPlugin - */ - private $plugin; + private \OCA\DAV\Connector\Sabre\TagsPlugin $plugin; public function setUp(): void { parent::setUp(); $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + $this->tree = $this->getMockBuilder('\\' . \Sabre\DAV\Tree::class) ->disableOriginalConstructor() ->getMock(); - $this->tagger = $this->createMock('\OCP\ITags'); - $this->tagManager = $this->createMock('\OCP\ITagManager'); + $this->tagger = $this->createMock('\\' . \OCP\ITags::class); + $this->tagManager = $this->createMock('\\' . \OCP\ITagManager::class); $this->tagManager->expects($this->any()) ->method('load') ->with('files') @@ -78,7 +72,7 @@ public function setUp(): void { * @dataProvider tagsGetPropertiesDataProvider */ public function testGetProperties($tags, $requestedProperties, $expectedProperties) { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + $node = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Node::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -117,13 +111,13 @@ public function testGetProperties($tags, $requestedProperties, $expectedProperti * @dataProvider tagsGetPropertiesDataProvider */ public function testPreloadThenGetProperties($tags, $requestedProperties, $expectedProperties) { - $node1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $node1 = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $node1->expects($this->any()) ->method('getId') ->will($this->returnValue(111)); - $node2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $node2 = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $node2->expects($this->any()) @@ -138,7 +132,7 @@ public function testPreloadThenGetProperties($tags, $requestedProperties, $expec $expectedCallCount = 1; } - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + $node = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -253,7 +247,7 @@ public function tagsGetPropertiesDataProvider() { public function testUpdateTags() { // this test will replace the existing tags "tagremove" with "tag1" and "tag2" // and keep "tagkeep" - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + $node = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Node::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -305,7 +299,7 @@ public function testUpdateTags() { } public function testUpdateTagsFromScratch() { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + $node = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Node::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -354,7 +348,7 @@ public function testUpdateTagsFromScratch() { public function testUpdateFav() { // this test will replace the existing tags "tagremove" with "tag1" and "tag2" // and keep "tagkeep" - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + $node = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\Node::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) diff --git a/apps/dav/tests/unit/Connector/Sabre/ValidateRequestPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/ValidateRequestPluginTest.php index d3703e8a1328..5b0082a6c7ce 100644 --- a/apps/dav/tests/unit/Connector/Sabre/ValidateRequestPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/ValidateRequestPluginTest.php @@ -30,11 +30,9 @@ * @package OCA\DAV\Tests\unit\Connector\Sabre */ class ValidateRequestPluginTest extends TestCase { - /** @var \Sabre\DAV\Server */ - private $server; + private \Sabre\DAV\Server $server; - /** @var ValidateRequestPlugin */ - private $plugin; + private ?\OCA\DAV\Connector\Sabre\ValidateRequestPlugin $plugin = null; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php b/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php index 4e334ad19aad..02fc97a4a6cc 100644 --- a/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php +++ b/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php @@ -33,13 +33,13 @@ class BrowserErrorPagePluginTest extends \Test\TestCase { */ public function test($expectedCode, $exception) { /** @var BrowserErrorPagePlugin | PHPUnit\Framework\MockObject\MockObject $plugin */ - $plugin = $this->getMockBuilder('OCA\DAV\Files\BrowserErrorPagePlugin')->setMethods(['sendResponse', 'generateBody'])->getMock(); + $plugin = $this->getMockBuilder(\OCA\DAV\Files\BrowserErrorPagePlugin::class)->setMethods(['sendResponse', 'generateBody'])->getMock(); $plugin->expects($this->once())->method('generateBody')->willReturn(':boom:'); $plugin->expects($this->once())->method('sendResponse'); /** @var \Sabre\DAV\Server | PHPUnit\Framework\MockObject\MockObject $server */ - $server = $this->getMockBuilder('Sabre\DAV\Server')->disableOriginalConstructor()->getMock(); + $server = $this->getMockBuilder(\Sabre\DAV\Server::class)->disableOriginalConstructor()->getMock(); $server->expects($this->once())->method('on'); - $httpResponse = $this->getMockBuilder('Sabre\HTTP\Response')->disableOriginalConstructor()->getMock(); + $httpResponse = $this->getMockBuilder(\Sabre\HTTP\Response::class)->disableOriginalConstructor()->getMock(); $httpResponse->expects($this->once())->method('addHeaders'); $httpResponse->expects($this->once())->method('setStatus')->with($expectedCode); $httpResponse->expects($this->once())->method('setBody')->with(':boom:'); diff --git a/apps/dav/tests/unit/DAV/CopyPluginTest.php b/apps/dav/tests/unit/DAV/CopyPluginTest.php index f15351672aae..90ff55831ed2 100644 --- a/apps/dav/tests/unit/DAV/CopyPluginTest.php +++ b/apps/dav/tests/unit/DAV/CopyPluginTest.php @@ -37,15 +37,14 @@ class CopyPluginTest extends TestCase { /** @var Server | \PHPUnit\Framework\MockObject\MockObject */ - private $server; - /** @var CopyPlugin */ - private $plugin; + private \PHPUnit\Framework\MockObject\MockObject $server; + private \OCA\DAV\DAV\CopyPlugin $plugin; /** @var Tree | \PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** @var RequestInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var ResponseInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; public function setUp(): void { parent::setUp(); @@ -136,7 +135,7 @@ public function testCopyPluginRethrowForbidden() { ]); // make sure the plugin properly emits beforeBind and afterBind - $this->server->expects($this->once(2)) + $this->server->expects($this->once()) ->method('emit') ->with('beforeBind', ['destination.txt']) ->willReturn(true); diff --git a/apps/dav/tests/unit/DAV/FileCustomPropertiesBackendTest.php b/apps/dav/tests/unit/DAV/FileCustomPropertiesBackendTest.php index f16fdbe95689..ef28cba9b875 100644 --- a/apps/dav/tests/unit/DAV/FileCustomPropertiesBackendTest.php +++ b/apps/dav/tests/unit/DAV/FileCustomPropertiesBackendTest.php @@ -43,38 +43,28 @@ * @package OCA\DAV\Tests\unit\DAV */ class FileCustomPropertiesBackendTest extends \Test\TestCase { - /** - * @var \Sabre\DAV\Server - */ - private $server; + private \Sabre\DAV\Server $server; /** * @var Tree */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; - /** - * @var FileCustomPropertiesBackend - */ - private $backend; + private \OCA\DAV\DAV\FileCustomPropertiesBackend $backend; - /** - * @var FileCustomPropertiesPlugin - */ - private $plugin; + private \OCA\DAV\DAV\FileCustomPropertiesPlugin $plugin; /** * @var \OCP\IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** * @var IRootFolder | \PHPUnit_Framework_MockObject_MockObject Obj$rootFolder */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; - /** @var int */ - private $maxId; + private int $maxId; public function setUp(): void { parent::setUp(); @@ -85,7 +75,7 @@ public function setUp(): void { $userId = self::getUniqueID('testcustompropertiesuser'); - $this->user = $this->createMock('\OCP\IUser'); + $this->user = $this->createMock('\\' . \OCP\IUser::class); $this->user->expects($this->any()) ->method('getUID') ->will($this->returnValue($userId)); @@ -240,7 +230,7 @@ public function testPropFindMissingFileSoftFail() { * Test setting/getting properties */ public function testSetGetPropertiesForFile() { - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + $node = $this->createTestNode('\\' . \OCA\DAV\Connector\Sabre\File::class); $this->tree->expects($this->any()) ->method('getNodeForPath') ->with('/dummypath') @@ -277,9 +267,9 @@ public function testSetGetPropertiesForFile() { * Test getting properties from directory */ public function testGetPropertiesForDirectory() { - $rootNode = $this->createTestNode('\OCA\DAV\Connector\Sabre\Directory'); + $rootNode = $this->createTestNode('\\' . \OCA\DAV\Connector\Sabre\Directory::class); - $nodeSub = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + $nodeSub = $this->getMockBuilder('\\' . \OCA\DAV\Connector\Sabre\File::class) ->disableOriginalConstructor() ->getMock(); $nodeSub->expects($this->any()) diff --git a/apps/dav/tests/unit/DAV/GroupPrincipalTest.php b/apps/dav/tests/unit/DAV/GroupPrincipalTest.php index 8ec270ea9258..bc084955995e 100644 --- a/apps/dav/tests/unit/DAV/GroupPrincipalTest.php +++ b/apps/dav/tests/unit/DAV/GroupPrincipalTest.php @@ -29,10 +29,9 @@ class GroupPrincipalTest extends \Test\TestCase { /** @var IGroupManager | PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; - /** @var GroupPrincipalBackend */ - private $connector; + private \OCA\DAV\DAV\GroupPrincipalBackend $connector; public function setUp(): void { $this->groupManager = $this->getMockBuilder(IGroupManager::class) diff --git a/apps/dav/tests/unit/DAV/HookManagerTest.php b/apps/dav/tests/unit/DAV/HookManagerTest.php index 8f1568339b07..5574a8921a4a 100644 --- a/apps/dav/tests/unit/DAV/HookManagerTest.php +++ b/apps/dav/tests/unit/DAV/HookManagerTest.php @@ -35,19 +35,17 @@ class HookManagerTest extends TestCase { /** @var L10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; public function setUp(): void { parent::setUp(); - $this->l10n = $this->getMockBuilder('OC\L10N\L10N') + $this->l10n = $this->getMockBuilder(\OC\L10N\L10N::class) ->disableOriginalConstructor()->getMock(); $this->l10n ->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); } public function test() { diff --git a/apps/dav/tests/unit/DAV/LazyOpsPluginTest.php b/apps/dav/tests/unit/DAV/LazyOpsPluginTest.php index 9896545973a4..d32467e72ce6 100644 --- a/apps/dav/tests/unit/DAV/LazyOpsPluginTest.php +++ b/apps/dav/tests/unit/DAV/LazyOpsPluginTest.php @@ -36,18 +36,17 @@ use Test\TestCase; class LazyOpsPluginTest extends TestCase { - /** @var LazyOpsPlugin */ - private $plugin; + private \OCA\DAV\DAV\LazyOpsPlugin $plugin; /** @var ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var JobStatusMapper | \PHPUnit\Framework\MockObject\MockObject */ - private $jobStatusMapper; + private \PHPUnit\Framework\MockObject\MockObject $jobStatusMapper; /** @var IShutdownManager | \PHPUnit\Framework\MockObject\MockObject */ - private $shutdownManager; + private \PHPUnit\Framework\MockObject\MockObject $shutdownManager; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/DAV/LockPluginTest.php b/apps/dav/tests/unit/DAV/LockPluginTest.php index 7997468b7c1e..6f502b4f8a52 100644 --- a/apps/dav/tests/unit/DAV/LockPluginTest.php +++ b/apps/dav/tests/unit/DAV/LockPluginTest.php @@ -46,23 +46,22 @@ */ class LockPluginTest extends TestCase { /** @var Server | \PHPUnit\Framework\MockObject\MockObject */ - private $server; - /** @var LockPlugin */ - private $plugin; + private \PHPUnit\Framework\MockObject\MockObject $server; + private \OCA\DAV\Connector\Sabre\LockPlugin $plugin; /** @var Tree | \PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** @var LockMapper | \PHPUnit\Framework\MockObject\MockObject */ - private $lockMapper; + private \PHPUnit\Framework\MockObject\MockObject $lockMapper; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** * @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** * @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/DAV/MiscCustomPropertiesBackendTest.php b/apps/dav/tests/unit/DAV/MiscCustomPropertiesBackendTest.php index 33cb03e11962..92cb42ea2fc3 100644 --- a/apps/dav/tests/unit/DAV/MiscCustomPropertiesBackendTest.php +++ b/apps/dav/tests/unit/DAV/MiscCustomPropertiesBackendTest.php @@ -35,33 +35,26 @@ * @package OCA\DAV\Tests\unit\DAV */ class MiscCustomPropertiesBackendTest extends \Test\TestCase { - /** - * @var \Sabre\DAV\Server - */ - private $server; + private \Sabre\DAV\Server $server; /** * @var \Sabre\DAV\Tree */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; - /** - * @var MiscCustomPropertiesBackend - */ - private $plugin; + private \OCA\DAV\DAV\MiscCustomPropertiesBackend $plugin; /** * @var \OCP\IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; - /** @var int */ - private $maxId; + private int $maxId; public function setUp(): void { parent::setUp(); $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + $this->tree = $this->getMockBuilder('\\' . \Sabre\DAV\Tree::class) ->disableOriginalConstructor() ->getMock(); diff --git a/apps/dav/tests/unit/DAV/Sharing/PluginTest.php b/apps/dav/tests/unit/DAV/Sharing/PluginTest.php index 2a0e57fb7a5e..1ebe86942356 100644 --- a/apps/dav/tests/unit/DAV/Sharing/PluginTest.php +++ b/apps/dav/tests/unit/DAV/Sharing/PluginTest.php @@ -33,28 +33,26 @@ use Test\TestCase; class PluginTest extends TestCase { - /** @var Plugin */ - private $plugin; - /** @var Server */ - private $server; + private \OCA\DAV\DAV\Sharing\Plugin $plugin; + private \Sabre\DAV\Server $server; /** @var IShareable | \PHPUnit\Framework\MockObject\MockObject */ - private $book; + private \PHPUnit\Framework\MockObject\MockObject $book; public function setUp(): void { parent::setUp(); /** @var Auth | \PHPUnit\Framework\MockObject\MockObject $authBackend */ - $authBackend = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Auth')->disableOriginalConstructor()->getMock(); + $authBackend = $this->getMockBuilder(\OCA\DAV\Connector\Sabre\Auth::class)->disableOriginalConstructor()->getMock(); $authBackend->method('isDavAuthenticated')->willReturn(true); /** @var IRequest $request */ - $request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); + $request = $this->getMockBuilder(\OCP\IRequest::class)->disableOriginalConstructor()->getMock(); $this->plugin = new Plugin($authBackend, $request); $root = new SimpleCollection('root'); $this->server = new \Sabre\DAV\Server($root); /** @var SimpleCollection $node */ - $this->book = $this->getMockBuilder('OCA\DAV\DAV\Sharing\IShareable')-> + $this->book = $this->getMockBuilder(\OCA\DAV\DAV\Sharing\IShareable::class)-> disableOriginalConstructor()-> getMock(); $this->book->method('getName')->willReturn('addressbook1.vcf'); diff --git a/apps/dav/tests/unit/DAV/ViewOnlyPluginTest.php b/apps/dav/tests/unit/DAV/ViewOnlyPluginTest.php index 4de9905a6695..4176e885ed33 100644 --- a/apps/dav/tests/unit/DAV/ViewOnlyPluginTest.php +++ b/apps/dav/tests/unit/DAV/ViewOnlyPluginTest.php @@ -35,12 +35,11 @@ use OCA\DAV\Connector\Sabre\Exception\Forbidden; class ViewOnlyPluginTest extends TestCase { - /** @var ViewOnlyPlugin */ - private $plugin; + private \OCA\DAV\DAV\ViewOnlyPlugin $plugin; /** @var Tree | \PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** @var RequestInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; public function setUp(): void { $this->plugin = new ViewOnlyPlugin( diff --git a/apps/dav/tests/unit/Files/FileLocksBackendTest.php b/apps/dav/tests/unit/Files/FileLocksBackendTest.php index 9bafdafce7c5..f5357d2deec4 100644 --- a/apps/dav/tests/unit/Files/FileLocksBackendTest.php +++ b/apps/dav/tests/unit/Files/FileLocksBackendTest.php @@ -48,15 +48,14 @@ interface IPersistentLockingStorageTest extends IPersistentLockingStorage, IStor } class FileLocksBackendTest extends TestCase { - public const CREATION_TIME = 164419200; - public const CURRENT_TIME = 164419800; + public const CREATION_TIME = 164_419_200; + public const CURRENT_TIME = 164_419_800; - /** @var FileLocksBackend */ - private $plugin; + private \OCA\DAV\Files\FileLocksBackend $plugin; /** @var Tree | \PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** @var IPersistentLockingStorage | IStorage | \PHPUnit\Framework\MockObject\MockObject */ - private $storageOfFileToBeLocked; + private \PHPUnit\Framework\MockObject\MockObject $storageOfFileToBeLocked; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/Files/FilesHomeTest.php b/apps/dav/tests/unit/Files/FilesHomeTest.php index 7855d3cb1daf..10e1c63e66da 100644 --- a/apps/dav/tests/unit/Files/FilesHomeTest.php +++ b/apps/dav/tests/unit/Files/FilesHomeTest.php @@ -29,12 +29,11 @@ use Test\TestCase; class FilesHomeTest extends TestCase { - /** @var FilesHome */ - private $filesHome; + private \OCA\DAV\Files\FilesHome $filesHome; /** @var Directory | \PHPUnit\Framework\MockObject\MockObject */ - private $rootNode; + private \PHPUnit\Framework\MockObject\MockObject $rootNode; /** @var View | \PHPUnit\Framework\MockObject\MockObject */ - private $view; + private \PHPUnit\Framework\MockObject\MockObject $view; protected function setUp(): void { $this->view = $this->createMock(View::class); diff --git a/apps/dav/tests/unit/Files/PreviewPluginTest.php b/apps/dav/tests/unit/Files/PreviewPluginTest.php index 8e54ea39b20e..3942e8807402 100644 --- a/apps/dav/tests/unit/Files/PreviewPluginTest.php +++ b/apps/dav/tests/unit/Files/PreviewPluginTest.php @@ -45,15 +45,14 @@ class PreviewPluginTest extends TestCase { /** @var RequestInterface | MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IPreviewNode | MockObject */ - private $previewNode; + private \PHPUnit\Framework\MockObject\MockObject $previewNode; /** @var IPreview | MockObject */ - private $previewManager; - /** @var PreviewPlugin */ - private $plugin; + private \PHPUnit\Framework\MockObject\MockObject $previewManager; + private ?\OCA\DAV\Files\PreviewPlugin $plugin = null; /** @var ResponseInterface| MockObject */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; public function setUp(): void { parent::setUp(); @@ -73,7 +72,7 @@ public function setUp(): void { private function initPlugin(): void { /** @var ITimeFactory | MockObject $timeFactory */ $timeFactory = $this->createMock(ITimeFactory::class); - $timeFactory->method('getTime')->willReturn(1234567); + $timeFactory->method('getTime')->willReturn(1_234_567); $this->plugin = new PreviewPlugin($timeFactory, $this->previewManager); @@ -188,7 +187,7 @@ public function testPreviewCreatesImage(): void { ['Content-Type', 'application/octet-stream'], ['Content-Disposition', 'attachment'], ['Cache-Control', 'max-age=86400, must-revalidate'], - ['Expires', \gmdate('D, d M Y H:i:s', 1234567 + 86400) . ' GMT'] + ['Expires', \gmdate('D, d M Y H:i:s', 1_234_567 + 86400) . ' GMT'] ); $this->assertFalse($this->plugin->httpGet($this->request, $this->response)); diff --git a/apps/dav/tests/unit/Files/PublicFiles/PublicSharingAuthTest.php b/apps/dav/tests/unit/Files/PublicFiles/PublicSharingAuthTest.php index 6d9af364230c..e0c134af5921 100644 --- a/apps/dav/tests/unit/Files/PublicFiles/PublicSharingAuthTest.php +++ b/apps/dav/tests/unit/Files/PublicFiles/PublicSharingAuthTest.php @@ -41,9 +41,7 @@ public function testCheck($expectedResult, $shareNode, $authHeader = null) { $server = $this->createMock(Server::class); $server->tree = $tree; $manager = $this->createMock(IManager::class); - $manager->method('checkPassword')->willReturnCallback(static function ($share, $password) { - return $share->getPassword() === $password; - }); + $manager->method('checkPassword')->willReturnCallback(static fn ($share, $password) => $share->getPassword() === $password); $tree->method('getNodeForPath')->willReturn($shareNode); $auth = new PublicSharingAuth($server, $manager); diff --git a/apps/dav/tests/unit/Files/Sharing/PublicLinkEventsPluginTest.php b/apps/dav/tests/unit/Files/Sharing/PublicLinkEventsPluginTest.php index 3fe003d966e5..1a1af0224837 100644 --- a/apps/dav/tests/unit/Files/Sharing/PublicLinkEventsPluginTest.php +++ b/apps/dav/tests/unit/Files/Sharing/PublicLinkEventsPluginTest.php @@ -30,11 +30,10 @@ class PublicLinkEventsPluginTest extends TestCase { /** @var EventDispatcherInterface */ - private $dispatcher; + private \PHPUnit\Framework\MockObject\MockObject $dispatcher; /** @var Server */ - private $server; - /** @var PublicLinkEventsPlugin */ - private $publicLinkEventsPlugin; + private \PHPUnit\Framework\MockObject\MockObject $server; + private \OCA\DAV\Files\Sharing\PublicLinkEventsPlugin $publicLinkEventsPlugin; protected function setUp(): void { $this->dispatcher = $this->createMock(EventDispatcherInterface::class); diff --git a/apps/dav/tests/unit/JobStatus/Entity/JobStatusMapperTest.php b/apps/dav/tests/unit/JobStatus/Entity/JobStatusMapperTest.php index 382f254fe2a2..ec3b040a37c9 100644 --- a/apps/dav/tests/unit/JobStatus/Entity/JobStatusMapperTest.php +++ b/apps/dav/tests/unit/JobStatus/Entity/JobStatusMapperTest.php @@ -34,12 +34,10 @@ * @group DB */ class JobStatusMapperTest extends TestCase { - /** @var JobStatusMapper */ - private $mapper; + private \OCA\DAV\JobStatus\Entity\JobStatusMapper $mapper; /** @var IDBConnection */ private $database; - /** @var JobStatus */ - private $testJobStatus; + private \OCA\DAV\JobStatus\Entity\JobStatus $testJobStatus; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/JobStatus/JobStatusTest.php b/apps/dav/tests/unit/JobStatus/JobStatusTest.php index 67e275ae3e6d..009c6955c393 100644 --- a/apps/dav/tests/unit/JobStatus/JobStatusTest.php +++ b/apps/dav/tests/unit/JobStatus/JobStatusTest.php @@ -32,12 +32,10 @@ * @package OCA\DAV\Tests\Unit\JobStatus */ class JobStatusTest extends TestCase { - /** @var JobStatus */ - private $jobStatus; - /** @var JobStatusEntity */ - private $jobStatusEntity; + private \OCA\DAV\JobStatus\JobStatus $jobStatus; + private \OCA\DAV\JobStatus\Entity\JobStatus $jobStatusEntity; /** @var JobStatusMapper | \PHPUnit\Framework\MockObject\MockObject */ - private $mapper; + private \PHPUnit\Framework\MockObject\MockObject $mapper; protected function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/Meta/MetaPluginTest.php b/apps/dav/tests/unit/Meta/MetaPluginTest.php index 0ded1885c2d6..eb308973bf37 100644 --- a/apps/dav/tests/unit/Meta/MetaPluginTest.php +++ b/apps/dav/tests/unit/Meta/MetaPluginTest.php @@ -33,20 +33,19 @@ use Test\TestCase; class MetaPluginTest extends TestCase { - /** @var MetaPlugin */ - private $plugin; + private \OCA\DAV\Meta\MetaPlugin $plugin; /** * @var IRootFolder | MockObject */ - private $rootfolder; + private \PHPUnit\Framework\MockObject\MockObject $rootfolder; /** * @var IUserSession | MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** * @var Server | MockObject */ - private $server; + private \PHPUnit\Framework\MockObject\MockObject $server; public function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/ServerTest.php b/apps/dav/tests/unit/ServerTest.php index 3a0219dc050d..3a6175338c0f 100644 --- a/apps/dav/tests/unit/ServerTest.php +++ b/apps/dav/tests/unit/ServerTest.php @@ -54,7 +54,7 @@ public function providesUris() { 'principals' => ['principals/users/admin', ['caldav', 'oc-resource-sharing', 'carddav']], 'calendars' => ['calendars/admin', ['caldav', 'oc-resource-sharing']], 'addressbooks' => ['addressbooks/admin', ['carddav', 'oc-resource-sharing']], - 'files' => ['files/admin', ['OCA\DAV\DAV\ViewOnlyPlugin']] + 'files' => ['files/admin', [\OCA\DAV\DAV\ViewOnlyPlugin::class]] ]; } } diff --git a/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php b/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php index 664dbe50f594..8b069b6ce3dc 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php @@ -31,24 +31,24 @@ class SystemTagMappingNodeTest extends \Test\TestCase { /** * @var \OCP\SystemTag\ISystemTagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var \OCP\SystemTag\ISystemTagObjectMapper */ - private $tagMapper; + private \PHPUnit\Framework\MockObject\MockObject $tagMapper; /** * @var \OCP\IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->createMock('\OCP\SystemTag\ISystemTagManager'); - $this->tagMapper = $this->createMock('\OCP\SystemTag\ISystemTagObjectMapper'); - $this->user = $this->createMock('\OCP\IUser'); + $this->tagManager = $this->createMock('\\' . \OCP\SystemTag\ISystemTagManager::class); + $this->tagMapper = $this->createMock('\\' . \OCP\SystemTag\ISystemTagObjectMapper::class); + $this->user = $this->createMock('\\' . \OCP\IUser::class); } public function getMappingNode($tag = null) { @@ -100,12 +100,12 @@ public function tagNodeDeleteProviderPermissionException() { [ // cannot unassign invisible tag new SystemTag(1, 'Original', false, true), - 'Sabre\DAV\Exception\NotFound', + \Sabre\DAV\Exception\NotFound::class, ], [ // cannot unassign non-assignable tag new SystemTag(1, 'Original', true, false), - 'Sabre\DAV\Exception\Forbidden', + \Sabre\DAV\Exception\Forbidden::class, ], ]; } diff --git a/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php b/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php index 27f62824b972..23937e08935c 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php @@ -32,18 +32,18 @@ class SystemTagNodeTest extends \Test\TestCase { /** * @var \OCP\SystemTag\ISystemTagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var \OCP\IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->createMock('\OCP\SystemTag\ISystemTagManager'); - $this->user = $this->createMock('\OCP\IUser'); + $this->tagManager = $this->createMock('\\' . \OCP\SystemTag\ISystemTagManager::class); + $this->user = $this->createMock('\\' . \OCP\IUser::class); } protected function getTagNode($isAdmin = true, $tag = null) { @@ -130,37 +130,37 @@ public function tagNodeProviderPermissionException() { // changing permissions not allowed new SystemTag(1, 'Original', true, true), ['Original', false, true], - 'Sabre\DAV\Exception\Forbidden', + \Sabre\DAV\Exception\Forbidden::class, ], [ // changing permissions not allowed new SystemTag(1, 'Original', true, true), ['Original', true, false], - 'Sabre\DAV\Exception\Forbidden', + \Sabre\DAV\Exception\Forbidden::class, ], [ // changing permissions not allowed new SystemTag(1, 'Original', true, true), ['Original', false, false], - 'Sabre\DAV\Exception\Forbidden', + \Sabre\DAV\Exception\Forbidden::class, ], [ // changing non-assignable not allowed new SystemTag(1, 'Original', true, false), ['Rename', true, false], - 'Sabre\DAV\Exception\Forbidden', + \Sabre\DAV\Exception\Forbidden::class, ], [ // changing non-assignable not allowed new SystemTag(1, 'Original', true, false), ['Original', true, true], - 'Sabre\DAV\Exception\Forbidden', + \Sabre\DAV\Exception\Forbidden::class, ], [ // invisible tag does not exist new SystemTag(1, 'Original', false, false), ['Rename', false, false], - 'Sabre\DAV\Exception\NotFound', + \Sabre\DAV\Exception\NotFound::class, ], ]; } @@ -281,12 +281,12 @@ public function tagNodeDeleteProviderPermissionException() { [ // cannot delete invisible tag new SystemTag(1, 'Original', false, true), - 'Sabre\DAV\Exception\NotFound', + \Sabre\DAV\Exception\NotFound::class, ], [ // cannot delete non-assignable tag new SystemTag(1, 'Original', true, false), - 'Sabre\DAV\Exception\Forbidden', + \Sabre\DAV\Exception\Forbidden::class, ], ]; } diff --git a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php index b1acf989c3ef..c6fb9b30dfa0 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php @@ -46,53 +46,47 @@ class SystemTagPluginTest extends \Test\TestCase { public const USEREDITABLE_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::USEREDITABLE_PROPERTYNAME; public const WHITELISTEDINGROUP = \OCA\DAV\SystemTag\SystemTagPlugin::WHITELISTEDINGROUP; - /** - * @var \Sabre\DAV\Server - */ - private $server; + private \Sabre\DAV\Server $server; /** * @var \Sabre\DAV\Tree */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; /** * @var \OCP\SystemTag\ISystemTagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var IGroupManager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** * @var IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** * @var IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; - /** - * @var \OCA\DAV\SystemTag\SystemTagPlugin - */ - private $plugin; + private \OCA\DAV\SystemTag\SystemTagPlugin $plugin; public function setUp(): void { parent::setUp(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + $this->tree = $this->getMockBuilder('\\' . \Sabre\DAV\Tree::class) ->disableOriginalConstructor() ->getMock(); $this->server = new \Sabre\DAV\Server($this->tree); - $this->tagManager = $this->createMock('\OCP\SystemTag\ISystemTagManager'); - $this->groupManager = $this->createMock('\OCP\IGroupManager'); - $this->user = $this->createMock('\OCP\IUser'); - $this->userSession = $this->createMock('\OCP\IUserSession'); + $this->tagManager = $this->createMock('\\' . \OCP\SystemTag\ISystemTagManager::class); + $this->groupManager = $this->createMock('\\' . \OCP\IGroupManager::class); + $this->user = $this->createMock('\\' . \OCP\IUser::class); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); $this->userSession ->expects($this->any()) ->method('getUser') @@ -193,7 +187,7 @@ public function testGetProperties(ISystemTag $systemTag, $groups, $requestedProp ->with('admin') ->willReturn(true); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagNode::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -249,7 +243,7 @@ public function testGetPropertiesForbidden() { ->with('admin') ->willReturn(false); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagNode::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -284,7 +278,7 @@ public function testUpdatePropertiesAdmin() { ->with('admin') ->willReturn(true); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagNode::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -345,7 +339,7 @@ public function testUpdatePropertiesForbidden() { ->with('admin') ->willReturn(false); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagNode::class) ->disableOriginalConstructor() ->getMock(); $node->expects($this->any()) @@ -408,9 +402,9 @@ public function testCreateNotAssignableTagAsRegularUser($userVisible, $userAssig if (!empty($groups)) { $requestData['groups'] = $groups; } - $requestData = \json_encode($requestData); + $requestData = \json_encode($requestData, JSON_THROW_ON_ERROR); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagsByIdCollection::class) ->disableOriginalConstructor() ->getMock(); $this->tagManager->expects($this->never()) @@ -423,10 +417,10 @@ public function testCreateNotAssignableTagAsRegularUser($userVisible, $userAssig ->with('/systemtags') ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -504,7 +498,7 @@ public function testCreateTagInByIdCollectionAsRegularUser() { 'userEditable' => true ]); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagsByIdCollection::class) ->disableOriginalConstructor() ->getMock(); $this->tagManager->expects($this->once()) @@ -517,10 +511,10 @@ public function testCreateTagInByIdCollectionAsRegularUser() { ->with('/systemtags') ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -579,9 +573,9 @@ public function testCreateTagInByIdCollection($userVisible, $userAssignable, $gr if (!empty($groups)) { $requestData['groups'] = $groups; } - $requestData = \json_encode($requestData); + $requestData = \json_encode($requestData, JSON_THROW_ON_ERROR); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagsByIdCollection::class) ->disableOriginalConstructor() ->getMock(); $this->tagManager->expects($this->once()) @@ -604,10 +598,10 @@ public function testCreateTagInByIdCollection($userVisible, $userAssignable, $gr ->with('/systemtags') ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -637,8 +631,8 @@ public function testCreateTagInByIdCollection($userVisible, $userAssignable, $gr public function nodeClassProvider() { return [ - ['\OCA\DAV\SystemTag\SystemTagsByIdCollection'], - ['\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection'], + ['\\' . \OCA\DAV\SystemTag\SystemTagsByIdCollection::class], + ['\\' . \OCA\DAV\SystemTag\SystemTagsObjectMappingCollection::class], ]; } @@ -660,7 +654,7 @@ public function testCreateTagInMappingCollection() { 'userAssignable' => false, ]); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagsObjectMappingCollection::class) ->disableOriginalConstructor() ->getMock(); @@ -678,10 +672,10 @@ public function testCreateTagInMappingCollection() { ->method('createFile') ->with(1); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -714,7 +708,7 @@ public function testCreateTagInMappingCollection() { public function testCreateTagToUnknownNode() { $this->expectException(\Sabre\DAV\Exception\NotFound::class); - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection') + $node = $this->getMockBuilder('\\' . \OCA\DAV\SystemTag\SystemTagsObjectMappingCollection::class) ->disableOriginalConstructor() ->getMock(); @@ -728,10 +722,10 @@ public function testCreateTagToUnknownNode() { $node->expects($this->never()) ->method('createFile'); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -776,10 +770,10 @@ public function testCreateTagConflict($nodeClass) { ->with('/systemtags') ->will($this->returnValue($node)); - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + $request = $this->getMockBuilder(\Sabre\HTTP\RequestInterface::class) ->disableOriginalConstructor() ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + $response = $this->getMockBuilder(\Sabre\HTTP\ResponseInterface::class) ->disableOriginalConstructor() ->getMock(); diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php index 0b5dd3c4a42b..14f59c2825d8 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php @@ -31,29 +31,26 @@ class SystemTagsByIdCollectionTest extends \Test\TestCase { /** * @var \OCP\SystemTag\ISystemTagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; - /** - * @var \OCP\IUser - */ - private $user; + private ?\PHPUnit\Framework\MockObject\MockObject $user = null; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->createMock('\OCP\SystemTag\ISystemTagManager'); + $this->tagManager = $this->createMock('\\' . \OCP\SystemTag\ISystemTagManager::class); } public function getNode($isAdmin = true) { - $this->user = $this->createMock('\OCP\IUser'); + $this->user = $this->createMock('\\' . \OCP\IUser::class); $this->user->expects($this->any()) ->method('getUID') ->will($this->returnValue('testuser')); - $userSession = $this->createMock('\OCP\IUserSession'); + $userSession = $this->createMock('\\' . \OCP\IUserSession::class); $userSession->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $groupManager = $this->createMock('\OCP\IGroupManager'); + $groupManager = $this->createMock('\\' . \OCP\IGroupManager::class); $groupManager->expects($this->any()) ->method('isAdmin') ->with('testuser') @@ -99,7 +96,7 @@ public function testGetChild() { $childNode = $this->getNode()->getChild('123'); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $childNode); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $childNode); $this->assertEquals('123', $childNode->getName()); $this->assertEquals($tag, $childNode->getSystemTag()); } @@ -158,8 +155,8 @@ public function testGetChildrenAdmin() { $this->assertCount(2, $children); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[0]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[1]); $this->assertEquals($tag1, $children[0]->getSystemTag()); $this->assertEquals($tag2, $children[1]->getSystemTag()); } @@ -177,8 +174,8 @@ public function testGetChildrenNonAdmin() { $this->assertCount(2, $children); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[0]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[1]); $this->assertEquals($tag1, $children[0]->getSystemTag()); $this->assertEquals($tag2, $children[1]->getSystemTag()); } @@ -205,9 +202,9 @@ public function testGetChildrenWithStaticTagsAndOtherTags() { $children = $this->getNode(false)->getChildren(); $this->assertCount(3, $children); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[2]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[0]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[1]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[2]); $this->assertEquals($visibleTag, $children[0]->getSystemTag()); $this->assertEquals($restrictTag, $children[1]->getSystemTag()); $this->assertEquals($staticTag, $children[2]->getSystemTag()); @@ -236,8 +233,8 @@ public function testGetChildrenWithoutStaticTagsAndOtherTags() { $this->assertCount(2, $children); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[0]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagNode::class, $children[1]); $this->assertEquals($visibleTag, $children[0]->getSystemTag()); $this->assertEquals($restrictTag, $children[1]->getSystemTag()); } diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php index a2ba7915c968..ca8be9fd036a 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php @@ -30,25 +30,25 @@ class SystemTagsObjectMappingCollectionTest extends \Test\TestCase { /** * @var \OCP\SystemTag\ISystemTagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var \OCP\SystemTag\ISystemTagObjectMapper */ - private $tagMapper; + private \PHPUnit\Framework\MockObject\MockObject $tagMapper; /** * @var \OCP\IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->createMock('\OCP\SystemTag\ISystemTagManager'); - $this->tagMapper = $this->createMock('\OCP\SystemTag\ISystemTagObjectMapper'); + $this->tagManager = $this->createMock('\\' . \OCP\SystemTag\ISystemTagManager::class); + $this->tagMapper = $this->createMock('\\' . \OCP\SystemTag\ISystemTagObjectMapper::class); - $this->user = $this->createMock('\OCP\IUser'); + $this->user = $this->createMock('\\' . \OCP\IUser::class); } public function getNode() { @@ -88,9 +88,9 @@ public function testAssignTag() { public function permissionsProvider() { return [ // invisible, tag does not exist for user - [false, true, '\Sabre\DAV\Exception\PreconditionFailed'], + [false, true, '\\' . \Sabre\DAV\Exception\PreconditionFailed::class], // visible but static, cannot assign tag - [true, false, '\Sabre\DAV\Exception\Forbidden'], + [true, false, '\\' . \Sabre\DAV\Exception\Forbidden::class], ]; } @@ -186,7 +186,7 @@ public function testGetChild() { $childNode = $this->getNode()->getChild('555'); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $childNode); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagMappingNode::class, $childNode); $this->assertEquals('555', $childNode->getName()); } @@ -270,16 +270,14 @@ public function testGetChildren() { $this->tagManager->expects($this->exactly(3)) ->method('canUserSeeTag') - ->will($this->returnCallback(function ($tag) { - return $tag->isUserVisible(); - })); + ->will($this->returnCallback(fn ($tag) => $tag->isUserVisible())); $children = $this->getNode()->getChildren(); $this->assertCount(2, $children); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $children[1]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagMappingNode::class, $children[0]); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagMappingNode::class, $children[1]); $this->assertEquals(111, $children[0]->getObjectId()); $this->assertEquals('files', $children[0]->getObjectType()); diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php index 7f6a1307ea9e..0b480a7eaa0f 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php @@ -24,49 +24,46 @@ namespace OCA\DAV\Tests\unit\SystemTag; class SystemTagsObjectTypeCollectionTest extends \Test\TestCase { - /** - * @var \OCA\DAV\SystemTag\SystemTagsObjectTypeCollection - */ - private $node; + private \OCA\DAV\SystemTag\SystemTagsObjectTypeCollection $node; /** * @var \OCP\SystemTag\ISystemTagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var \OCP\SystemTag\ISystemTagObjectMapper */ - private $tagMapper; + private \PHPUnit\Framework\MockObject\MockObject $tagMapper; /** * @var \OCP\Files\Folder */ - private $userFolder; + private \PHPUnit\Framework\MockObject\MockObject $userFolder; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->createMock('\OCP\SystemTag\ISystemTagManager'); - $this->tagMapper = $this->createMock('\OCP\SystemTag\ISystemTagObjectMapper'); + $this->tagManager = $this->createMock('\\' . \OCP\SystemTag\ISystemTagManager::class); + $this->tagMapper = $this->createMock('\\' . \OCP\SystemTag\ISystemTagObjectMapper::class); - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('testuser')); - $userSession = $this->createMock('\OCP\IUserSession'); + $userSession = $this->createMock('\\' . \OCP\IUserSession::class); $userSession->expects($this->any()) ->method('getUser') ->will($this->returnValue($user)); - $groupManager = $this->createMock('\OCP\IGroupManager'); + $groupManager = $this->createMock('\\' . \OCP\IGroupManager::class); $groupManager->expects($this->any()) ->method('isAdmin') ->with('testuser') ->will($this->returnValue(true)); - $this->userFolder = $this->createMock('\OCP\Files\Folder'); + $this->userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); - $fileRoot = $this->createMock('\OCP\Files\IRootFolder'); + $fileRoot = $this->createMock('\\' . \OCP\Files\IRootFolder::class); $fileRoot->expects($this->any()) ->method('getUserfolder') ->with('testuser') @@ -105,7 +102,7 @@ public function testGetChild() { ->will($this->returnValue([true])); $childNode = $this->node->getChild('555'); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection', $childNode); + $this->assertInstanceOf('\\' . \OCA\DAV\SystemTag\SystemTagsObjectMappingCollection::class, $childNode); $this->assertEquals('555', $childNode->getName()); } diff --git a/apps/dav/tests/unit/TrashBin/TrashBinFileTest.php b/apps/dav/tests/unit/TrashBin/TrashBinFileTest.php index 05bd7bd63856..934ee4731181 100644 --- a/apps/dav/tests/unit/TrashBin/TrashBinFileTest.php +++ b/apps/dav/tests/unit/TrashBin/TrashBinFileTest.php @@ -34,14 +34,11 @@ use Test\TestCase; class TrashBinFileTest extends TestCase { - /** - * @var TrashBinFile - */ - private $trashBinFile; + private \OCA\DAV\TrashBin\TrashBinFile $trashBinFile; /** * @var TrashBinManager | MockObject */ - private $trashBinManager; + private \PHPUnit\Framework\MockObject\MockObject $trashBinManager; public function providesExceptions() : array { return [ diff --git a/apps/dav/tests/unit/TrashBin/TrashBinFolderTest.php b/apps/dav/tests/unit/TrashBin/TrashBinFolderTest.php index b8cb50d74ceb..efe921ec44ce 100644 --- a/apps/dav/tests/unit/TrashBin/TrashBinFolderTest.php +++ b/apps/dav/tests/unit/TrashBin/TrashBinFolderTest.php @@ -29,18 +29,15 @@ use Test\TestCase; class TrashBinFolderTest extends TestCase { - /** - * @var TrashBinFolder - */ - private $trashBinFolder; + private \OCA\DAV\TrashBin\TrashBinFolder $trashBinFolder; /** * @var TrashBinManager | MockObject */ - private $trashBinManager; + private \PHPUnit\Framework\MockObject\MockObject $trashBinManager; /** * @var FileInfo | MockObject */ - private $fileInfo; + private \PHPUnit\Framework\MockObject\MockObject $fileInfo; protected function setUp(): void { parent::setUp(); @@ -51,8 +48,8 @@ protected function setUp(): void { $this->fileInfo->method('getId')->willReturn(666); $this->fileInfo->method('getMimeType')->willReturn('foo'); $this->fileInfo->method('getEtag')->willReturn('abcdefgh'); - $this->fileInfo->method('getMtime')->willReturn(789123456); - $this->fileInfo->method('getSize')->willReturn(12345678); + $this->fileInfo->method('getMtime')->willReturn(789_123_456); + $this->fileInfo->method('getSize')->willReturn(12_345_678); $this->fileInfo->method('getPath')->willReturn('/alice/files_trashbin/files/folder.d1561467869/foo'); $this->trashBinManager->method('getLocation')->willReturn('.'); @@ -127,11 +124,11 @@ public function providesMethods() { ['666', 'getName'], ['foo', 'getContentType'], ['"abcdefgh"', 'getEtag'], - [789123456, 'getLastModified'], - [12345678, 'getSize'], + [789_123_456, 'getLastModified'], + [12_345_678, 'getSize'], ['foo', 'getOriginalFileName'], ['folder/foo', 'getOriginalLocation'], - [1561467869, 'getDeleteTimestamp'], + [1_561_467_869, 'getDeleteTimestamp'], ]; } } diff --git a/apps/dav/tests/unit/TrashBin/TrashBinHomeTest.php b/apps/dav/tests/unit/TrashBin/TrashBinHomeTest.php index f216ccd1e586..6aedde7b1d6c 100644 --- a/apps/dav/tests/unit/TrashBin/TrashBinHomeTest.php +++ b/apps/dav/tests/unit/TrashBin/TrashBinHomeTest.php @@ -27,14 +27,11 @@ use Test\TestCase; class TrashBinHomeTest extends TestCase { - /** - * @var TrashBinHome - */ - private $trashBinHome; + private \OCA\DAV\TrashBin\TrashBinHome $trashBinHome; /** * @var TrashBinManager | \PHPUnit\Framework\MockObject\MockObject */ - private $trashBinManager; + private \PHPUnit\Framework\MockObject\MockObject $trashBinManager; protected function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/TreeTest.php b/apps/dav/tests/unit/TreeTest.php index d0122be95ff1..c2d827f48472 100644 --- a/apps/dav/tests/unit/TreeTest.php +++ b/apps/dav/tests/unit/TreeTest.php @@ -31,9 +31,9 @@ class TreeTest1 extends TestCase { /** @var ICollection | \PHPUnit\Framework\MockObject\MockObject */ - private $rootNode; + private \PHPUnit\Framework\MockObject\MockObject $rootNode; /** @var Tree | \PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \OCA\DAV\Tree $tree; private $copyHookParams; private $postCopyHookParams; diff --git a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php index 1d0a39374b15..4bc0d0a21410 100644 --- a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php +++ b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php @@ -56,7 +56,7 @@ public function providesNodes() { $tonofnodes = []; $tonofdata = ""; for ($i = 0; $i < 101; $i++) { - $thisdata = \rand(0, 100); // variable length and content + $thisdata = random_int(0, 100); // variable length and content $tonofdata .= $thisdata; \array_push($tonofnodes, $this->buildNode($i, $thisdata)); } @@ -120,7 +120,7 @@ private function makeData($count) { } private function buildNode($name, $data) { - $node = $this->getMockBuilder('\Sabre\DAV\File') + $node = $this->getMockBuilder('\\' . \Sabre\DAV\File::class) ->setMethods(['getName', 'get', 'getSize']) ->getMockForAbstractClass(); diff --git a/apps/dav/tests/unit/Upload/ChunkLocationProviderTest.php b/apps/dav/tests/unit/Upload/ChunkLocationProviderTest.php index b0d13b7955d5..2516668f75ad 100644 --- a/apps/dav/tests/unit/Upload/ChunkLocationProviderTest.php +++ b/apps/dav/tests/unit/Upload/ChunkLocationProviderTest.php @@ -31,13 +31,13 @@ class ChunkLocationProviderTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ChunkLocationProvider | \PHPUnit\Framework\MockObject\MockObject */ - private $provider; + private \OCA\DAV\Upload\ChunkLocationProvider $provider; /** @var IUser | \PHPUnit\Framework\MockObject\MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var IStorageFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $factory; + private \PHPUnit\Framework\MockObject\MockObject $factory; protected function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/Upload/ChunkingPluginTest.php b/apps/dav/tests/unit/Upload/ChunkingPluginTest.php index a0291740abba..b1295de09f5b 100644 --- a/apps/dav/tests/unit/Upload/ChunkingPluginTest.php +++ b/apps/dav/tests/unit/Upload/ChunkingPluginTest.php @@ -32,29 +32,26 @@ class ChunkingPluginTest extends TestCase { /** * @var \Sabre\DAV\Server | \PHPUnit\Framework\MockObject\MockObject */ - private $server; + private \PHPUnit\Framework\MockObject\MockObject $server; /** * @var \Sabre\DAV\Tree | \PHPUnit\Framework\MockObject\MockObject */ - private $tree; + private \PHPUnit\Framework\MockObject\MockObject $tree; - /** - * @var ChunkingPlugin - */ - private $plugin; + private \OCA\DAV\Upload\ChunkingPlugin $plugin; /** @var RequestInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var ResponseInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; public function setUp(): void { parent::setUp(); - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + $this->server = $this->getMockBuilder('\\' . \Sabre\DAV\Server::class) ->disableOriginalConstructor() ->getMock(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + $this->tree = $this->getMockBuilder('\\' . \Sabre\DAV\Tree::class) ->disableOriginalConstructor() ->getMock(); @@ -168,12 +165,12 @@ public function testBeforeMoveSizeIsWrong() { */ public function expectedAndActualSizeData() { return [ - ['12345678910', 12345678910.0], - ['12345678910', 12345678910.0123], - ['9999999999999', 9999999999999.0], - ['9999999999999.9999', 9999999999999.9999], - ['999999999999999.9999', 999999999999999.9999], - ['9999999999999999999', 9999999999999999999], + ['12345678910', 12_345_678_910.0], + ['12345678910', 12_345_678_910.0123], + ['9999999999999', 9_999_999_999_999.0], + ['9999999999999.9999', 9_999_999_999_999.9999], + ['999999999999999.9999', 999_999_999_999_999.9999], + ['9999999999999999999', 9_999_999_999_999_999_999.0], ]; } diff --git a/apps/dav/tests/unit/Upload/FutureFileTest.php b/apps/dav/tests/unit/Upload/FutureFileTest.php index 0a4afbe0d922..35dcb8a7cbe0 100644 --- a/apps/dav/tests/unit/Upload/FutureFileTest.php +++ b/apps/dav/tests/unit/Upload/FutureFileTest.php @@ -40,7 +40,7 @@ public function testGetName() { public function testGetLastModified() { $f = $this->mockFutureFile(); - $this->assertEquals(12121212, $f->getLastModified()); + $this->assertEquals(12_121_212, $f->getLastModified()); } public function testGetSize() { @@ -55,7 +55,7 @@ public function testGet() { } public function testDelete() { - $d = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Directory') + $d = $this->getMockBuilder(\OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->setMethods(['delete']) ->getMock(); @@ -89,7 +89,7 @@ public function testSetName() { * @return \OCA\DAV\Upload\FutureFile */ private function mockFutureFile() { - $d = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Directory') + $d = $this->getMockBuilder(\OCA\DAV\Connector\Sabre\Directory::class) ->disableOriginalConstructor() ->setMethods(['getETag', 'getLastModified', 'getChildren']) ->getMock(); @@ -100,7 +100,7 @@ private function mockFutureFile() { $d->expects($this->any()) ->method('getLastModified') - ->willReturn(12121212); + ->willReturn(12_121_212); $d->expects($this->any()) ->method('getChildren') diff --git a/apps/dav/tests/unit/bootstrap.php b/apps/dav/tests/unit/bootstrap.php index 356a1ccaa4cc..52f49fb7bb20 100644 --- a/apps/dav/tests/unit/bootstrap.php +++ b/apps/dav/tests/unit/bootstrap.php @@ -25,7 +25,7 @@ require_once __DIR__.'/../../../../lib/base.php'; -if (!\class_exists('PHPUnit\Framework\TestCase')) { +if (!\class_exists(\PHPUnit\Framework\TestCase::class)) { require_once('PHPUnit/Autoload.php'); } diff --git a/apps/federatedfilesharing/appinfo/app.php b/apps/federatedfilesharing/appinfo/app.php index f23d01d29a0f..b33df5b78159 100644 --- a/apps/federatedfilesharing/appinfo/app.php +++ b/apps/federatedfilesharing/appinfo/app.php @@ -26,11 +26,9 @@ $app = new \OCA\FederatedFileSharing\AppInfo\Application(); $manager = \OC::$server->getNotificationManager(); -$manager->registerNotifier(function () { - return new Notifier( - \OC::$server->getL10NFactory() - ); -}, function () { +$manager->registerNotifier(fn () => new Notifier( + \OC::$server->getL10NFactory() +), function () { $l = \OC::$server->getL10N('files_sharing'); return [ 'id' => 'files_sharing', diff --git a/apps/federatedfilesharing/lib/AddressHandler.php b/apps/federatedfilesharing/lib/AddressHandler.php index 16c487128e91..1015666e87da 100644 --- a/apps/federatedfilesharing/lib/AddressHandler.php +++ b/apps/federatedfilesharing/lib/AddressHandler.php @@ -31,11 +31,9 @@ * @package OCA\FederatedFileSharing */ class AddressHandler { - /** @var IL10N */ - private $l; + private \OCP\IL10N $l; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; /** * AddressHandler constructor. diff --git a/apps/federatedfilesharing/lib/AppInfo/Application.php b/apps/federatedfilesharing/lib/AppInfo/Application.php index 180c4bc64aa4..1497fb9a930c 100644 --- a/apps/federatedfilesharing/lib/AppInfo/Application.php +++ b/apps/federatedfilesharing/lib/AppInfo/Application.php @@ -54,103 +54,87 @@ public function __construct() { $container->registerService( 'AddressHandler', - function ($c) use ($server) { - return new AddressHandler( - $server->getURLGenerator(), - $server->getL10N('federatedfilesharing') - ); - } + fn ($c) => new AddressHandler( + $server->getURLGenerator(), + $server->getL10N('federatedfilesharing') + ) ); $container->registerService( 'DiscoveryManager', - function ($c) use ($server) { - return new DiscoveryManager( - $server->getMemCacheFactory(), - $server->getHTTPClientService() - ); - } + fn ($c) => new DiscoveryManager( + $server->getMemCacheFactory(), + $server->getHTTPClientService() + ) ); $container->registerService( 'Notifications', - function ($c) use ($server) { - return new Notifications( - $c->query('AddressHandler'), - $server->getHTTPClientService(), - $c->query('DiscoveryManager'), - $c->query('NotificationManager'), - $server->getJobList(), - $server->getConfig() - ); - } + fn ($c) => new Notifications( + $c->query('AddressHandler'), + $server->getHTTPClientService(), + $c->query('DiscoveryManager'), + $c->query('NotificationManager'), + $server->getJobList(), + $server->getConfig() + ) ); $container->registerService( 'FederatedShareManager', - function ($c) use ($server) { - return new FedShareManager( - $this->getFederatedShareProvider(), - $c->query('Notifications'), - $server->getUserManager(), - $server->getActivityManager(), - $server->getNotificationManager(), - $c->query('AddressHandler'), - $c->query('Permissions'), - $server->getEventDispatcher() - ); - } + fn ($c) => new FedShareManager( + $this->getFederatedShareProvider(), + $c->query('Notifications'), + $server->getUserManager(), + $server->getActivityManager(), + $server->getNotificationManager(), + $c->query('AddressHandler'), + $c->query('Permissions'), + $server->getEventDispatcher() + ) ); $container->registerService( 'OcmMiddleware', - function ($c) use ($server) { - return new OcmMiddleware( - $this->getFederatedShareProvider(), - $server->getAppManager(), - $server->getUserManager(), - $c->query('AddressHandler'), - $server->getLogger() - ); - } + fn ($c) => new OcmMiddleware( + $this->getFederatedShareProvider(), + $server->getAppManager(), + $server->getUserManager(), + $c->query('AddressHandler'), + $server->getLogger() + ) ); $container->registerService( 'RequestHandlerController', - function ($c) use ($server) { - return new RequestHandlerController( - $c->query('AppName'), - $c->query('Request'), - $c->query('OcmMiddleware'), - $server->getUserManager(), - $c->query('AddressHandler'), - $c->query('FederatedShareManager') - ); - } + fn ($c) => new RequestHandlerController( + $c->query('AppName'), + $c->query('Request'), + $c->query('OcmMiddleware'), + $server->getUserManager(), + $c->query('AddressHandler'), + $c->query('FederatedShareManager') + ) ); $container->registerService( 'OcmController', - function ($c) use ($server) { - return new OcmController( - $c->query('AppName'), - $c->query('Request'), - $c->query('OcmMiddleware'), - $server->getURLGenerator(), - $server->getUserManager(), - $c->query('AddressHandler'), - $c->query('FederatedShareManager'), - $server->getLogger(), - $server->getConfig() - ); - } + fn ($c) => new OcmController( + $c->query('AppName'), + $c->query('Request'), + $c->query('OcmMiddleware'), + $server->getURLGenerator(), + $server->getUserManager(), + $c->query('AddressHandler'), + $c->query('FederatedShareManager'), + $server->getLogger(), + $server->getConfig() + ) ); $container->registerService( 'NotificationManager', - function ($c) { - return new NotificationManager(); - } + fn ($c) => new NotificationManager() ); $container->registerService( diff --git a/apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php b/apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php index 8c278979853a..6250cfd166ce 100644 --- a/apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php +++ b/apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php @@ -37,17 +37,16 @@ * @package OCA\FederatedFileSharing\BackgroundJob */ class RetryJob extends Job { - /** @var bool */ - private $retainJob = true; + private bool $retainJob = true; /** @var Notifications */ private $notifications; /** @var int max number of attempts to send the request */ - private $maxTry = 20; + private int $maxTry = 20; /** @var int how much time should be between two tries (10 minutes) */ - private $interval = 600; + private int $interval = 600; /** * UnShare constructor. @@ -84,7 +83,7 @@ protected function run($argument) { $remoteId = $argument['remoteId']; $token = $argument['token']; $action = $argument['action']; - $data = \json_decode($argument['data'], true); + $data = \json_decode($argument['data'], true, 512, JSON_THROW_ON_ERROR); $try = (int)$argument['try'] + 1; $result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try); @@ -102,7 +101,7 @@ protected function run($argument) { */ protected function reAddJob(IJobList $jobList, array $argument) { $jobList->add( - 'OCA\FederatedFileSharing\BackgroundJob\RetryJob', + \OCA\FederatedFileSharing\BackgroundJob\RetryJob::class, [ 'remote' => $argument['remote'], 'remoteId' => $argument['remoteId'], diff --git a/apps/federatedfilesharing/lib/Command/PollIncomingShares.php b/apps/federatedfilesharing/lib/Command/PollIncomingShares.php index 482375399559..9ba48adfdffb 100644 --- a/apps/federatedfilesharing/lib/Command/PollIncomingShares.php +++ b/apps/federatedfilesharing/lib/Command/PollIncomingShares.php @@ -37,21 +37,15 @@ use Symfony\Component\Console\Output\OutputInterface; class PollIncomingShares extends Command { - /** @var IDBConnection */ - private $dbConnection; + private \OCP\IDBConnection $dbConnection; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IStorageFactory */ - private $loader; + private \OCP\Files\Storage\IStorageFactory $loader; - /** @var Manager */ - private $externalManager; + private ?\OCA\Files_Sharing\External\Manager $externalManager = null; - /** @var MountProvider | null */ - - private $externalMountProvider; + private ?\OCA\Files_Sharing\External\MountProvider $externalMountProvider = null; /** * PollIncomingShares constructor. @@ -103,7 +97,7 @@ public function execute(InputInterface $input, OutputInterface $output): int { try { $shareData = $this->getExternalShareData($data['user'], $mount->getMountPoint()); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) { - $encodedData = \json_encode($shareData); + $encodedData = \json_encode($shareData, JSON_THROW_ON_ERROR); $output->writeln( "User: \"{$data['user']}\", Share data: $encodedData" ); diff --git a/apps/federatedfilesharing/lib/Controller/OcmController.php b/apps/federatedfilesharing/lib/Controller/OcmController.php index 74e1d8559840..6ddb6eda38a0 100644 --- a/apps/federatedfilesharing/lib/Controller/OcmController.php +++ b/apps/federatedfilesharing/lib/Controller/OcmController.php @@ -47,10 +47,7 @@ class OcmController extends Controller { public const API_VERSION = '1.0-proposal1'; - /** - * @var OcmMiddleware - */ - private $ocmMiddleware; + private \OCA\FederatedFileSharing\Middleware\OcmMiddleware $ocmMiddleware; /** * @var IURLGenerator @@ -77,8 +74,7 @@ class OcmController extends Controller { */ protected $logger; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** * OcmController constructor. diff --git a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php index a67094929978..14e0549699b0 100644 --- a/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php +++ b/apps/federatedfilesharing/lib/Controller/RequestHandlerController.php @@ -50,17 +50,13 @@ * @package OCA\FederatedFileSharing\API */ class RequestHandlerController extends OCSController { - /** @var OcmMiddleware */ - private $ocmMiddleware; + private \OCA\FederatedFileSharing\Middleware\OcmMiddleware $ocmMiddleware; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var AddressHandler */ - private $addressHandler; + private \OCA\FederatedFileSharing\AddressHandler $addressHandler; - /** @var FedShareManager */ - private $fedShareManager; + private \OCA\FederatedFileSharing\FedShareManager $fedShareManager; /** * Server2Server constructor. diff --git a/apps/federatedfilesharing/lib/Controller/SharingPersonalSettingsController.php b/apps/federatedfilesharing/lib/Controller/SharingPersonalSettingsController.php index c36ca26bab58..d08867fe6694 100644 --- a/apps/federatedfilesharing/lib/Controller/SharingPersonalSettingsController.php +++ b/apps/federatedfilesharing/lib/Controller/SharingPersonalSettingsController.php @@ -34,11 +34,9 @@ class SharingPersonalSettingsController extends Controller { 'auto_accept_share_trusted' ]; - /** @var IConfig $config */ - private $config; + private \OCP\IConfig $config; - /** @var IUserSession $userSession */ - private $userSession; + private \OCP\IUserSession $userSession; public function __construct(string $appName, IRequest $request, IConfig $config, IUserSession $userSession) { parent::__construct($appName, $request); @@ -96,9 +94,7 @@ private function validateParameter($key, $value) { private function getUserRequestParams() { return \array_filter( $this->request->getParams(), - function ($key) { - return (\substr($key, 0, 1) !== '_'); - }, + fn ($key) => \substr($key, 0, 1) !== '_', ARRAY_FILTER_USE_KEY ); } diff --git a/apps/federatedfilesharing/lib/DiscoveryManager.php b/apps/federatedfilesharing/lib/DiscoveryManager.php index 20ecc6239869..de2bec7e9527 100644 --- a/apps/federatedfilesharing/lib/DiscoveryManager.php +++ b/apps/federatedfilesharing/lib/DiscoveryManager.php @@ -80,7 +80,7 @@ private function isSafeUrl($url) { private function discover($remote) { // Check if something is in the cache if ($cacheData = $this->cache->get($remote)) { - return \json_decode($cacheData, true); + return \json_decode($cacheData, true, 512, JSON_THROW_ON_ERROR); } // Default response body @@ -111,7 +111,7 @@ private function discover($remote) { } // Write into cache - $this->cache->set($remote, \json_encode($discoveredServices)); + $this->cache->set($remote, \json_encode($discoveredServices, JSON_THROW_ON_ERROR)); return $discoveredServices; } @@ -127,7 +127,7 @@ private function discover($remote) { private function ocmDiscover($remote) { // Check if something is in the cache if ($cacheData = $this->cache->get('OCM' . $remote)) { - return \json_decode($cacheData, true); + return \json_decode($cacheData, true, 512, JSON_THROW_ON_ERROR); } // Default response body @@ -156,7 +156,7 @@ private function ocmDiscover($remote) { } // Write into cache - $this->cache->set('OCM' . $remote, \json_encode($discoveredServices)); + $this->cache->set('OCM' . $remote, \json_encode($discoveredServices, JSON_THROW_ON_ERROR)); return $discoveredServices; } return [ @@ -184,14 +184,12 @@ private function makeRequest($url) { ] ); if ($response->getStatusCode() === 200) { - $decodedService = \json_decode($response->getBody(), true); + $decodedService = \json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR); } if (\is_array($decodedService) === false) { $decodedService = []; } - } catch (ClientException $e) { - // Don't throw any exception since exceptions are handled before - } catch (ConnectException $e) { + } catch (ClientException|ConnectException $e) { // Don't throw any exception since exceptions are handled before } return $decodedService; diff --git a/apps/federatedfilesharing/lib/FedShareManager.php b/apps/federatedfilesharing/lib/FedShareManager.php index 0e99a11fbb59..d29ba43dc85e 100644 --- a/apps/federatedfilesharing/lib/FedShareManager.php +++ b/apps/federatedfilesharing/lib/FedShareManager.php @@ -39,40 +39,19 @@ class FedShareManager { public const ACTION_URL = 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/'; - /** - * @var FederatedShareProvider - */ - private $federatedShareProvider; + private \OCA\FederatedFileSharing\FederatedShareProvider $federatedShareProvider; - /** - * @var Notifications - */ - private $notifications; + private \OCA\FederatedFileSharing\Notifications $notifications; - /** - * @var IUserManager - */ - private $userManager; + private \OCP\IUserManager $userManager; - /** - * @var ActivityManager - */ - private $activityManager; + private \OCP\Activity\IManager $activityManager; - /** - * @var NotificationManager - */ - private $notificationManager; + private \OCP\Notification\IManager $notificationManager; - /** - * @var AddressHandler - */ - private $addressHandler; + private \OCA\FederatedFileSharing\AddressHandler $addressHandler; - /** - * @var EventDispatcherInterface - */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher; /** * FedShareManager constructor. @@ -217,7 +196,7 @@ public function reShare(IShare $share, $remoteId, $shareWith, $permissions = nul public function acceptShare(IShare $share) { $uid = $this->getCorrectUid($share); $fileId = $share->getNode()->getId(); - list($file, $link) = $this->getFile($uid, $fileId); + [$file, $link] = $this->getFile($uid, $fileId); $this->publishActivity( $uid, Activity::SUBJECT_REMOTE_SHARE_ACCEPTED, @@ -243,7 +222,7 @@ public function declineShare(IShare $share) { $uid = $this->getCorrectUid($share); $fileId = $share->getNode()->getId(); $this->federatedShareProvider->removeShareFromTable($share); - list($file, $link) = $this->getFile($uid, $fileId); + [$file, $link] = $this->getFile($uid, $fileId); $this->publishActivity( $uid, Activity::SUBJECT_REMOTE_SHARE_DECLINED, @@ -360,7 +339,7 @@ public function isFederatedReShare(IShare $share) { protected function notifyRemote($share, $callback) { if ($share->getShareOwner() !== $share->getSharedBy()) { try { - list(, $remote) = $this->addressHandler->splitUserRemote( + [, $remote] = $this->addressHandler->splitUserRemote( $share->getSharedBy() ); $remoteId = $this->federatedShareProvider->getRemoteId($share); diff --git a/apps/federatedfilesharing/lib/FederatedShareProvider.php b/apps/federatedfilesharing/lib/FederatedShareProvider.php index 5989f3af249e..69bc2b422e18 100644 --- a/apps/federatedfilesharing/lib/FederatedShareProvider.php +++ b/apps/federatedfilesharing/lib/FederatedShareProvider.php @@ -49,41 +49,29 @@ class FederatedShareProvider implements IShareProvider { public const SHARE_TYPE_REMOTE = 6; - /** @var IDBConnection */ - private $dbConnection; + private \OCP\IDBConnection $dbConnection; - /** @var EventDispatcherInterface */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher; - /** @var AddressHandler */ - private $addressHandler; + private \OCA\FederatedFileSharing\AddressHandler $addressHandler; - /** @var Notifications */ - private $notifications; + private \OCA\FederatedFileSharing\Notifications $notifications; - /** @var TokenHandler */ - private $tokenHandler; + private \OCA\FederatedFileSharing\TokenHandler $tokenHandler; - /** @var IL10N */ - private $l; + private \OCP\IL10N $l; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var string */ - private $externalShareTable = 'share_external'; + private string $externalShareTable = 'share_external'; - /** @var string */ - private $shareTable = 'share'; + private string $shareTable = 'share'; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; /** * DefaultShareProvider constructor. @@ -184,7 +172,7 @@ public function create(IShare $share) { $uidOwner = $remoteShare['owner'] . '@' . $remoteShare['remote']; $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $expiration, 'tmp_token_' . \time()); $share->setId($shareId); - list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId); + [$token, $remoteId] = $this->askOwnerToReShare($shareWith, $share, $shareId); // remote share was create successfully if we get a valid token as return $send = \is_string($token) && $token !== ''; } catch (\Exception $e) { @@ -296,7 +284,7 @@ protected function askOwnerToReShare($shareWith, IShare $share, $shareId) { $remoteId = $remoteShare['remote_id']; $remote = $remoteShare['remote']; - list($token, $remoteId) = $this->notifications->requestReShare( + [$token, $remoteId] = $this->notifications->requestReShare( $token, $remoteId, $shareId, @@ -420,9 +408,9 @@ protected function sendPermissionUpdate(IShare $share) { $remoteId = $this->getRemoteId($share); // if the local user is the owner we send the permission change to the initiator if ($this->userManager->userExists($share->getShareOwner())) { - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); + [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy()); } else { // ... if not we send the permission change to the owner - list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); + [, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner()); } $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions()); } @@ -521,7 +509,7 @@ public function getChildren(IShare $parent) { * @param IShare $share */ public function delete(IShare $share) { - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith()); + [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedWith()); $isOwner = false; @@ -540,9 +528,9 @@ public function delete(IShare $share) { if ($this->shouldNotifyRemote($share)) { $remoteId = $this->getRemoteId($share); if ($isOwner) { - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); + [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy()); } else { - list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); + [, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner()); } $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken()); } @@ -562,9 +550,9 @@ protected function revokeShare($share, $isOwner) { // also send a unShare request to the initiator if ($this->shouldNotifyRemote($share)) { if ($isOwner) { - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); + [, $remote] = $this->addressHandler->splitUserRemote($share->getSharedBy()); } else { - list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); + [, $remote] = $this->addressHandler->splitUserRemote($share->getShareOwner()); } $remoteId = $this->getRemoteId($share); $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken()); diff --git a/apps/federatedfilesharing/lib/Middleware/OcmMiddleware.php b/apps/federatedfilesharing/lib/Middleware/OcmMiddleware.php index a873be4e242d..4ff0dd57c5d7 100644 --- a/apps/federatedfilesharing/lib/Middleware/OcmMiddleware.php +++ b/apps/federatedfilesharing/lib/Middleware/OcmMiddleware.php @@ -102,9 +102,7 @@ public function assertNotNull($params) { $nullKeys = \array_keys( \array_filter( $params, - function ($b) { - return $b === null; - } + fn ($b) => $b === null ) ); if (\count($nullKeys) > 0) { diff --git a/apps/federatedfilesharing/lib/Notifications.php b/apps/federatedfilesharing/lib/Notifications.php index f7a32c226cd0..9265fb5cb961 100644 --- a/apps/federatedfilesharing/lib/Notifications.php +++ b/apps/federatedfilesharing/lib/Notifications.php @@ -34,24 +34,17 @@ class Notifications { public const RESPONSE_FORMAT = 'json'; // default response format for ocs calls + private \OCA\FederatedFileSharing\AddressHandler $addressHandler; - /** @var AddressHandler */ - private $addressHandler; + private \OCP\Http\Client\IClientService $httpClientService; - /** @var IClientService */ - private $httpClientService; + private \OCA\FederatedFileSharing\DiscoveryManager $discoveryManager; - /** @var DiscoveryManager */ - private $discoveryManager; + private \OCA\FederatedFileSharing\Ocm\NotificationManager $notificationManager; - /** @var NotificationManager */ - private $notificationManager; + private \OCP\BackgroundJob\IJobList $jobList; - /** @var IJobList */ - private $jobList; - - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** * @param AddressHandler $addressHandler @@ -123,7 +116,7 @@ public function sendRemoteShare( } if ($remoteShareSuccess === true) { \OC_Hook::emit( - 'OCP\Share', + \OCP\Share::class, 'federated_share_added', ['server' => $shareWithAddress->getHostName()] ); @@ -157,7 +150,7 @@ public function requestReShare($token, $id, $shareId, $remote, $shareWith, $perm ); $result = $this->tryHttpPostToShareEndpoint($url, '/notifications', $ocmFields, true); if (isset($result['statusCode']) && $result['statusCode'] === Http::STATUS_CREATED) { - $response = \json_decode($result['result'], true); + $response = \json_decode($result['result'], true, 512, JSON_THROW_ON_ERROR); if (\is_array($response) && isset($response['sharedSecret'], $response['providerId'])) { return [ $response['sharedSecret'], @@ -176,7 +169,7 @@ public function requestReShare($token, $id, $shareId, $remote, $shareWith, $perm $url = $this->addressHandler->removeProtocolFromUrl($remote); $result = $this->tryHttpPostToShareEndpoint(\rtrim($url, '/'), '/' . $id . '/reshare', $fields); - $status = \json_decode($result['result'], true); + $status = \json_decode($result['result'], true, 512, JSON_THROW_ON_ERROR); $httpRequestSuccessful = $result['success']; $validToken = isset($status['ocs']['data']['token']) && \is_string($status['ocs']['data']['token']); @@ -288,20 +281,20 @@ public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = '/' ); $result = $this->tryHttpPostToShareEndpoint($url, '/' . $remoteId . '/' . $action, $fields); - $status = \json_decode($result['result'], true); + $status = \json_decode($result['result'], true, 512, JSON_THROW_ON_ERROR); if ($result['success'] && $this->isOcsStatusOk($status)) { return true; } elseif ($try === 0) { // only add new job on first try $this->jobList->add( - 'OCA\FederatedFileSharing\BackgroundJob\RetryJob', + \OCA\FederatedFileSharing\BackgroundJob\RetryJob::class, [ 'remote' => $remote, 'remoteId' => $remoteId, 'token' => $token, 'action' => $action, - 'data' => \json_encode($data), + 'data' => \json_encode($data, JSON_THROW_ON_ERROR), 'try' => $try, 'lastRun' => $this->getTimestamp() ] @@ -451,7 +444,7 @@ protected function sendPreOcmRemoteShare(Address $shareWithAddress, Address $own ]; $url = $shareWithAddress->getHostName(); $result = $this->tryHttpPostToShareEndpoint($url, '', $fields); - $status = \json_decode($result['result'], true); + $status = \json_decode($result['result'], true, 512, JSON_THROW_ON_ERROR); if ($result['success'] && $this->isOcsStatusOk($status)) { return true; } diff --git a/apps/federatedfilesharing/lib/Panels/SharingPersonalPanel.php b/apps/federatedfilesharing/lib/Panels/SharingPersonalPanel.php index 94a2e027e469..adbccec11bb9 100644 --- a/apps/federatedfilesharing/lib/Panels/SharingPersonalPanel.php +++ b/apps/federatedfilesharing/lib/Panels/SharingPersonalPanel.php @@ -28,11 +28,9 @@ use OCP\Template; class SharingPersonalPanel implements ISettings { - /** @var IConfig $config */ - private $config; + private \OCP\IConfig $config; - /** @var IUserSession $userSession */ - private $userSession; + private \OCP\IUserSession $userSession; public function __construct(IConfig $config, IUserSession $userSession) { $this->config = $config; diff --git a/apps/federatedfilesharing/lib/TokenHandler.php b/apps/federatedfilesharing/lib/TokenHandler.php index 2429cbf28a38..3df846dd28ec 100644 --- a/apps/federatedfilesharing/lib/TokenHandler.php +++ b/apps/federatedfilesharing/lib/TokenHandler.php @@ -31,8 +31,7 @@ class TokenHandler { public const TOKEN_LENGTH = 15; - /** @var ISecureRandom */ - private $secureRandom; + private \OCP\Security\ISecureRandom $secureRandom; /** * TokenHandler constructor. diff --git a/apps/federatedfilesharing/tests/AddressHandlerTest.php b/apps/federatedfilesharing/tests/AddressHandlerTest.php index 2258fe2acb1d..6f46e2af4f4e 100644 --- a/apps/federatedfilesharing/tests/AddressHandlerTest.php +++ b/apps/federatedfilesharing/tests/AddressHandlerTest.php @@ -28,20 +28,19 @@ use OCP\IURLGenerator; class AddressHandlerTest extends \Test\TestCase { - /** @var AddressHandler */ - private $addressHandler; + private \OCA\FederatedFileSharing\AddressHandler $addressHandler; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $il10n; + private \PHPUnit\Framework\MockObject\MockObject $il10n; public function setUp(): void { parent::setUp(); - $this->urlGenerator = $this->createMock('OCP\IURLGenerator'); - $this->il10n = $this->createMock('OCP\IL10N'); + $this->urlGenerator = $this->createMock(\OCP\IURLGenerator::class); + $this->il10n = $this->createMock(\OCP\IL10N::class); $this->addressHandler = new AddressHandler($this->urlGenerator, $this->il10n); } @@ -85,7 +84,7 @@ public function dataTestSplitUserRemote() { * @param string $expectedUrl */ public function testSplitUserRemote($remote, $expectedUser, $expectedUrl) { - list($remoteUser, $remoteUrl) = $this->addressHandler->splitUserRemote($remote); + [$remoteUser, $remoteUrl] = $this->addressHandler->splitUserRemote($remote); $this->assertSame($expectedUser, $remoteUser); $this->assertSame($expectedUrl, $remoteUrl); } diff --git a/apps/federatedfilesharing/tests/Command/PollIncomingSharesTest.php b/apps/federatedfilesharing/tests/Command/PollIncomingSharesTest.php index 54885157d1ad..f99968c49f36 100644 --- a/apps/federatedfilesharing/tests/Command/PollIncomingSharesTest.php +++ b/apps/federatedfilesharing/tests/Command/PollIncomingSharesTest.php @@ -46,25 +46,24 @@ * @package OCA\FederatedFileSharing\Tests\Command */ class PollIncomingSharesTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; /** @var IDBConnection | MockObject */ - private $dbConnection; + private \PHPUnit\Framework\MockObject\MockObject $dbConnection; /** @var IUserManager | MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var MountProvider | MockObject */ - private $externalMountProvider; + private \PHPUnit\Framework\MockObject\MockObject $externalMountProvider; /** @var IStorageFactory | MockObject */ - private $loader; + private \PHPUnit\Framework\MockObject\MockObject $loader; /** * @var Manager | MockObject */ - private $externalManager; + private \PHPUnit\Framework\MockObject\MockObject $externalManager; protected function setUp(): void { parent::setUp(); diff --git a/apps/federatedfilesharing/tests/Controller/OcmControllerTest.php b/apps/federatedfilesharing/tests/Controller/OcmControllerTest.php index 6532d544a783..2a6a803f3868 100644 --- a/apps/federatedfilesharing/tests/Controller/OcmControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/OcmControllerTest.php @@ -50,57 +50,51 @@ class OcmControllerTest extends TestCase { /** * @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** * @var OcmMiddleware | \PHPUnit\Framework\MockObject\MockObject */ - private $ocmMiddleware; + private \PHPUnit\Framework\MockObject\MockObject $ocmMiddleware; /** * @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** * @var IAppManager | \PHPUnit\Framework\MockObject\MockObject */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; /** * @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** * @var AddressHandler | \PHPUnit\Framework\MockObject\MockObject */ - private $addressHandler; + private \PHPUnit\Framework\MockObject\MockObject $addressHandler; /** * @var FedShareManager | \PHPUnit\Framework\MockObject\MockObject */ - private $fedShareManager; + private \PHPUnit\Framework\MockObject\MockObject $fedShareManager; /** * @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** * @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; - /** - * @var OcmController - */ - private $ocmController; + private \OCA\FederatedFileSharing\Controller\OcmController $ocmController; - /** - * @var string - */ - private $shareToken = 'abc'; + private string $shareToken = 'abc'; protected function setUp(): void { parent::setUp(); diff --git a/apps/federatedfilesharing/tests/Controller/RequestHandlerTest.php b/apps/federatedfilesharing/tests/Controller/RequestHandlerTest.php index fe9df1709d13..8cfb40d82fad 100644 --- a/apps/federatedfilesharing/tests/Controller/RequestHandlerTest.php +++ b/apps/federatedfilesharing/tests/Controller/RequestHandlerTest.php @@ -56,27 +56,27 @@ class RequestHandlerTest extends TestCase { /** * @var IRequest | MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** * @var OcmMiddleware */ - private $ocmMiddleware; + private \PHPUnit\Framework\MockObject\MockObject $ocmMiddleware; /** * @var IUserManager | MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** * @var AddressHandler | MockObject */ - private $addressHandler; + private \PHPUnit\Framework\MockObject\MockObject $addressHandler; /** * @var FedShareManager | MockObject */ - private $fedShareManager; + private \PHPUnit\Framework\MockObject\MockObject $fedShareManager; private RequestHandlerController $requestHandlerController; diff --git a/apps/federatedfilesharing/tests/Controller/SharingPersonalSettingsControllerTest.php b/apps/federatedfilesharing/tests/Controller/SharingPersonalSettingsControllerTest.php index 34d6c8d26c62..473c631cbb3c 100644 --- a/apps/federatedfilesharing/tests/Controller/SharingPersonalSettingsControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/SharingPersonalSettingsControllerTest.php @@ -32,16 +32,15 @@ class SharingPersonalSettingsControllerTest extends TestCase { /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject $config */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject $userSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; - /** @var SharingPersonalSettingsController $personalSettingsController */ - private $sharingPersonalSettingsController; + private \OCA\FederatedFileSharing\Controller\SharingPersonalSettingsController $sharingPersonalSettingsController; protected function setUp(): void { parent::setUp(); diff --git a/apps/federatedfilesharing/tests/DiscoveryManagerTest.php b/apps/federatedfilesharing/tests/DiscoveryManagerTest.php index 03e15af0293a..b4849a98685f 100644 --- a/apps/federatedfilesharing/tests/DiscoveryManagerTest.php +++ b/apps/federatedfilesharing/tests/DiscoveryManagerTest.php @@ -32,17 +32,16 @@ class DiscoveryManagerTest extends \Test\TestCase { /** @var ICache */ - private $cache; + private \PHPUnit\Framework\MockObject\MockObject $cache; /** @var IClient */ - private $client; - /** @var DiscoveryManager */ - private $discoveryManager; + private \PHPUnit\Framework\MockObject\MockObject $client; + private \OCA\FederatedFileSharing\DiscoveryManager $discoveryManager; public function setUp(): void { parent::setUp(); - $this->cache = $this->createMock('\OCP\ICache'); + $this->cache = $this->createMock('\\' . \OCP\ICache::class); /** @var ICacheFactory $cacheFactory */ - $cacheFactory = $this->getMockBuilder('\OCP\ICacheFactory') + $cacheFactory = $this->getMockBuilder('\\' . \OCP\ICacheFactory::class) ->disableOriginalConstructor()->getMock(); $cacheFactory ->expects($this->once()) @@ -50,10 +49,10 @@ public function setUp(): void { ->with('ocs-discovery') ->willReturn($this->cache); - $this->client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $this->client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); /** @var IClientService $clientService */ - $clientService = $this->getMockBuilder('\OCP\Http\Client\IClientService') + $clientService = $this->getMockBuilder('\\' . \OCP\Http\Client\IClientService::class) ->disableOriginalConstructor()->getMock(); $clientService ->expects($this->once()) @@ -68,7 +67,7 @@ public function setUp(): void { } public function testWithMalformedFormattedEndpointCached() { - $response = $this->createMock('\OCP\Http\Client\IResponse'); + $response = $this->createMock('\\' . \OCP\Http\Client\IResponse::class); $response ->expects($this->once()) ->method('getStatusCode') @@ -97,7 +96,7 @@ public function testWithMalformedFormattedEndpointCached() { ], ) ->willReturnOnConsecutiveCalls( - $this->createMock('\OCP\Http\Client\IResponse'), + $this->createMock('\\' . \OCP\Http\Client\IResponse::class), $response, ); @@ -125,7 +124,7 @@ public function testWithMalformedFormattedEndpointCached() { } public function testGetWebDavEndpointWithValidFormattedEndpointAndNotCached() { - $response = $this->createMock('\OCP\Http\Client\IResponse'); + $response = $this->createMock('\\' . \OCP\Http\Client\IResponse::class); $response ->expects($this->once()) ->method('getStatusCode') @@ -155,7 +154,7 @@ public function testGetWebDavEndpointWithValidFormattedEndpointAndNotCached() { ], ) ->willReturnOnConsecutiveCalls( - $this->createMock('\OCP\Http\Client\IResponse'), + $this->createMock('\\' . \OCP\Http\Client\IResponse::class), $response, ); @@ -164,7 +163,7 @@ public function testGetWebDavEndpointWithValidFormattedEndpointAndNotCached() { } public function testGetWebDavEndpointWithValidFormattedEndpointWithoutDataAndNotCached() { - $response = $this->createMock('\OCP\Http\Client\IResponse'); + $response = $this->createMock('\\' . \OCP\Http\Client\IResponse::class); $response ->expects($this->once()) ->method('getStatusCode') @@ -194,7 +193,7 @@ public function testGetWebDavEndpointWithValidFormattedEndpointWithoutDataAndNot ], ) ->willReturnOnConsecutiveCalls( - $this->createMock('\OCP\Http\Client\IResponse'), + $this->createMock('\\' . \OCP\Http\Client\IResponse::class), $response, ); @@ -203,7 +202,7 @@ public function testGetWebDavEndpointWithValidFormattedEndpointWithoutDataAndNot } public function testGetShareEndpointWithValidFormattedEndpointAndNotCached() { - $response = $this->createMock('\OCP\Http\Client\IResponse'); + $response = $this->createMock('\\' . \OCP\Http\Client\IResponse::class); $response ->expects($this->once()) ->method('getStatusCode') @@ -226,7 +225,7 @@ public function testGetShareEndpointWithValidFormattedEndpointAndNotCached() { } public function testWithMaliciousEndpointCached() { - $response = $this->createMock('\OCP\Http\Client\IResponse'); + $response = $this->createMock('\\' . \OCP\Http\Client\IResponse::class); $response ->expects($this->once()) ->method('getStatusCode') @@ -256,7 +255,7 @@ public function testWithMaliciousEndpointCached() { ], ) ->willReturnOnConsecutiveCalls( - $this->createMock('\OCP\Http\Client\IResponse'), + $this->createMock('\\' . \OCP\Http\Client\IResponse::class), $response, ); diff --git a/apps/federatedfilesharing/tests/External/ManagerTest.php b/apps/federatedfilesharing/tests/External/ManagerTest.php index a8938546cd77..e1e681a366a8 100644 --- a/apps/federatedfilesharing/tests/External/ManagerTest.php +++ b/apps/federatedfilesharing/tests/External/ManagerTest.php @@ -34,25 +34,24 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; class ManagerTest extends TestCase { - /** @var Manager */ - private $manager; + private \OCA\Files_Sharing\External\Manager $manager; /** @var IDBConnection | \PHPUnit\Framework\MockObject\MockObject */ - private $connection; + private \PHPUnit\Framework\MockObject\MockObject $connection; /** @var MountManager | \PHPUnit\Framework\MockObject\MockObject */ - private $mountManager; + private \PHPUnit\Framework\MockObject\MockObject $mountManager; /** @var IStorageFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $storageFactory; + private \PHPUnit\Framework\MockObject\MockObject $storageFactory; /** @var IManager | \PHPUnit\Framework\MockObject\MockObject */ - private $notificationManager; + private \PHPUnit\Framework\MockObject\MockObject $notificationManager; /** @var EventDispatcherInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; + private \PHPUnit\Framework\MockObject\MockObject $eventDispatcher; - private $uid = 'john doe'; + private string $uid = 'john doe'; protected function setUp():void { $this->connection = $this->createMock(IDBConnection::class); diff --git a/apps/federatedfilesharing/tests/FedShareManagerTest.php b/apps/federatedfilesharing/tests/FedShareManagerTest.php index 8bd482900baf..153a0d528cbf 100644 --- a/apps/federatedfilesharing/tests/FedShareManagerTest.php +++ b/apps/federatedfilesharing/tests/FedShareManagerTest.php @@ -44,28 +44,28 @@ */ class FedShareManagerTest extends TestCase { /** @var FederatedShareProvider | \PHPUnit\Framework\MockObject\MockObject */ - private $federatedShareProvider; + private \PHPUnit\Framework\MockObject\MockObject $federatedShareProvider; /** @var Notifications | \PHPUnit\Framework\MockObject\MockObject */ - private $notifications; + private \PHPUnit\Framework\MockObject\MockObject $notifications; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var ActivityManager | \PHPUnit\Framework\MockObject\MockObject */ - private $activityManager; + private \PHPUnit\Framework\MockObject\MockObject $activityManager; /** @var NotificationManager | \PHPUnit\Framework\MockObject\MockObject */ - private $notificationManager; + private \PHPUnit\Framework\MockObject\MockObject $notificationManager; /** @var FedShareManager | \PHPUnit\Framework\MockObject\MockObject */ - private $fedShareManager; + private \PHPUnit\Framework\MockObject\MockObject $fedShareManager; /** @var AddressHandler | \PHPUnit\Framework\MockObject\MockObject */ - private $addressHandler; + private \PHPUnit\Framework\MockObject\MockObject $addressHandler; /** @var EventDispatcherInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; + private \PHPUnit\Framework\MockObject\MockObject $eventDispatcher; protected function setUp(): void { parent::setUp(); @@ -270,7 +270,7 @@ public function testIsFederatedReShare() { ->method('getSharedBy') ->willReturn($shareInitiator); - $nodeMock = $this->getMockBuilder('OCP\Files\Node') + $nodeMock = $this->getMockBuilder(\OCP\Files\Node::class) ->disableOriginalConstructor()->getMock(); $share->expects($this->once()) ->method('getNode') diff --git a/apps/federatedfilesharing/tests/FederatedShareProviderTest.php b/apps/federatedfilesharing/tests/FederatedShareProviderTest.php index 689e9f150361..c7ea86518271 100644 --- a/apps/federatedfilesharing/tests/FederatedShareProviderTest.php +++ b/apps/federatedfilesharing/tests/FederatedShareProviderTest.php @@ -98,9 +98,7 @@ public function setUp(): void { $this->tokenHandler = $this->createMock(TokenHandler::class); $this->l = $this->createMock(IL10N::class); $this->l->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $this->logger = $this->createMock(ILogger::class); $this->rootFolder = $this->createMock(IRootFolder::class); $this->config = $this->createMock(IConfig::class); diff --git a/apps/federatedfilesharing/tests/Middleware/OcmMiddlewareTest.php b/apps/federatedfilesharing/tests/Middleware/OcmMiddlewareTest.php index 087e29d479cc..42422aa27a1d 100644 --- a/apps/federatedfilesharing/tests/Middleware/OcmMiddlewareTest.php +++ b/apps/federatedfilesharing/tests/Middleware/OcmMiddlewareTest.php @@ -41,35 +41,32 @@ * @group DB */ class OcmMiddlewareTest extends TestCase { - /** - * @var OcmMiddleware - */ - private $ocmMiddleware; + private \OCA\FederatedFileSharing\Middleware\OcmMiddleware $ocmMiddleware; /** * @var FederatedShareProvider | \PHPUnit\Framework\MockObject\MockObject */ - private $federatedShareProvider; + private \PHPUnit\Framework\MockObject\MockObject $federatedShareProvider; /** * @var IAppManager | \PHPUnit\Framework\MockObject\MockObject */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; /** * @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** * @var AddressHandler | \PHPUnit\Framework\MockObject\MockObject */ - private $addressHandler; + private \PHPUnit\Framework\MockObject\MockObject $addressHandler; /** * @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; protected function setUp(): void { parent::setUp(); diff --git a/apps/federatedfilesharing/tests/NotificationsTest.php b/apps/federatedfilesharing/tests/NotificationsTest.php index a8c2045447b3..0d56655293df 100644 --- a/apps/federatedfilesharing/tests/NotificationsTest.php +++ b/apps/federatedfilesharing/tests/NotificationsTest.php @@ -41,22 +41,22 @@ class NotificationsTest extends \Test\TestCase { /** @var AddressHandler | \PHPUnit\Framework\MockObject\MockObject */ - private $addressHandler; + private \PHPUnit\Framework\MockObject\MockObject $addressHandler; /** @var IClientService | \PHPUnit\Framework\MockObject\MockObject*/ - private $httpClientService; + private \PHPUnit\Framework\MockObject\MockObject $httpClientService; /** @var DiscoveryManager | \PHPUnit\Framework\MockObject\MockObject */ - private $discoveryManager; + private \PHPUnit\Framework\MockObject\MockObject $discoveryManager; /** @var NotificationManager | \PHPUnit\Framework\MockObject\MockObject */ - private $notificationManager; + private \OCA\FederatedFileSharing\Ocm\NotificationManager $notificationManager; /** @var IJobList | \PHPUnit\Framework\MockObject\MockObject */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); @@ -187,10 +187,8 @@ public function testOcmRequestsAreJson() { ->with( $this->anything(), $this->callback( - function ($options) { - return isset($options['json']) - && !isset($options['body']); - } + fn ($options) => isset($options['json']) + && !isset($options['body']) ) ) ->willReturn($responseMock); diff --git a/apps/federatedfilesharing/tests/Panels/AdminPanelTest.php b/apps/federatedfilesharing/tests/Panels/AdminPanelTest.php index 92c6bd74db31..9fb0af441c61 100644 --- a/apps/federatedfilesharing/tests/Panels/AdminPanelTest.php +++ b/apps/federatedfilesharing/tests/Panels/AdminPanelTest.php @@ -29,12 +29,11 @@ * @package OCA\FederatedFileSharing\Tests */ class AdminPanelTest extends \Test\TestCase { - /** @var AdminPanel */ - private $panel; + private \OCA\FederatedFileSharing\Panels\AdminPanel $panel; /** @var FederatedShareProvider */ - private $shareProvider; + private \PHPUnit\Framework\MockObject\MockObject $shareProvider; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); diff --git a/apps/federatedfilesharing/tests/Panels/GeneralPersonalPanelTest.php b/apps/federatedfilesharing/tests/Panels/GeneralPersonalPanelTest.php index 602ef9c4f0b2..11b474eec106 100644 --- a/apps/federatedfilesharing/tests/Panels/GeneralPersonalPanelTest.php +++ b/apps/federatedfilesharing/tests/Panels/GeneralPersonalPanelTest.php @@ -33,18 +33,17 @@ * @package OCA\FederatedFileSharing\Tests */ class GeneralPersonalPanelTest extends \Test\TestCase { - /** @var GeneralPersonalPanel */ - private $panel; + private \OCA\FederatedFileSharing\Panels\GeneralPersonalPanel $panel; /** @var IL10N */ - private $l; + private \PHPUnit\Framework\MockObject\MockObject $l; /** @var IURLGenerator */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var FederatedShareProvider */ - private $shareProvider; + private \PHPUnit\Framework\MockObject\MockObject $shareProvider; /** @var IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; public function setUp(): void { parent::setUp(); diff --git a/apps/federatedfilesharing/tests/Panels/SharingPersonalPanelTest.php b/apps/federatedfilesharing/tests/Panels/SharingPersonalPanelTest.php index 22d5233f7546..990ae1d7a0eb 100644 --- a/apps/federatedfilesharing/tests/Panels/SharingPersonalPanelTest.php +++ b/apps/federatedfilesharing/tests/Panels/SharingPersonalPanelTest.php @@ -27,13 +27,12 @@ class SharingPersonalPanelTest extends \Test\TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject $config */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject $userSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; - /** @var SharingPersonalPanel $personalPanel */ - private $sharingPersonalPanel; + private \OCA\FederatedFileSharing\Panels\SharingPersonalPanel $sharingPersonalPanel; protected function setUp(): void { $this->config = $this->getMockBuilder(IConfig::class) diff --git a/apps/federatedfilesharing/tests/TestCase.php b/apps/federatedfilesharing/tests/TestCase.php index 6f5628d63748..5c89d1bd31b1 100644 --- a/apps/federatedfilesharing/tests/TestCase.php +++ b/apps/federatedfilesharing/tests/TestCase.php @@ -100,7 +100,7 @@ protected static function loginHelper($user) { * reset init status for the share storage */ protected static function resetStorage() { - $storage = new \ReflectionClass('\OCA\Files_Sharing\SharedStorage'); + $storage = new \ReflectionClass('\\' . \OCA\Files_Sharing\SharedStorage::class); $isInitialized = $storage->getProperty('initialized'); $isInitialized->setAccessible(true); $isInitialized->setValue($storage, false); diff --git a/apps/federatedfilesharing/tests/TokenHandlerTest.php b/apps/federatedfilesharing/tests/TokenHandlerTest.php index 996ed0329116..516af1cbee13 100644 --- a/apps/federatedfilesharing/tests/TokenHandlerTest.php +++ b/apps/federatedfilesharing/tests/TokenHandlerTest.php @@ -27,19 +27,17 @@ use OCP\Security\ISecureRandom; class TokenHandlerTest extends \Test\TestCase { - /** @var TokenHandler */ - private $tokenHandler; + private \OCA\FederatedFileSharing\TokenHandler $tokenHandler; /** @var ISecureRandom | \PHPUnit\Framework\MockObject\MockObject */ - private $secureRandom; + private \PHPUnit\Framework\MockObject\MockObject $secureRandom; - /** @var int */ - private $expectedTokenLength = 15; + private int $expectedTokenLength = 15; public function setUp(): void { parent::setUp(); - $this->secureRandom = $this->createMock('OCP\Security\ISecureRandom'); + $this->secureRandom = $this->createMock(\OCP\Security\ISecureRandom::class); $this->tokenHandler = new TokenHandler($this->secureRandom); } diff --git a/apps/federatedfilesharing/tests/appinfo/ApplicationTest.php b/apps/federatedfilesharing/tests/appinfo/ApplicationTest.php index a9ed3313ad87..70a7fc643a54 100644 --- a/apps/federatedfilesharing/tests/appinfo/ApplicationTest.php +++ b/apps/federatedfilesharing/tests/appinfo/ApplicationTest.php @@ -62,15 +62,15 @@ public function testPublicPage($isOutgoingSharingEnabled, $isHandlerRegistered) if ($isHandlerRegistered === true) { $eventDispatcher->method('addListener') ->withConsecutive( - ['OCP\Share\Events\AcceptShare', $this->anything()], - ['OCP\Share\Events\DeclineShare', $this->anything()], + [\OCP\Share\Events\AcceptShare::class, $this->anything()], + [\OCP\Share\Events\DeclineShare::class, $this->anything()], ['OCA\Files_Sharing::loadAdditionalScripts', $this->anything()] ); } else { $eventDispatcher->method('addListener') ->withConsecutive( - ['OCP\Share\Events\AcceptShare', $this->anything()], - ['OCP\Share\Events\DeclineShare', $this->anything()] + [\OCP\Share\Events\AcceptShare::class, $this->anything()], + [\OCP\Share\Events\DeclineShare::class, $this->anything()] ); } $application->registerListeners(); diff --git a/apps/federatedfilesharing/tests/appinfo/Migrations/Version20190410160725Test.php b/apps/federatedfilesharing/tests/appinfo/Migrations/Version20190410160725Test.php index 04dbb698aada..e8eeb39aea50 100644 --- a/apps/federatedfilesharing/tests/appinfo/Migrations/Version20190410160725Test.php +++ b/apps/federatedfilesharing/tests/appinfo/Migrations/Version20190410160725Test.php @@ -3,7 +3,7 @@ namespace OCA\FederatedFileSharing\Tests\appinfo\Migrations; // FIXME: autoloader fails to load migration -require_once \dirname(\dirname(\dirname(__DIR__))) . "/appinfo/Migrations/Version20190410160725.php"; +require_once \dirname(__DIR__, 3) . "/appinfo/Migrations/Version20190410160725.php"; use Doctrine\DBAL\Schema\Table; use OCA\FederatedFileSharing\Migrations\Version20190410160725; diff --git a/apps/federation/lib/AppInfo/Application.php b/apps/federation/lib/AppInfo/Application.php index cd4d412998dd..7a2f6829da31 100644 --- a/apps/federation/lib/AppInfo/Application.php +++ b/apps/federation/lib/AppInfo/Application.php @@ -48,20 +48,16 @@ public function __construct($urlParams = []) { private function registerService() { $container = $this->getContainer(); - $container->registerService('addServerMiddleware', function (IAppContainer $c) { - return new AddServerMiddleware( - $c->getAppName(), - \OC::$server->getL10N($c->getAppName()), - \OC::$server->getLogger() - ); - }); + $container->registerService('addServerMiddleware', fn (IAppContainer $c) => new AddServerMiddleware( + $c->getAppName(), + \OC::$server->getL10N($c->getAppName()), + \OC::$server->getLogger() + )); - $container->registerService('DbHandler', function (IAppContainer $c) { - return new DbHandler( - \OC::$server->getDatabaseConnection(), - \OC::$server->getL10N($c->getAppName()) - ); - }); + $container->registerService('DbHandler', fn (IAppContainer $c) => new DbHandler( + \OC::$server->getDatabaseConnection(), + \OC::$server->getL10N($c->getAppName()) + )); $container->registerService('TrustedServers', function (IAppContainer $c) { $server = $c->getServer(); @@ -101,7 +97,7 @@ public function registerHooks() { $hooksManager = new Hooks($container->query('TrustedServers')); Util::connectHook( - 'OCP\Share', + \OCP\Share::class, 'federated_share_added', $hooksManager, 'addServerHook' diff --git a/apps/federation/lib/BackgroundJob/GetSharedSecret.php b/apps/federation/lib/BackgroundJob/GetSharedSecret.php index e8b8a9b40dea..656044b85602 100644 --- a/apps/federation/lib/BackgroundJob/GetSharedSecret.php +++ b/apps/federation/lib/BackgroundJob/GetSharedSecret.php @@ -52,11 +52,9 @@ class GetSharedSecret extends Job { /** @var IURLGenerator */ private $urlGenerator; - /** @var TrustedServers */ - private $trustedServers; + private ?\OCA\Federation\TrustedServers $trustedServers = null; - /** @var DbHandler */ - private $dbHandler; + private \OCA\Federation\DbHandler $dbHandler; /** @var ILogger */ private $logger; @@ -64,7 +62,7 @@ class GetSharedSecret extends Job { /** @var bool */ protected $retainJob = false; - private $endPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret'; + private string $endPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret'; /** * RequestSharedSecret constructor. @@ -84,11 +82,11 @@ public function __construct( ILogger $logger = null, DbHandler $dbHandler = null ) { - $this->logger = $logger ? $logger : \OC::$server->getLogger(); - $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient(); - $this->jobList = $jobList ? $jobList : \OC::$server->getJobList(); - $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator(); - $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation')); + $this->logger = $logger ?: \OC::$server->getLogger(); + $this->httpClient = $httpClient ?: \OC::$server->getHTTPClientService()->newClient(); + $this->jobList = $jobList ?: \OC::$server->getJobList(); + $this->urlGenerator = $urlGenerator ?: \OC::$server->getURLGenerator(); + $this->dbHandler = $dbHandler ?: new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation')); if ($trustedServers) { $this->trustedServers = $trustedServers; } else { @@ -179,7 +177,7 @@ protected function run($argument) { if ($status === Http::STATUS_OK && $result instanceof IResponse) { $body = $result->getBody(); - $result = \json_decode($body, true); + $result = \json_decode($body, true, 512, JSON_THROW_ON_ERROR); if (isset($result['ocs']['data']['sharedSecret'])) { $this->trustedServers->addSharedSecret( $target, diff --git a/apps/federation/lib/BackgroundJob/RequestSharedSecret.php b/apps/federation/lib/BackgroundJob/RequestSharedSecret.php index 9682d6085de7..7990a2f480a0 100644 --- a/apps/federation/lib/BackgroundJob/RequestSharedSecret.php +++ b/apps/federation/lib/BackgroundJob/RequestSharedSecret.php @@ -52,13 +52,11 @@ class RequestSharedSecret extends Job { /** @var IURLGenerator */ private $urlGenerator; - /** @var DbHandler */ - private $dbHandler; + private \OCA\Federation\DbHandler $dbHandler; - /** @var TrustedServers */ - private $trustedServers; + private ?\OCA\Federation\TrustedServers $trustedServers = null; - private $endPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret'; + private string $endPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret'; /** @var ILogger */ private $logger; @@ -82,10 +80,10 @@ public function __construct( TrustedServers $trustedServers = null, DbHandler $dbHandler = null ) { - $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient(); - $this->jobList = $jobList ? $jobList : \OC::$server->getJobList(); - $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator(); - $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation')); + $this->httpClient = $httpClient ?: \OC::$server->getHTTPClientService()->newClient(); + $this->jobList = $jobList ?: \OC::$server->getJobList(); + $this->urlGenerator = $urlGenerator ?: \OC::$server->getURLGenerator(); + $this->dbHandler = $dbHandler ?: new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation')); $this->logger = \OC::$server->getLogger(); if ($trustedServers) { $this->trustedServers = $trustedServers; diff --git a/apps/federation/lib/Command/SyncFederationAddressBooks.php b/apps/federation/lib/Command/SyncFederationAddressBooks.php index 138f2d2ee682..8e5f4a2097ca 100644 --- a/apps/federation/lib/Command/SyncFederationAddressBooks.php +++ b/apps/federation/lib/Command/SyncFederationAddressBooks.php @@ -28,8 +28,7 @@ use Symfony\Component\Console\Output\OutputInterface; class SyncFederationAddressBooks extends Command { - /** @var \OCA\Federation\SyncFederationAddressBooks */ - private $syncService; + private \OCA\Federation\SyncFederationAddressBooks $syncService; /** * @param \OCA\Federation\SyncFederationAddressBooks $syncService diff --git a/apps/federation/lib/Command/TrustedServerAdd.php b/apps/federation/lib/Command/TrustedServerAdd.php index 56ed63b085c9..f022ee595f09 100644 --- a/apps/federation/lib/Command/TrustedServerAdd.php +++ b/apps/federation/lib/Command/TrustedServerAdd.php @@ -28,8 +28,7 @@ class TrustedServerAdd extends Command { public const ERROR_ALREADY_TRUSTED = 1; public const ERROR_NO_OWNCLOUD_FOUND = 2; - /** @var TrustedServers */ - private $trustedServers; + private \OCA\Federation\TrustedServers $trustedServers; /** * @param TrustedServers $trustedServers diff --git a/apps/federation/lib/Command/TrustedServerList.php b/apps/federation/lib/Command/TrustedServerList.php index 232a6261dbd9..95bf253c0e76 100644 --- a/apps/federation/lib/Command/TrustedServerList.php +++ b/apps/federation/lib/Command/TrustedServerList.php @@ -26,8 +26,7 @@ use Symfony\Component\Console\Output\OutputInterface; class TrustedServerList extends Command { - /** @var TrustedServers */ - private $trustedServers; + private \OCA\Federation\TrustedServers $trustedServers; /** * @param TrustedServers $trustedServers diff --git a/apps/federation/lib/Command/TrustedServerRemove.php b/apps/federation/lib/Command/TrustedServerRemove.php index e122f2bda719..3b4e67da88c4 100644 --- a/apps/federation/lib/Command/TrustedServerRemove.php +++ b/apps/federation/lib/Command/TrustedServerRemove.php @@ -25,8 +25,7 @@ use Symfony\Component\Console\Output\OutputInterface; class TrustedServerRemove extends Command { - /** @var TrustedServers */ - private $trustedServers; + private \OCA\Federation\TrustedServers $trustedServers; /** * @param TrustedServers $trustedServers diff --git a/apps/federation/lib/Controller/OCSAuthAPIController.php b/apps/federation/lib/Controller/OCSAuthAPIController.php index 815b0b6ae4a9..8d310c05561f 100644 --- a/apps/federation/lib/Controller/OCSAuthAPIController.php +++ b/apps/federation/lib/Controller/OCSAuthAPIController.php @@ -43,20 +43,15 @@ * @package OCA\Federation\Controller */ class OCSAuthAPIController extends OCSController { - /** @var ISecureRandom */ - private $secureRandom; + private \OCP\Security\ISecureRandom $secureRandom; - /** @var IJobList */ - private $jobList; + private \OCP\BackgroundJob\IJobList $jobList; - /** @var TrustedServers */ - private $trustedServers; + private \OCA\Federation\TrustedServers $trustedServers; - /** @var DbHandler */ - private $dbHandler; + private \OCA\Federation\DbHandler $dbHandler; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; /** * OCSAuthAPI constructor. @@ -117,7 +112,7 @@ public function requestSharedSecret($url, $token) { // we ask for the shared secret so we no longer have to ask the other server // to request the shared secret $this->jobList->remove( - 'OCA\Federation\BackgroundJob\RequestSharedSecret', + \OCA\Federation\BackgroundJob\RequestSharedSecret::class, [ 'url' => $url, 'token' => $localToken @@ -125,7 +120,7 @@ public function requestSharedSecret($url, $token) { ); $this->jobList->add( - 'OCA\Federation\BackgroundJob\GetSharedSecret', + \OCA\Federation\BackgroundJob\GetSharedSecret::class, [ 'url' => $url, 'token' => $token, diff --git a/apps/federation/lib/Controller/SettingsController.php b/apps/federation/lib/Controller/SettingsController.php index fb44462c7824..0077db72b4be 100644 --- a/apps/federation/lib/Controller/SettingsController.php +++ b/apps/federation/lib/Controller/SettingsController.php @@ -29,11 +29,9 @@ use OCP\IRequest; class SettingsController extends Controller { - /** @var IL10N */ - private $l; + private \OCP\IL10N $l; - /** @var TrustedServers */ - private $trustedServers; + private \OCA\Federation\TrustedServers $trustedServers; /** * @param string $AppName diff --git a/apps/federation/lib/DAV/FedAuth.php b/apps/federation/lib/DAV/FedAuth.php index 2c01b47ba911..5655e2242efd 100644 --- a/apps/federation/lib/DAV/FedAuth.php +++ b/apps/federation/lib/DAV/FedAuth.php @@ -26,8 +26,7 @@ use Sabre\HTTP\ResponseInterface; class FedAuth extends AbstractBasic { - /** @var DbHandler */ - private $db; + private \OCA\Federation\DbHandler $db; /** * FedAuth constructor. diff --git a/apps/federation/lib/DbHandler.php b/apps/federation/lib/DbHandler.php index 207d42304420..c91e10965b0e 100644 --- a/apps/federation/lib/DbHandler.php +++ b/apps/federation/lib/DbHandler.php @@ -36,14 +36,11 @@ * @package OCA\Federation */ class DbHandler { - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; - /** @var IL10N */ - private $il10n; + private \OCP\IL10N $il10n; - /** @var string */ - private $dbTable = 'trusted_servers'; + private string $dbTable = 'trusted_servers'; /** * @param IDBConnection $connection diff --git a/apps/federation/lib/Hooks.php b/apps/federation/lib/Hooks.php index 95ffb6b68bbf..de7bda148fd3 100644 --- a/apps/federation/lib/Hooks.php +++ b/apps/federation/lib/Hooks.php @@ -22,8 +22,7 @@ namespace OCA\Federation; class Hooks { - /** @var TrustedServers */ - private $trustedServers; + private \OCA\Federation\TrustedServers $trustedServers; public function __construct(TrustedServers $trustedServers) { $this->trustedServers = $trustedServers; diff --git a/apps/federation/lib/SyncFederationAddressBooks.php b/apps/federation/lib/SyncFederationAddressBooks.php index 06deef9e0b6d..fe85d65dd2e2 100644 --- a/apps/federation/lib/SyncFederationAddressBooks.php +++ b/apps/federation/lib/SyncFederationAddressBooks.php @@ -29,8 +29,7 @@ class SyncFederationAddressBooks { /** @var DbHandler */ protected $dbHandler; - /** @var SyncService */ - private $syncService; + private \OCA\DAV\CardDAV\SyncService $syncService; /** * @param DbHandler $dbHandler diff --git a/apps/federation/lib/TrustedServers.php b/apps/federation/lib/TrustedServers.php index 809152253616..c2a73809f733 100644 --- a/apps/federation/lib/TrustedServers.php +++ b/apps/federation/lib/TrustedServers.php @@ -45,25 +45,19 @@ class TrustedServers { public const STATUS_ACCESS_REVOKED = 4; /** @var DbHandler dbHandler */ - private $dbHandler; + private \OCA\Federation\DbHandler $dbHandler; - /** @var IClientService */ - private $httpClientService; + private \OCP\Http\Client\IClientService $httpClientService; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var IJobList */ - private $jobList; + private \OCP\BackgroundJob\IJobList $jobList; - /** @var ISecureRandom */ - private $secureRandom; + private \OCP\Security\ISecureRandom $secureRandom; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var EventDispatcherInterface */ - private $dispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher; /** * @param DbHandler $dbHandler @@ -105,7 +99,7 @@ public function addServer($url) { $token = $this->secureRandom->generate(16); $this->dbHandler->addToken($url, $token); $this->jobList->add( - 'OCA\Federation\BackgroundJob\RequestSharedSecret', + \OCA\Federation\BackgroundJob\RequestSharedSecret::class, [ 'url' => $url, 'token' => $token @@ -238,7 +232,7 @@ public function isOwnCloudServer($url) { * @throws HintException */ protected function checkOwnCloudVersion($status) { - $decoded = \json_decode($status, true); + $decoded = \json_decode($status, true, 512, JSON_THROW_ON_ERROR); if (!empty($decoded) && isset($decoded['version'])) { if (!\version_compare($decoded['version'], '9.0.0', '>=')) { throw new HintException('Remote server version is too low. ownCloud 9.0 is required.'); diff --git a/apps/federation/tests/API/OCSAuthAPITest.php b/apps/federation/tests/API/OCSAuthAPITest.php index d5b5c60fbc11..57536d05785f 100644 --- a/apps/federation/tests/API/OCSAuthAPITest.php +++ b/apps/federation/tests/API/OCSAuthAPITest.php @@ -35,25 +35,24 @@ class OCSAuthAPITest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject | IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var \PHPUnit\Framework\MockObject\MockObject | ISecureRandom */ - private $secureRandom; + private \PHPUnit\Framework\MockObject\MockObject $secureRandom; /** @var \PHPUnit\Framework\MockObject\MockObject | JobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers */ - private $trustedServers; + private \PHPUnit\Framework\MockObject\MockObject $trustedServers; /** @var \PHPUnit\Framework\MockObject\MockObject | DbHandler */ - private $dbHandler; + private \PHPUnit\Framework\MockObject\MockObject $dbHandler; /** @var \PHPUnit\Framework\MockObject\MockObject | ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; - /** @var OCSAuthAPIController */ - private $ocsAuthApi; + private \OCA\Federation\Controller\OCSAuthAPIController $ocsAuthApi; public function setUp(): void { parent::setUp(); @@ -99,9 +98,9 @@ public function testRequestSharedSecret($token, $localToken, $isTrustedServer, $ if ($expected === Http::STATUS_OK) { $this->jobList->expects($this->once())->method('add') - ->with('OCA\Federation\BackgroundJob\GetSharedSecret', ['url' => $url, 'token' => $token]); + ->with(\OCA\Federation\BackgroundJob\GetSharedSecret::class, ['url' => $url, 'token' => $token]); $this->jobList->expects($this->once())->method('remove') - ->with('OCA\Federation\BackgroundJob\RequestSharedSecret', ['url' => $url, 'token' => $localToken]); + ->with(\OCA\Federation\BackgroundJob\RequestSharedSecret::class, ['url' => $url, 'token' => $localToken]); } else { $this->jobList->expects($this->never())->method('add'); $this->jobList->expects($this->never())->method('remove'); diff --git a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php index 036ece63d8ab..52a7d1309ce6 100644 --- a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php @@ -43,41 +43,40 @@ */ class GetSharedSecretTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject | IClient */ - private $httpClient; + private \PHPUnit\Framework\MockObject\MockObject $httpClient; /** @var \PHPUnit\Framework\MockObject\MockObject | IJobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var \PHPUnit\Framework\MockObject\MockObject | IURLGenerator */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers */ - private $trustedServers; + private \PHPUnit\Framework\MockObject\MockObject $trustedServers; /** @var \PHPUnit\Framework\MockObject\MockObject | DbHandler */ - private $dbHandler; + private \PHPUnit\Framework\MockObject\MockObject $dbHandler; /** @var \PHPUnit\Framework\MockObject\MockObject | ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var \PHPUnit\Framework\MockObject\MockObject | IResponse */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; - /** @var GetSharedSecret */ - private $getSharedSecret; + private \OCA\Federation\BackgroundJob\GetSharedSecret $getSharedSecret; public function setUp(): void { parent::setUp(); - $this->httpClient = $this->createMock('OCP\Http\Client\IClient'); - $this->jobList = $this->createMock('OCP\BackgroundJob\IJobList'); - $this->urlGenerator = $this->createMock('OCP\IURLGenerator'); - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + $this->httpClient = $this->createMock(\OCP\Http\Client\IClient::class); + $this->jobList = $this->createMock(\OCP\BackgroundJob\IJobList::class); + $this->urlGenerator = $this->createMock(\OCP\IURLGenerator::class); + $this->trustedServers = $this->getMockBuilder(\OCA\Federation\TrustedServers::class) ->disableOriginalConstructor()->getMock(); - $this->dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler') + $this->dbHandler = $this->getMockBuilder(\OCA\Federation\DbHandler::class) ->disableOriginalConstructor()->getMock(); - $this->logger = $this->createMock('OCP\ILogger'); - $this->response = $this->createMock('OCP\Http\Client\IResponse'); + $this->logger = $this->createMock(\OCP\ILogger::class); + $this->response = $this->createMock(\OCP\Http\Client\IResponse::class); $this->getSharedSecret = new GetSharedSecret( $this->httpClient, @@ -97,7 +96,7 @@ public function setUp(): void { */ public function testExecute($isTrustedServer, $retainBackgroundJob) { /** @var GetSharedSecret |\PHPUnit\Framework\MockObject\MockObject $getSharedSecret */ - $getSharedSecret = $this->getMockBuilder('OCA\Federation\BackgroundJob\GetSharedSecret') + $getSharedSecret = $this->getMockBuilder(\OCA\Federation\BackgroundJob\GetSharedSecret::class) ->setConstructorArgs( [ $this->httpClient, diff --git a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php index b16cdb19321d..c4a80bd4058c 100644 --- a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php @@ -35,37 +35,36 @@ class RequestSharedSecretTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject | IClient */ - private $httpClient; + private \PHPUnit\Framework\MockObject\MockObject $httpClient; /** @var \PHPUnit\Framework\MockObject\MockObject | IJobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var \PHPUnit\Framework\MockObject\MockObject | IURLGenerator */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var \PHPUnit\Framework\MockObject\MockObject | DbHandler */ - private $dbHandler; + private \PHPUnit\Framework\MockObject\MockObject $dbHandler; /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers */ - private $trustedServers; + private \PHPUnit\Framework\MockObject\MockObject $trustedServers; /** @var \PHPUnit\Framework\MockObject\MockObject | IResponse */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; - /** @var RequestSharedSecret */ - private $requestSharedSecret; + private \OCA\Federation\BackgroundJob\RequestSharedSecret $requestSharedSecret; public function setUp(): void { parent::setUp(); - $this->httpClient = $this->createMock('OCP\Http\Client\IClient'); - $this->jobList = $this->createMock('OCP\BackgroundJob\IJobList'); - $this->urlGenerator = $this->createMock('OCP\IURLGenerator'); - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + $this->httpClient = $this->createMock(\OCP\Http\Client\IClient::class); + $this->jobList = $this->createMock(\OCP\BackgroundJob\IJobList::class); + $this->urlGenerator = $this->createMock(\OCP\IURLGenerator::class); + $this->trustedServers = $this->getMockBuilder(\OCA\Federation\TrustedServers::class) ->disableOriginalConstructor()->getMock(); - $this->dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler') + $this->dbHandler = $this->getMockBuilder(\OCA\Federation\DbHandler::class) ->disableOriginalConstructor()->getMock(); - $this->response = $this->createMock('OCP\Http\Client\IResponse'); + $this->response = $this->createMock(\OCP\Http\Client\IResponse::class); $this->requestSharedSecret = new RequestSharedSecret( $this->httpClient, @@ -84,7 +83,7 @@ public function setUp(): void { */ public function testExecute($isTrustedServer, $retainBackgroundJob) { /** @var RequestSharedSecret |\PHPUnit\Framework\MockObject\MockObject $requestSharedSecret */ - $requestSharedSecret = $this->getMockBuilder('OCA\Federation\BackgroundJob\RequestSharedSecret') + $requestSharedSecret = $this->getMockBuilder(\OCA\Federation\BackgroundJob\RequestSharedSecret::class) ->setConstructorArgs( [ $this->httpClient, diff --git a/apps/federation/tests/Command/TrustedServerAddTest.php b/apps/federation/tests/Command/TrustedServerAddTest.php index e656b99e09b4..e0d3fda48107 100644 --- a/apps/federation/tests/Command/TrustedServerAddTest.php +++ b/apps/federation/tests/Command/TrustedServerAddTest.php @@ -29,10 +29,10 @@ */ class TrustedServerAddTest extends TestCase { /** @var TrustedServers */ - private $trustedServers; + private \PHPUnit\Framework\MockObject\MockObject $trustedServers; /** @var TrustedServerAdd */ - private $command; + private \Symfony\Component\Console\Tester\CommandTester $command; protected function setUp(): void { $this->trustedServers = $this->createMock(TrustedServers::class); diff --git a/apps/federation/tests/Command/TrustedServerListTest.php b/apps/federation/tests/Command/TrustedServerListTest.php index 231857958add..bd67243cfea3 100644 --- a/apps/federation/tests/Command/TrustedServerListTest.php +++ b/apps/federation/tests/Command/TrustedServerListTest.php @@ -29,10 +29,10 @@ */ class TrustedServerListTest extends TestCase { /** @var TrustedServers */ - private $trustedServers; + private \PHPUnit\Framework\MockObject\MockObject $trustedServers; /** @var TrustedServerList */ - private $command; + private \Symfony\Component\Console\Tester\CommandTester $command; protected function setUp(): void { $this->trustedServers = $this->createMock(TrustedServers::class); diff --git a/apps/federation/tests/Command/TrustedServerRemoveTest.php b/apps/federation/tests/Command/TrustedServerRemoveTest.php index 7a8a9898b7be..0bc5dcb486f5 100644 --- a/apps/federation/tests/Command/TrustedServerRemoveTest.php +++ b/apps/federation/tests/Command/TrustedServerRemoveTest.php @@ -29,10 +29,10 @@ */ class TrustedServerRemoveTest extends TestCase { /** @var TrustedServers */ - private $trustedServers; + private \PHPUnit\Framework\MockObject\MockObject $trustedServers; /** @var TrustedServerRemove */ - private $command; + private \Symfony\Component\Console\Tester\CommandTester $command; protected function setUp(): void { $this->trustedServers = $this->createMock(TrustedServers::class); diff --git a/apps/federation/tests/Controller/SettingsControllerTest.php b/apps/federation/tests/Controller/SettingsControllerTest.php index 1448cae51634..b7417c23a47a 100644 --- a/apps/federation/tests/Controller/SettingsControllerTest.php +++ b/apps/federation/tests/Controller/SettingsControllerTest.php @@ -27,24 +27,23 @@ use Test\TestCase; class SettingsControllerTest extends TestCase { - /** @var SettingsController */ - private $controller; + private \OCA\Federation\Controller\SettingsController $controller; /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Federation\TrustedServers */ - private $trustedServers; + private \PHPUnit\Framework\MockObject\MockObject $trustedServers; public function setUp(): void { parent::setUp(); - $this->request = $this->createMock('OCP\IRequest'); - $this->l10n = $this->createMock('OCP\IL10N'); - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + $this->request = $this->createMock(\OCP\IRequest::class); + $this->l10n = $this->createMock(\OCP\IL10N::class); + $this->trustedServers = $this->getMockBuilder(\OCA\Federation\TrustedServers::class) ->disableOriginalConstructor()->getMock(); $this->controller = new SettingsController( diff --git a/apps/federation/tests/DAV/FedAuthTest.php b/apps/federation/tests/DAV/FedAuthTest.php index 538e71dc8739..5d1e487bd60b 100644 --- a/apps/federation/tests/DAV/FedAuthTest.php +++ b/apps/federation/tests/DAV/FedAuthTest.php @@ -35,7 +35,7 @@ class FedAuthTest extends TestCase { */ public function testFedAuth($expected, $user, $password) { /** @var DbHandler | \PHPUnit\Framework\MockObject\MockObject $db */ - $db = $this->getMockBuilder('OCA\Federation\DbHandler')->disableOriginalConstructor()->getMock(); + $db = $this->getMockBuilder(\OCA\Federation\DbHandler::class)->disableOriginalConstructor()->getMock(); $db->method('auth')->willReturn(true); $auth = new FedAuth($db); $result = self::invokePrivate($auth, 'validateUserPass', [$user, $password]); diff --git a/apps/federation/tests/DbHandlerTest.php b/apps/federation/tests/DbHandlerTest.php index 4ea5eda66541..d9aeb481b592 100644 --- a/apps/federation/tests/DbHandlerTest.php +++ b/apps/federation/tests/DbHandlerTest.php @@ -33,23 +33,21 @@ * @group DB */ class DbHandlerTest extends TestCase { - /** @var DbHandler */ - private $dbHandler; + private \OCA\Federation\DbHandler $dbHandler; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $il10n; + private \PHPUnit\Framework\MockObject\MockObject $il10n; /** @var IDBConnection */ private $connection; - /** @var string */ - private $dbTable = 'trusted_servers'; + private string $dbTable = 'trusted_servers'; public function setUp(): void { parent::setUp(); $this->connection = \OC::$server->getDatabaseConnection(); - $this->il10n = $this->createMock('OCP\IL10N'); + $this->il10n = $this->createMock(\OCP\IL10N::class); $this->dbHandler = new DbHandler( $this->connection, diff --git a/apps/federation/tests/HooksTest.php b/apps/federation/tests/HooksTest.php index ff03847c2890..71cad3abf5b6 100644 --- a/apps/federation/tests/HooksTest.php +++ b/apps/federation/tests/HooksTest.php @@ -28,15 +28,14 @@ class HooksTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers */ - private $trustedServers; + private \PHPUnit\Framework\MockObject\MockObject $trustedServers; - /** @var Hooks */ - private $hooks; + private \OCA\Federation\Hooks $hooks; public function setUp(): void { parent::setUp(); - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + $this->trustedServers = $this->getMockBuilder(\OCA\Federation\TrustedServers::class) ->disableOriginalConstructor()->getMock(); $this->hooks = new Hooks($this->trustedServers); diff --git a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php index 1a5808d17e8a..4c7458c87b52 100644 --- a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php +++ b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php @@ -31,23 +31,22 @@ class AddServerMiddlewareTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject | ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; - /** @var AddServerMiddleware */ - private $middleware; + private \OCA\Federation\Middleware\AddServerMiddleware $middleware; /** @var \PHPUnit\Framework\MockObject\MockObject | Controller */ - private $controller; + private \PHPUnit\Framework\MockObject\MockObject $controller; public function setUp(): void { parent::setUp(); - $this->logger = $this->createMock('OCP\ILogger'); - $this->l10n = $this->createMock('OCP\IL10N'); - $this->controller = $this->getMockBuilder('OCP\AppFramework\Controller') + $this->logger = $this->createMock(\OCP\ILogger::class); + $this->l10n = $this->createMock(\OCP\IL10N::class); + $this->controller = $this->getMockBuilder(\OCP\AppFramework\Controller::class) ->disableOriginalConstructor()->getMock(); $this->middleware = new AddServerMiddleware( @@ -70,9 +69,7 @@ public function testAfterException($exception, $message, $hint) { $this->l10n->expects($this->any())->method('t') ->willReturnCallback( - function ($message) { - return $message; - } + fn ($message) => $message ); $result = $this->middleware->afterException($this->controller, 'method', $exception); diff --git a/apps/federation/tests/PanelTest.php b/apps/federation/tests/PanelTest.php index c28cfd2f013f..5416ee41f3bf 100644 --- a/apps/federation/tests/PanelTest.php +++ b/apps/federation/tests/PanelTest.php @@ -37,24 +37,23 @@ * @package OCA\Federation\Tests */ class PanelTest extends \Test\TestCase { - /** @var Admin */ - private $panel; + private \OCA\Federation\Panels\Admin $panel; /** @var IDBConnection */ - private $connection; + private \PHPUnit\Framework\MockObject\MockObject $connection; /** @var IL10N */ - private $l; + private \PHPUnit\Framework\MockObject\MockObject $l; /** @var ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IJobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var IClientService */ - private $clientService; + private \PHPUnit\Framework\MockObject\MockObject $clientService; /** @var ISecureRandom */ - private $secureRandom; + private \PHPUnit\Framework\MockObject\MockObject $secureRandom; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var EventDispatcherInterface */ - private $eventDispatcher; + private \PHPUnit\Framework\MockObject\MockObject $eventDispatcher; public function setUp(): void { parent::setUp(); diff --git a/apps/federation/tests/SyncFederationAddressbooksTest.php b/apps/federation/tests/SyncFederationAddressbooksTest.php index 6a7b7c09e6fa..1bbd3b07047f 100644 --- a/apps/federation/tests/SyncFederationAddressbooksTest.php +++ b/apps/federation/tests/SyncFederationAddressbooksTest.php @@ -27,12 +27,11 @@ use OCA\Federation\SyncFederationAddressBooks; class SyncFederationAddressbooksTest extends \Test\TestCase { - /** @var array */ - private $callBacks = []; + private array $callBacks = []; public function testSync() { /** @var DbHandler | \PHPUnit\Framework\MockObject\MockObject $dbHandler */ - $dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler')-> + $dbHandler = $this->getMockBuilder(\OCA\Federation\DbHandler::class)-> disableOriginalConstructor()-> getMock(); $dbHandler->method('getAllServer')-> @@ -46,7 +45,7 @@ public function testSync() { ]); $dbHandler->expects($this->once())->method('setServerStatus')-> with('https://cloud.drop.box', 1, '1'); - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') + $syncService = $this->getMockBuilder(\OCA\DAV\CardDAV\SyncService::class) ->disableOriginalConstructor() ->getMock(); $syncService->expects($this->once())->method('syncRemoteAddressBook') @@ -62,7 +61,7 @@ public function testSync() { public function testException() { /** @var DbHandler | \PHPUnit\Framework\MockObject\MockObject $dbHandler */ - $dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler')-> + $dbHandler = $this->getMockBuilder(\OCA\Federation\DbHandler::class)-> disableOriginalConstructor()-> getMock(); $dbHandler->method('getAllServer')-> @@ -74,7 +73,7 @@ public function testException() { 'sync_token' => '0' ] ]); - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') + $syncService = $this->getMockBuilder(\OCA\DAV\CardDAV\SyncService::class) ->disableOriginalConstructor() ->getMock(); $syncService->expects($this->once())->method('syncRemoteAddressBook') diff --git a/apps/federation/tests/TrustedServersTest.php b/apps/federation/tests/TrustedServersTest.php index 1f0126e0a60e..40798dea984c 100644 --- a/apps/federation/tests/TrustedServersTest.php +++ b/apps/federation/tests/TrustedServersTest.php @@ -38,55 +38,53 @@ class TrustedServersTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers */ - private $trustedServers; + private \OCA\Federation\TrustedServers $trustedServers; /** @var \PHPUnit\Framework\MockObject\MockObject | DbHandler */ - private $dbHandler; + private \PHPUnit\Framework\MockObject\MockObject $dbHandler; /** @var \PHPUnit\Framework\MockObject\MockObject | IClientService */ - private $httpClientService; + private \PHPUnit\Framework\MockObject\MockObject $httpClientService; /** @var \PHPUnit\Framework\MockObject\MockObject | IClient */ - private $httpClient; + private \PHPUnit\Framework\MockObject\MockObject $httpClient; /** @var \PHPUnit\Framework\MockObject\MockObject | IResponse */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; /** @var \PHPUnit\Framework\MockObject\MockObject | ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var \PHPUnit\Framework\MockObject\MockObject | IJobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var \PHPUnit\Framework\MockObject\MockObject | ISecureRandom */ - private $secureRandom; + private \PHPUnit\Framework\MockObject\MockObject $secureRandom; /** @var \PHPUnit\Framework\MockObject\MockObject | IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var \PHPUnit\Framework\MockObject\MockObject | EventDispatcherInterface */ - private $dispatcher; + private \PHPUnit\Framework\MockObject\MockObject $dispatcher; public function setUp(): void { parent::setUp(); - $this->dbHandler = $this->getMockBuilder('\OCA\Federation\DbHandler') + $this->dbHandler = $this->getMockBuilder('\\' . \OCA\Federation\DbHandler::class) ->disableOriginalConstructor()->getMock(); - $this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface') + $this->dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class) ->disableOriginalConstructor()->getMock(); $this->dispatcher->expects($this->any())->method('dispatch') ->will( - $this->returnCallback(function ($object) { - return $object; - }) + $this->returnCallback(fn ($object) => $object) ); - $this->httpClientService = $this->createMock('OCP\Http\Client\IClientService'); - $this->httpClient = $this->createMock('OCP\Http\Client\IClient'); - $this->response = $this->createMock('OCP\Http\Client\IResponse'); - $this->logger = $this->createMock('OCP\ILogger'); - $this->jobList = $this->createMock('OCP\BackgroundJob\IJobList'); - $this->secureRandom = $this->createMock('OCP\Security\ISecureRandom'); - $this->config = $this->createMock('OCP\IConfig'); + $this->httpClientService = $this->createMock(\OCP\Http\Client\IClientService::class); + $this->httpClient = $this->createMock(\OCP\Http\Client\IClient::class); + $this->response = $this->createMock(\OCP\Http\Client\IResponse::class); + $this->logger = $this->createMock(\OCP\ILogger::class); + $this->jobList = $this->createMock(\OCP\BackgroundJob\IJobList::class); + $this->secureRandom = $this->createMock(\OCP\Security\ISecureRandom::class); + $this->config = $this->createMock(\OCP\IConfig::class); $this->trustedServers = new TrustedServers( $this->dbHandler, @@ -106,7 +104,7 @@ public function setUp(): void { */ public function testAddServer($success) { /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers $trustedServers */ - $trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + $trustedServers = $this->getMockBuilder(\OCA\Federation\TrustedServers::class) ->setConstructorArgs( [ $this->dbHandler, @@ -131,7 +129,7 @@ public function testAddServer($success) { $this->dbHandler->expects($this->once())->method('addToken')->with('https://url', 'token'); $this->jobList->expects($this->once())->method('add') ->with( - 'OCA\Federation\BackgroundJob\RequestSharedSecret', + \OCA\Federation\BackgroundJob\RequestSharedSecret::class, ['url' => 'https://url', 'token' => 'token'] ); } else { @@ -215,7 +213,7 @@ public function testRemoveServer() { ->willReturnCallback( function ($event, $eventId) { $this->assertSame($eventId, 'OCP\Federation\TrustedServerEvent::remove'); - $this->assertInstanceOf('Symfony\Component\EventDispatcher\GenericEvent', $event); + $this->assertInstanceOf(\Symfony\Component\EventDispatcher\GenericEvent::class, $event); /** @var \Symfony\Component\EventDispatcher\GenericEvent $event */ $this->assertSame('url_hash', $event->getSubject()); } @@ -266,7 +264,7 @@ public function testIsOwnCloudServer($statusCode, $isValidOwnCloudVersion, $expe $server = 'server1'; /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers $trustedServers */ - $trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + $trustedServers = $this->getMockBuilder(\OCA\Federation\TrustedServers::class) ->setConstructorArgs( [ $this->dbHandler, diff --git a/apps/files/ajax/download.php b/apps/files/ajax/download.php index d08f566c2e32..0504c2a7a150 100644 --- a/apps/files/ajax/download.php +++ b/apps/files/ajax/download.php @@ -33,8 +33,8 @@ \OC::$server->getSession()->close(); // files can be an array with multiple "files[]=one.txt&files[]=two.txt" or a single file with "files=filename.txt" -$files_list = isset($_GET['files']) ? $_GET['files'] : ''; -$dir = isset($_GET['dir']) ? $_GET['dir']: ''; +$files_list = $_GET['files'] ?? ''; +$dir = $_GET['dir'] ?? ''; // in case we get only a single file if (!\is_array($files_list)) { @@ -45,9 +45,7 @@ $files_list = []; } } else { - $files_list = \array_map(function ($file) { - return $file; - }, $files_list); + $files_list = \array_map(fn ($file) => $file, $files_list); } /** @@ -58,7 +56,7 @@ if (isset($_GET['downloadStartSecret']) && !isset($_GET['downloadStartSecret'][32]) && \preg_match('!^[a-zA-Z0-9]+$!', $_GET['downloadStartSecret']) === 1) { - \setcookie('ocDownloadStarted', $_GET['downloadStartSecret'], \time() + 20, '/'); + \setcookie('ocDownloadStarted', $_GET['downloadStartSecret'], ['expires' => \time() + 20, 'path' => '/']); } $server_params = ['head' => \OC::$server->getRequest()->getMethod() == 'HEAD']; diff --git a/apps/files/ajax/list.php b/apps/files/ajax/list.php index 93fb69b55e41..ab8dea0d4217 100644 --- a/apps/files/ajax/list.php +++ b/apps/files/ajax/list.php @@ -45,7 +45,7 @@ $sortAttribute = isset($_GET['sort']) ? (string)$_GET['sort'] : 'name'; $sortDirection = isset($_GET['sortdirection']) ? ($_GET['sortdirection'] === 'desc') : false; - $mimetypeFilters = isset($_GET['mimetypes']) ? \json_decode($_GET['mimetypes']) : ''; + $mimetypeFilters = isset($_GET['mimetypes']) ? \json_decode($_GET['mimetypes'], null, 512, JSON_THROW_ON_ERROR) : ''; $files = []; // Clean up duplicates from array @@ -80,7 +80,7 @@ \OCP\Util::logException('files', $e); OCP\JSON::error([ 'data' => [ - 'exception' => '\OCP\Files\StorageNotAvailableException', + 'exception' => '\\' . \OCP\Files\StorageNotAvailableException::class, 'message' => $l->t('Storage is temporarily not available') ] ]); @@ -88,7 +88,7 @@ \OCP\Util::logException('files', $e); OCP\JSON::error([ 'data' => [ - 'exception' => '\OCP\Files\StorageInvalidException', + 'exception' => '\\' . \OCP\Files\StorageInvalidException::class, 'message' => $l->t('Storage invalid') ] ]); diff --git a/apps/files/appinfo/app.php b/apps/files/appinfo/app.php index 8ecd79fcc4c6..6aab604eda92 100644 --- a/apps/files/appinfo/app.php +++ b/apps/files/appinfo/app.php @@ -27,7 +27,7 @@ // required for translation purpose // t('Files') -\OC::$server->getSearch()->registerProvider('OC\Search\Provider\File', ['apps' => ['files']]); +\OC::$server->getSearch()->registerProvider(\OC\Search\Provider\File::class, ['apps' => ['files']]); // instantiate to make sure services get registered $app = new \OCA\Files\AppInfo\Application(); @@ -50,17 +50,15 @@ ]; }); -\OC::$server->getActivityManager()->registerExtension(function () { - return new \OCA\Files\Activity( - \OC::$server->query('L10NFactory'), - \OC::$server->getURLGenerator(), - \OC::$server->getActivityManager(), - new \OCA\Files\ActivityHelper( - \OC::$server->getTagManager() - ), - \OC::$server->getDatabaseConnection(), - \OC::$server->getConfig() - ); -}); +\OC::$server->getActivityManager()->registerExtension(fn () => new \OCA\Files\Activity( + \OC::$server->query('L10NFactory'), + \OC::$server->getURLGenerator(), + \OC::$server->getActivityManager(), + new \OCA\Files\ActivityHelper( + \OC::$server->getTagManager() + ), + \OC::$server->getDatabaseConnection(), + \OC::$server->getConfig() +)); -\OCP\Util::connectHook('\OCP\Config', 'js', '\OCA\Files\App', 'extendJsConfig'); +\OCP\Util::connectHook('\OCP\Config', 'js', '\\' . \OCA\Files\App::class, 'extendJsConfig'); diff --git a/apps/files/lib/App.php b/apps/files/lib/App.php index 786588519bb0..07c70f98eb27 100644 --- a/apps/files/lib/App.php +++ b/apps/files/lib/App.php @@ -25,10 +25,7 @@ namespace OCA\Files; class App { - /** - * @var \OCP\INavigationManager - */ - private static $navigationManager; + private static ?\OC\NavigationManager $navigationManager = null; /** * Returns the app's navigation manager diff --git a/apps/files/lib/AppInfo/Application.php b/apps/files/lib/AppInfo/Application.php index b197f59cc3f3..4f866d6709fb 100644 --- a/apps/files/lib/AppInfo/Application.php +++ b/apps/files/lib/AppInfo/Application.php @@ -39,60 +39,48 @@ public function __construct(array $urlParams= []) { /** * Controllers */ - $container->registerService('APIController', function (IContainer $c) use ($server) { - return new ApiController( - $c->query('AppName'), - $c->query('Request'), - $server->getUserSession(), - $c->query('TagService'), - $server->getPreviewManager(), - $server->getShareManager(), - $server->getConfig() - ); - }); + $container->registerService('APIController', fn (IContainer $c) => new ApiController( + $c->query('AppName'), + $c->query('Request'), + $server->getUserSession(), + $c->query('TagService'), + $server->getPreviewManager(), + $server->getShareManager(), + $server->getConfig() + )); - $container->registerService('ViewController', function (IContainer $c) use ($server) { - return new ViewController( - $c->query('AppName'), - $c->query('Request'), - $server->getURLGenerator(), - $c->query('L10N'), - $server->getConfig(), - $server->getEventDispatcher(), - $server->getUserSession(), - $server->getAppManager(), - $server->getRootFolder() - ); - }); + $container->registerService('ViewController', fn (IContainer $c) => new ViewController( + $c->query('AppName'), + $c->query('Request'), + $server->getURLGenerator(), + $c->query('L10N'), + $server->getConfig(), + $server->getEventDispatcher(), + $server->getUserSession(), + $server->getAppManager(), + $server->getRootFolder() + )); /** * Core */ - $container->registerService('L10N', function (IContainer $c) { - return $c->query('ServerContainer')->getL10N($c->query('AppName')); - }); + $container->registerService('L10N', fn (IContainer $c) => $c->query('ServerContainer')->getL10N($c->query('AppName'))); /** * Services */ - $container->registerService('TagService', function (IContainer $c) { - return new TagService( - $c->query('ServerContainer')->getUserSession(), - $c->query('ServerContainer')->getTagManager(), - $c->query('ServerContainer')->getLazyRootFolder() - ); - }); + $container->registerService('TagService', fn (IContainer $c) => new TagService( + $c->query('ServerContainer')->getUserSession(), + $c->query('ServerContainer')->getTagManager(), + $c->query('ServerContainer')->getLazyRootFolder() + )); - $container->registerService('OCP\Lock\ILockingProvider', function (IContainer $c) { - return $c->query('ServerContainer')->getLockingProvider(); - }); - $container->registerService('OCP\Files\IMimeTypeLoader', function (IContainer $c) { - return $c->query('ServerContainer')->getMimeTypeLoader(); - }); + $container->registerService(\OCP\Lock\ILockingProvider::class, fn (IContainer $c) => $c->query('ServerContainer')->getLockingProvider()); + $container->registerService(\OCP\Files\IMimeTypeLoader::class, fn (IContainer $c) => $c->query('ServerContainer')->getMimeTypeLoader()); /* * Register capabilities */ - $container->registerCapability('OCA\Files\Capabilities'); + $container->registerCapability(\OCA\Files\Capabilities::class); } } diff --git a/apps/files/lib/BackgroundJob/CleanupPersistentFileLocks.php b/apps/files/lib/BackgroundJob/CleanupPersistentFileLocks.php index 9f7274a62e82..245b63960d5b 100644 --- a/apps/files/lib/BackgroundJob/CleanupPersistentFileLocks.php +++ b/apps/files/lib/BackgroundJob/CleanupPersistentFileLocks.php @@ -34,8 +34,7 @@ class CleanupPersistentFileLocks extends TimedJob { * @var int $defaultIntervalMin **/ protected $defaultIntervalMin = 30; - /** @var LockMapper */ - private $lockMapper; + private \OC\Lock\Persistent\LockMapper $lockMapper; /** * CleanupPersistentFileLocks constructor. diff --git a/apps/files/lib/Command/CheckCache.php b/apps/files/lib/Command/CheckCache.php index e744407419cc..43355ec66160 100644 --- a/apps/files/lib/Command/CheckCache.php +++ b/apps/files/lib/Command/CheckCache.php @@ -36,8 +36,7 @@ class CheckCache extends Command { public const ERROR_NOT_A_FILE = 2; public const ERROR_CANNOT_OPEN = 3; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; public function __construct(IRootFolder $rootFolder) { parent::__construct(); diff --git a/apps/files/lib/Command/RemoveStorageCache.php b/apps/files/lib/Command/RemoveStorageCache.php index 174eea439d6d..0879c371bfc8 100644 --- a/apps/files/lib/Command/RemoveStorageCache.php +++ b/apps/files/lib/Command/RemoveStorageCache.php @@ -36,8 +36,7 @@ class RemoveStorageCache extends Command { private const DEFAULT_CHUNK_SIZE = 1000; - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; public function __construct(IDBConnection $connection) { parent::__construct(); diff --git a/apps/files/lib/Command/Scan.php b/apps/files/lib/Command/Scan.php index e35e05ffbf8a..eca168c05b53 100644 --- a/apps/files/lib/Command/Scan.php +++ b/apps/files/lib/Command/Scan.php @@ -50,18 +50,12 @@ use Symfony\Component\Console\Output\OutputInterface; class Scan extends Base { - /** @var IUserManager $userManager */ - private $userManager; - /** @var IGroupManager $groupManager */ - private $groupManager; - /** @var ILockingProvider */ - private $lockingProvider; - /** @var IMimeTypeLoader */ - private $mimeTypeLoader; - /** @var ILogger */ - private $logger; - /** @var IConfig */ - private $config; + private \OCP\IUserManager $userManager; + private \OCP\IGroupManager $groupManager; + private \OCP\Lock\ILockingProvider $lockingProvider; + private \OCP\Files\IMimeTypeLoader $mimeTypeLoader; + private \OCP\ILogger $logger; + private \OCP\IConfig $config; /** @var float */ protected $execTime = 0; /** @var int */ @@ -177,7 +171,7 @@ protected function scanFiles($user, $path, $verbose, OutputInterface $output, $b $connection = $this->reconnectToDatabase($output); $scanner = new \OC\Files\Utils\Scanner($user, $connection, \OC::$server->getLogger()); if ($shouldRepair) { - $scanner->listen('\OC\Files\Utils\Scanner', 'beforeScanStorage', function ($storage) use ($output, $connection) { + $scanner->listen('\\' . \OC\Files\Utils\Scanner::class, 'beforeScanStorage', function ($storage) use ($output, $connection) { try { // FIXME: this will lock the storage even if there is nothing to repair $storage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider); @@ -204,42 +198,42 @@ protected function scanFiles($user, $path, $verbose, OutputInterface $output, $b # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception # printout and count if ($verbose) { - $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) { + $scanner->listen('\\' . \OC\Files\Utils\Scanner::class, 'scanFile', function ($path) use ($output) { $output->writeln("\tFile $path"); $this->filesCounter += 1; if ($this->hasBeenInterrupted()) { throw new InterruptedException(); } }); - $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) { + $scanner->listen('\\' . \OC\Files\Utils\Scanner::class, 'scanFolder', function ($path) use ($output) { $output->writeln("\tFolder $path"); $this->foldersCounter += 1; if ($this->hasBeenInterrupted()) { throw new InterruptedException(); } }); - $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) { + $scanner->listen('\\' . \OC\Files\Utils\Scanner::class, 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) { $output->writeln("Error while scanning, storage not available (" . $e->getMessage() . ")"); }); # count only } else { - $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function () { + $scanner->listen('\\' . \OC\Files\Utils\Scanner::class, 'scanFile', function () { $this->filesCounter += 1; if ($this->hasBeenInterrupted()) { throw new InterruptedException(); } }); - $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function () { + $scanner->listen('\\' . \OC\Files\Utils\Scanner::class, 'scanFolder', function () { $this->foldersCounter += 1; if ($this->hasBeenInterrupted()) { throw new InterruptedException(); } }); } - $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) { + $scanner->listen('\\' . \OC\Files\Utils\Scanner::class, 'scanFile', function ($path) use ($output) { $this->checkScanWarning($path, $output); }); - $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) { + $scanner->listen('\\' . \OC\Files\Utils\Scanner::class, 'scanFolder', function ($path) use ($output) { $this->checkScanWarning($path, $output); }); @@ -247,7 +241,7 @@ protected function scanFiles($user, $path, $verbose, OutputInterface $output, $b if ($backgroundScan) { $scanner->backgroundScan($path); } else { - $scanner->scan($path, $shouldRepair); + $scanner->scan($path); } } catch (ForbiddenException $e) { $output->writeln("Home storage for user $user not writable"); @@ -301,7 +295,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } } elseif ($inputPath) { $inputPath = '/' . \trim($inputPath, '/'); - list(, $user, ) = \explode('/', $inputPath, 3); + [, $user, ] = \explode('/', $inputPath, 3); $users = [$user]; } elseif ($input->getOption('all')) { // we can only repair all storages in bulk (more efficient) if singleuser or maintenance mode @@ -389,7 +383,7 @@ protected function userScan($users, $inputPath, $shouldRepairStoragesIndividuall $user_count += 1; if ($this->userManager->userExists($user)) { $user = $this->userManager->get($user)->getUID(); - $path = $inputPath ? $inputPath : '/' . $user; + $path = $inputPath ?: '/' . $user; # add an extra line when verbose is set to optical separate users if ($verbose) { $output->writeln(""); @@ -490,7 +484,7 @@ protected function getItemsPerSecond() { * @return string */ protected function formatExecTime() { - list($secs, $tens) = \explode('.', \sprintf("%.1f", ($this->execTime))); + [$secs, $tens] = \explode('.', \sprintf("%.1f", ($this->execTime))); # if you want to have microseconds add this: . '.' . $tens; return \date('H:i:s', $secs); diff --git a/apps/files/lib/Command/TransferOwnership.php b/apps/files/lib/Command/TransferOwnership.php index a9ff6c54a9ad..553372b81084 100644 --- a/apps/files/lib/Command/TransferOwnership.php +++ b/apps/files/lib/Command/TransferOwnership.php @@ -46,35 +46,27 @@ use Symfony\Component\Console\Question\ChoiceQuestion; class TransferOwnership extends Command { - /** @var IUserManager $userManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IManager */ - private $shareManager; + private \OCP\Share\IManager $shareManager; - /** @var IMountManager */ - private $mountManager; + private \OCP\Files\Mount\IMountManager $mountManager; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; - /** @var Manager */ - private $encryptionManager; + private \OC\Encryption\Manager $encryptionManager; - /** @var ProviderFactory */ - private $shareProviderFactory; + private \OC\Share20\ProviderFactory $shareProviderFactory; - /** @var bool */ - private $filesExist = false; + private bool $filesExist = false; - /** @var bool */ - private $foldersExist = false; + private bool $foldersExist = false; /** @var FileInfo[] */ - private $encryptedFiles = []; + private array $encryptedFiles = []; /** @var IShare[] */ - private $shares = []; + private array $shares = []; /** @var string */ private $sourceUser; @@ -85,8 +77,7 @@ class TransferOwnership extends Command { /** @var string */ private $inputPath; - /** @var string */ - private $finalTarget; + private ?string $finalTarget = null; public function __construct( IUserManager $userManager, diff --git a/apps/files/lib/Command/TroubleshootTransferOwnership.php b/apps/files/lib/Command/TroubleshootTransferOwnership.php index 94fb011f945e..50a7f9def34f 100644 --- a/apps/files/lib/Command/TroubleshootTransferOwnership.php +++ b/apps/files/lib/Command/TroubleshootTransferOwnership.php @@ -47,7 +47,7 @@ class TroubleshootTransferOwnership extends Command { */ protected $connection; - private $allowedOps = "all|invalid-owner|invalid-initiator"; + private string $allowedOps = "all|invalid-owner|invalid-initiator"; public function __construct(IDBConnection $connection, ProviderFactory $shareProviderFactory) { $this->connection = $connection; @@ -290,9 +290,7 @@ protected function getAllResharers() { $resharers = $cursor->fetchAll(); $cursor->closeCursor(); - $entities = \array_map(function ($row) { - return $row['uid_initiator']; - }, $resharers); + $entities = \array_map(fn ($row) => $row['uid_initiator'], $resharers); return $entities; } diff --git a/apps/files/lib/Command/VerifyChecksums.php b/apps/files/lib/Command/VerifyChecksums.php index c2d9a7d9c161..59fa91a435a4 100644 --- a/apps/files/lib/Command/VerifyChecksums.php +++ b/apps/files/lib/Command/VerifyChecksums.php @@ -48,16 +48,10 @@ class VerifyChecksums extends Command { public const EXIT_CHECKSUM_ERRORS = 1; public const EXIT_INVALID_ARGS = 2; - /** - * @var IRootFolder - */ - private $rootFolder; - /** - * @var IUserManager - */ - private $userManager; + private \OCP\Files\IRootFolder $rootFolder; + private \OCP\IUserManager $userManager; - private $exitStatus = self::EXIT_NO_ERRORS; + private int $exitStatus = self::EXIT_NO_ERRORS; /** * VerifyChecksums constructor. diff --git a/apps/files/lib/Controller/ApiController.php b/apps/files/lib/Controller/ApiController.php index fe0bfea9a90d..7f8af45ec523 100644 --- a/apps/files/lib/Controller/ApiController.php +++ b/apps/files/lib/Controller/ApiController.php @@ -46,16 +46,14 @@ * @package OCA\Files\Controller */ class ApiController extends Controller { - /** @var TagService */ - private $tagService; + private \OCA\Files\Service\TagService $tagService; /** @var IManager **/ - private $shareManager; - /** @var IPreview */ - private $previewManager; + private \OCP\Share\IManager $shareManager; + private \OCP\IPreview $previewManager; /** IUserSession */ - private $userSession; + private \OCP\IUserSession $userSession; /** IConfig */ - private $config; + private \OCP\IConfig $config; /** * @param string $appName @@ -126,7 +124,7 @@ public function updateFileTags($path, $tags = null) { if ($tags !== null) { try { $this->tagService->updateFileTags($path, $tags); - } catch (\OCP\Files\NotFoundException $e) { + } catch (\OCP\Files\NotFoundException|\Exception $e) { return new DataResponse([ 'message' => $e->getMessage() ], Http::STATUS_NOT_FOUND); @@ -134,10 +132,6 @@ public function updateFileTags($path, $tags = null) { return new DataResponse([ 'message' => $e->getMessage() ], Http::STATUS_SERVICE_UNAVAILABLE); - } catch (\Exception $e) { - return new DataResponse([ - 'message' => $e->getMessage() - ], Http::STATUS_NOT_FOUND); } $result['tags'] = $tags; } diff --git a/apps/files/lib/Controller/ViewController.php b/apps/files/lib/Controller/ViewController.php index e613d794aa8a..b1686db6ced7 100644 --- a/apps/files/lib/Controller/ViewController.php +++ b/apps/files/lib/Controller/ViewController.php @@ -224,9 +224,7 @@ public function index($dir = '', $view = '', $fileid = null, $details = null) { $navigationManager = \OCA\Files\App::getNavigationManager(); '@phan-var \OC\NavigationManager $navigationManager'; $navItems = $navigationManager->getAll(); - \usort($navItems, function ($item1, $item2) { - return $item1['order'] - $item2['order']; - }); + \usort($navItems, fn ($item1, $item2) => $item1['order'] - $item2['order']); $nav->assign('navigationItems', $navItems); $nav->assign('webdavUrl', $this->urlGenerator->getAbsoluteUrl($this->urlGenerator->linkTo('', 'remote.php') . '/dav/files/' . \rawurlencode($user) . '/')); diff --git a/apps/files/lib/Helper.php b/apps/files/lib/Helper.php index a8c32095c5ce..ff65eb5206bd 100644 --- a/apps/files/lib/Helper.php +++ b/apps/files/lib/Helper.php @@ -246,7 +246,7 @@ public static function sortFiles($files, $sortAttribute = 'name', $sortDescendin } elseif ($sortAttribute === 'size') { $sortFunc = 'compareSize'; } - \usort($files, ['\OCA\Files\Helper', $sortFunc]); + \usort($files, ['\\' . \OCA\Files\Helper::class, $sortFunc]); if ($sortDescending) { $files = \array_reverse($files); } diff --git a/apps/files/lib/Service/TagService.php b/apps/files/lib/Service/TagService.php index 6927cc343fa3..cf896241ea92 100644 --- a/apps/files/lib/Service/TagService.php +++ b/apps/files/lib/Service/TagService.php @@ -30,20 +30,11 @@ * Service class to manage tags on files. */ class TagService { - /** - * @var \OCP\IUserSession - */ - private $userSession; + private \OCP\IUserSession $userSession; - /** - * @var \OCP\ITagManager - */ - private $tagManager; + private \OCP\ITagManager $tagManager; - /** - * @var IRootFolder - */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; public function __construct( \OCP\IUserSession $userSession, diff --git a/apps/files/tests/ActivityHelperTest.php b/apps/files/tests/ActivityHelperTest.php index 50866de57519..8f47bf4d4847 100644 --- a/apps/files/tests/ActivityHelperTest.php +++ b/apps/files/tests/ActivityHelperTest.php @@ -35,17 +35,14 @@ class ActivityHelperTest extends \Test\TestCase { /** * @var ITagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var ITags */ - private $tags; + private \PHPUnit\Framework\MockObject\MockObject $tags; - /** - * @var ActivityHelper - */ - private $helper; + private \OCA\Files\ActivityHelper $helper; /** * @var string diff --git a/apps/files/tests/ActivityTest.php b/apps/files/tests/ActivityTest.php index 6aa66afe963b..194c99178eab 100644 --- a/apps/files/tests/ActivityTest.php +++ b/apps/files/tests/ActivityTest.php @@ -34,7 +34,7 @@ */ class ActivityTest extends TestCase { /** @var \OCP\Activity\IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $activityManager; + private \PHPUnit\Framework\MockObject\MockObject $activityManager; /** @var \OCP\IRequest|\PHPUnit\Framework\MockObject\MockObject */ protected $request; @@ -57,35 +57,33 @@ class ActivityTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder('OCP\IRequest') + $this->request = $this->getMockBuilder(\OCP\IRequest::class) ->disableOriginalConstructor() ->getMock(); - $this->session = $this->getMockBuilder('OCP\IUserSession') + $this->session = $this->getMockBuilder(\OCP\IUserSession::class) ->disableOriginalConstructor() ->getMock(); - $this->config = $this->getMockBuilder('OCP\IConfig') + $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->activityHelper = $this->getMockBuilder('OCA\Files\ActivityHelper') + $this->activityHelper = $this->getMockBuilder(\OCA\Files\ActivityHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->activityManager = $this->getMockBuilder('OC\Activity\Manager') + $this->activityManager = $this->getMockBuilder(\OC\Activity\Manager::class) ->setConstructorArgs([$this->request, $this->session, $this->config]) ->setMethods(['isFormattingFilteredObject']) ->getMock(); - $this->l10nFactory = $this->getMockBuilder('OCP\L10N\IFactory') + $this->l10nFactory = $this->getMockBuilder(\OCP\L10N\IFactory::class) ->disableOriginalConstructor() ->getMock(); - $deL10n = $this->getMockBuilder('\OCP\IL10N') + $deL10n = $this->getMockBuilder('\\' . \OCP\IL10N::class) ->disableOriginalConstructor() ->getMock(); $deL10n->expects($this->any()) ->method('t') - ->willReturnCallback(function ($argument) { - return 'translate(' . $argument . ')'; - }); + ->willReturnCallback(fn ($argument) => 'translate(' . $argument . ')'); $this->l10nFactory->expects($this->any()) ->method('get') @@ -97,16 +95,14 @@ protected function setUp(): void { $this->activityExtension = $activityExtension = new Activity( $this->l10nFactory, - $this->getMockBuilder('OCP\IURLGenerator')->disableOriginalConstructor()->getMock(), + $this->getMockBuilder(\OCP\IURLGenerator::class)->disableOriginalConstructor()->getMock(), $this->activityManager, $this->activityHelper, \OC::$server->getDatabaseConnection(), $this->config ); - $this->activityManager->registerExtension(function () use ($activityExtension) { - return $activityExtension; - }); + $this->activityManager->registerExtension(fn () => $activityExtension); } public function testNotificationTypes() { @@ -393,7 +389,7 @@ public function testQueryForFilter($will, $query, $parameters) { } public function executeQueryForFilter(array $result) { - list($resultQuery, $resultParameters) = $result; + [$resultQuery, $resultParameters] = $result; $resultQuery = \str_replace('`file`', '`user`', $resultQuery); $resultQuery = \str_replace('`type`', '`key`', $resultQuery); @@ -406,7 +402,7 @@ public function executeQueryForFilter(array $result) { } protected function mockUserSession($user) { - $mockUser = $this->getMockBuilder('\OCP\IUser') + $mockUser = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor() ->getMock(); $mockUser->expects($this->any()) diff --git a/apps/files/tests/BackgroundJob/ScanFilesTest.php b/apps/files/tests/BackgroundJob/ScanFilesTest.php index 3c7e96d6edd9..e06bda0c9739 100644 --- a/apps/files/tests/BackgroundJob/ScanFilesTest.php +++ b/apps/files/tests/BackgroundJob/ScanFilesTest.php @@ -33,19 +33,19 @@ */ class ScanFilesTest extends TestCase { /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUserManager */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var ScanFiles */ - private $scanFiles; + private \PHPUnit\Framework\MockObject\MockObject $scanFiles; public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('\OCP\IConfig'); - $this->userManager = $this->createMock('\OCP\IUserManager'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->userManager = $this->createMock('\\' . \OCP\IUserManager::class); - $this->scanFiles = $this->getMockBuilder('\OCA\Files\BackgroundJob\ScanFiles') + $this->scanFiles = $this->getMockBuilder('\\' . \OCA\Files\BackgroundJob\ScanFiles::class) ->setConstructorArgs([ $this->config, $this->userManager, @@ -77,7 +77,7 @@ public function testRunWithoutUsers() { } public function testRunWithUsers() { - $fakeUser = $this->createMock('\OCP\IUser'); + $fakeUser = $this->createMock('\\' . \OCP\IUser::class); $this->config ->expects($this->once()) ->method('getAppValue') diff --git a/apps/files/tests/Command/CheckCacheTest.php b/apps/files/tests/Command/CheckCacheTest.php index 8ad0b24775d5..4314334f62a2 100644 --- a/apps/files/tests/Command/CheckCacheTest.php +++ b/apps/files/tests/Command/CheckCacheTest.php @@ -36,11 +36,10 @@ */ class CheckCacheTest extends TestCase { /** @var IRootFolder */ - private $rootFolder; - /** @var CheckCache */ - private $command; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; + private \OCA\Files\Command\CheckCache $command; /**@var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/apps/files/tests/Command/DeleteOrphanedFilesTest.php b/apps/files/tests/Command/DeleteOrphanedFilesTest.php index 8fce8c3c5d2f..46c033c6363a 100644 --- a/apps/files/tests/Command/DeleteOrphanedFilesTest.php +++ b/apps/files/tests/Command/DeleteOrphanedFilesTest.php @@ -36,10 +36,7 @@ * @package OCA\Files\Tests\Command */ class DeleteOrphanedFilesTest extends TestCase { - /** - * @var DeleteOrphanedFiles - */ - private $command; + private \OCA\Files\Command\DeleteOrphanedFiles $command; /** * @var \OCP\IDBConnection @@ -85,10 +82,10 @@ protected function getFile($fileId) { * Test clearing orphaned files */ public function testClearFiles() { - $input = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface') + $input = $this->getMockBuilder(\Symfony\Component\Console\Input\InputInterface::class) ->disableOriginalConstructor() ->getMock(); - $output = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface') + $output = $this->getMockBuilder(\Symfony\Component\Console\Output\OutputInterface::class) ->disableOriginalConstructor() ->getMock(); diff --git a/apps/files/tests/Command/ScanTest.php b/apps/files/tests/Command/ScanTest.php index 228756300491..aa2cfeb708d6 100644 --- a/apps/files/tests/Command/ScanTest.php +++ b/apps/files/tests/Command/ScanTest.php @@ -63,17 +63,17 @@ class ScanTest extends TestCase { /** * @var ILockingProvider | \PHPUnit\Framework\MockObject\MockObject */ - private $lockingProvider; + private \PHPUnit\Framework\MockObject\MockObject $lockingProvider; /** * @var IMimeTypeLoader | \PHPUnit\Framework\MockObject\MockObject */ - private $mimeTypeLoader; + private \PHPUnit\Framework\MockObject\MockObject $mimeTypeLoader; /** * @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** * @var IUser @@ -85,15 +85,12 @@ class ScanTest extends TestCase { */ private $scanUser2; - /** - * @var CommandTester - */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; /** * @var string[] */ - private $groupsCreated = []; + private array $groupsCreated = []; protected function setUp(): void { if ($this->runsWithPrimaryObjectstorage()) { diff --git a/apps/files/tests/Command/TransferOwnershipTest.php b/apps/files/tests/Command/TransferOwnershipTest.php index 3e27c9e2d36c..97e11dceedde 100644 --- a/apps/files/tests/Command/TransferOwnershipTest.php +++ b/apps/files/tests/Command/TransferOwnershipTest.php @@ -73,12 +73,9 @@ class TransferOwnershipTest extends TestCase { /** * @var Manager | MockObject */ - private $encryptionManager; + private \PHPUnit\Framework\MockObject\MockObject $encryptionManager; - /** - * @var ProviderFactory - */ - private $providerFactory; + private \OC\Share20\ProviderFactory $providerFactory; /** * @var IUser @@ -105,10 +102,7 @@ class TransferOwnershipTest extends TestCase { */ private $shareReceiver; - /** - * @var CommandTester - */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); @@ -161,7 +155,7 @@ protected function tearDown(): void { \OC_Hook::clear('OC_Filesystem', 'post_write'); \OC_Hook::clear('OC_Filesystem', 'post_delete'); \OC_Hook::clear('OC_Filesystem', 'post_rename'); - \OC_Hook::clear('OCP\Share', 'post_update_permissions'); + \OC_Hook::clear(\OCP\Share::class, 'post_update_permissions'); parent::tearDown(); } diff --git a/apps/files/tests/Command/TroubleshootTransferOwnershipTest.php b/apps/files/tests/Command/TroubleshootTransferOwnershipTest.php index 49d229d919e7..1c6a7c3c7af7 100644 --- a/apps/files/tests/Command/TroubleshootTransferOwnershipTest.php +++ b/apps/files/tests/Command/TroubleshootTransferOwnershipTest.php @@ -36,10 +36,7 @@ * @package OCA\Files\Tests\Command */ class TroubleshootTransferOwnershipTest extends TestCase { - /** - * @var CommandTester - */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setup(): void { parent::setUp(); diff --git a/apps/files/tests/Command/VerifyChecksumsTest.php b/apps/files/tests/Command/VerifyChecksumsTest.php index 96e6d0ad86d3..b9179ba6e9cf 100644 --- a/apps/files/tests/Command/VerifyChecksumsTest.php +++ b/apps/files/tests/Command/VerifyChecksumsTest.php @@ -20,8 +20,7 @@ class VerifyChecksumsTest extends TestCase { public const BROKEN_CHECKSUM_STRING = '_BROKEN_'; - /** @var CommandTester */ - private $cmd; + private \Symfony\Component\Console\Tester\CommandTester $cmd; /** * @var \OCP\Files\IRootFolder @@ -38,10 +37,7 @@ class VerifyChecksumsTest extends TestCase { */ private $user2; - /** - * @var array - */ - private $testFiles; + private array $testFiles; public function setUp(): void { parent::setUp(); @@ -101,14 +97,12 @@ private function createFileForUser($uid, $path, $content) { return [ 'file' => $f, - 'expectedChecksums' => function () use ($content) { - return \sprintf( - Checksum::CHECKSUMS_DB_FORMAT, - \hash('sha1', $content), - \hash('md5', $content), - \hash('adler32', $content) - ); - }, + 'expectedChecksums' => fn () => \sprintf( + Checksum::CHECKSUMS_DB_FORMAT, + \hash('sha1', $content), + \hash('md5', $content), + \hash('adler32', $content) + ), ]; } diff --git a/apps/files/tests/Controller/ApiControllerTest.php b/apps/files/tests/Controller/ApiControllerTest.php index ba822a001965..fa6c55f70cb7 100644 --- a/apps/files/tests/Controller/ApiControllerTest.php +++ b/apps/files/tests/Controller/ApiControllerTest.php @@ -42,45 +42,43 @@ * @package OCA\Files\Controller */ class ApiControllerTest extends TestCase { - /** @var string */ - private $appName = 'files'; + private string $appName = 'files'; /** @var \OCP\IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var TagService */ - private $tagService; + private \PHPUnit\Framework\MockObject\MockObject $tagService; /** @var IPreview */ - private $preview; - /** @var ApiController */ - private $apiController; + private \PHPUnit\Framework\MockObject\MockObject $preview; + private \OCA\Files\Controller\ApiController $apiController; /** @var \OCP\Share\IManager */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** @var \OCP\IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { - $this->request = $this->getMockBuilder('\OCP\IRequest') + $this->request = $this->getMockBuilder('\\' . \OCP\IRequest::class) ->disableOriginalConstructor() ->getMock(); - $this->user = $this->createMock('\OCP\IUser'); + $this->user = $this->createMock('\\' . \OCP\IUser::class); $this->user->expects($this->any()) ->method('getUID') ->will($this->returnValue('user1')); - $userSession = $this->createMock('\OCP\IUserSession'); + $userSession = $this->createMock('\\' . \OCP\IUserSession::class); $userSession->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $this->tagService = $this->getMockBuilder('\OCA\Files\Service\TagService') + $this->tagService = $this->getMockBuilder('\\' . \OCA\Files\Service\TagService::class) ->disableOriginalConstructor() ->getMock(); - $this->shareManager = $this->getMockBuilder('\OCP\Share\IManager') + $this->shareManager = $this->getMockBuilder('\\' . \OCP\Share\IManager::class) ->disableOriginalConstructor() ->getMock(); - $this->preview = $this->getMockBuilder('\OCP\IPreview') + $this->preview = $this->getMockBuilder('\\' . \OCP\IPreview::class) ->disableOriginalConstructor() ->getMock(); - $this->config = $this->createMock('\OCP\IConfig'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); $this->apiController = new ApiController( $this->appName, diff --git a/apps/files/tests/Controller/ViewControllerTest.php b/apps/files/tests/Controller/ViewControllerTest.php index 49ef6152c969..d68ef511949e 100644 --- a/apps/files/tests/Controller/ViewControllerTest.php +++ b/apps/files/tests/Controller/ViewControllerTest.php @@ -48,50 +48,48 @@ */ class ViewControllerTest extends TestCase { /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var EventDispatcherInterface */ - private $eventDispatcher; + private \PHPUnit\Framework\MockObject\MockObject $eventDispatcher; /** @var ViewController | \PHPUnit\Framework\MockObject\MockObject */ - private $viewController; + private \PHPUnit\Framework\MockObject\MockObject $viewController; /** @var IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IAppManager | \PHPUnit\Framework\MockObject\MockObject */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; /** @var Folder | \PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; public function setUp(): void { parent::setUp(); - $this->request = $this->createMock('\OCP\IRequest'); - $this->urlGenerator = $this->createMock('\OCP\IURLGenerator'); - $this->l10n = $this->createMock('\OCP\IL10N'); - $this->config = $this->createMock('\OCP\IConfig'); - $this->eventDispatcher = $this->createMock('\Symfony\Component\EventDispatcher\EventDispatcherInterface'); + $this->request = $this->createMock('\\' . \OCP\IRequest::class); + $this->urlGenerator = $this->createMock('\\' . \OCP\IURLGenerator::class); + $this->l10n = $this->createMock('\\' . \OCP\IL10N::class); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->eventDispatcher = $this->createMock('\\' . \Symfony\Component\EventDispatcher\EventDispatcherInterface::class); $this->eventDispatcher->expects($this->any())->method('dispatch') ->will( - $this->returnCallback(function ($object) { - return $object; - }) + $this->returnCallback(fn ($object) => $object) ); - $this->userSession = $this->createMock('\OCP\IUserSession'); - $this->appManager = $this->createMock('\OCP\App\IAppManager'); - $this->user = $this->createMock('\OCP\IUser'); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); + $this->appManager = $this->createMock('\\' . \OCP\App\IAppManager::class); + $this->user = $this->createMock('\\' . \OCP\IUser::class); $this->user->expects($this->any()) ->method('getUID') ->will($this->returnValue('test@#?%test')); $this->userSession->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $this->rootFolder = $this->createMock('\OCP\Files\Folder'); - $this->viewController = $this->getMockBuilder('\OCA\Files\Controller\ViewController') + $this->rootFolder = $this->createMock('\\' . \OCP\Files\Folder::class); + $this->viewController = $this->getMockBuilder('\\' . \OCA\Files\Controller\ViewController::class) ->setConstructorArgs([ 'files', $this->request, @@ -332,12 +330,12 @@ public function showFileMethodProvider() { * @dataProvider showFileMethodProvider */ public function testShowFileRouteWithFolder($useShowFile) { - $node = $this->createMock('\OCP\Files\Folder'); + $node = $this->createMock('\\' . \OCP\Files\Folder::class); $node->expects($this->any()) ->method('getPath') ->will($this->returnValue('/test@#?%test/files/to sp@ce/a@b#?%')); - $baseFolder = $this->createMock('\OCP\Files\Folder'); + $baseFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('get') @@ -372,19 +370,19 @@ public function testShowFileRouteWithFolder($useShowFile) { * @dataProvider showFileMethodProvider */ public function testShowFileRouteWithFile($useShowFile) { - $parentNode = $this->createMock('\OCP\Files\Folder'); + $parentNode = $this->createMock('\\' . \OCP\Files\Folder::class); $parentNode->expects($this->any()) ->method('getPath') ->will($this->returnValue('test@#?%test/files/test')); - $baseFolder = $this->createMock('\OCP\Files\Folder'); + $baseFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('get') ->with('test@#?%test/files/') ->will($this->returnValue($baseFolder)); - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock('\\' . \OCP\Files\File::class); $node->expects($this->once()) ->method('getParent') ->will($this->returnValue($parentNode)); @@ -425,7 +423,7 @@ public function testShowFileRouteWithFile($useShowFile) { * @dataProvider showFileMethodProvider */ public function testShowFileRouteWithInvalidFileId($useShowFile) { - $baseFolder = $this->createMock('\OCP\Files\Folder'); + $baseFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('get') ->with('test@#?%test/files/') @@ -437,7 +435,7 @@ public function testShowFileRouteWithInvalidFileId($useShowFile) { ->will($this->returnValue([])); if ($useShowFile) { - $this->expectException('OCP\Files\NotFoundException'); + $this->expectException(\OCP\Files\NotFoundException::class); $this->viewController->showFile(123); } else { $this->viewController @@ -449,7 +447,7 @@ public function testShowFileRouteWithInvalidFileId($useShowFile) { 'ownerDisplayName' => 'MyDisplayName', ])); $response = $this->viewController->index('MyDir', 'MyView', '123'); - $this->assertInstanceOf('OCP\AppFramework\Http\TemplateResponse', $response); + $this->assertInstanceOf(\OCP\AppFramework\Http\TemplateResponse::class, $response); $params = $response->getParams(); $this->assertEquals(1, $params['fileNotFound']); } @@ -458,7 +456,7 @@ public function testShowFileRouteWithInvalidFileId($useShowFile) { /** */ public function testShowFileRouteWithInvalidFileIdLoggedIn() { - $baseFolder = $this->createMock('\OCP\Files\Folder'); + $baseFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('get') ->with('test@#?%test/files/') @@ -474,7 +472,7 @@ public function testShowFileRouteWithInvalidFileIdLoggedIn() { ->will($this->returnValue(true)); $response = $this->viewController->index('MyDir', 'MyView', '123'); - $this->assertInstanceOf('OCP\AppFramework\Http\TemplateResponse', $response); + $this->assertInstanceOf(\OCP\AppFramework\Http\TemplateResponse::class, $response); $params = $response->getParams(); $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); } @@ -483,7 +481,7 @@ public function testShowFileRouteWithInvalidFileIdLoggedIn() { * @dataProvider showFileMethodProvider */ public function testShowFileRouteWithDispatcher($useShowFile) { - $baseFolder = $this->createMock('\OCP\Files\Folder'); + $baseFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('get') ->with('test@#?%test/files/') diff --git a/apps/files/tests/HelperTest.php b/apps/files/tests/HelperTest.php index 57b561b3ce6d..83176207b526 100644 --- a/apps/files/tests/HelperTest.php +++ b/apps/files/tests/HelperTest.php @@ -49,10 +49,10 @@ private function makeFileInfo($name, $size, $mtime, $isDir = false) { */ private function getTestFileList() { return [ - self::makeFileInfo('a.txt', 4, 2.3 * \pow(10, 9)), + self::makeFileInfo('a.txt', 4, 2.3 * 10 ** 9), self::makeFileInfo('q.txt', 5, 150), self::makeFileInfo('subdir2', 87, 128, true), - self::makeFileInfo('b.txt', 2.2 * \pow(10, 9), 800), + self::makeFileInfo('b.txt', 2.2 * 10 ** 9, 800), self::makeFileInfo('o.txt', 12, 100), self::makeFileInfo('subdir', 88, 125, true), ]; diff --git a/apps/files/tests/Service/TagServiceTest.php b/apps/files/tests/Service/TagServiceTest.php index 591e64b34a29..b6b425c7a965 100644 --- a/apps/files/tests/Service/TagServiceTest.php +++ b/apps/files/tests/Service/TagServiceTest.php @@ -48,10 +48,7 @@ class TagServiceTest extends \Test\TestCase { */ private $root; - /** - * @var \OCA\Files\Service\TagService - */ - private $tagService; + private \OCA\Files\Service\TagService $tagService; /** * @var \OCP\ITagManager @@ -65,7 +62,7 @@ protected function setUp(): void { \OC_User::setUserId($this->user); \OC_Util::setupFS($this->user); /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject $userSession */ - $userSession = $this->createMock('\OCP\IUserSession'); + $userSession = $this->createMock('\\' . \OCP\IUserSession::class); $userSession->expects($this->any()) ->method('getUser') ->withAnyParameters() diff --git a/apps/files_external/ajax/oauth2.php b/apps/files_external/ajax/oauth2.php index 22ffa1669d76..23ba6045ae9f 100644 --- a/apps/files_external/ajax/oauth2.php +++ b/apps/files_external/ajax/oauth2.php @@ -57,7 +57,7 @@ try { $token = $client->authenticate((string)$_POST['code']); OCP\JSON::success(['data' => [ - 'token' => \json_encode($token) + 'token' => \json_encode($token, JSON_THROW_ON_ERROR) ]]); } catch (Exception $exception) { OCP\JSON::error(['data' => [ diff --git a/apps/files_external/appinfo/Migrations/Version20210511082903.php b/apps/files_external/appinfo/Migrations/Version20210511082903.php index 3199a69a3d2e..a59fce45bc92 100644 --- a/apps/files_external/appinfo/Migrations/Version20210511082903.php +++ b/apps/files_external/appinfo/Migrations/Version20210511082903.php @@ -12,14 +12,10 @@ use OCP\ILogger; class Version20210511082903 implements ISimpleMigration { - /** @var IGlobalStoragesService */ - private $storageService; - /** @var ICrypto */ - private $crypto; - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; + private \OCP\Files\External\Service\IGlobalStoragesService $storageService; + private \OCP\Security\ICrypto $crypto; + private \OCP\IConfig $config; + private \OCP\ILogger $logger; public function __construct( IGlobalStoragesService $storageService, diff --git a/apps/files_external/appinfo/Migrations/Version20220329110116.php b/apps/files_external/appinfo/Migrations/Version20220329110116.php index 62ef9ad00166..34e46979d53e 100644 --- a/apps/files_external/appinfo/Migrations/Version20220329110116.php +++ b/apps/files_external/appinfo/Migrations/Version20220329110116.php @@ -14,12 +14,9 @@ use phpseclib3\Crypt\RSA as RSACrypt; class Version20220329110116 implements ISimpleMigration { - /** @var IGlobalStoragesService */ - private $storageService; - /** @var ILogger */ - private $logger; - /** @var IConfig */ - private $config; + private \OCP\Files\External\Service\IGlobalStoragesService $storageService; + private \OCP\ILogger $logger; + private \OCP\IConfig $config; public function __construct(IGlobalStoragesService $storageService, ILogger $logger, IConfig $config) { $this->storageService = $storageService; diff --git a/apps/files_external/appinfo/app.php b/apps/files_external/appinfo/app.php index 9e5de116ac31..6be01a4857fd 100644 --- a/apps/files_external/appinfo/app.php +++ b/apps/files_external/appinfo/app.php @@ -31,7 +31,7 @@ $appContainer = \OC_Mount_Config::$app->getContainer(); $config = \OC::$server->getConfig(); -if (\class_exists('OCA\Files\App') && $config->getAppValue('core', 'enable_external_storage', 'no') === 'yes') { +if (\class_exists(\OCA\Files\App::class) && $config->getAppValue('core', 'enable_external_storage', 'no') === 'yes') { \OCA\Files\App::getNavigationManager()->add(function () { $l = \OC::$server->getL10N('files_external'); return [ diff --git a/apps/files_external/appinfo/routes.php b/apps/files_external/appinfo/routes.php index fa33a62b0298..707a59a3f5db 100644 --- a/apps/files_external/appinfo/routes.php +++ b/apps/files_external/appinfo/routes.php @@ -58,6 +58,6 @@ \OCP\API::register( 'get', '/apps/files_external/api/v1/mounts', - ['\OCA\Files_External\Lib\Api', 'getUserMounts'], + ['\\' . \OCA\Files_External\Lib\Api::class, 'getUserMounts'], 'files_external' ); diff --git a/apps/files_external/lib/AppInfo/Application.php b/apps/files_external/lib/AppInfo/Application.php index a6e37364f055..9a45f6f521bb 100644 --- a/apps/files_external/lib/AppInfo/Application.php +++ b/apps/files_external/lib/AppInfo/Application.php @@ -44,21 +44,11 @@ public function __construct(array $urlParams = []) { $container = $this->getContainer(); - $container->registerService('OCP\Files\Config\IUserMountCache', function (IAppContainer $c) { - return $c->getServer()->query('UserMountCache'); - }); - $container->registerService('OCP\Files\External\IStoragesBackendService', function (IAppContainer $c) { - return $c->getServer()->query('StoragesBackendService'); - }); - $container->registerService('OCP\Files\External\Service\IGlobalStoragesService', function (IAppContainer $c) { - return $c->getServer()->query('OCP\Files\External\Service\IGlobalStoragesService'); - }); - $container->registerService('OCP\Files\External\Service\IUserGlobalStoragesService', function (IAppContainer $c) { - return $c->getServer()->query('OCP\Files\External\Service\IUserGlobalStoragesService'); - }); - $container->registerService('OCP\Files\External\Service\IUserStoragesService', function (IAppContainer $c) { - return $c->getServer()->query('OCP\Files\External\Service\IUserStoragesService'); - }); + $container->registerService(\OCP\Files\Config\IUserMountCache::class, fn (IAppContainer $c) => $c->getServer()->query('UserMountCache')); + $container->registerService(\OCP\Files\External\IStoragesBackendService::class, fn (IAppContainer $c) => $c->getServer()->query('StoragesBackendService')); + $container->registerService(\OCP\Files\External\Service\IGlobalStoragesService::class, fn (IAppContainer $c) => $c->getServer()->query(\OCP\Files\External\Service\IGlobalStoragesService::class)); + $container->registerService(\OCP\Files\External\Service\IUserGlobalStoragesService::class, fn (IAppContainer $c) => $c->getServer()->query(\OCP\Files\External\Service\IUserGlobalStoragesService::class)); + $container->registerService(\OCP\Files\External\Service\IUserStoragesService::class, fn (IAppContainer $c) => $c->getServer()->query(\OCP\Files\External\Service\IUserStoragesService::class)); $backendService = $container->getServer()->query('StoragesBackendService'); $backendService->registerBackendProvider($this); @@ -72,17 +62,17 @@ public function getBackends() { $container = $this->getContainer(); $backends = [ - $container->query('OCA\Files_External\Lib\Backend\DAV'), - $container->query('OCA\Files_External\Lib\Backend\OwnCloud'), - $container->query('OCA\Files_External\Lib\Backend\SFTP'), - $container->query('OCA\Files_External\Lib\Backend\Google'), - $container->query('OCA\Files_External\Lib\Backend\SFTP_Key'), - $container->query('OCA\Files_External\Lib\Backend\SMB'), + $container->query(\OCA\Files_External\Lib\Backend\DAV::class), + $container->query(\OCA\Files_External\Lib\Backend\OwnCloud::class), + $container->query(\OCA\Files_External\Lib\Backend\SFTP::class), + $container->query(\OCA\Files_External\Lib\Backend\Google::class), + $container->query(\OCA\Files_External\Lib\Backend\SFTP_Key::class), + $container->query(\OCA\Files_External\Lib\Backend\SMB::class), $container->query(SMB2::class), - $container->query('OCA\Files_External\Lib\Backend\SMB_OC'), + $container->query(\OCA\Files_External\Lib\Backend\SMB_OC::class), ]; - $backends[] = $container->query('OCA\Files_External\Lib\Backend\Local'); + $backends[] = $container->query(\OCA\Files_External\Lib\Backend\Local::class); return $backends; } @@ -95,17 +85,17 @@ public function getAuthMechanisms() { return [ // AuthMechanism::SCHEME_OAUTH1 mechanisms - $container->query('OCA\Files_External\Lib\Auth\OAuth1\OAuth1'), + $container->query(\OCA\Files_External\Lib\Auth\OAuth1\OAuth1::class), // AuthMechanism::SCHEME_OAUTH2 mechanisms - $container->query('OCA\Files_External\Lib\Auth\OAuth2\OAuth2'), + $container->query(\OCA\Files_External\Lib\Auth\OAuth2\OAuth2::class), // AuthMechanism::SCHEME_PUBLICKEY mechanisms - $container->query('OCA\Files_External\Lib\Auth\PublicKey\RSA'), + $container->query(\OCA\Files_External\Lib\Auth\PublicKey\RSA::class), // AuthMechanism::SCHEME_OPENSTACK mechanisms - $container->query('OCA\Files_External\Lib\Auth\OpenStack\OpenStack'), - $container->query('OCA\Files_External\Lib\Auth\OpenStack\Rackspace'), + $container->query(\OCA\Files_External\Lib\Auth\OpenStack\OpenStack::class), + $container->query(\OCA\Files_External\Lib\Auth\OpenStack\Rackspace::class), ]; } } diff --git a/apps/files_external/lib/Command/Applicable.php b/apps/files_external/lib/Command/Applicable.php index 70e923666f13..3423e10fa947 100644 --- a/apps/files_external/lib/Command/Applicable.php +++ b/apps/files_external/lib/Command/Applicable.php @@ -39,15 +39,9 @@ class Applicable extends Base { */ protected $globalService; - /** - * @var IUserManager - */ - private $userManager; + private \OCP\IUserManager $userManager; - /** - * @var IGroupManager - */ - private $groupManager; + private \OCP\IGroupManager $groupManager; public function __construct( IGlobalStoragesService $globalService, diff --git a/apps/files_external/lib/Command/Backends.php b/apps/files_external/lib/Command/Backends.php index c2fc1dd413f6..f8f92ffb88aa 100644 --- a/apps/files_external/lib/Command/Backends.php +++ b/apps/files_external/lib/Command/Backends.php @@ -32,8 +32,7 @@ use Symfony\Component\Console\Output\OutputInterface; class Backends extends Base { - /** @var IStoragesBackendService */ - private $backendService; + private \OCP\Files\External\IStoragesBackendService $backendService; public function __construct( IStoragesBackendService $backendService @@ -101,9 +100,7 @@ private function serializeAuthBackend(\JsonSerializable $backend) { $result['storage_class'] = $backend->getStorageClass(); $authBackends = $this->backendService->getAuthMechanismsByScheme(\array_keys($backend->getAuthSchemes())); $result['supported_authentication_backends'] = \array_keys($authBackends); - $authConfig = \array_map(function (AuthMechanism $auth) { - return $this->serializeAuthBackend($auth)['configuration']; - }, $authBackends); + $authConfig = \array_map(fn (AuthMechanism $auth) => $this->serializeAuthBackend($auth)['configuration'], $authBackends); $result['authentication_configuration'] = \array_combine(\array_keys($authBackends), $authConfig); } return $result; @@ -114,11 +111,7 @@ private function serializeAuthBackend(\JsonSerializable $backend) { * @return string[] */ private function formatConfiguration(array $parameters) { - $configuration = \array_filter($parameters, function (DefinitionParameter $parameter) { - return $parameter->getType() !== DefinitionParameter::VALUE_HIDDEN; - }); - return \array_map(function (DefinitionParameter $parameter) { - return $parameter->getTypeName(); - }, $configuration); + $configuration = \array_filter($parameters, fn (DefinitionParameter $parameter) => $parameter->getType() !== DefinitionParameter::VALUE_HIDDEN); + return \array_map(fn (DefinitionParameter $parameter) => $parameter->getTypeName(), $configuration); } } diff --git a/apps/files_external/lib/Command/Config.php b/apps/files_external/lib/Command/Config.php index a253439d303a..726a2a492836 100644 --- a/apps/files_external/lib/Command/Config.php +++ b/apps/files_external/lib/Command/Config.php @@ -93,7 +93,7 @@ protected function getOption(IStorageConfig $mount, $key, OutputInterface $outpu $value = $mount->getBackendOption($key); } if (!\is_string($value)) { // show bools and objects correctly - $value = \json_encode($value); + $value = \json_encode($value, JSON_THROW_ON_ERROR); } $output->writeln($value); } @@ -105,7 +105,7 @@ protected function getOption(IStorageConfig $mount, $key, OutputInterface $outpu * @param OutputInterface $output */ protected function setOption(IStorageConfig $mount, $key, $value, OutputInterface $output) { - $decoded = \json_decode($value, true); + $decoded = \json_decode($value, true, 512, JSON_THROW_ON_ERROR); if ($decoded !== null) { $value = $decoded; } diff --git a/apps/files_external/lib/Command/Create.php b/apps/files_external/lib/Command/Create.php index ea93edd4ec11..95dc994c58d6 100644 --- a/apps/files_external/lib/Command/Create.php +++ b/apps/files_external/lib/Command/Create.php @@ -41,26 +41,15 @@ use Symfony\Component\Console\Output\OutputInterface; class Create extends Base { - /** - * @var IGlobalStoragesService - */ - private $globalService; + private \OCP\Files\External\Service\IGlobalStoragesService $globalService; - /** - * @var IUserStoragesService - */ - private $userService; + private \OCP\Files\External\Service\IUserStoragesService $userService; - /** - * @var IUserManager - */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IStoragesBackendService */ - private $backendService; + private \OCP\Files\External\IStoragesBackendService $backendService; - /** @var IUserSession */ - private $userSession; + private \OCP\IUserSession $userSession; public function __construct( IGlobalStoragesService $globalService, @@ -151,7 +140,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $output->writeln('Invalid mount configuration option "' . $configOption . '"'); return 1; } - list($key, $value) = \explode('=', $configOption, 2); + [$key, $value] = \explode('=', $configOption, 2); if (!$this->validateParam($key, $value, $storageBackend, $authBackend)) { $output->writeln('Unknown configuration for backends "' . $key . '"'); return 1; diff --git a/apps/files_external/lib/Command/Import.php b/apps/files_external/lib/Command/Import.php index de7f8968f937..1080800b3ec8 100644 --- a/apps/files_external/lib/Command/Import.php +++ b/apps/files_external/lib/Command/Import.php @@ -37,28 +37,15 @@ use Symfony\Component\Console\Output\OutputInterface; class Import extends Base { - /** - * @var IGlobalStoragesService - */ - private $globalService; + private \OCP\Files\External\Service\IGlobalStoragesService $globalService; - /** - * @var IUserStoragesService - */ - private $userService; + private \OCP\Files\External\Service\IUserStoragesService $userService; - /** - * @var IUserSession - */ - private $userSession; + private \OCP\IUserSession $userSession; - /** - * @var IUserManager - */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IStoragesBackendService */ - private $backendService; + private \OCP\Files\External\IStoragesBackendService $backendService; public function __construct( IGlobalStoragesService $globalService, @@ -115,7 +102,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $output->writeln('Error while reading json'); return 1; } - $data = \json_decode($json, true); + $data = \json_decode($json, true, 512, JSON_THROW_ON_ERROR); if (!\is_array($data)) { $output->writeln('Error while parsing json'); return 1; @@ -131,9 +118,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (!isset($data[0])) { //normalize to an array of mounts $data = [$data]; } - $mounts = \array_map(function ($entry) use ($storageService) { - return $this->parseData($entry, $storageService); - }, $data); + $mounts = \array_map(fn ($entry) => $this->parseData($entry, $storageService), $data); } if ($user) { @@ -188,8 +173,8 @@ private function parseData(array $data, IStoragesService $storageService) { $mount->setAuthMechanism($authBackend); $mount->setBackendOptions($data['configuration']); $mount->setMountOptions($data['options']); - $mount->setApplicableUsers(isset($data['applicable_users']) ? $data['applicable_users'] : []); - $mount->setApplicableGroups(isset($data['applicable_groups']) ? $data['applicable_groups'] : []); + $mount->setApplicableUsers($data['applicable_users'] ?? []); + $mount->setApplicableGroups($data['applicable_groups'] ?? []); return $mount; } diff --git a/apps/files_external/lib/Command/ListCommand.php b/apps/files_external/lib/Command/ListCommand.php index d3ead5ebcc6e..40e184c37404 100644 --- a/apps/files_external/lib/Command/ListCommand.php +++ b/apps/files_external/lib/Command/ListCommand.php @@ -218,9 +218,7 @@ public function listMounts($userId, array $mounts, InputInterface $input, Output }, $values); } - $configStrings = \array_map(function ($key, $value) { - return $key . ': ' . \json_encode($value); - }, $keys, $values); + $configStrings = \array_map(fn ($key, $value) => $key . ': ' . \json_encode($value, JSON_THROW_ON_ERROR), $keys, $values); $configString = \implode(', ', $configStrings); $mountOptions = $config->getMountOptions(); @@ -236,9 +234,7 @@ public function listMounts($userId, array $mounts, InputInterface $input, Output $keys = \array_keys($mountOptions); $values = \array_values($mountOptions); - $optionsStrings = \array_map(function ($key, $value) { - return $key . ': ' . \json_encode($value); - }, $keys, $values); + $optionsStrings = \array_map(fn ($key, $value) => $key . ': ' . \json_encode($value, JSON_THROW_ON_ERROR), $keys, $values); $optionsString = \implode(', ', $optionsStrings); // output dependent on option shortview @@ -300,9 +296,7 @@ public function listMounts($userId, array $mounts, InputInterface $input, Output }, $mounts); if ($outputIsJson) { - $keys = \array_map(function ($header) { - return \strtolower(\str_replace(' ', '_', $header)); - }, $headers); + $keys = \array_map(fn ($header) => \strtolower(\str_replace(' ', '_', $header)), $headers); $pairs = []; foreach ($rows as $array_1) { @@ -310,7 +304,7 @@ public function listMounts($userId, array $mounts, InputInterface $input, Output } if ($outputType === self::OUTPUT_FORMAT_JSON) { - $output->writeln(\json_encode(\array_values($pairs))); + $output->writeln(\json_encode(\array_values($pairs), JSON_THROW_ON_ERROR)); } else { $output->writeln(\json_encode(\array_values($pairs), JSON_PRETTY_PRINT)); } diff --git a/apps/files_external/lib/Command/Option.php b/apps/files_external/lib/Command/Option.php index 4796025bc2ea..d124a45f38fd 100644 --- a/apps/files_external/lib/Command/Option.php +++ b/apps/files_external/lib/Command/Option.php @@ -54,7 +54,7 @@ protected function configure() { protected function getOption(IStorageConfig $mount, $key, OutputInterface $output) { $value = $mount->getMountOption($key); if (!\is_string($value)) { // show bools and objects correctly - $value = \json_encode($value); + $value = \json_encode($value, JSON_THROW_ON_ERROR); } $output->writeln($value); } @@ -66,7 +66,7 @@ protected function getOption(IStorageConfig $mount, $key, OutputInterface $outpu * @param OutputInterface $output */ protected function setOption(IStorageConfig $mount, $key, $value, OutputInterface $output) { - $decoded = \json_decode($value, true); + $decoded = \json_decode($value, true, 512, JSON_THROW_ON_ERROR); if ($decoded !== null) { $value = $decoded; } diff --git a/apps/files_external/lib/Command/Verify.php b/apps/files_external/lib/Command/Verify.php index 1013016a1348..65a8758f4bd2 100644 --- a/apps/files_external/lib/Command/Verify.php +++ b/apps/files_external/lib/Command/Verify.php @@ -108,7 +108,7 @@ private function updateStorageStatus(IStorageConfig &$storage, $configInput, Out $output->writeln('Invalid mount configuration option "' . $configOption . '"'); return; } - list($key, $value) = \explode('=', $configOption, 2); + [$key, $value] = \explode('=', $configOption, 2); $storage->setBackendOption($key, $value); } @@ -123,7 +123,7 @@ private function updateStorageStatus(IStorageConfig &$storage, $configInput, Out ) ); } catch (InsufficientDataForMeaningfulAnswerException $e) { - $status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE; + $status = $e->getCode() ?: StorageNotAvailableException::STATUS_INDETERMINATE; $storage->setStatus( $status, $e->getMessage() diff --git a/apps/files_external/lib/Controller/AjaxController.php b/apps/files_external/lib/Controller/AjaxController.php index 48a7d412b45e..1fa185494c48 100644 --- a/apps/files_external/lib/Controller/AjaxController.php +++ b/apps/files_external/lib/Controller/AjaxController.php @@ -31,8 +31,7 @@ use OCP\IRequest; class AjaxController extends Controller { - /** @var RSA */ - private $rsaMechanism; + private \OCA\Files_External\Lib\Auth\PublicKey\RSA $rsaMechanism; public function __construct($appName, IRequest $request, RSA $rsaMechanism) { parent::__construct($appName, $request); diff --git a/apps/files_external/lib/Controller/StoragesController.php b/apps/files_external/lib/Controller/StoragesController.php index 9b4fdf85ab9e..8434e572360c 100644 --- a/apps/files_external/lib/Controller/StoragesController.php +++ b/apps/files_external/lib/Controller/StoragesController.php @@ -254,7 +254,7 @@ protected function updateStorageStatus(IStorageConfig &$storage, $testOnly = tru ) ); } catch (InsufficientDataForMeaningfulAnswerException $e) { - $status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE; + $status = $e->getCode() ?: StorageNotAvailableException::STATUS_INDETERMINATE; $storage->setStatus( $status, $this->l10n->t('Insufficient data: %s', [$e->getMessage()]) diff --git a/apps/files_external/lib/Controller/UserGlobalStoragesController.php b/apps/files_external/lib/Controller/UserGlobalStoragesController.php index da1ebfebdcbc..1c2329090d07 100644 --- a/apps/files_external/lib/Controller/UserGlobalStoragesController.php +++ b/apps/files_external/lib/Controller/UserGlobalStoragesController.php @@ -43,10 +43,7 @@ * User global storages controller */ class UserGlobalStoragesController extends StoragesController { - /** - * @var IUserSession - */ - private $userSession; + private \OCP\IUserSession $userSession; /** * Creates a new user global storages controller. diff --git a/apps/files_external/lib/Controller/UserStoragesController.php b/apps/files_external/lib/Controller/UserStoragesController.php index 38432873a67c..7d6506177aff 100644 --- a/apps/files_external/lib/Controller/UserStoragesController.php +++ b/apps/files_external/lib/Controller/UserStoragesController.php @@ -41,10 +41,7 @@ * User storages controller */ class UserStoragesController extends StoragesController { - /** - * @var IUserSession - */ - private $userSession; + private \OCP\IUserSession $userSession; /** * Creates a new user storages controller. diff --git a/apps/files_external/lib/Lib/Backend/DAV.php b/apps/files_external/lib/Lib/Backend/DAV.php index f050cffc8597..b60a39975407 100644 --- a/apps/files_external/lib/Lib/Backend/DAV.php +++ b/apps/files_external/lib/Lib/Backend/DAV.php @@ -34,8 +34,8 @@ class DAV extends ExternalBackend { public function __construct(IL10N $l) { $this ->setIdentifier('dav') - ->addIdentifierAlias('\OC\Files\Storage\DAV') // legacy compat - ->setStorageClass('\OC\Files\Storage\DAV') + ->addIdentifierAlias('\\' . \OC\Files\Storage\DAV::class) // legacy compat + ->setStorageClass('\\' . \OC\Files\Storage\DAV::class) ->setText($l->t('WebDAV')) ->addParameters([ (new DefinitionParameter('host', $l->t('URL'))), diff --git a/apps/files_external/lib/Lib/Backend/Google.php b/apps/files_external/lib/Lib/Backend/Google.php index 869b1495ecba..42432845db14 100644 --- a/apps/files_external/lib/Lib/Backend/Google.php +++ b/apps/files_external/lib/Lib/Backend/Google.php @@ -36,7 +36,7 @@ public function __construct(IL10N $l) { $this ->setIdentifier('googledrive') ->addIdentifierAlias('\OC\Files\Storage\Google') // legacy compat - ->setStorageClass('\OCA\Files_External\Lib\Storage\Google') + ->setStorageClass('\\' . \OCA\Files_External\Lib\Storage\Google::class) ->setText($l->t('Google Drive')) ->addParameters([ // all parameters handled in OAuth2 mechanism diff --git a/apps/files_external/lib/Lib/Backend/Local.php b/apps/files_external/lib/Lib/Backend/Local.php index adb39fa71a3d..82f254c342bb 100644 --- a/apps/files_external/lib/Lib/Backend/Local.php +++ b/apps/files_external/lib/Lib/Backend/Local.php @@ -32,8 +32,8 @@ class Local extends ExternalBackend { public function __construct(IL10N $l) { $this ->setIdentifier('local') - ->addIdentifierAlias('\OC\Files\Storage\Local') // legacy compat - ->setStorageClass('\OC\Files\Storage\Local') + ->addIdentifierAlias('\\' . \OC\Files\Storage\Local::class) // legacy compat + ->setStorageClass('\\' . \OC\Files\Storage\Local::class) ->setText($l->t('Local')) ->addParameters([ (new DefinitionParameter('datadir', $l->t('Location'))), diff --git a/apps/files_external/lib/Lib/Backend/OwnCloud.php b/apps/files_external/lib/Lib/Backend/OwnCloud.php index b7ac9f274d49..30b2358c7936 100644 --- a/apps/files_external/lib/Lib/Backend/OwnCloud.php +++ b/apps/files_external/lib/Lib/Backend/OwnCloud.php @@ -32,7 +32,7 @@ public function __construct(IL10N $l) { $this ->setIdentifier('owncloud') ->addIdentifierAlias('\OC\Files\Storage\OwnCloud') // legacy compat - ->setStorageClass('\OCA\Files_External\Lib\Storage\OwnCloud') + ->setStorageClass('\\' . \OCA\Files_External\Lib\Storage\OwnCloud::class) ->setText($l->t('ownCloud')) ->addParameters([ (new DefinitionParameter('host', $l->t('URL'))), diff --git a/apps/files_external/lib/Lib/Backend/SFTP.php b/apps/files_external/lib/Lib/Backend/SFTP.php index 9c23f0fda067..21237475031e 100644 --- a/apps/files_external/lib/Lib/Backend/SFTP.php +++ b/apps/files_external/lib/Lib/Backend/SFTP.php @@ -32,7 +32,7 @@ public function __construct(IL10N $l) { $this ->setIdentifier('sftp') ->addIdentifierAlias('\OC\Files\Storage\SFTP') // legacy compat - ->setStorageClass('\OCA\Files_External\Lib\Storage\SFTP') + ->setStorageClass('\\' . \OCA\Files_External\Lib\Storage\SFTP::class) ->setText($l->t('SFTP')) ->addParameters([ (new DefinitionParameter('host', $l->t('Host'))), diff --git a/apps/files_external/lib/Lib/Backend/SFTP_Key.php b/apps/files_external/lib/Lib/Backend/SFTP_Key.php index 4010c7e701bc..5603ab60efb9 100644 --- a/apps/files_external/lib/Lib/Backend/SFTP_Key.php +++ b/apps/files_external/lib/Lib/Backend/SFTP_Key.php @@ -31,7 +31,7 @@ class SFTP_Key extends ExternalBackend { public function __construct(IL10N $l, SFTP $sftpBackend) { $this ->setIdentifier('\OC\Files\Storage\SFTP_Key') - ->setStorageClass('\OCA\Files_External\Lib\Storage\SFTP') + ->setStorageClass('\\' . \OCA\Files_External\Lib\Storage\SFTP::class) ->setText($l->t('SFTP with secret key login')) ->addParameters([ (new DefinitionParameter('host', $l->t('Host'))), diff --git a/apps/files_external/lib/Lib/Backend/SMB.php b/apps/files_external/lib/Lib/Backend/SMB.php index ab4e30c3e128..2a5f93fc717c 100644 --- a/apps/files_external/lib/Lib/Backend/SMB.php +++ b/apps/files_external/lib/Lib/Backend/SMB.php @@ -37,7 +37,7 @@ public function __construct(IL10N $l) { $this ->setIdentifier('smb') ->addIdentifierAlias('\OC\Files\Storage\SMB') // legacy compat - ->setStorageClass('\OCA\Files_External\Lib\Storage\SMB') + ->setStorageClass('\\' . \OCA\Files_External\Lib\Storage\SMB::class) ->setText($l->t('SMB Personal (unique file IDs)')) ->addParameters([ (new DefinitionParameter('host', $l->t('Host'))), diff --git a/apps/files_external/lib/Lib/Backend/SMB2.php b/apps/files_external/lib/Lib/Backend/SMB2.php index d565c497fa57..71de82ab5d3c 100644 --- a/apps/files_external/lib/Lib/Backend/SMB2.php +++ b/apps/files_external/lib/Lib/Backend/SMB2.php @@ -35,7 +35,7 @@ class SMB2 extends ExternalBackend { public function __construct(IL10N $l) { $this ->setIdentifier('smb-coll') - ->setStorageClass('\OCA\Files_External\Lib\Storage\SMB2') + ->setStorageClass('\\' . \OCA\Files_External\Lib\Storage\SMB2::class) ->setText($l->t('SMB Collaborative (shared file IDs)')) ->addParameters([ (new DefinitionParameter('host', $l->t('Host'))), diff --git a/apps/files_external/lib/Lib/Backend/SMB_OC.php b/apps/files_external/lib/Lib/Backend/SMB_OC.php index 04b2c065cc42..ddaf179ccd47 100644 --- a/apps/files_external/lib/Lib/Backend/SMB_OC.php +++ b/apps/files_external/lib/Lib/Backend/SMB_OC.php @@ -40,7 +40,7 @@ class SMB_OC extends ExternalBackend { public function __construct(IL10N $l, SMB $smbBackend) { $this ->setIdentifier('\OC\Files\Storage\SMB_OC') - ->setStorageClass('\OCA\Files_External\Lib\Storage\SMB') + ->setStorageClass('\\' . \OCA\Files_External\Lib\Storage\SMB::class) ->setText($l->t('SMB / CIFS using OC login')) ->addParameters([ (new DefinitionParameter('host', $l->t('Host'))), diff --git a/apps/files_external/lib/Lib/Cache/SmbCacheWrapper.php b/apps/files_external/lib/Lib/Cache/SmbCacheWrapper.php index e9894606fd2b..8d5a15dccaa0 100644 --- a/apps/files_external/lib/Lib/Cache/SmbCacheWrapper.php +++ b/apps/files_external/lib/Lib/Cache/SmbCacheWrapper.php @@ -38,10 +38,7 @@ * @package OCA\Files_External\Lib\Cache */ class SmbCacheWrapper extends CacheWrapper { - /** - * @var SMB - */ - private $smb; + private \OCA\Files_External\Lib\Storage\SMB $smb; public function __construct(ICache $cache, SMB $smb) { parent::__construct($cache); @@ -57,16 +54,12 @@ public function get($file) { public function getFolderContents($folder) { $children = parent::getFolderContents($folder); - return \array_filter($children, function (ICacheEntry $c) { - return $this->canAccess($c->getPath()); - }); + return \array_filter($children, fn (ICacheEntry $c) => $this->canAccess($c->getPath())); } public function getFolderContentsById($fileId) { $children = parent::getFolderContentsById($fileId); - return \array_filter($children, function (ICacheEntry $c) { - return $this->canAccess($c->getPath()); - }); + return \array_filter($children, fn (ICacheEntry $c) => $this->canAccess($c->getPath())); } private function canAccess($file): bool { diff --git a/apps/files_external/lib/Lib/RSAStore.php b/apps/files_external/lib/Lib/RSAStore.php index 4d8524291584..9ba4db4bfa57 100644 --- a/apps/files_external/lib/Lib/RSAStore.php +++ b/apps/files_external/lib/Lib/RSAStore.php @@ -30,12 +30,10 @@ * Store and retrieve phpseclib3 RSA private keys */ class RSAStore { - private static $rsaStore = null; + private static ?\OCA\Files_External\Lib\RSAStore $rsaStore = null; - /** @var ICredentialsManager */ - private $credentialsManager; - /** @var IConfig */ - private $config; + private \OCP\Security\ICredentialsManager $credentialsManager; + private \OCP\IConfig $config; /** * Get the global instance of the RSAStore. If no one is set yet, a new @@ -92,7 +90,7 @@ public function storeData(PrivateKey $rsaKey, string $userId): string { 'rsaId' => $keyId, 'userId' => $userId, ]; - return \base64_encode(\json_encode($keyData)); + return \base64_encode(\json_encode($keyData, JSON_THROW_ON_ERROR)); } /** @@ -103,7 +101,7 @@ public function storeData(PrivateKey $rsaKey, string $userId): string { * @return PrivateKey the stored private key */ public function retrieveData(string $token): PrivateKey { - $keyData = \json_decode(\base64_decode($token), true); + $keyData = \json_decode(\base64_decode($token), true, 512, JSON_THROW_ON_ERROR); $privateKey = $this->credentialsManager->retrieve($keyData['userId'], $keyData['rsaId']); $password = $this->config->getSystemValue('secret', ''); diff --git a/apps/files_external/lib/Lib/Storage/Google.php b/apps/files_external/lib/Lib/Storage/Google.php index 74b1cf3694df..c6aca1d6b979 100644 --- a/apps/files_external/lib/Lib/Storage/Google.php +++ b/apps/files_external/lib/Lib/Storage/Google.php @@ -42,16 +42,16 @@ use Icewind\Streams\RetryWrapper; class Google extends \OCP\Files\Storage\StorageAdapter { - private $client; - private $id; + private ?\Google_Client $client = null; + private ?string $id = null; private $root; - private $service; + private ?\Google\Service\Drive $service = null; private $driveFiles; - private static $tempFiles = []; + private static array $tempFiles = []; - private $defaultFieldsForFile; - private $defaultFieldsForFolderScan; + private ?string $defaultFieldsForFile = null; + private ?string $defaultFieldsForFolderScan = null; // Google Doc mimetypes public const FOLDER = 'application/vnd.google-apps.folder'; @@ -75,13 +75,13 @@ public function __construct($params) { $this->client->setClientId($params['client_id']); $this->client->setClientSecret($params['client_secret']); $this->client->setScopes(['https://www.googleapis.com/auth/drive']); - $this->client->setAccessToken(\json_decode($params['token'], true)); + $this->client->setAccessToken(\json_decode($params['token'], true, 512, JSON_THROW_ON_ERROR)); // note: API connection is lazy $this->service = new Drive($this->client); - $token = \json_decode($params['token'], true); + $token = \json_decode($params['token'], true, 512, JSON_THROW_ON_ERROR); $this->id = 'google::'.\substr($params['client_id'], 0, 30).$token['created']; - $this->root = isset($params['root']) ? $params['root'] : ''; + $this->root = $params['root'] ?? ''; } else { throw new \Exception('Creating Google storage failed'); } diff --git a/apps/files_external/lib/Lib/Storage/SMB.php b/apps/files_external/lib/Lib/Storage/SMB.php index 3551bb7abbf9..b7d278fb10aa 100644 --- a/apps/files_external/lib/Lib/Storage/SMB.php +++ b/apps/files_external/lib/Lib/Storage/SMB.php @@ -87,7 +87,7 @@ public function __construct($params) { if (!empty($loggedParams['password'])) { $loggedParams['password'] = '***removed***'; } - $this->log('enter: '.__FUNCTION__.'('.\json_encode($loggedParams).')'); + $this->log('enter: '.__FUNCTION__.'('.\json_encode($loggedParams, JSON_THROW_ON_ERROR).')'); if (isset($params['host'], $params['user'], $params['password'], $params['share'])) { $domain = $params['domain'] ?? ''; @@ -100,7 +100,7 @@ public function __construct($params) { $shareClass = \get_class($this->share); $this->log("using $shareClass for the connection"); - $this->root = isset($params['root']) ? $params['root'] : '/'; + $this->root = $params['root'] ?? '/'; if (!$this->root || $this->root[0] != '/') { $this->root = '/' . $this->root; } @@ -108,7 +108,7 @@ public function __construct($params) { $this->root .= '/'; } } else { - $ex = new \Exception('Invalid configuration: '.\json_encode($loggedParams)); + $ex = new \Exception('Invalid configuration: '.\json_encode($loggedParams, JSON_THROW_ON_ERROR)); $this->leave(__FUNCTION__, $ex); throw $ex; } @@ -183,9 +183,7 @@ protected function getFileInfo($path) { 0, $this->statCache[$path]->getMTime(), $mode, - function () { - return []; - } + fn () => [] ); } } catch (ConnectException $e) { @@ -205,9 +203,7 @@ function () { 0, $this->shareMTime(), IFileInfo::MODE_DIRECTORY, - function () { - return []; - } + fn () => [] ); } else { $this->leave(__FUNCTION__, $e); @@ -250,9 +246,7 @@ protected function getFolderContents($path) { //remember entry so we can answer file_exists and filetype without a full stat $this->statCache[$fullPath] = $fileInfo; } - } catch (NotFoundException $e) { - $this->swallow(__FUNCTION__, $e); - } catch (ForbiddenException $e) { + } catch (NotFoundException|ForbiddenException $e) { $this->swallow(__FUNCTION__, $e); } } @@ -584,10 +578,9 @@ public function opendir($path) { $result = false; try { $files = $this->getFolderContents($path); - $names = \array_map(function ($info) { - /** @var \Icewind\SMB\IFileInfo $info */ - return $info->getName(); - }, $files); + $names = \array_map(fn ($info) => + /** @var \Icewind\SMB\IFileInfo $info */ + $info->getName(), $files); $result = IteratorDirectory::wrap($names); } catch (ConnectException $e) { $ex = new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e); diff --git a/apps/files_external/lib/Lib/Storage/SMB2.php b/apps/files_external/lib/Lib/Storage/SMB2.php index 84de3d9e5eac..7178b9b92247 100644 --- a/apps/files_external/lib/Lib/Storage/SMB2.php +++ b/apps/files_external/lib/Lib/Storage/SMB2.php @@ -24,10 +24,7 @@ use OCA\Files_External\Lib\Cache\SmbCacheWrapper; class SMB2 extends SMB { - /** - * @var SMB - */ - private $userSpecificSmb; + private \OCA\Files_External\Lib\Storage\SMB $userSpecificSmb; public function __construct($params) { $this->userSpecificSmb = new SMB($params); diff --git a/apps/files_external/lib/config.php b/apps/files_external/lib/config.php index 14cb250ef1db..368ad9620c5c 100644 --- a/apps/files_external/lib/config.php +++ b/apps/files_external/lib/config.php @@ -62,9 +62,7 @@ public static function dependencyMessage($backends) { } foreach ($dependencyGroups as $module => $dependants) { - $backends = \implode(', ', \array_map(function ($backend) { - return '' . $backend->getText() . ''; - }, $dependants)); + $backends = \implode(', ', \array_map(fn ($backend) => '' . $backend->getText() . '', $dependants)); $message .= '
' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends); } diff --git a/apps/files_external/tests/Command/ApplicableTest.php b/apps/files_external/tests/Command/ApplicableTest.php index ea597b937294..b9b66c313c94 100644 --- a/apps/files_external/tests/Command/ApplicableTest.php +++ b/apps/files_external/tests/Command/ApplicableTest.php @@ -27,9 +27,9 @@ class ApplicableTest extends CommandTest { private function getInstance($storageService) { /** @var \OCP\IUserManager|\PHPUnit\Framework\MockObject\MockObject $userManager */ - $userManager = $this->createMock('\OCP\IUserManager'); + $userManager = $this->createMock('\\' . \OCP\IUserManager::class); /** @var \OCP\IGroupManager|\PHPUnit\Framework\MockObject\MockObject $groupManager */ - $groupManager = $this->createMock('\OCP\IGroupManager'); + $groupManager = $this->createMock('\\' . \OCP\IGroupManager::class); $userManager->expects($this->any()) ->method('userExists') @@ -54,7 +54,7 @@ public function testListEmpty() { 'output' => 'json' ]); - $result = \json_decode($this->executeCommand($command, $input), true); + $result = \json_decode($this->executeCommand($command, $input), true, 512, JSON_THROW_ON_ERROR); $this->assertEquals(['users' => [], 'groups' => []], $result); } @@ -71,7 +71,7 @@ public function testList() { 'output' => 'json' ]); - $result = \json_decode($this->executeCommand($command, $input), true); + $result = \json_decode($this->executeCommand($command, $input), true, 512, JSON_THROW_ON_ERROR); $this->assertEquals(['users' => ['test', 'asd'], 'groups' => []], $result); } diff --git a/apps/files_external/tests/Command/CommandTest.php b/apps/files_external/tests/Command/CommandTest.php index c07c934c5603..8dfdbf646fb2 100644 --- a/apps/files_external/tests/Command/CommandTest.php +++ b/apps/files_external/tests/Command/CommandTest.php @@ -37,7 +37,7 @@ abstract class CommandTest extends TestCase { * @return \OCP\Files\External\Service\IGlobalStoragesService|\PHPUnit\Framework\MockObject\MockObject */ protected function getGlobalStorageService(array $mounts = []) { - $mock = $this->createMock('OCP\Files\External\Service\IGlobalStoragesService'); + $mock = $this->createMock(\OCP\Files\External\Service\IGlobalStoragesService::class); $this->bindMounts($mock, $mounts); diff --git a/apps/files_external/tests/Command/ListCommandTest.php b/apps/files_external/tests/Command/ListCommandTest.php index c9afec78f0de..ed3776828a8a 100644 --- a/apps/files_external/tests/Command/ListCommandTest.php +++ b/apps/files_external/tests/Command/ListCommandTest.php @@ -38,21 +38,21 @@ class ListCommandTest extends CommandTest { */ private function getInstance() { /** @var \OCP\Files\External\Service\IGlobalStoragesService|\PHPUnit\Framework\MockObject\MockObject $globalService */ - $globalService = $this->createMock('\OCP\Files\External\Service\IGlobalStoragesService'); + $globalService = $this->createMock('\\' . \OCP\Files\External\Service\IGlobalStoragesService::class); /** @var \OC\Files\External\Service\IUserStoragesService|\PHPUnit\Framework\MockObject\MockObject $userService */ - $userService = $this->createMock('\OCP\Files\External\Service\IUserStoragesService'); + $userService = $this->createMock('\\' . \OCP\Files\External\Service\IUserStoragesService::class); /** @var \OCP\IUserManager|\PHPUnit\Framework\MockObject\MockObject $userManager */ - $userManager = $this->createMock('\OCP\IUserManager'); + $userManager = $this->createMock('\\' . \OCP\IUserManager::class); /** @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject $userSession */ - $userSession = $this->createMock('\OCP\IUserSession'); + $userSession = $this->createMock('\\' . \OCP\IUserSession::class); return new ListCommand($globalService, $userService, $userSession, $userManager); } public function testListAuthIdentifier() { - $l10n = $this->createMock('\OCP\IL10N', null, [], '', false); - $session = $this->createMock('\OCP\ISession'); - $crypto = $this->createMock('\OCP\Security\ICrypto'); + $l10n = $this->createMock('\\' . \OCP\IL10N::class); + $session = $this->createMock('\\' . \OCP\ISession::class); + $crypto = $this->createMock('\\' . \OCP\Security\ICrypto::class); $instance = $this->getInstance(); // FIXME: use mock of IStorageConfig $mount1 = new StorageConfig(); @@ -67,15 +67,15 @@ public function testListAuthIdentifier() { $output = new BufferedOutput(); $instance->listMounts('', [$mount1, $mount2], $input, $output); - $output = \json_decode($output->fetch(), true); + $output = \json_decode($output->fetch(), true, 512, JSON_THROW_ON_ERROR); $this->assertNotEquals($output[0]['authentication_type'], $output[1]['authentication_type']); } public function testDisplayWarningForIncomplete() { - $l10n = $this->createMock('\OCP\IL10N', null, [], '', false); - $session = $this->createMock('\OCP\ISession'); - $crypto = $this->createMock('\OCP\Security\ICrypto'); + $l10n = $this->createMock('\\' . \OCP\IL10N::class); + $session = $this->createMock('\\' . \OCP\ISession::class); + $crypto = $this->createMock('\\' . \OCP\Security\ICrypto::class); $instance = $this->getInstance(); // FIXME: use mock of IStorageConfig $mount1 = new StorageConfig(); @@ -133,9 +133,9 @@ public function providesShortView() { * @param $mountOptions */ public function testShortView($options, $expectedResult, $mountOptions) { - $l10n = $this->createMock('\OCP\IL10N', null, [], '', false); - $session = $this->createMock('\OCP\ISession'); - $crypto = $this->createMock('\OCP\Security\ICrypto'); + $l10n = $this->createMock('\\' . \OCP\IL10N::class); + $session = $this->createMock('\\' . \OCP\ISession::class); + $crypto = $this->createMock('\\' . \OCP\Security\ICrypto::class); $instance = $this->getInstance(); // FIXME: use mock of IStorageConfig $mount1 = new StorageConfig(); @@ -156,7 +156,7 @@ public function testShortView($options, $expectedResult, $mountOptions) { $instance->listMounts('user1', [$mount1, $mount2], $input, $output); $output = $output->fetch(); if (isset($options['output']) && ($options['output'] === 'json')) { - $results = \json_decode($output, true); + $results = \json_decode($output, true, 512, JSON_THROW_ON_ERROR); $countResults = \count($results); for ($i = 0; $i < $countResults; $i++) { @@ -210,9 +210,9 @@ public function providesLongView() { * @param $mountOptions */ public function testLongView($options, $expectedResult, $mountOptions) { - $l10n = $this->createMock('\OCP\IL10N', null, [], '', false); - $session = $this->createMock('\OCP\ISession'); - $crypto = $this->createMock('\OCP\Security\ICrypto'); + $l10n = $this->createMock('\\' . \OCP\IL10N::class); + $session = $this->createMock('\\' . \OCP\ISession::class); + $crypto = $this->createMock('\\' . \OCP\Security\ICrypto::class); $instance = $this->getInstance(); // FIXME: use mock of IStorageConfig $mount1 = new StorageConfig(); @@ -231,7 +231,7 @@ public function testLongView($options, $expectedResult, $mountOptions) { $instance->listMounts('user1', [$mount1, $mount2], $input, $output); $output = $output->fetch(); if (isset($options['output']) && ($options['output'] === 'json')) { - $results = \json_decode($output, true); + $results = \json_decode($output, true, 512, JSON_THROW_ON_ERROR); $countResults = \count($results); for ($i = 0; $i < $countResults; $i++) { @@ -283,9 +283,9 @@ public function providesImportableFormat() { * @param $mountOptions */ public function testImportableFormat($options, $expectedResult, $mountOptions) { - $l10n = $this->createMock('\OCP\IL10N', null, [], '', false); - $session = $this->createMock('\OCP\ISession'); - $crypto = $this->createMock('\OCP\Security\ICrypto'); + $l10n = $this->createMock('\\' . \OCP\IL10N::class); + $session = $this->createMock('\\' . \OCP\ISession::class); + $crypto = $this->createMock('\\' . \OCP\Security\ICrypto::class); $instance = $this->getInstance(); // FIXME: use mock of IStorageConfig $mount1 = new StorageConfig(); @@ -304,7 +304,7 @@ public function testImportableFormat($options, $expectedResult, $mountOptions) { $instance->listMounts('user1', [$mount1, $mount2], $input, $output); $output = $output->fetch(); if (isset($options['output']) && ($options['output'] === 'json')) { - $results = \json_decode($output, true); + $results = \json_decode($output, true, 512, JSON_THROW_ON_ERROR); $countResults = \count($results); for ($i = 0; $i < $countResults; $i++) { diff --git a/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php b/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php index 6e45b6ca927f..de16211d6fd0 100644 --- a/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php +++ b/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php @@ -34,17 +34,17 @@ class GlobalStoragesControllerTest extends StoragesControllerTest { public function setUp(): void { parent::setUp(); - $this->service = $this->createMock('\OCP\Files\External\Service\IGlobalStoragesService'); + $this->service = $this->createMock('\\' . \OCP\Files\External\Service\IGlobalStoragesService::class); $this->service->method('getVisibilityType') ->willReturn(IStoragesBackendService::VISIBILITY_ADMIN); $this->controller = new GlobalStoragesController( 'files_external', - $this->createMock('\OCP\IRequest'), - $this->createMock('\OCP\IL10N'), + $this->createMock('\\' . \OCP\IRequest::class), + $this->createMock('\\' . \OCP\IL10N::class), $this->service, - $this->createMock('\OCP\ILogger') + $this->createMock('\\' . \OCP\ILogger::class) ); } diff --git a/apps/files_external/tests/Controller/StoragesControllerTest.php b/apps/files_external/tests/Controller/StoragesControllerTest.php index faa1b2d74910..28ab052c6da8 100644 --- a/apps/files_external/tests/Controller/StoragesControllerTest.php +++ b/apps/files_external/tests/Controller/StoragesControllerTest.php @@ -56,8 +56,8 @@ public function tearDown(): void { /** * @return \OCP\Files\External\Backend\Backend */ - protected function getBackendMock($class = '\OCA\Files_External\Lib\Backend\SMB', $storageClass = '\OCA\Files_External\Lib\Storage\SMB') { - $backend = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + protected function getBackendMock($class = '\\' . \OCA\Files_External\Lib\Backend\SMB::class, $storageClass = '\\' . \OCA\Files_External\Lib\Storage\SMB::class) { + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->disableOriginalConstructor() ->getMock(); $backend->method('getStorageClass') @@ -70,8 +70,8 @@ protected function getBackendMock($class = '\OCA\Files_External\Lib\Backend\SMB' /** * @return \OCP\Files\External\Backend\Backend */ - protected function getBackendMockLocal($class = '\OCA\Files_External\Lib\Backend\Local', $storageClass = '\OC\Files\Storage\Local') { - $backend = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + protected function getBackendMockLocal($class = '\\' . \OCA\Files_External\Lib\Backend\Local::class, $storageClass = '\\' . \OC\Files\Storage\Local::class) { + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->disableOriginalConstructor() ->getMock(); $backend->method('getStorageClass') @@ -85,7 +85,7 @@ protected function getBackendMockLocal($class = '\OCA\Files_External\Lib\Backend * @return \OCP\Files\External\Auth\AuthMechanism */ protected function getAuthMechMock($scheme = 'null', $class = '\OCA\Files_External\Lib\Auth\NullMechanism') { - $authMech = $this->getMockBuilder('\OCP\Files\External\Auth\AuthMechanism') + $authMech = $this->getMockBuilder('\\' . \OCP\Files\External\Auth\AuthMechanism::class) ->disableOriginalConstructor() ->getMock(); $authMech->method('getScheme') @@ -123,7 +123,7 @@ public function testAddStorage() { $response = $this->controller->create( 'mount', - '\OCA\Files_External\Lib\Storage\SMB', + '\\' . \OCA\Files_External\Lib\Storage\SMB::class, '\OCA\Files_External\Lib\Auth\NullMechanism', [], [], @@ -200,7 +200,7 @@ public function testUpdateStorage() { $response = $this->controller->update( 1, 'mount', - '\OCA\Files_External\Lib\Storage\SMB', + '\\' . \OCA\Files_External\Lib\Storage\SMB::class, '\OCA\Files_External\Lib\Auth\NullMechanism', [], [], @@ -242,7 +242,7 @@ public function testAddOrUpdateStorageInvalidMountPoint($mountPoint) { $response = $this->controller->create( $mountPoint, - '\OCA\Files_External\Lib\Storage\SMB', + '\\' . \OCA\Files_External\Lib\Storage\SMB::class, '\OCA\Files_External\Lib\Auth\NullMechanism', [], [], @@ -256,7 +256,7 @@ public function testAddOrUpdateStorageInvalidMountPoint($mountPoint) { $response = $this->controller->update( 1, $mountPoint, - '\OCA\Files_External\Lib\Storage\SMB', + '\\' . \OCA\Files_External\Lib\Storage\SMB::class, '\OCA\Files_External\Lib\Auth\NullMechanism', [], [], @@ -333,7 +333,7 @@ public function testUpdateStorageNonExisting() { $response = $this->controller->update( 255, 'mount', - '\OCA\Files_External\Lib\Storage\SMB', + '\\' . \OCA\Files_External\Lib\Storage\SMB::class, '\OCA\Files_External\Lib\Auth\NullMechanism', [], [], @@ -429,7 +429,7 @@ public function testValidateStorage($backendValidate, $authMechValidate, $expect $response = $this->controller->create( 'mount', - '\OCA\Files_External\Lib\Storage\SMB', + '\\' . \OCA\Files_External\Lib\Storage\SMB::class, '\OCA\Files_External\Lib\Auth\NullMechanism', [], [], @@ -544,9 +544,7 @@ public function testIndex() { $expected = [$expectedStorage1, $expectedStorage2, $expectedStorage3]; $result = $this->controller->index(); - $actual = \array_map(function ($item) { - return $item->jsonSerialize(); - }, $result->getData()); + $actual = \array_map(fn ($item) => $item->jsonSerialize(), $result->getData()); $this->assertEquals(Http::STATUS_OK, $result->getStatus()); $this->assertEquals($expected, $actual); } diff --git a/apps/files_external/tests/Controller/UserStoragesControllerTest.php b/apps/files_external/tests/Controller/UserStoragesControllerTest.php index 9e85f2f4afe5..4dd8469bbd2e 100644 --- a/apps/files_external/tests/Controller/UserStoragesControllerTest.php +++ b/apps/files_external/tests/Controller/UserStoragesControllerTest.php @@ -40,18 +40,18 @@ class UserStoragesControllerTest extends StoragesControllerTest { public function setUp(): void { parent::setUp(); - $this->service = $this->createMock('\OCP\Files\External\Service\IUserStoragesService'); + $this->service = $this->createMock('\\' . \OCP\Files\External\Service\IUserStoragesService::class); $this->service->method('getVisibilityType') ->willReturn(IStoragesBackendService::VISIBILITY_PERSONAL); $this->controller = new UserStoragesController( 'files_external', - $this->createMock('\OCP\IRequest'), - $this->createMock('\OCP\IL10N'), + $this->createMock('\\' . \OCP\IRequest::class), + $this->createMock('\\' . \OCP\IL10N::class), $this->service, - $this->createMock('\OCP\IUserSession'), - $this->createMock('\OCP\ILogger') + $this->createMock('\\' . \OCP\IUserSession::class), + $this->createMock('\\' . \OCP\ILogger::class) ); } @@ -78,7 +78,7 @@ public function testAddOrUpdateStorageDisallowedBackend() { $response = $this->controller->create( 'mount', - '\OCA\Files_External\Lib\Storage\SMB', + '\\' . \OCA\Files_External\Lib\Storage\SMB::class, '\Auth\Mechanism', [], [], @@ -92,7 +92,7 @@ public function testAddOrUpdateStorageDisallowedBackend() { $response = $this->controller->update( 1, 'mount', - '\OCA\Files_External\Lib\Storage\SMB', + '\\' . \OCA\Files_External\Lib\Storage\SMB::class, '\Auth\Mechanism', [], [], diff --git a/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php b/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php index 1719dd077de3..9b8a24e4825f 100644 --- a/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php +++ b/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php @@ -36,10 +36,10 @@ public static function checkDependencies() { } public function testCheckDependencies() { - $trait = $this->getMockForTrait('\OCA\Files_External\Lib\LegacyDependencyCheckPolyfill'); + $trait = $this->getMockForTrait('\\' . \OCA\Files_External\Lib\LegacyDependencyCheckPolyfill::class); $trait->expects($this->once()) ->method('getStorageClass') - ->willReturn('\OCA\Files_External\Tests\LegacyDependencyCheckPolyfillTest'); + ->willReturn('\\' . \OCA\Files_External\Tests\LegacyDependencyCheckPolyfillTest::class); $dependencies = $trait->checkDependencies(); $this->assertCount(2, $dependencies); diff --git a/apps/files_external/tests/Panels/AdminTest.php b/apps/files_external/tests/Panels/AdminTest.php index 7c27ffa125c9..0fe64db8b9eb 100644 --- a/apps/files_external/tests/Panels/AdminTest.php +++ b/apps/files_external/tests/Panels/AdminTest.php @@ -31,16 +31,15 @@ * @package OCA\Files_External\Tests */ class AdminTest extends \Test\TestCase { - /** @var Admin */ - private $panel; + private \OCA\Files_External\Panels\Admin $panel; /** @var IStoragesBackendService */ - private $backendService; + private \PHPUnit\Framework\MockObject\MockObject $backendService; /** @var IGlobalStoragesService */ - private $storagesService; + private \PHPUnit\Framework\MockObject\MockObject $storagesService; /** @var Manager */ - private $encManager; + private \PHPUnit\Framework\MockObject\MockObject $encManager; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); diff --git a/apps/files_external/tests/Panels/PersonalTest.php b/apps/files_external/tests/Panels/PersonalTest.php index 90f272a484eb..1f53addb42a9 100644 --- a/apps/files_external/tests/Panels/PersonalTest.php +++ b/apps/files_external/tests/Panels/PersonalTest.php @@ -31,16 +31,15 @@ * @package OCA\Files_External\Tests */ class PersonalTest extends \Test\TestCase { - /** @var Personal */ - private $panel; + private \OCA\Files_External\Panels\Personal $panel; /** @var IStoragesBackendService */ - private $backendService; + private \PHPUnit\Framework\MockObject\MockObject $backendService; /** @var IUserStoragesService */ - private $storagesService; + private \PHPUnit\Framework\MockObject\MockObject $storagesService; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var Manager */ - private $encManager; + private \PHPUnit\Framework\MockObject\MockObject $encManager; public function setUp(): void { parent::setUp(); diff --git a/apps/files_external/tests/RSAStoreTest.php b/apps/files_external/tests/RSAStoreTest.php index b63c4fc0fae1..25b1210dd2f6 100644 --- a/apps/files_external/tests/RSAStoreTest.php +++ b/apps/files_external/tests/RSAStoreTest.php @@ -28,11 +28,10 @@ class RSAStoreTest extends \Test\TestCase { /** @var ICredentialsManager */ - private $credentialsManager; + private \PHPUnit\Framework\MockObject\MockObject $credentialsManager; /** @var IConfig */ - private $config; - /** @var RSAStore */ - private $rsaStore; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OCA\Files_External\Lib\RSAStore $rsaStore; protected function setUp(): void { $this->credentialsManager = $this->createMock(ICredentialsManager::class); diff --git a/apps/files_sharing/ajax/shareinfo.php b/apps/files_sharing/ajax/shareinfo.php index d7adffcc79da..c9fae4d2f5e5 100644 --- a/apps/files_sharing/ajax/shareinfo.php +++ b/apps/files_sharing/ajax/shareinfo.php @@ -64,9 +64,7 @@ $isWritable = $linkItem['permissions'] & (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_CREATE); if (!$isWritable) { - \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, $storage) { - return new \OC\Files\Storage\Wrapper\PermissionsMask(['storage' => $storage, 'mask' => \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_SHARE]); - }); + \OC\Files\Filesystem::addStorageWrapper('readonly', fn ($mountPoint, $storage) => new \OC\Files\Storage\Wrapper\PermissionsMask(['storage' => $storage, 'mask' => \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_SHARE])); } $rootInfo = \OC\Files\Filesystem::getFileInfo($path); diff --git a/apps/files_sharing/appinfo/app.php b/apps/files_sharing/appinfo/app.php index 62a03f04c15c..5fff330d92f6 100644 --- a/apps/files_sharing/appinfo/app.php +++ b/apps/files_sharing/appinfo/app.php @@ -31,8 +31,8 @@ \OCA\Files_Sharing\Helper::registerHooks(); -\OCP\Share::registerBackend('file', 'OCA\Files_Sharing\ShareBackend\File'); -\OCP\Share::registerBackend('folder', 'OCA\Files_Sharing\ShareBackend\Folder', 'file'); +\OCP\Share::registerBackend('file', \OCA\Files_Sharing\ShareBackend\File::class); +\OCP\Share::registerBackend('folder', \OCA\Files_Sharing\ShareBackend\Folder::class, 'file'); $application = new \OCA\Files_Sharing\AppInfo\Application(); $application->registerMountProviders(); @@ -56,16 +56,14 @@ function () { // \OCP\Util::addStyle('files_sharing', 'sharetabview'); -\OC::$server->getActivityManager()->registerExtension(function () { - return new \OCA\Files_Sharing\Activity( - \OC::$server->query('L10NFactory'), - \OC::$server->getURLGenerator(), - \OC::$server->getActivityManager() - ); -}); +\OC::$server->getActivityManager()->registerExtension(fn () => new \OCA\Files_Sharing\Activity( + \OC::$server->query('L10NFactory'), + \OC::$server->getURLGenerator(), + \OC::$server->getActivityManager() +)); $config = \OC::$server->getConfig(); -if (\class_exists('OCA\Files\App') && $config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes') { +if (\class_exists(\OCA\Files\App::class) && $config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes') { \OCA\Files\App::getNavigationManager()->add(function () { $l = \OC::$server->getL10N('files_sharing'); return [ diff --git a/apps/files_sharing/lib/AppInfo/Application.php b/apps/files_sharing/lib/AppInfo/Application.php index 11cd5437d8b4..a043b715c1d9 100644 --- a/apps/files_sharing/lib/AppInfo/Application.php +++ b/apps/files_sharing/lib/AppInfo/Application.php @@ -47,7 +47,7 @@ use OCP\Notification\Events\RegisterNotifierEvent; class Application extends App { - private $isProviderRegistered = false; + private bool $isProviderRegistered = false; public function __construct(array $urlParams = []) { parent::__construct('files_sharing', $urlParams); @@ -58,53 +58,47 @@ public function __construct(array $urlParams = []) { /** * Controllers */ - $container->registerService('ShareController', function (SimpleContainer $c) use ($server) { - return new ShareController( - $c->query('AppName'), - $c->query('Request'), - $server->getConfig(), - $server->getURLGenerator(), - $server->getUserManager(), - $server->getLogger(), - $server->getActivityManager(), - $server->getShareManager(), - $server->getSession(), - $server->getPreviewManager(), - $server->getRootFolder(), - $server->getUserSession(), - $server->getEventDispatcher() - ); - }); - $container->registerService('ExternalSharesController', function (SimpleContainer $c) use ($server) { - return new ExternalSharesController( - $c->query('AppName'), - $c->query('Request'), - $c->query('ExternalManager'), - $c->query('HttpClientService'), - $server->getEventDispatcher(), - $server->getConfig() - ); - }); - - $container->registerService('Share20OcsController', function (SimpleContainer $c) use ($server) { - return new Share20OcsController( - $c->query('AppName'), - $server->getRequest(), - $server->getShareManager(), - $server->getGroupManager(), - $server->getUserManager(), - $server->getRootFolder(), - $server->getURLGenerator(), - $server->getUserSession(), - $server->getL10N('files_sharing'), - $server->getConfig(), - $c->query(NotificationPublisher::class), - $server->getEventDispatcher(), - $c->query(SharingBlacklist::class), - $c->query(SharingAllowlist::class), - $c->query(UserTypeHelper::class) - ); - }); + $container->registerService('ShareController', fn (SimpleContainer $c) => new ShareController( + $c->query('AppName'), + $c->query('Request'), + $server->getConfig(), + $server->getURLGenerator(), + $server->getUserManager(), + $server->getLogger(), + $server->getActivityManager(), + $server->getShareManager(), + $server->getSession(), + $server->getPreviewManager(), + $server->getRootFolder(), + $server->getUserSession(), + $server->getEventDispatcher() + )); + $container->registerService('ExternalSharesController', fn (SimpleContainer $c) => new ExternalSharesController( + $c->query('AppName'), + $c->query('Request'), + $c->query('ExternalManager'), + $c->query('HttpClientService'), + $server->getEventDispatcher(), + $server->getConfig() + )); + + $container->registerService('Share20OcsController', fn (SimpleContainer $c) => new Share20OcsController( + $c->query('AppName'), + $server->getRequest(), + $server->getShareManager(), + $server->getGroupManager(), + $server->getUserManager(), + $server->getRootFolder(), + $server->getURLGenerator(), + $server->getUserSession(), + $server->getL10N('files_sharing'), + $server->getConfig(), + $c->query(NotificationPublisher::class), + $server->getEventDispatcher(), + $c->query(SharingBlacklist::class), + $c->query(SharingAllowlist::class), + $c->query(UserTypeHelper::class) + )); $container->registerService('RemoteOcsController', function (SimpleContainer $c) use ($server) { $user = $server->getUserSession()->getUser(); @@ -129,9 +123,7 @@ public function __construct(array $urlParams = []) { /** * Core class wrappers */ - $container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) { - return $server->getHTTPClientService(); - }); + $container->registerService('HttpClientService', fn (SimpleContainer $c) => $server->getHTTPClientService()); $container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) { $user = $server->getUserSession()->getUser(); $uid = $user ? $user->getUID() : null; @@ -148,14 +140,12 @@ public function __construct(array $urlParams = []) { /** * Middleware */ - $container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) { - return new SharingCheckMiddleware( - $c->query('AppName'), - $server->getConfig(), - $server->getAppManager(), - $c['ControllerMethodReflector'] - ); - }); + $container->registerService('SharingCheckMiddleware', fn (SimpleContainer $c) => new SharingCheckMiddleware( + $c->query('AppName'), + $server->getConfig(), + $server->getAppManager(), + $c['ControllerMethodReflector'] + )); // Execute middlewares $container->registerMiddleware('SharingCheckMiddleware'); @@ -175,29 +165,25 @@ public function __construct(array $urlParams = []) { $server = $c->query('ServerContainer'); return new \OCA\Files_Sharing\External\MountProvider( $server->getDatabaseConnection(), - function () use ($c) { - return $c->query('ExternalManager'); - } + fn () => $c->query('ExternalManager') ); }); - $container->registerService('Hooks', function ($c) { - return new Hooks( - $c->getServer()->getLazyRootFolder(), - $c->getServer()->getUrlGenerator(), - $c->getServer()->getEventDispatcher(), - $c->getServer()->getShareManager(), - $c->query(NotificationPublisher::class), - $c->getServer()->getActivityManager(), - $c->query(SharingAllowlist::class), - $c->getServer()->getUserSession() - ); - }); + $container->registerService('Hooks', fn ($c) => new Hooks( + $c->getServer()->getLazyRootFolder(), + $c->getServer()->getUrlGenerator(), + $c->getServer()->getEventDispatcher(), + $c->getServer()->getShareManager(), + $c->query(NotificationPublisher::class), + $c->getServer()->getActivityManager(), + $c->query(SharingAllowlist::class), + $c->getServer()->getUserSession() + )); /* * Register capabilities */ - $container->registerCapability('OCA\Files_Sharing\Capabilities'); + $container->registerCapability(\OCA\Files_Sharing\Capabilities::class); } public function registerMountProviders() { diff --git a/apps/files_sharing/lib/Cache.php b/apps/files_sharing/lib/Cache.php index c6c8fb2aeb59..1dbf4be0d0cd 100644 --- a/apps/files_sharing/lib/Cache.php +++ b/apps/files_sharing/lib/Cache.php @@ -42,15 +42,9 @@ class Cache extends CacheJail { */ private $storage; - /** - * @var IStorage - */ - private $sourceStorage; + private \OCP\Files\Storage\IStorage $sourceStorage; - /** - * @var ICacheEntry - */ - private $sourceRootInfo; + private \OCP\Files\Cache\ICacheEntry $sourceRootInfo; /** * @var \OCP\Files\Cache\ICache @@ -74,7 +68,7 @@ public function __construct($storage, IStorage $sourceStorage, ICacheEntry $sour } protected function formatCacheEntry($entry) { - $path = isset($entry['path']) ? $entry['path'] : ''; + $path = $entry['path'] ?? ''; $entry = parent::formatCacheEntry($entry); $sharePermissions = $this->storage->getPermissions($path); if (isset($entry['permissions'])) { diff --git a/apps/files_sharing/lib/Capabilities.php b/apps/files_sharing/lib/Capabilities.php index c250797fc0e6..32141c33fca6 100644 --- a/apps/files_sharing/lib/Capabilities.php +++ b/apps/files_sharing/lib/Capabilities.php @@ -33,30 +33,16 @@ * @package OCA\Files_Sharing */ class Capabilities implements ICapability { - /** @var IManager */ - private $shareManager; - /** @var IConfig */ - private $config; + private \OCP\Share\IManager $shareManager; + private \OCP\IConfig $config; - /** - * @var UserSearch - */ - private $userSearch; + private \OCP\Util\UserSearch $userSearch; - /** - * @var IL10N - */ - private $l10n; + private \OCP\IL10N $l10n; - /** - * @var SharingAllowlist - */ - private $sharingAllowlist; + private \OCA\Files_Sharing\SharingAllowlist $sharingAllowlist; - /** - * @var IUserSession - */ - private $userSession; + private \OCP\IUserSession $userSession; /** * Capabilities constructor. diff --git a/apps/files_sharing/lib/Controller/NotificationController.php b/apps/files_sharing/lib/Controller/NotificationController.php index 39d96da6aa6e..c8adb5ffd9e9 100644 --- a/apps/files_sharing/lib/Controller/NotificationController.php +++ b/apps/files_sharing/lib/Controller/NotificationController.php @@ -36,18 +36,12 @@ use OCP\Share\Exceptions\GenericShareException; class NotificationController extends OCSController { - /** @var MailNotifications */ - private $mailNotifications; - /** @var IUserSession */ - private $userSession; - /** @var IUserManager */ - private $userManager; - /** @var IGroupManager */ - private $groupManager; - /** @var IRootFolder */ - private $rootFolder; - /** @var IL10N */ - private $l; + private \OC\Share\MailNotifications $mailNotifications; + private \OCP\IUserSession $userSession; + private \OCP\IUserManager $userManager; + private \OCP\IGroupManager $groupManager; + private \OCP\Files\IRootFolder $rootFolder; + private \OCP\IL10N $l; public function __construct( string $appName, IRequest $request, @@ -127,10 +121,9 @@ public function notifyRecipients($itemSource, $itemType, $shareType, $recipient) $recipientList = $group->searchUsers(''); } // don't send a mail to the user who shared the file - $recipientList = \array_filter($recipientList, function ($user) { - /** @var IUser $user */ - return $user->getUID() !== $this->userSession->getUser()->getUID(); - }); + $recipientList = \array_filter($recipientList, fn ($user) => + /** @var IUser $user */ + $user->getUID() !== $this->userSession->getUser()->getUID()); $userFolder = $this->rootFolder->getUserFolder($sender->getUID()); $nodes = $userFolder->getById($itemSource, true); diff --git a/apps/files_sharing/lib/Controller/PersonalSettingsController.php b/apps/files_sharing/lib/Controller/PersonalSettingsController.php index 1b6b360c3260..1b7cfbb9caac 100644 --- a/apps/files_sharing/lib/Controller/PersonalSettingsController.php +++ b/apps/files_sharing/lib/Controller/PersonalSettingsController.php @@ -35,11 +35,9 @@ class PersonalSettingsController extends Controller { 'allow_share_dialog_user_enumeration' ]; - /** @var IConfig $config */ - private $config; + private \OCP\IConfig $config; - /** @var IUserSession $userSession */ - private $userSession; + private \OCP\IUserSession $userSession; public function __construct(string $appName, IRequest $request, IConfig $config, IUserSession $userSession) { parent::__construct($appName, $request); @@ -97,9 +95,7 @@ private function validateParameter($key, $value) { private function getUserRequestParams() { return \array_filter( $this->request->getParams(), - function ($key) { - return (\substr($key, 0, 1) !== '_'); - }, + fn ($key) => \substr($key, 0, 1) !== '_', ARRAY_FILTER_USE_KEY ); } diff --git a/apps/files_sharing/lib/Controller/RemoteOcsController.php b/apps/files_sharing/lib/Controller/RemoteOcsController.php index 8d82b28cf736..12cfcaaad416 100644 --- a/apps/files_sharing/lib/Controller/RemoteOcsController.php +++ b/apps/files_sharing/lib/Controller/RemoteOcsController.php @@ -149,9 +149,7 @@ public function getShares($includingPending = false) { foreach ($this->externalManager->getAcceptedShares() as $shareInfo) { try { $shares[] = $this->extendShareInfo($shareInfo); - } catch (StorageNotAvailableException $e) { - //TODO: Log the exception here? There are several logs already below the stack - } catch (StorageInvalidException $e) { + } catch (StorageNotAvailableException|StorageInvalidException $e) { //TODO: Log the exception here? There are several logs already below the stack } } @@ -164,9 +162,7 @@ public function getShares($includingPending = false) { foreach ($groupExternalManager->getAcceptedShares() as $shareInfo) { try { $shares[] = $this->extendShareInfo($shareInfo); - } catch (StorageNotAvailableException $e) { - $this->logger->logException($e, ['app' => 'files_sharing']); - } catch (StorageInvalidException $e) { + } catch (StorageNotAvailableException|StorageInvalidException $e) { $this->logger->logException($e, ['app' => 'files_sharing']); } } diff --git a/apps/files_sharing/lib/Controller/Share20OcsController.php b/apps/files_sharing/lib/Controller/Share20OcsController.php index 0a2d706cb78b..8978074c6be4 100644 --- a/apps/files_sharing/lib/Controller/Share20OcsController.php +++ b/apps/files_sharing/lib/Controller/Share20OcsController.php @@ -61,37 +61,24 @@ * @package OCA\Files_Sharing\Controller */ class Share20OcsController extends OCSController { - /** @var IManager */ - private $shareManager; - /** @var IGroupManager */ - private $groupManager; - /** @var IUserManager */ - private $userManager; - /** @var IRootFolder */ - private $rootFolder; - /** @var IUserSession */ - private $userSession; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var IL10N */ - private $l; - /** @var IConfig */ - private $config; - /** @var NotificationPublisher */ - private $notificationPublisher; - /** @var EventDispatcher */ - private $eventDispatcher; - /** @var SharingBlacklist */ - private $sharingBlacklist; - /** @var SharingAllowlist */ - private $sharingAllowlist; + private \OCP\Share\IManager $shareManager; + private \OCP\IGroupManager $groupManager; + private \OCP\IUserManager $userManager; + private \OCP\Files\IRootFolder $rootFolder; + private \OCP\IUserSession $userSession; + private \OCP\IURLGenerator $urlGenerator; + private \OCP\IL10N $l; + private \OCP\IConfig $config; + private \OCA\Files_Sharing\Service\NotificationPublisher $notificationPublisher; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; + private \OCA\Files_Sharing\SharingBlacklist $sharingBlacklist; + private \OCA\Files_Sharing\SharingAllowlist $sharingAllowlist; /** * @var string */ private $additionalInfoField; - /** @var UserTypeHelper */ - private $userTypeHelper; + private \OC\Helper\UserTypeHelper $userTypeHelper; /** @var Folder[] */ private $currentUserFolder; @@ -278,7 +265,7 @@ protected function formatShare(IShare $share, $received = false) { $result['attributes'] = null; if ($attributes = $share->getAttributes()) { - $result['attributes'] = \json_encode($attributes->toArray()); + $result['attributes'] = \json_encode($attributes->toArray(), JSON_THROW_ON_ERROR); } return $result; @@ -421,7 +408,7 @@ public function createShare() { * We check the permissions via webdav. But the permissions of the mount point * do not equal the share permissions. Here we fix that for federated mounts. */ - if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { + if ($path->getStorage()->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class)) { $permissions &= ~($permissions & ~$path->getPermissions()); } @@ -640,9 +627,7 @@ private function getSharedWithMe($node, $includeTags, $requestedShareTypes, $sta ); } - $shares = \array_filter($shares, function (IShare $share) { - return $share->getShareOwner() !== $this->userSession->getUser()->getUID(); - }); + $shares = \array_filter($shares, fn (IShare $share) => $share->getShareOwner() !== $this->userSession->getUser()->getUID()); $formatted = []; foreach ($shares as $share) { @@ -1237,9 +1222,9 @@ private function getShareById($id, $recipient = null) { private function setShareAttributes(IShare $share, $formattedShareAttributes) { $newShareAttributes = $this->shareManager->newShare()->newAttributes(); foreach ($formattedShareAttributes as $formattedAttr) { - $value = isset($formattedAttr['value']) ? $formattedAttr['value'] : null; + $value = $formattedAttr['value'] ?? null; if (isset($formattedAttr['enabled'])) { - $value = (bool) \json_decode($formattedAttr['enabled']); + $value = (bool) \json_decode($formattedAttr['enabled'], null, 512, JSON_THROW_ON_ERROR); } if ($value !== null) { $newShareAttributes->setAttribute( diff --git a/apps/files_sharing/lib/Controller/ShareesController.php b/apps/files_sharing/lib/Controller/ShareesController.php index ecf6b9bfa22e..608c0029a4d0 100644 --- a/apps/files_sharing/lib/Controller/ShareesController.php +++ b/apps/files_sharing/lib/Controller/ShareesController.php @@ -312,9 +312,7 @@ protected function getGroups($search) { } $groups = $this->groupManager->search($search, $this->limit, $this->offset, 'sharing'); - $groupIds = \array_map(function (IGroup $group) { - return $group->getGID(); - }, $groups); + $groupIds = \array_map(fn (IGroup $group) => $group->getGID(), $groups); if (!$this->shareeEnumeration || \sizeof($groups) < $this->limit) { $this->reachedEndFor[] = 'groups'; @@ -324,9 +322,7 @@ protected function getGroups($search) { if (!empty($groups) && ($this->shareWithMembershipGroupOnly || $this->shareeEnumerationGroupMembers)) { // Intersect all the groups that match with the groups this user is a member of $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser(), 'sharing'); - $userGroups = \array_map(function (IGroup $group) { - return $group->getGID(); - }, $userGroups); + $userGroups = \array_map(fn (IGroup $group) => $group->getGID(), $userGroups); $groupIds = \array_intersect($groupIds, $userGroups); } @@ -435,7 +431,7 @@ protected function getRemote($search) { $lowerSearch = \strtolower($search); foreach ($cloudIds as $cloudId) { - list(, $serverUrl) = $this->splitUserRemote($cloudId); + [, $serverUrl] = $this->splitUserRemote($cloudId); if (\strtolower($cloudId) === $lowerSearch) { $foundRemoteById = true; diff --git a/apps/files_sharing/lib/Controllers/ExternalSharesController.php b/apps/files_sharing/lib/Controllers/ExternalSharesController.php index ccf6bc8221ac..70aa1ada0834 100644 --- a/apps/files_sharing/lib/Controllers/ExternalSharesController.php +++ b/apps/files_sharing/lib/Controllers/ExternalSharesController.php @@ -40,19 +40,13 @@ * @package OCA\Files_Sharing\Controllers */ class ExternalSharesController extends Controller { - /** @var \OCA\Files_Sharing\External\Manager */ - private $externalManager; + private \OCA\Files_Sharing\External\Manager $externalManager; /** @var \OCA\Files_Sharing\External\Manager */ private $groupExternalManager = null; - /** @var IClientService */ - private $clientService; - /** - * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface - */ - private $dispatcher; + private \OCP\Http\Client\IClientService $clientService; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher; - /** @var IConfig $config */ - private $config; + private \OCP\IConfig $config; public const group_share_type = "group"; /** @@ -191,7 +185,7 @@ protected function testUrl($remote, $checkVersion = false) { 'timeout' => 3, 'connect_timeout' => 3, ] - )->getBody()); + )->getBody(), null, 512, JSON_THROW_ON_ERROR); if ($checkVersion) { return !empty($response->version) && \version_compare($response->version, '7.0.0', '>='); diff --git a/apps/files_sharing/lib/Controllers/ShareController.php b/apps/files_sharing/lib/Controllers/ShareController.php index b2c1146fc627..2d2bdc6274ea 100644 --- a/apps/files_sharing/lib/Controllers/ShareController.php +++ b/apps/files_sharing/lib/Controllers/ShareController.php @@ -238,7 +238,7 @@ protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = $exception = $e; } } - \OC_Hook::emit('OCP\Share', 'share_link_access', [ + \OC_Hook::emit(\OCP\Share::class, 'share_link_access', [ 'itemType' => $itemType, 'itemSource' => $itemSource, 'uidOwner' => $uidOwner, @@ -533,7 +533,7 @@ public function downloadShare($token, $files = null, $path = '', $downloadStartS && !isset($downloadStartSecret[32]) && \preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) { // FIXME: set on the response once we use an actual app framework response - \setcookie('ocDownloadStarted', $downloadStartSecret, \time() + 20, '/'); + \setcookie('ocDownloadStarted', $downloadStartSecret, ['expires' => \time() + 20, 'path' => '/']); } $this->emitAccessShareHook($share); diff --git a/apps/files_sharing/lib/ExpireSharesJob.php b/apps/files_sharing/lib/ExpireSharesJob.php index 41b5c25889d9..3c6637735d47 100644 --- a/apps/files_sharing/lib/ExpireSharesJob.php +++ b/apps/files_sharing/lib/ExpireSharesJob.php @@ -34,25 +34,13 @@ * Delete all shares that are expired */ class ExpireSharesJob extends TimedJob { - /** - * @var IManager $shareManager - */ - private $shareManager; + private \OCP\Share\IManager $shareManager; - /** - * @var IDBConnection $connection - */ - private $connection; + private \OCP\IDBConnection $connection; - /** - * @var DefaultShareProvider $defaultShareProvider - */ - private $defaultShareProvider; + private \OC\Share20\DefaultShareProvider $defaultShareProvider; - /** - * @var ActivityIManager $activityManager - */ - private $activityManager; + private \OCP\Activity\IManager $activityManager; /** * sets the correct interval for this timed job diff --git a/apps/files_sharing/lib/External/Cache.php b/apps/files_sharing/lib/External/Cache.php index 3c6ed9ef7e65..7144d6bc1a03 100644 --- a/apps/files_sharing/lib/External/Cache.php +++ b/apps/files_sharing/lib/External/Cache.php @@ -24,7 +24,7 @@ namespace OCA\Files_Sharing\External; class Cache extends \OC\Files\Cache\Cache { - private $remote; + private string $remote; private $remoteUser; private $storage; @@ -35,7 +35,7 @@ class Cache extends \OC\Files\Cache\Cache { */ public function __construct($storage, $remote, $remoteUser) { $this->storage = $storage; - list(, $remote) = \explode('://', $remote, 2); + [, $remote] = \explode('://', $remote, 2); $this->remote = $remote; $this->remoteUser = $remoteUser; parent::__construct($storage); diff --git a/apps/files_sharing/lib/External/Manager.php b/apps/files_sharing/lib/External/Manager.php index d49b1aab0bee..bb6c508f51de 100644 --- a/apps/files_sharing/lib/External/Manager.php +++ b/apps/files_sharing/lib/External/Manager.php @@ -48,30 +48,15 @@ class Manager { */ private $uid; - /** - * @var \OCP\IDBConnection - */ - private $connection; + private \OCP\IDBConnection $connection; - /** - * @var \OC\Files\Mount\Manager - */ - private $mountManager; + private \OC\Files\Mount\Manager $mountManager; - /** - * @var \OCP\Files\Storage\IStorageFactory - */ - private $storageLoader; + private \OCP\Files\Storage\IStorageFactory $storageLoader; - /** - * @var IManager - */ - private $notificationManager; + private \OCP\Notification\IManager $notificationManager; - /** - * @var EventDispatcherInterface - */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher; /** * @param \OCP\IDBConnection $connection @@ -111,7 +96,7 @@ public function __construct( * @return Mount|null */ public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) { - $user = $user ? $user : $this->uid; + $user = $user ?: $this->uid; $accepted = $accepted ? 1 : 0; $name = Filesystem::normalizePath('/' . $name); @@ -272,7 +257,7 @@ public function acceptShare($id) { ] ); $this->eventDispatcher->dispatch($event, 'remoteshare.accepted'); - \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $share['remote']]); + \OC_Hook::emit(\OCP\Share::class, 'federated_share_added', ['server' => $share['remote']]); $this->processNotification($id); return true; diff --git a/apps/files_sharing/lib/External/MountProvider.php b/apps/files_sharing/lib/External/MountProvider.php index 949dc45d6feb..81074c4c5bfb 100644 --- a/apps/files_sharing/lib/External/MountProvider.php +++ b/apps/files_sharing/lib/External/MountProvider.php @@ -29,10 +29,7 @@ class MountProvider implements IMountProvider { public const STORAGE = '\OCA\Files_Sharing\External\Storage'; - /** - * @var \OCP\IDBConnection - */ - private $connection; + private \OCP\IDBConnection $connection; /** * @var callable diff --git a/apps/files_sharing/lib/External/ScanExternalSharesJob.php b/apps/files_sharing/lib/External/ScanExternalSharesJob.php index 2df95335409a..8af4014c4c0b 100644 --- a/apps/files_sharing/lib/External/ScanExternalSharesJob.php +++ b/apps/files_sharing/lib/External/ScanExternalSharesJob.php @@ -49,8 +49,7 @@ class ScanExternalSharesJob extends TimedJob { /** @var IDBConnection */ private $connection; - /** @var Manager */ - private $externalManager; + private ?\OCA\Files_Sharing\External\Manager $externalManager = null; /** @var IConfig */ private $config; /** @var IUserManager */ diff --git a/apps/files_sharing/lib/External/Storage.php b/apps/files_sharing/lib/External/Storage.php index ebeb93233081..e94a2ceac9db 100644 --- a/apps/files_sharing/lib/External/Storage.php +++ b/apps/files_sharing/lib/External/Storage.php @@ -56,8 +56,7 @@ class Storage extends DAV implements ISharedStorage { private $config; /** @var \OCP\ICertificateManager */ private $certificateManager; - /** @var bool */ - private $updateChecked = false; + private bool $updateChecked = false; /** * @var \OCA\Files_Sharing\External\Manager @@ -73,9 +72,9 @@ public function __construct($options) { $this->certificateManager = $options['certificateManager']; $this->remote = $options['remote']; $this->remoteUser = $options['owner']; - list($protocol, $remote) = \explode('://', $this->remote); + [$protocol, $remote] = \explode('://', $this->remote); if (\strpos($remote, '/')) { - list($host, $root) = \explode('/', $remote, 2); + [$host, $root] = \explode('/', $remote, 2); } else { $host = $remote; $root = ''; @@ -350,11 +349,9 @@ private function testRemoteUrl($url) { 'timeout' => 10, 'connect_timeout' => 10, ])->getBody(); - $data = \json_decode($result); + $data = \json_decode($result, null, 512, JSON_THROW_ON_ERROR); $returnValue = (\is_object($data) && !empty($data->version)); - } catch (ConnectException $e) { - $returnValue = false; - } catch (ClientException $e) { + } catch (ConnectException|ClientException $e) { $returnValue = false; } @@ -363,7 +360,7 @@ private function testRemoteUrl($url) { } public function getOwner($path) { - list(, $remote) = \explode('://', $this->remote, 2); + [, $remote] = \explode('://', $this->remote, 2); return $this->remoteUser . '@' . $remote; } diff --git a/apps/files_sharing/lib/Helper.php b/apps/files_sharing/lib/Helper.php index a770ba239be2..537b782f3748 100644 --- a/apps/files_sharing/lib/Helper.php +++ b/apps/files_sharing/lib/Helper.php @@ -38,12 +38,12 @@ class Helper { public static function registerHooks() { - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook'); - \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren'); + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\\' . \OCA\Files_Sharing\Updater::class, 'renameHook'); + \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\\' . \OCA\Files_Sharing\Hooks::class, 'unshareChildren'); - \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser'); + \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\\' . \OCA\Files_Sharing\Hooks::class, 'deleteUser'); - \OCP\Util::connectHook('\OCP\Config', 'js', '\OCA\Files_Sharing\Hooks', 'extendJsConfig'); + \OCP\Util::connectHook('\OCP\Config', 'js', '\\' . \OCA\Files_Sharing\Hooks::class, 'extendJsConfig'); } /** diff --git a/apps/files_sharing/lib/Hooks.php b/apps/files_sharing/lib/Hooks.php index e2ae171b034b..f694ce6d926a 100644 --- a/apps/files_sharing/lib/Hooks.php +++ b/apps/files_sharing/lib/Hooks.php @@ -36,45 +36,24 @@ use OCP\Activity\IManager as ActivityManager; class Hooks { - /** - * @var IURLGenerator - */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; - /** - * @var IRootFolder - */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; /** * @var IUserSession|null */ private $userSession; - /** - * @var EventDispatcher - */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; - /** - * @var \OCP\Share\IManager - */ - private $shareManager; + private \OCP\Share\IManager $shareManager; - /** - * @var NotificationPublisher - */ - private $notificationPublisher; + private \OCA\Files_Sharing\Service\NotificationPublisher $notificationPublisher; - /** - * @var SharingAllowlist - */ - private $sharingAllowlist; + private \OCA\Files_Sharing\SharingAllowlist $sharingAllowlist; - /** - * @var ActivityManager - */ - private $activityManager; + private \OCP\Activity\IManager $activityManager; /** * Hooks constructor. @@ -129,7 +108,7 @@ public static function unshareChildren($params) { $mountManager = \OC\Files\Filesystem::getMountManager(); $mountedShares = $mountManager->findIn($path); foreach ($mountedShares as $mount) { - if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) { + if ($mount->getStorage()->instanceOfStorage(\OCA\Files_Sharing\ISharedStorage::class)) { $mountPoint = $mount->getMountPoint(); $view->unlink($mountPoint); } @@ -252,9 +231,7 @@ private function getCurrentUserUid() { } private function filterSharesByFileId($shares, $fileId) { - return \array_filter($shares, function (IShare $share) use ($fileId) { - return \strval($share->getNodeId()) === \strval($fileId); - }); + return \array_filter($shares, fn (IShare $share) => \strval($share->getNodeId()) === \strval($fileId)); } /** diff --git a/apps/files_sharing/lib/Migration.php b/apps/files_sharing/lib/Migration.php index 1550b4a01f34..d2c0b5fbd8fa 100644 --- a/apps/files_sharing/lib/Migration.php +++ b/apps/files_sharing/lib/Migration.php @@ -34,14 +34,12 @@ * @group DB */ class Migration { - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; /** @var array with all shares we already saw */ private $shareCache; - /** @var string */ - private $table = 'share'; + private string $table = 'share'; public function __construct(IDBConnection $connection) { $this->connection = $connection; diff --git a/apps/files_sharing/lib/MountProvider.php b/apps/files_sharing/lib/MountProvider.php index 57e5d258399d..f5124223a1c4 100644 --- a/apps/files_sharing/lib/MountProvider.php +++ b/apps/files_sharing/lib/MountProvider.php @@ -71,11 +71,9 @@ public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) { $shares = $this->shareManager->getAllSharedWith($user->getUID(), $requiredShareTypes, null); // filter out excluded shares and group shares that includes self - $shares = \array_filter($shares, function (\OCP\Share\IShare $share) use ($user) { - return $share->getPermissions() > 0 + $shares = \array_filter($shares, fn (\OCP\Share\IShare $share) => $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID() - && $share->getState() === \OCP\Share::STATE_ACCEPTED; - }); + && $share->getState() === \OCP\Share::STATE_ACCEPTED); $superShares = $this->buildSuperShares($shares, $user); @@ -83,7 +81,7 @@ public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) { foreach ($superShares as $share) { try { $shareMount = new SharedMount( - '\OCA\Files_Sharing\SharedStorage', + '\\' . \OCA\Files_Sharing\SharedStorage::class, $mounts, [ 'user' => $user->getUID(), diff --git a/apps/files_sharing/lib/Panels/Admin/SettingsPanel.php b/apps/files_sharing/lib/Panels/Admin/SettingsPanel.php index 94e1d3702808..1ae08ff8d140 100644 --- a/apps/files_sharing/lib/Panels/Admin/SettingsPanel.php +++ b/apps/files_sharing/lib/Panels/Admin/SettingsPanel.php @@ -25,11 +25,9 @@ use OCA\Files_Sharing\SharingAllowlist; class SettingsPanel implements ISettings { - /** @var SharingBlacklist */ - private $sharingBlacklist; + private \OCA\Files_Sharing\SharingBlacklist $sharingBlacklist; - /** @var SharingAllowlist */ - private $sharingAllowlist; + private \OCA\Files_Sharing\SharingAllowlist $sharingAllowlist; public function __construct(SharingBlacklist $sharingBlacklist, SharingAllowlist $sharingAllowlist) { $this->sharingBlacklist = $sharingBlacklist; diff --git a/apps/files_sharing/lib/Panels/Personal/PersonalPanel.php b/apps/files_sharing/lib/Panels/Personal/PersonalPanel.php index 1bce47b28e59..5d22d5c7220d 100644 --- a/apps/files_sharing/lib/Panels/Personal/PersonalPanel.php +++ b/apps/files_sharing/lib/Panels/Personal/PersonalPanel.php @@ -42,14 +42,11 @@ class PersonalPanel implements ISettings { public const GLOBAL_CONFIG_PREFIX = 'shareapi_'; - /** @var IConfig $config */ - private $config; + private \OCP\IConfig $config; - /** @var IUserSession $userSession */ - private $userSession; + private \OCP\IUserSession $userSession; - /** @var IL10N */ - private $l10n; + private \OCP\IL10N $l10n; public function __construct(IConfig $config, IUserSession $userSession, IL10N $l10n) { $this->config = $config; diff --git a/apps/files_sharing/lib/Scanner.php b/apps/files_sharing/lib/Scanner.php index fc5f3910ce0e..2a73ac6bbfb3 100644 --- a/apps/files_sharing/lib/Scanner.php +++ b/apps/files_sharing/lib/Scanner.php @@ -47,7 +47,7 @@ public function getData($path) { return null; } '@phan-var \OC\Files\Storage\Storage $this->storage'; - list($sourceStorage, $internalPath) = $this->storage->resolvePath($path); + [$sourceStorage, $internalPath] = $this->storage->resolvePath($path); $data['permissions'] = $sourceStorage->getPermissions($internalPath); return $data; } @@ -56,10 +56,10 @@ private function getSourceScanner() { if ($this->sourceScanner) { return $this->sourceScanner; } - if ($this->storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) { + if ($this->storage->instanceOfStorage('\\' . \OCA\Files_Sharing\SharedStorage::class)) { /** @var \OC\Files\Storage\Storage $storage */ '@phan-var \OC\Files\Storage\Storage $this->storage'; - list($storage) = $this->storage->resolvePath(''); + [$storage] = $this->storage->resolvePath(''); $this->sourceScanner = $storage->getScanner(); return $this->sourceScanner; } else { @@ -76,7 +76,7 @@ public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $loc $sourceScanner = $this->getSourceScanner(); if ($sourceScanner instanceof NoopScanner) { '@phan-var \OC\Files\Storage\Storage $this->storage'; - list(, $internalPath) = $this->storage->resolvePath($path); + [, $internalPath] = $this->storage->resolvePath($path); return $sourceScanner->scan($internalPath, $recursive, $reuse, $lock); } else { return parent::scan($path, $recursive, $reuse, $lock); @@ -92,7 +92,7 @@ public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = $sourceScanner = $this->getSourceScanner(); if ($sourceScanner instanceof NoopScanner) { '@phan-var \OC\Files\Storage\Storage $this->storage'; - list(, $internalPath) = $this->storage->resolvePath($file); + [, $internalPath] = $this->storage->resolvePath($file); return parent::scan($internalPath, self::SCAN_SHALLOW, $reuseExisting, $lock); } else { return parent::scanFile($file, $reuseExisting, $parentId, $cacheData, $lock); diff --git a/apps/files_sharing/lib/Service/NotificationPublisher.php b/apps/files_sharing/lib/Service/NotificationPublisher.php index 9bdaf09aa348..9ed670e601ce 100644 --- a/apps/files_sharing/lib/Service/NotificationPublisher.php +++ b/apps/files_sharing/lib/Service/NotificationPublisher.php @@ -26,14 +26,10 @@ use OCP\Share\IShare; class NotificationPublisher { - /** @var \OCP\Notification\IManager */ - private $notificationManager; - /** @var IGroupManager */ - private $groupManager; - /** @var IUserManager */ - private $userManager; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\Notification\IManager $notificationManager; + private \OCP\IGroupManager $groupManager; + private \OCP\IUserManager $userManager; + private \OCP\IURLGenerator $urlGenerator; public function __construct( \OCP\Notification\IManager $notificationManager, diff --git a/apps/files_sharing/lib/ShareBackend/Folder.php b/apps/files_sharing/lib/ShareBackend/Folder.php index 315a8912837e..9493fd8028aa 100644 --- a/apps/files_sharing/lib/ShareBackend/Folder.php +++ b/apps/files_sharing/lib/ShareBackend/Folder.php @@ -50,8 +50,8 @@ public function getParents($itemSource, $shareWith = null, $owner = null) { $share['file_path'] = $name; $displayNameOwner = \OCP\User::getDisplayName($share['uid_owner']); $displayNameShareWith = \OCP\User::getDisplayName($share['share_with']); - $share['displayname_owner'] = ($displayNameOwner) ? $displayNameOwner : $share['uid_owner']; - $share['share_with_displayname'] = ($displayNameShareWith) ? $displayNameShareWith : $share['uid_owner']; + $share['displayname_owner'] = $displayNameOwner ?: $share['uid_owner']; + $share['share_with_displayname'] = $displayNameShareWith ?: $share['uid_owner']; $result[] = $share; } diff --git a/apps/files_sharing/lib/SharedMount.php b/apps/files_sharing/lib/SharedMount.php index d5b017126b7e..642a3524d793 100644 --- a/apps/files_sharing/lib/SharedMount.php +++ b/apps/files_sharing/lib/SharedMount.php @@ -40,10 +40,7 @@ class SharedMount extends MountPoint implements MoveableMount { */ protected $storage = null; - /** - * @var \OC\Files\View - */ - private $recipientView; + private \OC\Files\View $recipientView; /** * @var string @@ -190,7 +187,7 @@ public function isTargetAllowed($target) { // note: $currentMount has a trailing slash. It doesn't matter for the check below $isRename = \dirname($currentMount) === \dirname($target); - list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target); + [$targetStorage, $targetInternalPath] = \OC\Files\Filesystem::resolvePath($target); // note: cannot use the view because the target is already locked $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath); if ($isRename) { diff --git a/apps/files_sharing/lib/SharedPropagator.php b/apps/files_sharing/lib/SharedPropagator.php index 448b1b7d8e3a..99af3ba1ee09 100644 --- a/apps/files_sharing/lib/SharedPropagator.php +++ b/apps/files_sharing/lib/SharedPropagator.php @@ -38,7 +38,7 @@ class SharedPropagator extends Propagator { */ public function propagateChange($internalPath, $time, $sizeDifference = 0) { /** @var \OC\Files\Storage\Storage $storage */ - list($storage, $sourceInternalPath) = $this->storage->resolvePath($internalPath); + [$storage, $sourceInternalPath] = $this->storage->resolvePath($internalPath); return $storage->getPropagator()->propagateChange($sourceInternalPath, $time, $sizeDifference); } } diff --git a/apps/files_sharing/lib/SharedStorage.php b/apps/files_sharing/lib/SharedStorage.php index b8cb951c7102..38cbc580d7e6 100644 --- a/apps/files_sharing/lib/SharedStorage.php +++ b/apps/files_sharing/lib/SharedStorage.php @@ -58,17 +58,14 @@ class SharedStorage extends \OC\Files\Storage\Wrapper\Jail implements ISharedSto */ private $ownerView; - private $initialized = false; + private bool $initialized = false; /** * @var ICacheEntry */ private $sourceRootInfo; - /** - * @var IStorage - */ - private $sourceStorage; + private ?\OC\Files\Storage\FailedStorage $sourceStorage = null; /** @var string */ private $user; @@ -101,7 +98,7 @@ private function init() { try { Filesystem::initMountPoints($this->superShare->getShareOwner()); $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId(), false); - list($this->sourceStorage, $sourceInternalPath) = $this->ownerView->resolvePath($sourcePath); + [$this->sourceStorage, $sourceInternalPath] = $this->ownerView->resolvePath($sourcePath); $this->sourceRootInfo = $this->sourceStorage->getCache()->get($sourceInternalPath); // adjust jail $this->rootPath = $sourceInternalPath; @@ -123,7 +120,7 @@ private function init() { * @inheritdoc */ public function instanceOfStorage($class) { - if (\in_array($class, ['\OC\Files\Storage\Home', '\OC\Files\ObjectStore\HomeObjectStoreStorage'])) { + if (\in_array($class, ['\\' . \OC\Files\Storage\Home::class, '\\' . \OC\Files\ObjectStore\HomeObjectStoreStorage::class])) { return false; } return parent::instanceOfStorage($class); @@ -184,7 +181,7 @@ public function isReadable($path) { if (!$this->file_exists($path)) { return false; } - list($storage, $internalPath) = $this->resolvePath($path); + [$storage, $internalPath] = $this->resolvePath($path); return $storage->isReadable($internalPath); } @@ -375,7 +372,7 @@ public function unshareStorage() { */ public function acquireLock($path, $type, ILockingProvider $provider) { /** @var \OCP\Files\Storage $targetStorage */ - list($targetStorage, $targetInternalPath) = $this->resolvePath($path); + [$targetStorage, $targetInternalPath] = $this->resolvePath($path); $targetStorage->acquireLock($targetInternalPath, $type, $provider); // lock the parent folders of the owner when locking the share as recipient if ($path === '') { @@ -391,7 +388,7 @@ public function acquireLock($path, $type, ILockingProvider $provider) { */ public function releaseLock($path, $type, ILockingProvider $provider) { /** @var \OCP\Files\Storage $targetStorage */ - list($targetStorage, $targetInternalPath) = $this->resolvePath($path); + [$targetStorage, $targetInternalPath] = $this->resolvePath($path); $targetStorage->releaseLock($targetInternalPath, $type, $provider); // unlock the parent folders of the owner when unlocking the share as recipient if ($path === '') { @@ -407,7 +404,7 @@ public function releaseLock($path, $type, ILockingProvider $provider) { */ public function changeLock($path, $type, ILockingProvider $provider) { /** @var \OCP\Files\Storage $targetStorage */ - list($targetStorage, $targetInternalPath) = $this->resolvePath($path); + [$targetStorage, $targetInternalPath] = $this->resolvePath($path); $targetStorage->changeLock($targetInternalPath, $type, $provider); } diff --git a/apps/files_sharing/lib/SharingAllowlist.php b/apps/files_sharing/lib/SharingAllowlist.php index 9bcc96726e24..da96cb423c07 100644 --- a/apps/files_sharing/lib/SharingAllowlist.php +++ b/apps/files_sharing/lib/SharingAllowlist.php @@ -35,11 +35,9 @@ * This class won't prevent the sharing action by itself. */ class SharingAllowlist { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var IGroupManager */ - private $groupManager; + private \OCP\IGroupManager $groupManager; public function __construct(IConfig $config, IGroupManager $groupManager) { $this->config = $config; @@ -69,7 +67,7 @@ public function isGroupInPublicShareSharersAllowlist(IGroup $group) { * @param string[] $ids a list with the ids of the groups in allowlist */ public function setPublicShareSharersGroupsAllowlist(array $ids) { - $this->config->setAppValue('files_sharing', 'public_share_sharers_groups_allowlist', \json_encode($ids)); + $this->config->setAppValue('files_sharing', 'public_share_sharers_groups_allowlist', \json_encode($ids, JSON_THROW_ON_ERROR)); } /** @@ -118,7 +116,7 @@ public function isUserInPublicShareSharersGroupsAllowlist(IUser $user) { */ private function fetchPublicShareSharersGroupsAllowlist() { $configuredAllowlist = $this->config->getAppValue('files_sharing', 'public_share_sharers_groups_allowlist', '[]'); - $parsedValues = json_decode($configuredAllowlist, true); - return $parsedValues === null ? [] : $parsedValues; + $parsedValues = json_decode($configuredAllowlist, true, 512, JSON_THROW_ON_ERROR); + return $parsedValues ?? []; } } diff --git a/apps/files_sharing/lib/SharingBlacklist.php b/apps/files_sharing/lib/SharingBlacklist.php index c8716a3479a8..ad142d07c47c 100644 --- a/apps/files_sharing/lib/SharingBlacklist.php +++ b/apps/files_sharing/lib/SharingBlacklist.php @@ -32,10 +32,9 @@ * This class won't prevent the sharing action by itself. */ class SharingBlacklist { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - private $blacklistCache = null; + private ?array $blacklistCache = null; public function __construct(IConfig $config) { $this->config = $config; @@ -65,7 +64,7 @@ public function clearCache() { * @param string[] $ids a list with the ids of the groups to be blacklisted */ public function setBlacklistedReceiverGroups(array $ids) { - $this->config->setAppValue('files_sharing', 'blacklisted_receiver_groups', \json_encode($ids)); + $this->config->setAppValue('files_sharing', 'blacklisted_receiver_groups', \json_encode($ids, JSON_THROW_ON_ERROR)); $this->blacklistCache = null; // clear the cache } @@ -96,7 +95,7 @@ private function initCache() { */ private function fetchBlacklistedReceiverGroupIds() { $configuredBlacklist = $this->config->getAppValue('files_sharing', 'blacklisted_receiver_groups', '[]'); - $decodedGroups = \json_decode($configuredBlacklist, true); + $decodedGroups = \json_decode($configuredBlacklist, true, 512, JSON_THROW_ON_ERROR); if (!\is_array($decodedGroups)) { $decodedGroups = []; diff --git a/apps/files_sharing/lib/Updater.php b/apps/files_sharing/lib/Updater.php index b791471a0f29..530f6eabbc9f 100644 --- a/apps/files_sharing/lib/Updater.php +++ b/apps/files_sharing/lib/Updater.php @@ -99,7 +99,7 @@ private static function renameChildren($oldPath, $newPath) { $mountManager = \OC\Files\Filesystem::getMountManager(); $mountedShares = $mountManager->findIn('/' . \OCP\User::getUser() . '/files/' . $oldPath); foreach ($mountedShares as $mount) { - if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) { + if ($mount->getStorage()->instanceOfStorage(\OCA\Files_Sharing\ISharedStorage::class)) { $mountPoint = $mount->getMountPoint(); $target = \str_replace($absOldPath, $absNewPath, $mountPoint); '@phan-var \OCA\Files_Sharing\SharedMount $mount'; diff --git a/apps/files_sharing/lib/ViewOnly.php b/apps/files_sharing/lib/ViewOnly.php index 0c8bd4b29f9c..0d0d78b7de34 100644 --- a/apps/files_sharing/lib/ViewOnly.php +++ b/apps/files_sharing/lib/ViewOnly.php @@ -30,8 +30,7 @@ * Handles restricting for download of files */ class ViewOnly { - /** @var Folder */ - private $userFolder; + private \OCP\Files\Folder $userFolder; public function __construct(Folder $userFolder) { $this->userFolder = $userFolder; diff --git a/apps/files_sharing/public.php b/apps/files_sharing/public.php index 8c74ce4bb62b..6c4086433ba3 100644 --- a/apps/files_sharing/public.php +++ b/apps/files_sharing/public.php @@ -24,7 +24,7 @@ // This file is just used to redirect the legacy sharing URLs (< ownCloud 8) to the new ones $urlGenerator = \OC::$server->getURLGenerator(); -$token = isset($_GET['t']) ? $_GET['t'] : ''; +$token = $_GET['t'] ?? ''; $route = isset($_GET['download']) ? 'files_sharing.sharecontroller.downloadShare' : 'files_sharing.sharecontroller.showShare'; if ($token !== '') { diff --git a/apps/files_sharing/tests/API/ShareesTest.php b/apps/files_sharing/tests/API/ShareesTest.php index a131131b861d..e0363db0f319 100644 --- a/apps/files_sharing/tests/API/ShareesTest.php +++ b/apps/files_sharing/tests/API/ShareesTest.php @@ -1128,9 +1128,7 @@ public function testGetGroups( ->with($searchTerm, self::invokePrivate($this->sharees, 'limit'), self::invokePrivate($this->sharees, 'offset')) ->willReturn($groupResponse); - $getGroupValueMap = \array_map(function ($group) { - return [$group->getGID(), $group]; - }, $groupResponse); + $getGroupValueMap = \array_map(fn ($group) => [$group->getGID(), $group], $groupResponse); $this->groupManager->method('get') ->will($this->returnValueMap($getGroupValueMap)); @@ -1151,9 +1149,7 @@ public function testGetGroups( // don't care about the particular implementation of the method // just mark the group as blacklisted based on the displayname $this->sharingBlacklist->method('isGroupBlacklisted') - ->will($this->returnCallback(function (IGroup $group) use ($blacklistedGroupNames) { - return \in_array($group->getDisplayName(), $blacklistedGroupNames, true); - })); + ->will($this->returnCallback(fn (IGroup $group) => \in_array($group->getDisplayName(), $blacklistedGroupNames, true))); } self::invokePrivate($this->sharees, 'getGroups', [$searchTerm]); @@ -1568,9 +1564,7 @@ public function testGetRemoteCustom() { $mockedRemoteClass = \get_class($this->customRemoteSearchMock); // need to register the mock as service. It will be removed in the tearDown - \OC::$server->registerService($mockedRemoteClass, function () { - return $this->customRemoteSearchMock; - }); + \OC::$server->registerService($mockedRemoteClass, fn () => $this->customRemoteSearchMock); $this->config->method('getSystemValue') ->with('sharing.remoteShareesSearch') @@ -1715,14 +1709,14 @@ public function testSearchInvalid($message, $search = '', $itemType = null, $pag $sharees = $this->getMockBuilder(ShareesController::class) ->setConstructorArgs([ 'files_sharing', - $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(), + $this->getMockBuilder(\OCP\IRequest::class)->disableOriginalConstructor()->getMock(), $this->groupManager, $this->userManager, $this->contactsManager, $this->config, $this->session, - $this->getMockBuilder('OCP\IURLGenerator')->disableOriginalConstructor()->getMock(), - $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(), + $this->getMockBuilder(\OCP\IURLGenerator::class)->disableOriginalConstructor()->getMock(), + $this->getMockBuilder(\OCP\ILogger::class)->disableOriginalConstructor()->getMock(), $this->shareManager, $this->sharingBlacklist, $this->userSearch @@ -1997,7 +1991,7 @@ protected function assertOCSError(array $ocs, $message) { * @param string $expectedUrl */ public function testSplitUserRemote($remote, $expectedUser, $expectedUrl) { - list($remoteUser, $remoteUrl) = $this->sharees->splitUserRemote($remote); + [$remoteUser, $remoteUrl] = $this->sharees->splitUserRemote($remote); $this->assertSame($expectedUser, $remoteUser); $this->assertSame($expectedUrl, $remoteUrl); } diff --git a/apps/files_sharing/tests/ActivityTest.php b/apps/files_sharing/tests/ActivityTest.php index de3b096b7b5b..fad86b03e46f 100644 --- a/apps/files_sharing/tests/ActivityTest.php +++ b/apps/files_sharing/tests/ActivityTest.php @@ -34,21 +34,18 @@ * @package OCA\Files_Sharing\Tests */ class ActivityTest extends TestCase { - /** - * @var Activity - */ - private $activity; + private \OCA\Files_Sharing\Activity $activity; protected function setUp(): void { parent::setUp(); $this->activity = new Activity( - $this->getMockBuilder('OCP\L10N\IFactory') + $this->getMockBuilder(\OCP\L10N\IFactory::class) ->disableOriginalConstructor() ->getMock(), - $this->getMockBuilder('OCP\IURLGenerator') + $this->getMockBuilder(\OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(), - $this->getMockBuilder('OCP\Activity\IManager') + $this->getMockBuilder(\OCP\Activity\IManager::class) ->disableOriginalConstructor() ->getMock() ); diff --git a/apps/files_sharing/tests/ApiTest.php b/apps/files_sharing/tests/ApiTest.php index 79151b05c3e6..bda7c04f013a 100644 --- a/apps/files_sharing/tests/ApiTest.php +++ b/apps/files_sharing/tests/ApiTest.php @@ -46,13 +46,12 @@ class ApiTest extends TestCase { public const TEST_FOLDER_NAME = '/folder_share_api_test'; - private static $tempStorage; + private static ?\OC\Files\Storage\Temporary $tempStorage = null; /** @var \OCP\Files\Folder */ private $userFolder; - /** @var string */ - private $subsubfolder; + private string $subsubfolder; protected function setUp(): void { parent::setUp(); @@ -95,12 +94,7 @@ protected function tearDown(): void { private function createRequest(array $data) { $request = $this->createMock(IRequest::class); $request->method('getParam') - ->will($this->returnCallback(function ($param, $default = null) use ($data) { - if (isset($data[$param])) { - return $data[$param]; - } - return $default; - })); + ->will($this->returnCallback(fn ($param, $default = null) => $data[$param] ?? $default)); return $request; } @@ -121,9 +115,7 @@ private function createOCS($request, $userId) { $l = $this->createMock(IL10N::class); $l->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); return new \OCA\Files_Sharing\Controller\Share20OcsController( 'files_sharing', @@ -1350,7 +1342,7 @@ public function testShareStorageMountPoint() { // needed because the sharing code sometimes switches the user internally and mounts the user's // storages. In our case the temp storage isn't mounted automatically, so doing it in the post hook // (similar to how ext storage works) - \OCP\Util::connectHook('OC_Filesystem', 'post_initMountPoints', '\OCA\Files_Sharing\Tests\ApiTest', 'initTestMountPointsHook'); + \OCP\Util::connectHook('OC_Filesystem', 'post_initMountPoints', '\\' . \OCA\Files_Sharing\Tests\ApiTest::class, 'initTestMountPointsHook'); // logging in will auto-mount the temp storage for user1 as well self::loginHelper(self::TEST_FILES_SHARING_API_USER1); @@ -1376,7 +1368,7 @@ public function testShareStorageMountPoint() { $this->shareManager->deleteShare($share); - \OC_Hook::clear('OC_Filesystem', 'post_initMountPoints', '\OCA\Files_Sharing\Tests\ApiTest', 'initTestMountPointsHook'); + \OC_Hook::clear('OC_Filesystem', 'post_initMountPoints'); } /** */ diff --git a/apps/files_sharing/tests/CacheTest.php b/apps/files_sharing/tests/CacheTest.php index d74e6bab6843..81bce45c707e 100644 --- a/apps/files_sharing/tests/CacheTest.php +++ b/apps/files_sharing/tests/CacheTest.php @@ -88,7 +88,7 @@ protected function setUp(): void { $this->view->file_put_contents('container/shareddir/subdir/another too.txt', $textData); $this->view->file_put_contents('container/shareddir/subdir/not a text file.xml', ''); - list($this->ownerStorage, ) = $this->view->resolvePath(''); + [$this->ownerStorage, ] = $this->view->resolvePath(''); $this->ownerCache = $this->ownerStorage->getCache(); $this->ownerStorage->getScanner()->scan(''); @@ -118,7 +118,7 @@ protected function setUp(): void { // retrieve the shared storage $secondView = new View('/' . self::TEST_FILES_SHARING_API_USER2); - list($this->sharedStorage, ) = $secondView->resolvePath('files/shareddir'); + [$this->sharedStorage, ] = $secondView->resolvePath('files/shareddir'); $this->sharedCache = $this->sharedStorage->getCache(); } @@ -207,7 +207,7 @@ public function searchDataProvider() { */ public function testSearch() { foreach ($this->searchDataProvider() as $data) { - list($pattern, $expectedFiles) = $data; + [$pattern, $expectedFiles] = $data; $results = $this->sharedStorage->getCache()->search($pattern); @@ -442,10 +442,9 @@ private function verifyFiles($examples, $results) { $this->assertCount( \count($examples), $results, - 'Files found: ' . \implode(', ', \array_map(function ($f) { - /** @var FileInfo | ICacheEntry $f */ - return $f->getPath(); - }, $results)) + 'Files found: ' . \implode(', ', \array_map(fn ($f) => + /** @var FileInfo | ICacheEntry $f */ + $f->getPath(), $results)) ); foreach ($examples as $example) { @@ -490,7 +489,7 @@ public function testGetPathByIdDirectShare() { self::loginHelper(self::TEST_FILES_SHARING_API_USER2); $this->assertTrue(\OC\Files\Filesystem::file_exists('/test.txt')); - list($sharedStorage) = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test.txt'); + [$sharedStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test.txt'); /** * @var \OCA\Files_Sharing\SharedStorage $sharedStorage */ @@ -520,7 +519,7 @@ public function testGetPathByIdShareSubFolder() { self::loginHelper(self::TEST_FILES_SHARING_API_USER2); $this->assertTrue(\OC\Files\Filesystem::file_exists('/foo')); - list($sharedStorage) = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo'); + [$sharedStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo'); /** * @var \OCA\Files_Sharing\SharedStorage $sharedStorage */ @@ -545,11 +544,11 @@ public function testNumericStorageId() { $this->shareManager->createShare($share); \OC_Util::tearDownFS(); - list($sourceStorage) = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/foo'); + [$sourceStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/foo'); self::loginHelper(self::TEST_FILES_SHARING_API_USER2); $this->assertTrue(\OC\Files\Filesystem::file_exists('/foo')); - list($sharedStorage) = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo'); + [$sharedStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo'); $this->assertEquals($sourceStorage->getCache()->getNumericStorageId(), $sharedStorage->getCache()->getNumericStorageId()); } diff --git a/apps/files_sharing/tests/CapabilitiesTest.php b/apps/files_sharing/tests/CapabilitiesTest.php index 241da53c023d..2670fd136d60 100644 --- a/apps/files_sharing/tests/CapabilitiesTest.php +++ b/apps/files_sharing/tests/CapabilitiesTest.php @@ -41,13 +41,13 @@ class CapabilitiesTest extends \Test\TestCase { protected $userSearch; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var IManager | \PHPUnit\Framework\MockObject\MockObject */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var SharingAllowlist | \PHPUnit\Framework\MockObject\MockObject */ - private $sharingAllowlist; + private \PHPUnit\Framework\MockObject\MockObject $sharingAllowlist; /** * @@ -94,7 +94,7 @@ private function getFilesSharingPart(array $data) { * @return string[] */ private function getResults(array $map) { - $stub = $this->getMockBuilder('\OCP\IConfig')->disableOriginalConstructor()->getMock(); + $stub = $this->getMockBuilder('\\' . \OCP\IConfig::class)->disableOriginalConstructor()->getMock(); $stub->method('getAppValue')->will($this->returnValueMap($map)); $cap = new Capabilities($this->shareManager, $stub, $this->userSearch, $this->l10n, $this->sharingAllowlist, $this->userSession); $result = $this->getFilesSharingPart($cap->getCapabilities()); diff --git a/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php b/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php index 01401ac2fb37..ec311b648641 100644 --- a/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php +++ b/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php @@ -33,17 +33,14 @@ * @package OCA\Files_Sharing\Tests\Command */ class CleanupRemoteStoragesTest extends TestCase { - /** - * @var CleanupRemoteStorages - */ - private $command; + private \OCA\Files_Sharing\Command\CleanupRemoteStorages $command; /** * @var \OCP\IDBConnection */ private $connection; - private $storages = [ + private array $storages = [ ['id' => 'shared::7b4a322b22f9d0047c38d77d471ce3cf', 'share_token' => 'f2c69dad1dc0649f26976fd210fc62e1', 'remote' => 'https://hostname.tld/owncloud1', 'user' => 'user1'], ['id' => 'shared::efe3b456112c3780da6155d3a9b9141c', 'share_token' => 'f2c69dad1dc0649f26976fd210fc62e2', 'remote' => 'https://hostname.tld/owncloud2', 'user' => 'user2'], ['notExistingId' => 'shared::33323d9f4ca416a9e3525b435354bc6f', 'share_token' => 'f2c69dad1dc0649f26976fd210fc62e3', 'remote' => 'https://hostname.tld/owncloud3', 'user' => 'user3'], @@ -158,10 +155,10 @@ private function doesStorageExist($numericId) { * Test cleanup of orphaned storages */ public function testCleanup() { - $input = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface') + $input = $this->getMockBuilder(\Symfony\Component\Console\Input\InputInterface::class) ->disableOriginalConstructor() ->getMock(); - $output = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface') + $output = $this->getMockBuilder(\Symfony\Component\Console\Output\OutputInterface::class) ->disableOriginalConstructor() ->getMock(); diff --git a/apps/files_sharing/tests/Controller/NotificationControllerTest.php b/apps/files_sharing/tests/Controller/NotificationControllerTest.php index 457d567b6e33..a55d7b89e415 100644 --- a/apps/files_sharing/tests/Controller/NotificationControllerTest.php +++ b/apps/files_sharing/tests/Controller/NotificationControllerTest.php @@ -35,21 +35,20 @@ class NotificationControllerTest extends TestCase { /** @var IRequest | MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var MailNotifications | MockObject */ - private $mailNotifications; + private \PHPUnit\Framework\MockObject\MockObject $mailNotifications; /** @var IUserSession | MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IUserManager | MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IGroupManager | MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var IRootFolder | MockObject */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; /** @var IL10N | MockObject */ - private $l; - /** @var NotificationController $notificationController */ - private $notificationController; + private \PHPUnit\Framework\MockObject\MockObject $l; + private \OCA\Files_Sharing\Controller\NotificationController $notificationController; protected function setUp(): void { parent::setUp(); diff --git a/apps/files_sharing/tests/Controller/PersonalSettingsControllerTest.php b/apps/files_sharing/tests/Controller/PersonalSettingsControllerTest.php index f9c3ee9b472d..0df64b2d55a4 100644 --- a/apps/files_sharing/tests/Controller/PersonalSettingsControllerTest.php +++ b/apps/files_sharing/tests/Controller/PersonalSettingsControllerTest.php @@ -32,16 +32,15 @@ class PersonalSettingsControllerTest extends TestCase { /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject $config */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject $userSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; - /** @var PersonalSettingsController $personalSettingsController */ - private $personalSettingsController; + private \OCA\Files_Sharing\Controller\PersonalSettingsController $personalSettingsController; protected function setUp(): void { parent::setUp(); diff --git a/apps/files_sharing/tests/Controller/Share20OcsControllerTest.php b/apps/files_sharing/tests/Controller/Share20OcsControllerTest.php index 9a671357c788..dcd43f2d3666 100644 --- a/apps/files_sharing/tests/Controller/Share20OcsControllerTest.php +++ b/apps/files_sharing/tests/Controller/Share20OcsControllerTest.php @@ -65,49 +65,48 @@ */ class Share20OcsControllerTest extends TestCase { /** @var Manager | MockObject */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** @var IGroupManager | MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var IUserManager | MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IRequest | MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IRootFolder | MockObject */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; /** @var IURLGenerator */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IUser */ - private $currentUser; + private \PHPUnit\Framework\MockObject\MockObject $currentUser; /** @var IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; - /** @var Share20OcsController */ - private $ocs; + private \OCA\Files_Sharing\Controller\Share20OcsController $ocs; /** @var IL10N */ - private $l; + private \PHPUnit\Framework\MockObject\MockObject $l; /** @var NotificationPublisher */ - private $notificationPublisher; + private \PHPUnit\Framework\MockObject\MockObject $notificationPublisher; - private $eventDispatcher; + private \PHPUnit\Framework\MockObject\MockObject $eventDispatcher; /** @var SharingBlacklist */ - private $sharingBlacklist; + private \PHPUnit\Framework\MockObject\MockObject $sharingBlacklist; /** @var SharingAllowlist */ - private $sharingAllowlist; + private \PHPUnit\Framework\MockObject\MockObject $sharingAllowlist; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUser */ - private $sharee; + private \PHPUnit\Framework\MockObject\MockObject $sharee; /** @var UserTypeHelper */ - private $userTypeHelper; + private \PHPUnit\Framework\MockObject\MockObject $userTypeHelper; protected function setUp(): void { $this->shareManager = $this->getMockBuilder(IManager::class) @@ -148,11 +147,9 @@ protected function setUp(): void { $this->sharee = $this->createMock(IUser::class); $this->sharee->method('getUID')->willReturn('validUser'); - $this->l = $this->createMock('\OCP\IL10N'); + $this->l = $this->createMock('\\' . \OCP\IL10N::class); $this->l->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $this->config = $this->createMock(IConfig::class); $this->config->method('getAppValue') @@ -272,7 +269,7 @@ public function testDeleteShareShareNotFound() { } public function testDeleteShare() { - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock('\\' . \OCP\Files\File::class); $share = $this->newShare(); $share->setSharedBy($this->currentUser->getUID()) @@ -299,7 +296,7 @@ public function testDeleteShare() { } public function testDeleteShareLocked() { - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock('\\' . \OCP\Files\File::class); $share = $this->newShare(); $share->setSharedBy($this->currentUser->getUID()) @@ -391,35 +388,35 @@ public function createShare( public function dataGetShare() { $data = []; - $cache = $this->getMockBuilder('OC\Files\Cache\Cache') + $cache = $this->getMockBuilder(\OC\Files\Cache\Cache::class) ->disableOriginalConstructor() ->getMock(); $cache->method('getNumericStorageId')->willReturn(101); - $storage = $this->getMockBuilder('OC\Files\Storage\Storage') + $storage = $this->getMockBuilder(\OC\Files\Storage\Storage::class) ->disableOriginalConstructor() ->getMock(); $storage->method('getId')->willReturn('STORAGE'); $storage->method('getCache')->willReturn($cache); - $parentFolder = $this->createMock('OCP\Files\Folder'); + $parentFolder = $this->createMock(\OCP\Files\Folder::class); $parentFolder->method('getId')->willReturn(3); - $file = $this->createMock('OCP\Files\File'); + $file = $this->createMock(\OCP\Files\File::class); $file->method('getId')->willReturn(1); $file->method('getPath')->willReturn('file'); $file->method('getStorage')->willReturn($storage); $file->method('getParent')->willReturn($parentFolder); $file->method('getMimeType')->willReturn('myMimeType'); - $folder = $this->createMock('OCP\Files\Folder'); + $folder = $this->createMock(\OCP\Files\Folder::class); $folder->method('getId')->willReturn(2); $folder->method('getPath')->willReturn('folder'); $folder->method('getStorage')->willReturn($storage); $folder->method('getParent')->willReturn($parentFolder); $folder->method('getMimeType')->willReturn('myFolderMimeType'); - list($shareAttributes, $shareAttributesReturnJson) = $this->mockShareAttributes(); + [$shareAttributes, $shareAttributesReturnJson] = $this->mockShareAttributes(); // File shared with user $share = $this->createShare( @@ -607,7 +604,7 @@ public function testGetShare(\OCP\Share\IShare $share, array $result) { ->with($share->getFullId()) ->willReturn($share); - $userFolder = $this->createMock('OCP\Files\Folder'); + $userFolder = $this->createMock(\OCP\Files\Folder::class); $userFolder ->method('getRelativePath') ->will($this->returnArgument(0)); @@ -624,19 +621,19 @@ public function testGetShare(\OCP\Share\IShare $share, array $result) { ->method('linkToRouteAbsolute') ->willReturn('url'); - $initiator = $this->createMock('OCP\IUser'); + $initiator = $this->createMock(\OCP\IUser::class); $initiator->method('getUID')->willReturn('initiatorId'); $initiator->method('getDisplayName')->willReturn('initiatorDisplay'); - $owner = $this->createMock('OCP\IUser'); + $owner = $this->createMock(\OCP\IUser::class); $owner->method('getUID')->willReturn('ownerId'); $owner->method('getDisplayName')->willReturn('ownerDisplay'); - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->method('getUID')->willReturn('userId'); $user->method('getDisplayName')->willReturn('userDisplay'); - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(\OCP\IGroup::class); $group->method('getGID')->willReturn('groupId'); $this->userManager->method('get')->will($this->returnValueMap([ @@ -669,31 +666,31 @@ public function testGetShareInvalidNode() { } public function testCanAccessShare() { - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareOwner')->willReturn($this->currentUser->getUID()); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getSharedBy')->willReturn($this->currentUser->getUID()); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareType')->willReturn(Share::SHARE_TYPE_USER); $share->method('getSharedWith')->willReturn($this->currentUser->getUID()); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareType')->willReturn(Share::SHARE_TYPE_USER); - $share->method('getSharedWith')->willReturn($this->createMock('OCP\IUser')); + $share->method('getSharedWith')->willReturn($this->createMock(\OCP\IUser::class)); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareType')->willReturn(Share::SHARE_TYPE_GROUP); $share->method('getSharedWith')->willReturn('group'); - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(\OCP\IGroup::class); $group->method('inGroup')->with($this->currentUser)->willReturn(true); - $group2 = $this->createMock('OCP\IGroup'); + $group2 = $this->createMock(\OCP\IGroup::class); $group2->method('inGroup')->with($this->currentUser)->willReturn(false); $this->groupManager->method('get')->will($this->returnValueMap([ @@ -703,30 +700,30 @@ public function testCanAccessShare() { ])); $this->assertTrue(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareType')->willReturn(Share::SHARE_TYPE_GROUP); $share->method('getSharedWith')->willReturn('group2'); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); // null group - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_GROUP); $share->method('getSharedWith')->willReturn('groupnull'); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareType')->willReturn(Share::SHARE_TYPE_LINK); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); // should not happen ever again, but who knows... let's cover it - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareType')->willReturn(Share::SHARE_TYPE_USER); $share->method('getState')->willReturn(Share::STATE_ACCEPTED); $share->method('getPermissions')->willReturn(0); $this->assertFalse(self::invokePrivate($this->ocs, 'canAccessShare', [$share])); // legacy zero permission entries from group sub-shares, let it pass - $share = $this->createMock('OCP\Share\IShare'); + $share = $this->createMock(\OCP\Share\IShare::class); $share->method('getShareType')->willReturn(Share::SHARE_TYPE_GROUP); $share->method('getSharedWith')->willReturn('group'); $share->method('getState')->willReturn(Share::STATE_REJECTED); @@ -750,7 +747,7 @@ public function testCreateShareInvalidPath() { ['path', null, 'invalid-path'], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') @@ -781,16 +778,16 @@ public function testCreateShareUserNoShareWith() { ['shareType', $this->any(), Share::SHARE_TYPE_USER], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -837,16 +834,16 @@ public function testCreateShareUserNoValidShareWith($shareWith) { ['shareWith', $this->any(), $shareWith], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -883,16 +880,16 @@ public function testCreateShareUser() { ['shareWith', null, 'validUser'], ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -910,15 +907,13 @@ public function testCreateShareUser() { ->with(ILockingProvider::LOCK_SHARED); $this->shareManager->method('createShare') - ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) { - return $share->getNode() === $path && + ->with($this->callback(fn (\OCP\Share\IShare $share) => $share->getNode() === $path && $share->getPermissions() === ( \OCP\Constants::PERMISSION_ALL ) && $share->getShareType() === Share::SHARE_TYPE_USER && $share->getSharedWith() === 'validUser' && - $share->getSharedBy() === 'currentUser'; - })) + $share->getSharedBy() === 'currentUser')) ->will($this->returnArgument(0)); $expected = new Result(); @@ -946,16 +941,16 @@ public function testCreateShareGroupNoValidShareWith($shareWith) { ['shareWith', null, $shareWith], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -991,16 +986,16 @@ public function testCreateShareGroupBlacklisted() { ['shareWith', null, 'validGroup'], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -1042,16 +1037,16 @@ public function testCreateShareGroup() { ['shareWith', null, 'validGroup'], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -1076,13 +1071,11 @@ public function testCreateShareGroup() { ->with(ILockingProvider::LOCK_SHARED); $this->shareManager->method('createShare') - ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) { - return $share->getNode() === $path && + ->with($this->callback(fn (\OCP\Share\IShare $share) => $share->getNode() === $path && $share->getPermissions() === \OCP\Constants::PERMISSION_ALL && $share->getShareType() === Share::SHARE_TYPE_GROUP && $share->getSharedWith() === 'validGroup' && - $share->getSharedBy() === 'currentUser'; - })) + $share->getSharedBy() === 'currentUser')) ->will($this->returnArgument(0)); $this->sharingBlacklist->method('isGroupBlacklisted')->willReturn(false); @@ -1107,16 +1100,16 @@ public function testCreateShareGroupNotAllowed() { ['shareWith', null, 'validGroup'], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -1146,10 +1139,10 @@ public function testCreateShareLinkNoLinksAllowed() { ['shareType', '-1', Share::SHARE_TYPE_LINK], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1173,10 +1166,10 @@ public function testCreateShareLinkNoPublicUpload() { ['publicUpload', null, 'true'], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1201,10 +1194,10 @@ public function testCreateShareLinkNotInAllowlist() { ['publicUpload', null, 'true'], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1233,10 +1226,10 @@ public function testCreateShareLinkPublicUploadFile() { ['publicUpload', null, 'true'], ])); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1266,10 +1259,10 @@ public function testCreateShareLinkPublicUploadFolder() { ['password', '', ''], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1280,14 +1273,12 @@ public function testCreateShareLinkPublicUploadFolder() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { - return $share->getNode() === $path && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getNode() === $path && $share->getShareType() === Share::SHARE_TYPE_LINK && $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && - $share->getExpirationDate() === null; - }) + $share->getExpirationDate() === null) )->will($this->returnArgument(0)); $expected = new Result(null); @@ -1310,10 +1301,10 @@ public function testCreateShareLinkReadWritePermissions() { ['password', '', ''], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1324,14 +1315,12 @@ public function testCreateShareLinkReadWritePermissions() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { - return $share->getNode() === $path && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getNode() === $path && $share->getShareType() === Share::SHARE_TYPE_LINK && $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && - $share->getExpirationDate() === null; - }) + $share->getExpirationDate() === null) )->will($this->returnArgument(0)); $expected = new Result(null); @@ -1354,10 +1343,10 @@ public function testCreateShareLinkCreateOnlyFolder() { ['password', '', ''], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1368,14 +1357,12 @@ public function testCreateShareLinkCreateOnlyFolder() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { - return $share->getNode() === $path && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getNode() === $path && $share->getShareType() === Share::SHARE_TYPE_LINK && $share->getPermissions() === (\OCP\Constants::PERMISSION_CREATE) && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && - $share->getExpirationDate() === null; - }) + $share->getExpirationDate() === null) )->will($this->returnArgument(0)); $expected = new Result(null); @@ -1398,10 +1385,10 @@ public function testCreateShareLinkCreateOnlyFolderPublicUploadDisabled() { ['password', '', ''], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1430,10 +1417,10 @@ public function testCreateShareLinkDefaultPerms() { ['password', '', ''], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1444,14 +1431,12 @@ public function testCreateShareLinkDefaultPerms() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(false); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { - return $share->getNode() === $path && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getNode() === $path && $share->getShareType() === Share::SHARE_TYPE_LINK && $share->getPermissions() === (\OCP\Constants::PERMISSION_READ) && $share->getSharedBy() === 'currentUser' && $share->getPassword() === null && - $share->getExpirationDate() === null; - }) + $share->getExpirationDate() === null) )->will($this->returnArgument(0)); $expected = new Result(null); @@ -1474,10 +1459,10 @@ public function testCreateShareLinkPassword() { ['password', '', 'password'], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1488,14 +1473,12 @@ public function testCreateShareLinkPassword() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('createShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($path) { - return $share->getNode() === $path && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getNode() === $path && $share->getShareType() === Share::SHARE_TYPE_LINK && $share->getPermissions() === \OCP\Constants::PERMISSION_READ && $share->getSharedBy() === 'currentUser' && $share->getPassword() === 'password' && - $share->getExpirationDate() === null; - }) + $share->getExpirationDate() === null) )->will($this->returnArgument(0)); $expected = new Result(null); @@ -1523,16 +1506,16 @@ public function testCreateShareRemoteNoValidShareWith($shareWith) { ['shareWith', $this->any(), $shareWith] ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -1564,10 +1547,10 @@ public function testCreateShareValidExpireDate() { ['password', '', ''], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1611,10 +1594,10 @@ public function testCreateShareInvalidExpireDate() { ['password', '', ''], ])); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $this->rootFolder->method('getUserFolder')->with($this->currentUser->getUID())->will($this->returnSelf()); @@ -1650,16 +1633,16 @@ public function testCreateReshareOfFederatedMountNoDeletePermissions() { ['shareWith', null, 'validUser'], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\Folder'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(true); $path->method('getStorage')->willReturn($storage); $path->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ); @@ -1673,16 +1656,14 @@ public function testCreateReshareOfFederatedMountNoDeletePermissions() { $this->shareManager ->expects($this->once()) ->method('createShare') - ->with($this->callback(function (\OCP\Share\IShare $share) { - return $share->getPermissions() === \OCP\Constants::PERMISSION_READ; - })) + ->with($this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === \OCP\Constants::PERMISSION_READ)) ->will($this->returnArgument(0)); $ocs->createShare(); } public function testUpdateShareCantChange() { - $node = $this->createMock('\OCP\Files\Folder'); + $node = $this->createMock('\\' . \OCP\Files\Folder::class); $share = $this->newShare(); $share->setNode($node); @@ -1700,7 +1681,7 @@ public function testUpdateShareCantChange() { } public function testUpdateNoParametersLink() { - $node = $this->createMock('\OCP\Files\Folder'); + $node = $this->createMock('\\' . \OCP\Files\Folder::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) @@ -1723,7 +1704,7 @@ public function testUpdateNoParametersLink() { public function testUpdateNoParametersOther() { $ocs = $this->mockFormatShare(); - $node = $this->createMock('\OCP\Files\Folder'); + $node = $this->createMock('\\' . \OCP\Files\Folder::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) @@ -1733,11 +1714,9 @@ public function testUpdateNoParametersOther() { $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { - return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === \OCP\Constants::PERMISSION_ALL && $share->getPassword() === null && - $share->getExpirationDate() === null; - }) + $share->getExpirationDate() === null) )->will($this->returnArgument(0)); $this->shareManager->method('getSharedWith')->willReturn([]); @@ -1757,7 +1736,7 @@ public function testUpdateLinkShareClear() { $ocs = $this->mockFormatShare(); - $node = $this->createMock('\OCP\Files\Folder'); + $node = $this->createMock('\\' . \OCP\Files\Folder::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) @@ -1786,11 +1765,9 @@ public function testUpdateLinkShareClear() { $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { - return $share->getPermissions() === \OCP\Constants::PERMISSION_READ && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === \OCP\Constants::PERMISSION_READ && $share->getPassword() === null && - $share->getExpirationDate() === null; - }) + $share->getExpirationDate() === null) )->will($this->returnArgument(0)); $expected = new Result(null); @@ -1809,7 +1786,7 @@ public function testUpdateLinkShareSet() { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -1859,7 +1836,7 @@ public function testUpdateLinkShareEnablePublicUpload($params) { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -1907,7 +1884,7 @@ public function testUpdateLinkShareInvalidDate() { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -1959,7 +1936,7 @@ public function publicUploadParamsProvider() { public function testUpdateLinkSharePublicUploadNotAllowed($params) { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -1984,7 +1961,7 @@ public function testUpdateLinkSharePublicUploadNotAllowed($params) { public function testUpdateLinkSharePublicUploadOnFile() { $ocs = $this->mockFormatShare(); - $file = $this->createMock('\OCP\Files\File'); + $file = $this->createMock('\\' . \OCP\Files\File::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2016,7 +1993,7 @@ public function testUpdateLinkSharePasswordDoesNotChangeOther() { $date = new \DateTime('2000-01-01'); $date->setTime(0, 0, 0); - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock('\\' . \OCP\Files\File::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) @@ -2042,11 +2019,9 @@ public function testUpdateLinkSharePasswordDoesNotChangeOther() { $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { - return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === \OCP\Constants::PERMISSION_ALL && $share->getPassword() === 'newpassword' && - $share->getExpirationDate() === $date; - }) + $share->getExpirationDate() === $date) )->will($this->returnArgument(0)); $expected = new Result(null); @@ -2059,7 +2034,7 @@ public function testUpdateLinkSharePasswordDoesNotChangeOther() { public function testUpdateLinkShareExpireDateDoesNotChangeOther() { $ocs = $this->mockFormatShare(); - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock('\\' . \OCP\Files\File::class); $share = $this->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) ->setSharedBy($this->currentUser->getUID()) @@ -2113,7 +2088,7 @@ public function testUpdateLinkSharePublicUploadDoesNotChangeOther() { $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2135,11 +2110,9 @@ public function testUpdateLinkSharePublicUploadDoesNotChangeOther() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { - return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) && $share->getPassword() === 'password' && - $share->getExpirationDate() === $date; - }) + $share->getExpirationDate() === $date) )->will($this->returnArgument(0)); $expected = new Result(null); @@ -2160,7 +2133,7 @@ public function testUpdateLinkSharePermissions() { $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2181,11 +2154,9 @@ public function testUpdateLinkSharePermissions() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { - return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) && $share->getPassword() === 'password' && - $share->getExpirationDate() === $date; - }) + $share->getExpirationDate() === $date) )->will($this->returnArgument(0)); $this->shareManager->method('getSharedWith')->willReturn([]); @@ -2206,7 +2177,7 @@ public function testUpdateLinkShareCreateOnly() { $ocs = $this->mockFormatShare(); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2225,9 +2196,7 @@ public function testUpdateLinkShareCreateOnly() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { - return $share->getPermissions() === \OCP\Constants::PERMISSION_CREATE; - }) + $this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === \OCP\Constants::PERMISSION_CREATE) )->will($this->returnArgument(0)); $this->shareManager->method('getSharedWith')->willReturn([]); @@ -2244,7 +2213,7 @@ public function testUpdateLinkShareInvalidPermissions() { $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2274,7 +2243,7 @@ public function testUpdateLinkShareInvalidPermissions() { public function testUpdateOtherPermissions() { $ocs = $this->mockFormatShare(); - $file = $this->createMock('\OCP\Files\File'); + $file = $this->createMock('\\' . \OCP\Files\File::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_ALL) @@ -2292,9 +2261,7 @@ public function testUpdateOtherPermissions() { $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) { - return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL; - }) + $this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === \OCP\Constants::PERMISSION_ALL) )->will($this->returnArgument(0)); $this->shareManager->method('getSharedWith')->willReturn([]); @@ -2311,7 +2278,7 @@ public function testUpdateLinkShareNameAlone() { $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_READ) @@ -2329,9 +2296,7 @@ public function testUpdateLinkShareNameAlone() { $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { - return $share->getName() === 'another'; - }) + $this->callback(fn (\OCP\Share\IShare $share) => $share->getName() === 'another') )->will($this->returnArgument(0)); $this->shareManager->method('getSharedWith')->willReturn([]); @@ -2348,7 +2313,7 @@ public function testUpdateLinkShareKeepNameWhenNotSpecified() { $date = new \DateTime('2000-01-01'); - $folder = $this->createMock('\OCP\Files\Folder'); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); $share = \OC::$server->getShareManager()->newShare(); $share->setPermissions(\OCP\Constants::PERMISSION_READ) @@ -2366,11 +2331,9 @@ public function testUpdateLinkShareKeepNameWhenNotSpecified() { $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share); $this->shareManager->expects($this->once())->method('updateShare')->with( - $this->callback(function (\OCP\Share\IShare $share) use ($date) { - return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ) && + $this->callback(fn (\OCP\Share\IShare $share) => $share->getPermissions() === (\OCP\Constants::PERMISSION_READ) && $share->getPassword() === 'test' && - $share->getName() === 'somename'; - }) + $share->getName() === 'somename') )->will($this->returnArgument(0)); $this->shareManager->method('getSharedWith')->willReturn([]); @@ -2383,9 +2346,9 @@ public function testUpdateLinkShareKeepNameWhenNotSpecified() { } private function getMockFileFolder() { - $file = $this->createMock('\OCP\Files\File'); - $folder = $this->createMock('\OCP\Files\Folder'); - $parent = $this->createMock('\OCP\Files\Folder'); + $file = $this->createMock('\\' . \OCP\Files\File::class); + $folder = $this->createMock('\\' . \OCP\Files\Folder::class); + $parent = $this->createMock('\\' . \OCP\Files\Folder::class); $file->method('getMimeType')->willReturn('myMimeType'); $folder->method('getMimeType')->willReturn('myFolderMimeType'); @@ -2400,9 +2363,9 @@ private function getMockFileFolder() { $file->method('getParent')->willReturn($parent); $folder->method('getParent')->willReturn($parent); - $cache = $this->createMock('OCP\Files\Cache\ICache'); + $cache = $this->createMock(\OCP\Files\Cache\ICache::class); $cache->method('getNumericStorageId')->willReturn(100); - $storage = $this->createMock('\OCP\Files\Storage'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); $storage->method('getId')->willReturn('storageId'); $storage->method('getCache')->willReturn($cache); @@ -2413,14 +2376,14 @@ private function getMockFileFolder() { } public function dataFormatShare() { - list($file, $folder) = $this->getMockFileFolder(); - $owner = $this->createMock('\OCP\IUser'); + [$file, $folder] = $this->getMockFileFolder(); + $owner = $this->createMock('\\' . \OCP\IUser::class); $owner->method('getDisplayName')->willReturn('ownerDN'); - $initiator = $this->createMock('\OCP\IUser'); + $initiator = $this->createMock('\\' . \OCP\IUser::class); $initiator->method('getDisplayName')->willReturn('initiatorDN'); - $recipient = $this->createMock('\OCP\IUser'); + $recipient = $this->createMock('\\' . \OCP\IUser::class); $recipient->method('getDisplayName')->willReturn('recipientDN'); - list($shareAttributes, $shareAttributesReturnJson) = $this->mockShareAttributes(); + [$shareAttributes, $shareAttributesReturnJson] = $this->mockShareAttributes(); $result = []; @@ -2446,7 +2409,7 @@ public function dataFormatShare() { 'share_with_user_type' => Constants::USER_TYPE_USER, 'permissions' => 1, 'attributes' => $shareAttributesReturnJson, - 'stime' => 946684862, + 'stime' => 946_684_862, 'parent' => null, 'expiration' => null, 'token' => null, @@ -2478,7 +2441,7 @@ public function dataFormatShare() { 'additional_info_owner' => null, 'permissions' => 1, 'attributes' => $shareAttributesReturnJson, - 'stime' => 946684862, + 'stime' => 946_684_862, 'parent' => null, 'expiration' => null, 'token' => null, @@ -2526,7 +2489,7 @@ public function dataFormatShare() { 'displayname_owner' => 'initiator', 'permissions' => 1, 'attributes' => null, - 'stime' => 946684862, + 'stime' => 946_684_862, 'parent' => null, 'expiration' => null, 'token' => null, @@ -2567,7 +2530,7 @@ public function dataFormatShare() { 'displayname_owner' => 'initiator', 'permissions' => 1, 'attributes' => null, - 'stime' => 946684862, + 'stime' => 946_684_862, 'parent' => null, 'expiration' => null, 'token' => null, @@ -2607,7 +2570,7 @@ public function dataFormatShare() { 'displayname_owner' => 'initiator', 'permissions' => 1, 'attributes' => null, - 'stime' => 946684862, + 'stime' => 946_684_862, 'parent' => null, 'expiration' => null, 'token' => null, @@ -2650,7 +2613,7 @@ public function dataFormatShare() { 'displayname_owner' => 'initiator', 'permissions' => 1, 'attributes' => null, - 'stime' => 946684862, + 'stime' => 946_684_862, 'parent' => null, 'expiration' => '2001-01-02 00:00:00', 'token' => 'myToken', @@ -2692,7 +2655,7 @@ public function dataFormatShare() { 'displayname_owner' => 'initiator', 'permissions' => 1, 'attributes' => null, - 'stime' => 946684862, + 'stime' => 946_684_862, 'parent' => null, 'expiration' => null, 'token' => null, @@ -2741,7 +2704,7 @@ public function dataFormatShare() { public function testFormatShare(array $expects, \OCP\Share\IShare $share, array $users, $exception) { $this->userManager->method('get')->will($this->returnValueMap($users)); - $recipientGroup = $this->createMock('\OCP\IGroup'); + $recipientGroup = $this->createMock('\\' . \OCP\IGroup::class); $recipientGroup->method('getDisplayName')->willReturn('recipientGroupDisplayName'); $this->groupManager->method('get')->will($this->returnValueMap([ ['recipientGroup', $recipientGroup], @@ -2778,7 +2741,7 @@ public function testFormatShare(array $expects, \OCP\Share\IShare $share, array * @return Share20OcsController */ public function getOcsDisabledAPI() { - $shareManager = $this->getMockBuilder('OCP\Share\IManager') + $shareManager = $this->getMockBuilder(\OCP\Share\IManager::class) ->disableOriginalConstructor() ->getMock(); $shareManager @@ -2906,7 +2869,7 @@ public function testGetShareAdditionalInfo($configValue, $expectedInfo, $expecte $this->userTypeHelper ); - list($file, ) = $this->getMockFileFolder(); + [$file, ] = $this->getMockFileFolder(); $share = \OC::$server->getShareManager()->newShare(); $share->setShareType(Share::SHARE_TYPE_USER) @@ -3196,7 +3159,7 @@ public function testGetSharesSharedWithMe($requestedPath, $stateFilter, $shareTy $groupShareNonOwner->setShareType(\OCP\Share::SHARE_TYPE_GROUP); $groupShareNonOwner->setPermissions(\OCP\Constants::PERMISSION_ALL); - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(\OCP\IGroup::class); $group->method('inGroup')->with($this->currentUser)->willReturn(true); $this->groupManager->method('get')->with('group1')->willReturn($group); @@ -3374,7 +3337,7 @@ public function testAcceptRejectShare($method, $target, $targetExists, $expected ->method('updateShareForRecipient') ->with($userShare, 'currentUser'); - $userFolder = $this->createMock('OCP\Files\Folder'); + $userFolder = $this->createMock(\OCP\Files\Folder::class); if ($method === 'acceptShare') { // deduplicate if ($targetExists) { @@ -3503,7 +3466,7 @@ public function testAcceptRejectShareMultiple($method, $target, $targetExists, $ ->method('updateShareForRecipient') ->withConsecutive([$userShare], [$groupShare]); - $userFolder = $this->createMock('OCP\Files\Folder'); + $userFolder = $this->createMock(\OCP\Files\Folder::class); if ($method === 'acceptShare') { // deduplicate if ($targetExists) { @@ -3568,7 +3531,7 @@ public function testAcceptRejectShareApiDisabled($method, $target, $targetExists $ocs = $this->getOcsDisabledAPI(); $expected = new Result(null, 404, 'Share API is disabled'); - $result = $ocs->$method(123); + $result = $ocs->{$method}(); $this->assertEquals($expected, $result); } @@ -3606,7 +3569,7 @@ public function testAcceptRejectShareInvalidId($method, $target, $targetExists, ->method('updateShareForRecipient'); $expected = new Result(null, 404, 'Wrong share ID, share doesn\'t exist'); - $result = $this->ocs->$method(123); + $result = $this->ocs->{$method}(); $this->assertEquals($expected, $result); } @@ -3627,7 +3590,7 @@ public function testAcceptRejectShareAccessDenied($method, $target, $targetExist ->method('updateShareForRecipient'); $expected = new Result(null, 404, 'Wrong share ID, share doesn\'t exist'); - $result = $this->ocs->$method(123); + $result = $this->ocs->{$method}(); $this->assertEquals($expected, $result); } @@ -3649,14 +3612,14 @@ public function testAcceptRejectShareAccessNotRecipient($method, $target, $targe $userShare->setShareOwner('currentUser'); $expected = new Result(null, 403, 'Only recipient can change accepted state'); - $result = $this->ocs->$method(123); + $result = $this->ocs->{$method}(); $this->assertEquals($expected, $result); $userShare->setShareOwner('anotherUser'); $userShare->setSharedBy('currentUser'); - $result = $this->ocs->$method(123); + $result = $this->ocs->{$method}(); $this->assertEquals($expected, $result); } @@ -3703,7 +3666,7 @@ public function testAcceptRejectShareOperationError($method, $target, $targetExi ->willReturn($userFolder); $expected = new Result(null, 400, 'operation error'); - $result = $this->ocs->$method(123); + $result = $this->ocs->{$method}(); $this->assertEquals($expected, $result); } @@ -3718,12 +3681,10 @@ public function testSettingAttributes($attributes, $expectedAttributeObject) { $share->setShareOwner('shareOwner'); $ocs = $this->mockFormatShare(); - $ocs->expects(self::once())->method('formatShare')->willReturnCallback(static function (IShare $share) { - return [ + $ocs->expects(self::once())->method('formatShare')->willReturnCallback(static fn (IShare $share) => [ 'permissions' => $share->getPermissions(), 'attributes' => $share->getAttributes() - ]; - }); + ]); $this->request ->method('getParam') @@ -3735,16 +3696,16 @@ public function testSettingAttributes($attributes, $expectedAttributeObject) { ['shareWith', null, 'validUser'], ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) @@ -3828,12 +3789,10 @@ public function testPermissionsViaAttributes($expectedPermission, $attributes) { $share->setShareOwner('shareOwner'); $ocs = $this->mockFormatShare(); - $ocs->expects(self::once())->method('formatShare')->willReturnCallback(static function (IShare $share) { - return [ + $ocs->expects(self::once())->method('formatShare')->willReturnCallback(static fn (IShare $share) => [ 'permissions' => $share->getPermissions(), 'attributes' => $share->getAttributes() - ]; - }); + ]); $this->request ->method('getParam') @@ -3845,16 +3804,16 @@ public function testPermissionsViaAttributes($expectedPermission, $attributes) { ['shareWith', null, 'validUser'], ]); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $this->rootFolder->expects($this->once()) ->method('getUserFolder') ->with('currentUser') ->willReturn($userFolder); - $path = $this->createMock('\OCP\Files\File'); - $storage = $this->createMock('OCP\Files\Storage'); + $path = $this->createMock('\\' . \OCP\Files\File::class); + $storage = $this->createMock(\OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); $path->method('getStorage')->willReturn($storage); $userFolder->expects($this->once()) diff --git a/apps/files_sharing/tests/Controllers/ExternalShareControllerTest.php b/apps/files_sharing/tests/Controllers/ExternalShareControllerTest.php index 0d9ee014986c..cf3933fa9265 100644 --- a/apps/files_sharing/tests/Controllers/ExternalShareControllerTest.php +++ b/apps/files_sharing/tests/Controllers/ExternalShareControllerTest.php @@ -40,19 +40,19 @@ */ class ExternalShareControllerTest extends \Test\TestCase { /** @var IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var \OCA\Files_Sharing\External\Manager */ - private $externalManager; + private \PHPUnit\Framework\MockObject\MockObject $externalManager; /** @var IClientService */ - private $clientService; + private \PHPUnit\Framework\MockObject\MockObject $clientService; public function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder('\\OCP\\IRequest') + $this->request = $this->getMockBuilder('\\' . \OCP\IRequest::class) ->disableOriginalConstructor()->getMock(); - $this->externalManager = $this->getMockBuilder('\\OCA\\Files_Sharing\\External\\Manager') + $this->externalManager = $this->getMockBuilder('\\' . \OCA\Files_Sharing\External\Manager::class) ->disableOriginalConstructor()->getMock(); - $this->clientService = $this->getMockBuilder('\\OCP\Http\\Client\\IClientService') + $this->clientService = $this->getMockBuilder('\\' . \OCP\Http\Client\IClientService::class) ->disableOriginalConstructor()->getMock(); } @@ -145,9 +145,9 @@ public function testDestroy() { } public function testRemoteWithValidHttps() { - $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); - $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse') + $response = $this->getMockBuilder('\\' . \OCP\Http\Client\IResponse::class) ->disableOriginalConstructor()->getMock(); $response ->expects($this->exactly(2)) @@ -167,9 +167,9 @@ public function testRemoteWithValidHttps() { } public function testRemoteWithWorkingHttp() { - $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); - $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse') + $response = $this->getMockBuilder('\\' . \OCP\Http\Client\IResponse::class) ->disableOriginalConstructor()->getMock(); $client ->method('get') @@ -187,9 +187,9 @@ public function testRemoteWithWorkingHttp() { } public function testRemoteWithInvalidRemote() { - $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); - $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse') + $response = $this->getMockBuilder('\\' . \OCP\Http\Client\IResponse::class) ->disableOriginalConstructor()->getMock(); $client ->method('get') diff --git a/apps/files_sharing/tests/Controllers/ShareControllerTest.php b/apps/files_sharing/tests/Controllers/ShareControllerTest.php index 1475b2ab6f92..8652bde06fce 100644 --- a/apps/files_sharing/tests/Controllers/ShareControllerTest.php +++ b/apps/files_sharing/tests/Controllers/ShareControllerTest.php @@ -53,50 +53,48 @@ class ShareControllerTest extends \Test\TestCase { /** @var string */ private $oldUser; - /** @var string */ - private $appName = 'files_sharing'; - /** @var ShareController */ - private $shareController; + private string $appName = 'files_sharing'; + private \OCA\Files_Sharing\Controllers\ShareController $shareController; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var ISession | \PHPUnit\Framework\MockObject\MockObject */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; /** @var \OCP\IPreview | \PHPUnit\Framework\MockObject\MockObject */ - private $previewManager; + private \PHPUnit\Framework\MockObject\MockObject $previewManager; /** @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var \OC\Share20\Manager | \PHPUnit\Framework\MockObject\MockObject */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var EventDispatcher | \PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; protected function setUp(): void { parent::setUp(); $this->appName = 'files_sharing'; - $this->shareManager = $this->getMockBuilder('\OC\Share20\Manager')->disableOriginalConstructor()->getMock(); - $this->urlGenerator = $this->createMock('\OCP\IURLGenerator'); - $this->session = $this->createMock('\OCP\ISession'); - $this->previewManager = $this->createMock('\OCP\IPreview'); - $this->config = $this->createMock('\OCP\IConfig'); - $this->userManager = $this->createMock('\OCP\IUserManager'); + $this->shareManager = $this->getMockBuilder('\\' . \OC\Share20\Manager::class)->disableOriginalConstructor()->getMock(); + $this->urlGenerator = $this->createMock('\\' . \OCP\IURLGenerator::class); + $this->session = $this->createMock('\\' . \OCP\ISession::class); + $this->previewManager = $this->createMock('\\' . \OCP\IPreview::class); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->userManager = $this->createMock('\\' . \OCP\IUserManager::class); $this->eventDispatcher = new EventDispatcher(); $this->shareController = new \OCA\Files_Sharing\Controllers\ShareController( $this->appName, - $this->createMock('\OCP\IRequest'), + $this->createMock('\\' . \OCP\IRequest::class), $this->config, $this->urlGenerator, $this->userManager, - $this->createMock('\OCP\ILogger'), - $this->createMock('\OCP\Activity\IManager'), + $this->createMock('\\' . \OCP\ILogger::class), + $this->createMock('\\' . \OCP\Activity\IManager::class), $this->shareManager, $this->session, $this->previewManager, - $this->createMock('\OCP\Files\IRootFolder'), - $this->createMock('\OCP\IUserSession'), + $this->createMock('\\' . \OCP\Files\IRootFolder::class), + $this->createMock('\\' . \OCP\IUserSession::class), $this->eventDispatcher ); @@ -269,7 +267,7 @@ public function testAuthenticateInvalidPassword() { ->method('set'); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['access'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'share_link_access', $hookListner, 'access'); + \OCP\Util::connectHook(\OCP\Share::class, 'share_link_access', $hookListner, 'access'); $calledShareLinkAccess = []; $this->eventDispatcher->addListener( @@ -297,14 +295,12 @@ function () use (&$afterLinkAuthCalled) { $hookListner->expects($this->once()) ->method('access') - ->with($this->callback(function (array $data) { - return $data['itemType'] === 'file' && + ->with($this->callback(fn (array $data) => $data['itemType'] === 'file' && $data['itemSource'] === 100 && $data['uidOwner'] === 'initiator' && $data['token'] === 'token' && $data['errorCode'] === 403 && - $data['errorMessage'] === 'Wrong password'; - })); + $data['errorMessage'] === 'Wrong password')); $response = $this->shareController->authenticate('token', 'invalidpassword'); $expectedResponse = new TemplateResponse($this->appName, 'authenticate', ['wrongpw' => true], 'guest'); @@ -358,11 +354,11 @@ public function testShowShareNotAuthenticated() { } public function testShowShare() { - $owner = $this->createMock('OCP\IUser'); + $owner = $this->createMock(\OCP\IUser::class); $owner->method('getDisplayName')->willReturn('ownerDisplay'); $owner->method('getUID')->willReturn('ownerUID'); - $file = $this->createMock('OCP\Files\File'); + $file = $this->createMock(\OCP\Files\File::class); $file->method('getName')->willReturn('file1.txt'); $file->method('getMimetype')->willReturn('text/plain'); $file->method('getSize')->willReturn(33); @@ -447,11 +443,11 @@ public function testShowShare() { public function testShowShareInvalid() { $this->expectException(\OCP\Files\NotFoundException::class); - $owner = $this->createMock('OCP\IUser'); + $owner = $this->createMock(\OCP\IUser::class); $owner->method('getDisplayName')->willReturn('ownerDisplay'); $owner->method('getUID')->willReturn('ownerUID'); - $file = $this->createMock('OCP\Files\File'); + $file = $this->createMock(\OCP\Files\File::class); $file->method('getName')->willReturn('file1.txt'); $file->method('getMimetype')->willReturn('text/plain'); $file->method('getSize')->willReturn(33); @@ -492,7 +488,7 @@ public function testShowShareInvalid() { } public function testDownloadShare() { - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $share->method('getPassword')->willReturn('password'); $this->shareManager @@ -517,7 +513,7 @@ public function testDownloadShare() { public function testDownloadShareNoReadPermission() { $this->expectException(\OCP\Files\NotFoundException::class); - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $share->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_CREATE); $this->shareManager diff --git a/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php b/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php index 5b6e3d3c73a6..c26e46603439 100644 --- a/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php +++ b/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php @@ -38,10 +38,7 @@ class DeleteOrphanedSharesJobTest extends \Test\TestCase { */ private static $trashBinStatus; - /** - * @var DeleteOrphanedSharesJob - */ - private $job; + private \OCA\Files_Sharing\DeleteOrphanedSharesJob $job; /** * @var \OCP\IDBConnection @@ -156,7 +153,7 @@ public function testClearShares() { public function testKeepNonFileShares() { self::loginAsUser($this->user1); - \OCP\Share::registerBackend('test', 'Test\Share\Backend'); + \OCP\Share::registerBackend('test', \Test\Share\Backend::class); $this->assertTrue( \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), diff --git a/apps/files_sharing/tests/EtagPropagationTest.php b/apps/files_sharing/tests/EtagPropagationTest.php index 2240db0743e1..6d0361b5a3d3 100644 --- a/apps/files_sharing/tests/EtagPropagationTest.php +++ b/apps/files_sharing/tests/EtagPropagationTest.php @@ -64,9 +64,9 @@ protected function setUpShares() { $view1->file_put_contents('/sub1/sub2/folder/file.txt', 'foobar'); $view1->file_put_contents('/sub1/sub2/folder/inside/file.txt', 'foobar'); $folderInfo = $view1->getFileInfo('/sub1/sub2/folder'); - $this->assertInstanceOf('\OC\Files\FileInfo', $folderInfo); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $folderInfo); $fileInfo = $view1->getFileInfo('/foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $fileInfo); $node = $rootFolder->getUserFolder(self::TEST_FILES_SHARING_API_USER1) ->get('/foo.txt'); @@ -95,7 +95,7 @@ protected function setUpShares() { $shareManager->createShare($share); $folderInfo = $view1->getFileInfo('/directReshare'); - $this->assertInstanceOf('\OC\Files\FileInfo', $folderInfo); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $folderInfo); $node = $rootFolder->getUserFolder(self::TEST_FILES_SHARING_API_USER1) ->get('/directReshare'); @@ -119,7 +119,7 @@ protected function setUpShares() { $view2->mkdir('/sub1/sub2'); $view2->rename('/folder', '/sub1/sub2/folder'); $insideInfo = $view2->getFileInfo('/sub1/sub2/folder/inside'); - $this->assertInstanceOf('\OC\Files\FileInfo', $insideInfo); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $insideInfo); $node = $rootFolder->getUserFolder(self::TEST_FILES_SHARING_API_USER2) ->get('/sub1/sub2/folder/inside'); @@ -132,7 +132,7 @@ protected function setUpShares() { $shareManager->createShare($share); $folderInfo = $view2->getFileInfo('/directReshare'); - $this->assertInstanceOf('\OC\Files\FileInfo', $folderInfo); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $folderInfo); $node = $rootFolder->getUserFolder(self::TEST_FILES_SHARING_API_USER2) ->get('/directReshare'); @@ -270,7 +270,7 @@ public function testOwnerDeleteInReShare() { public function testOwnerUnshares() { self::loginAsUser(self::TEST_FILES_SHARING_API_USER1); $folderInfo = $this->rootView->getFileInfo('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/sub1/sub2/folder'); - $this->assertInstanceOf('\OC\Files\FileInfo', $folderInfo); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $folderInfo); $node = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1)->get('/sub1/sub2/folder'); $shareManager = \OC::$server->getShareManager(); @@ -293,7 +293,7 @@ public function testOwnerUnshares() { public function testOwnerUnsharesFlatReshares() { self::loginAsUser(self::TEST_FILES_SHARING_API_USER1); $folderInfo = $this->rootView->getFileInfo('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/sub1/sub2/folder/inside'); - $this->assertInstanceOf('\OC\Files\FileInfo', $folderInfo); + $this->assertInstanceOf('\\' . \OC\Files\FileInfo::class, $folderInfo); $node = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1)->get('/sub1/sub2/folder/inside'); $shareManager = \OC::$server->getShareManager(); @@ -448,9 +448,7 @@ public function testEtagChangeOnPermissionsChange() { $shares = $this->shareManager->getSharesBy(self::TEST_FILES_SHARING_API_USER1, \OCP\Share::SHARE_TYPE_USER, $node); /** @var \OCP\Share\IShare[] $shares */ - $shares = \array_filter($shares, function (\OCP\Share\IShare $share) { - return $share->getSharedWith() === self::TEST_FILES_SHARING_API_USER2; - }); + $shares = \array_filter($shares, fn (\OCP\Share\IShare $share) => $share->getSharedWith() === self::TEST_FILES_SHARING_API_USER2); $this->assertCount(1, $shares); $share = $shares[0]; diff --git a/apps/files_sharing/tests/ExpireSharesJobTest.php b/apps/files_sharing/tests/ExpireSharesJobTest.php index dc7ef0282f53..cf6e9cd4cf87 100644 --- a/apps/files_sharing/tests/ExpireSharesJobTest.php +++ b/apps/files_sharing/tests/ExpireSharesJobTest.php @@ -37,10 +37,7 @@ * @package OCA\Files_Sharing\Tests */ class ExpireSharesJobTest extends \Test\TestCase { - /** - * @var ExpireSharesJob - */ - private $job; + private \OCA\Files_Sharing\ExpireSharesJob $job; /** * @var IManager @@ -55,12 +52,12 @@ class ExpireSharesJobTest extends \Test\TestCase { /** * @var DefaultShareProvider| MockObject */ - private $defaultShareProvider; + private \PHPUnit\Framework\MockObject\MockObject $defaultShareProvider; /** * @var \OCP\Activity\IManager | MockObject */ - private $activityManager; + private \PHPUnit\Framework\MockObject\MockObject $activityManager; /** * @var string diff --git a/apps/files_sharing/tests/External/CacheTest.php b/apps/files_sharing/tests/External/CacheTest.php index 6f4a8a5f10a5..ef831c1359ef 100644 --- a/apps/files_sharing/tests/External/CacheTest.php +++ b/apps/files_sharing/tests/External/CacheTest.php @@ -36,12 +36,9 @@ class CacheTest extends TestCase { /** * @var \OC\Files\Storage\Storage **/ - private $storage; + private \PHPUnit\Framework\MockObject\MockObject $storage; - /** - * @var \OCA\Files_Sharing\External\Cache - */ - private $cache; + private \OCA\Files_Sharing\External\Cache $cache; /** * @var string @@ -53,7 +50,7 @@ protected function setUp(): void { $this->remoteUser = self::getUniqueID('remoteuser'); - $this->storage = $this->getMockBuilder('\OCA\Files_Sharing\External\Storage') + $this->storage = $this->getMockBuilder('\\' . \OCA\Files_Sharing\External\Storage::class) ->disableOriginalConstructor() ->getMock(); $this->storage diff --git a/apps/files_sharing/tests/External/ManagerTest.php b/apps/files_sharing/tests/External/ManagerTest.php index d9bebf9511c8..242d5bc8edac 100644 --- a/apps/files_sharing/tests/External/ManagerTest.php +++ b/apps/files_sharing/tests/External/ManagerTest.php @@ -46,13 +46,12 @@ class ManagerTest extends TestCase { use UserTrait; /** @var Manager **/ - private $manager; + private \OCA\Files_Sharing\External\Manager $manager; /** @var \OC\Files\Mount\Manager */ private $mountManager; - /** @var \PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; + private \PHPUnit\Framework\MockObject\MockObject $eventDispatcher; private $uid; @@ -60,7 +59,7 @@ class ManagerTest extends TestCase { * @var \OCP\IUser */ private $user; - private $mountProvider; + private \OCA\Files_Sharing\External\MountProvider $mountProvider; protected function setUp(): void { parent::setUp(); @@ -80,9 +79,7 @@ protected function setUp(): void { $eventDispatcher, $this->uid ); - $this->mountProvider = new MountProvider(\OC::$server->getDatabaseConnection(), function () { - return $this->manager; - }); + $this->mountProvider = new MountProvider(\OC::$server->getDatabaseConnection(), fn () => $this->manager); } private function setupMounts() { @@ -153,9 +150,7 @@ public function testAddShare() { ->withConsecutive( [ $this->callback( - function ($event) use ($openShares) { - return $this->verifyShareEvent($event, $openShares[0], AcceptShare::class); - } + fn ($event) => $this->verifyShareEvent($event, $openShares[0], AcceptShare::class) ), AcceptShare::class ], @@ -207,9 +202,7 @@ function ($event) use ($openShares) { ->withConsecutive( [ $this->callback( - function ($event) use ($openShares) { - return $this->verifyShareEvent($event, $openShares[1], DeclineShare::class); - } + fn ($event) => $this->verifyShareEvent($event, $openShares[1], DeclineShare::class) ), DeclineShare::class ], @@ -244,17 +237,13 @@ function ($event) use ($openShares) { ->withConsecutive( [ $this->callback( - function ($event) use ($openShares) { - return $this->verifyShareEvent($event, $openShares[0], DeclineShare::class); - } + fn ($event) => $this->verifyShareEvent($event, $openShares[0], DeclineShare::class) ), DeclineShare::class ], [ $this->callback( - function ($event) use ($acceptedShares) { - return $this->verifyShareEvent($event, $acceptedShares[0], DeclineShare::class); - } + fn ($event) => $this->verifyShareEvent($event, $acceptedShares[0], DeclineShare::class) ), DeclineShare::class ], @@ -315,18 +304,18 @@ protected function assertExternalShareEntry($expected, $actual, $share, $mountPo private function assertMount($mountPoint) { $mountPoint = \rtrim($mountPoint, '/'); $mount = $this->mountManager->find($this->getFullPath($mountPoint)); - $this->assertInstanceOf('\OCA\Files_Sharing\External\Mount', $mount); - $this->assertInstanceOf('\OCP\Files\Mount\IMountPoint', $mount); + $this->assertInstanceOf('\\' . \OCA\Files_Sharing\External\Mount::class, $mount); + $this->assertInstanceOf('\\' . \OCP\Files\Mount\IMountPoint::class, $mount); $this->assertEquals($this->getFullPath($mountPoint), \rtrim($mount->getMountPoint(), '/')); $storage = $mount->getStorage(); - $this->assertInstanceOf('\OCA\Files_Sharing\External\Storage', $storage); + $this->assertInstanceOf('\\' . \OCA\Files_Sharing\External\Storage::class, $storage); } private function assertNotMount($mountPoint) { $mountPoint = \rtrim($mountPoint, '/'); $mount = $this->mountManager->find($this->getFullPath($mountPoint)); if ($mount) { - $this->assertInstanceOf('\OCP\Files\Mount\IMountPoint', $mount); + $this->assertInstanceOf('\\' . \OCP\Files\Mount\IMountPoint::class, $mount); $this->assertNotEquals($this->getFullPath($mountPoint), \rtrim($mount->getMountPoint(), '/')); } else { $this->assertNull($mount); diff --git a/apps/files_sharing/tests/External/MountProviderTest.php b/apps/files_sharing/tests/External/MountProviderTest.php index f8236452d125..6d3d008afbb4 100644 --- a/apps/files_sharing/tests/External/MountProviderTest.php +++ b/apps/files_sharing/tests/External/MountProviderTest.php @@ -38,10 +38,9 @@ */ class MountProviderTest extends TestCase { /** @var IDBConnection */ - private $dbConnection; + private \PHPUnit\Framework\MockObject\MockObject $dbConnection; - /** @var MountProvider */ - private $mountProvider; + private \OCA\Files_Sharing\External\MountProvider $mountProvider; public function setUp(): void { parent::setUp(); diff --git a/apps/files_sharing/tests/External/ScanExternalSharesJobTest.php b/apps/files_sharing/tests/External/ScanExternalSharesJobTest.php index 1761f668fd4c..bea174bca552 100644 --- a/apps/files_sharing/tests/External/ScanExternalSharesJobTest.php +++ b/apps/files_sharing/tests/External/ScanExternalSharesJobTest.php @@ -45,10 +45,10 @@ */ class ScanExternalSharesJobTest extends TestCase { /** @var Manager */ - private $externalManager; + private \PHPUnit\Framework\MockObject\MockObject $externalManager; /** @var IUserManager */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IDBConnection */ private $connection; diff --git a/apps/files_sharing/tests/HooksTest.php b/apps/files_sharing/tests/HooksTest.php index b7e930015aa6..25b74c54a178 100644 --- a/apps/files_sharing/tests/HooksTest.php +++ b/apps/files_sharing/tests/HooksTest.php @@ -48,47 +48,44 @@ class HooksTest extends \Test\TestCase { /** * @var EventDispatcherInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; /** * @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** * @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** * @var IRootFolder | \PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; /** * @var \OCP\Share\IManager | \PHPUnit\Framework\MockObject\MockObject */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** * @var NotificationPublisher | \PHPUnit\Framework\MockObject\MockObject */ - private $notificationPublisher; + private \PHPUnit\Framework\MockObject\MockObject $notificationPublisher; /** * @var ActivityManager | \PHPUnit\Framework\MockObject\MockObject */ - private $activityManager; + private \PHPUnit\Framework\MockObject\MockObject $activityManager; /** * @var SharingAllowlist | \PHPUnit\Framework\MockObject\MockObject */ - private $sharingAllowlist; + private \PHPUnit\Framework\MockObject\MockObject $sharingAllowlist; - /** - * @var Hooks - */ - private $hooks; + private \OCA\Files_Sharing\Hooks $hooks; public function setUp(): void { $this->eventDispatcher = new EventDispatcher(); diff --git a/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php b/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php index 0f04f5ed7b94..c6b544671c75 100644 --- a/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php +++ b/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php @@ -34,24 +34,23 @@ */ class SharingCheckMiddlewareTest extends \Test\TestCase { /** @var \OCP\IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var \OCP\App\IAppManager */ - private $appManager; - /** @var SharingCheckMiddleware */ - private $sharingCheckMiddleware; + private \PHPUnit\Framework\MockObject\MockObject $appManager; + private \OCA\Files_Sharing\Middleware\SharingCheckMiddleware $sharingCheckMiddleware; /** @var \OCP\AppFramework\Controller */ - private $controllerMock; + private \PHPUnit\Framework\MockObject\MockObject $controllerMock; /** @var IControllerMethodReflector */ - private $reflector; + private \PHPUnit\Framework\MockObject\MockObject $reflector; protected function setUp(): void { - $this->config = $this->getMockBuilder('\OCP\IConfig') + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor()->getMock(); - $this->appManager = $this->getMockBuilder('\OCP\App\IAppManager') + $this->appManager = $this->getMockBuilder('\\' . \OCP\App\IAppManager::class) ->disableOriginalConstructor()->getMock(); - $this->controllerMock = $this->getMockBuilder('\OCP\AppFramework\Controller') + $this->controllerMock = $this->getMockBuilder('\\' . \OCP\AppFramework\Controller::class) ->disableOriginalConstructor()->getMock(); - $this->reflector = $this->getMockBuilder('\OCP\AppFramework\Utility\IControllerMethodReflector') + $this->reflector = $this->getMockBuilder('\\' . \OCP\AppFramework\Utility\IControllerMethodReflector::class) ->disableOriginalConstructor()->getMock(); $this->sharingCheckMiddleware = new SharingCheckMiddleware( @@ -188,7 +187,7 @@ public function testBeforeControllerWithExternalShareControllerWithSharingEnable ->method('getAppValue') ->will($this->returnValueMap($config)); - $controller = $this->getMockBuilder('\OCA\Files_Sharing\Controllers\ExternalSharesController') + $controller = $this->getMockBuilder('\\' . \OCA\Files_Sharing\Controllers\ExternalSharesController::class) ->disableOriginalConstructor()->getMock(); $exceptionThrown = false; @@ -218,7 +217,7 @@ public function testBeforeControllerWithShareControllerWithSharingEnabled() { ) ->willReturnOnConsecutiveCalls('yes', 'yes'); - $controller = $this->getMockBuilder('\OCA\Files_Sharing\Controllers\ShareController') + $controller = $this->getMockBuilder('\\' . \OCA\Files_Sharing\Controllers\ShareController::class) ->disableOriginalConstructor()->getMock(); $this->sharingCheckMiddleware->beforeController($controller, 'myMethod'); @@ -236,7 +235,7 @@ public function testBeforeControllerWithShareControllerWithSharingEnabledAPIDisa ->with('files_sharing') ->will($this->returnValue(true)); - $controller = $this->getMockBuilder('\OCA\Files_Sharing\Controllers\ShareController') + $controller = $this->getMockBuilder('\\' . \OCA\Files_Sharing\Controllers\ShareController::class) ->disableOriginalConstructor()->getMock(); $this->sharingCheckMiddleware->beforeController($controller, 'myMethod'); diff --git a/apps/files_sharing/tests/MigrationTest.php b/apps/files_sharing/tests/MigrationTest.php index fc70ff75d879..87e105f6faca 100644 --- a/apps/files_sharing/tests/MigrationTest.php +++ b/apps/files_sharing/tests/MigrationTest.php @@ -36,10 +36,9 @@ class MigrationTest extends TestCase { /** @var \OCP\IDBConnection */ private $connection; - /** @var Migration */ - private $migration; + private \OCA\Files_Sharing\Migration $migration; - private $table = 'share'; + private string $table = 'share'; public function setUp(): void { parent::setUp(); diff --git a/apps/files_sharing/tests/MountProviderTest.php b/apps/files_sharing/tests/MountProviderTest.php index 32ad3bcd414e..614e3b870d23 100644 --- a/apps/files_sharing/tests/MountProviderTest.php +++ b/apps/files_sharing/tests/MountProviderTest.php @@ -36,32 +36,31 @@ * @group DB */ class MountProviderTest extends \Test\TestCase { - /** @var MountProvider */ - private $provider; + private \OCA\Files_Sharing\MountProvider $provider; /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var IStorageFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $loader; + private \PHPUnit\Framework\MockObject\MockObject $loader; /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('OCP\IConfig'); - $this->user = $this->createMock('OCP\IUser'); - $this->loader = $this->createMock('OCP\Files\Storage\IStorageFactory'); - $this->shareManager = $this->createMock('\OCP\Share\IManager'); - $this->logger = $this->createMock('\OCP\ILogger'); + $this->config = $this->createMock(\OCP\IConfig::class); + $this->user = $this->createMock(\OCP\IUser::class); + $this->loader = $this->createMock(\OCP\Files\Storage\IStorageFactory::class); + $this->shareManager = $this->createMock('\\' . \OCP\Share\IManager::class); + $this->logger = $this->createMock('\\' . \OCP\ILogger::class); $this->provider = new MountProvider($this->config, $this->shareManager, $this->logger); } @@ -111,7 +110,7 @@ private function makeMockShare($id, $nodeId, $owner = 'user2', $target = null, $ ->method('getShareTime') ->will($this->returnValue( // compute share time based on id, simulating share order - new \DateTime('@' . (1469193980 + 1000 * $id)) + new \DateTime('@' . (1_469_193_980 + 1000 * $id)) )); if ($state === null) { @@ -131,8 +130,8 @@ private function makeMockShare($id, $nodeId, $owner = 'user2', $target = null, $ * - pending shares */ public function testExcludeShares() { - $rootFolder = $this->createMock('\OCP\Files\IRootFolder'); - $userManager = $this->createMock('\OCP\IUserManager'); + $rootFolder = $this->createMock('\\' . \OCP\Files\IRootFolder::class); + $userManager = $this->createMock('\\' . \OCP\IUserManager::class); $attr1 = []; $attr2 = [["scope" => "permission", "key" => "download", "enabled" => true]]; @@ -149,7 +148,7 @@ public function testExcludeShares() { $this->makeMockShare(5, 100, 'user1', '/share4', 31, $attr2), ]; - $userGroupUserShares = \array_merge($userShares, $groupShares); + $userGroupUserShares = [...$userShares, ...$groupShares]; $this->user->expects($this->any()) ->method('getUID') @@ -164,9 +163,7 @@ public function testExcludeShares() { ->method('getSharedWith'); $this->shareManager->expects($this->any()) ->method('newShare') - ->will($this->returnCallback(function () use ($rootFolder, $userManager) { - return new \OC\Share20\Share($rootFolder, $userManager); - })); + ->will($this->returnCallback(fn () => new \OC\Share20\Share($rootFolder, $userManager))); $storage = $this->createMock(Storage::class); $storage->method('getPermissions')->willReturn(1); @@ -175,8 +172,8 @@ public function testExcludeShares() { $mounts = $this->provider->getMountsForUser($this->user, $this->loader); $this->assertCount(2, $mounts); - $this->assertInstanceOf('OCA\Files_Sharing\SharedMount', $mounts[0]); - $this->assertInstanceOf('OCA\Files_Sharing\SharedMount', $mounts[1]); + $this->assertInstanceOf(\OCA\Files_Sharing\SharedMount::class, $mounts[0]); + $this->assertInstanceOf(\OCA\Files_Sharing\SharedMount::class, $mounts[1]); $mountedShare1 = $mounts[0]->getShare(); @@ -197,8 +194,8 @@ public function testExcludeShares() { } public function testShareFailedStorage() { - $rootFolder = $this->createMock('\OCP\Files\IRootFolder'); - $userManager = $this->createMock('\OCP\IUserManager'); + $rootFolder = $this->createMock('\\' . \OCP\Files\IRootFolder::class); + $userManager = $this->createMock('\\' . \OCP\IUserManager::class); $attr2 = [["scope" => "permission", "key" => "download", "enabled" => true]]; $share = $this->makeMockShare(2, 100, 'user2', '/share2', 31, $attr2); @@ -216,14 +213,12 @@ public function testShareFailedStorage() { ->method('getSharedWith'); $this->shareManager->expects($this->any()) ->method('newShare') - ->will($this->returnCallback(function () use ($rootFolder, $userManager) { - return new \OC\Share20\Share($rootFolder, $userManager); - })); + ->will($this->returnCallback(fn () => new \OC\Share20\Share($rootFolder, $userManager))); $storage = $this->createMock(Storage::class); $storage->method('getPermissions')->willReturn(0); $this->loader->method('getInstance') - ->with($this->anything(), '\OCA\Files_Sharing\SharedStorage', $this->anything()) + ->with($this->anything(), '\\' . \OCA\Files_Sharing\SharedStorage::class, $this->anything()) ->willReturn($storage); $mounts = $this->provider->getMountsForUser($this->user, $this->loader); @@ -376,15 +371,11 @@ public function mergeSharesDataProvider() { * @param array $expectedShares array of expected supershare specs */ public function testMergeShares($userShares, $groupShares, $expectedShares, $moveFails = false) { - $rootFolder = $this->createMock('\OCP\Files\IRootFolder'); - $userManager = $this->createMock('\OCP\IUserManager'); + $rootFolder = $this->createMock('\\' . \OCP\Files\IRootFolder::class); + $userManager = $this->createMock('\\' . \OCP\IUserManager::class); - $userShares = \array_map(function ($shareSpec) { - return $this->makeMockShare($shareSpec[0], $shareSpec[1], $shareSpec[2], $shareSpec[3], $shareSpec[4], $shareSpec[5]); - }, $userShares); - $groupShares = \array_map(function ($shareSpec) { - return $this->makeMockShare($shareSpec[0], $shareSpec[1], $shareSpec[2], $shareSpec[3], $shareSpec[4], $shareSpec[5]); - }, $groupShares); + $userShares = \array_map(fn ($shareSpec) => $this->makeMockShare($shareSpec[0], $shareSpec[1], $shareSpec[2], $shareSpec[3], $shareSpec[4], $shareSpec[5]), $userShares); + $groupShares = \array_map(fn ($shareSpec) => $this->makeMockShare($shareSpec[0], $shareSpec[1], $shareSpec[2], $shareSpec[3], $shareSpec[4], $shareSpec[5]), $groupShares); $this->user->expects($this->any()) ->method('getUID') @@ -402,9 +393,7 @@ public function testMergeShares($userShares, $groupShares, $expectedShares, $mov $this->shareManager->expects($this->any()) ->method('newShare') - ->will($this->returnCallback(function () use ($rootFolder, $userManager) { - return new \OC\Share20\Share($rootFolder, $userManager); - })); + ->will($this->returnCallback(fn () => new \OC\Share20\Share($rootFolder, $userManager))); if ($moveFails) { $this->shareManager->expects($this->any()) @@ -422,7 +411,7 @@ public function testMergeShares($userShares, $groupShares, $expectedShares, $mov foreach ($mounts as $index => $mount) { $expectedShare = $expectedShares[$index]; - $this->assertInstanceOf('OCA\Files_Sharing\SharedMount', $mount); + $this->assertInstanceOf(\OCA\Files_Sharing\SharedMount::class, $mount); // supershare $share = $mount->getShare(); diff --git a/apps/files_sharing/tests/NotifierTest.php b/apps/files_sharing/tests/NotifierTest.php index d0fc576476ca..9b4dd77f5189 100644 --- a/apps/files_sharing/tests/NotifierTest.php +++ b/apps/files_sharing/tests/NotifierTest.php @@ -33,25 +33,22 @@ use OCP\IUser; class NotifierTest extends \Test\TestCase { - /** - * @var Notifier - */ - private $notifier; + private \OCA\Files_Sharing\Notifier $notifier; /** @var INotificationManager */ - private $notificationManager; + private \PHPUnit\Framework\MockObject\MockObject $notificationManager; /** @var IShareManager */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** @var IGroupManager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var IUserManager */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); diff --git a/apps/files_sharing/tests/Panels/Admin/SettingsPanelTest.php b/apps/files_sharing/tests/Panels/Admin/SettingsPanelTest.php index f5b9c9b3a1f4..92953dd30175 100644 --- a/apps/files_sharing/tests/Panels/Admin/SettingsPanelTest.php +++ b/apps/files_sharing/tests/Panels/Admin/SettingsPanelTest.php @@ -26,13 +26,13 @@ class SettingsPanelTest extends \Test\TestCase { /** @var SharingBlacklist | \PHPUnit\Framework\MockObject\MockObject */ - private $sharingBlacklist; + private \PHPUnit\Framework\MockObject\MockObject $sharingBlacklist; /** @var SharingAllowlist | \PHPUnit\Framework\MockObject\MockObject */ - private $sharingAllowlist; + private \PHPUnit\Framework\MockObject\MockObject $sharingAllowlist; /** @var SettingsPanel | \PHPUnit\Framework\MockObject\MockObject */ - private $settingsPanel; + private \OCA\Files_Sharing\Panels\Admin\SettingsPanel $settingsPanel; protected function setUp(): void { $this->sharingBlacklist = $this->getMockBuilder(SharingBlacklist::class) diff --git a/apps/files_sharing/tests/Panels/Personal/PersonalPanelTest.php b/apps/files_sharing/tests/Panels/Personal/PersonalPanelTest.php index 64a3dc312fe5..8fcb727f62fe 100644 --- a/apps/files_sharing/tests/Panels/Personal/PersonalPanelTest.php +++ b/apps/files_sharing/tests/Panels/Personal/PersonalPanelTest.php @@ -28,16 +28,15 @@ class PersonalPanelTest extends \Test\TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject $config */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject $userSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject $l10n */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; - /** @var PersonalPanel $personalPanel */ - private $personalPanel; + private \OCA\Files_Sharing\Panels\Personal\PersonalPanel $personalPanel; protected function setUp(): void { $this->config = $this->getMockBuilder(IConfig::class) diff --git a/apps/files_sharing/tests/Panels/Personal/SectionTest.php b/apps/files_sharing/tests/Panels/Personal/SectionTest.php index a8a91a38dd35..6610e0676aa6 100644 --- a/apps/files_sharing/tests/Panels/Personal/SectionTest.php +++ b/apps/files_sharing/tests/Panels/Personal/SectionTest.php @@ -25,10 +25,9 @@ class SectionTest extends \Test\TestCase { /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject $l */ - private $l; + private \PHPUnit\Framework\MockObject\MockObject $l; - /** @var Section $section */ - private $section; + private \OCA\Files_Sharing\Panels\Personal\Section $section; protected function setUp(): void { $this->l = $this->getMockBuilder(IL10N::class) diff --git a/apps/files_sharing/tests/PermissionsTest.php b/apps/files_sharing/tests/PermissionsTest.php index 4629e292b946..6c163d1dd26d 100644 --- a/apps/files_sharing/tests/PermissionsTest.php +++ b/apps/files_sharing/tests/PermissionsTest.php @@ -42,8 +42,7 @@ class PermissionsTest extends TestCase { /** @var Storage */ private $sharedCacheRestrictedShare; - /** @var View */ - private $secondView; + private \OC\Files\View $secondView; /** @var Storage */ private $ownerStorage; @@ -72,7 +71,7 @@ protected function setUp(): void { $this->view->file_put_contents('container/shareddir/textfile.txt', $textData); $this->view->file_put_contents('container/shareddirrestricted/textfile1.txt', $textData); - list($this->ownerStorage, $internalPath) = $this->view->resolvePath(''); + [$this->ownerStorage, $internalPath] = $this->view->resolvePath(''); $this->ownerCache = $this->ownerStorage->getCache(); $this->ownerStorage->getScanner()->scan(''); @@ -102,8 +101,8 @@ protected function setUp(): void { // retrieve the shared storage $this->secondView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2); - list($this->sharedStorage, $internalPath) = $this->secondView->resolvePath('files/shareddir'); - list($this->sharedStorageRestrictedShare, $internalPath) = $this->secondView->resolvePath('files/shareddirrestricted'); + [$this->sharedStorage, $internalPath] = $this->secondView->resolvePath('files/shareddir'); + [$this->sharedStorageRestrictedShare, $internalPath] = $this->secondView->resolvePath('files/shareddirrestricted'); $this->sharedCache = $this->sharedStorage->getCache(); $this->sharedCacheRestrictedShare = $this->sharedStorageRestrictedShare->getCache(); } diff --git a/apps/files_sharing/tests/PropagationTestCase.php b/apps/files_sharing/tests/PropagationTestCase.php index d892db7dcd23..24b098ff56c3 100644 --- a/apps/files_sharing/tests/PropagationTestCase.php +++ b/apps/files_sharing/tests/PropagationTestCase.php @@ -44,7 +44,7 @@ protected function tearDown(): void { \OC_Hook::clear('OC_Filesystem', 'post_write'); \OC_Hook::clear('OC_Filesystem', 'post_delete'); \OC_Hook::clear('OC_Filesystem', 'post_rename'); - \OC_Hook::clear('OCP\Share', 'post_update_permissions'); + \OC_Hook::clear(\OCP\Share::class, 'post_update_permissions'); parent::tearDown(); } diff --git a/apps/files_sharing/tests/Service/NotificationPublisherTest.php b/apps/files_sharing/tests/Service/NotificationPublisherTest.php index 3e3345f2ba9c..167f3e410065 100644 --- a/apps/files_sharing/tests/Service/NotificationPublisherTest.php +++ b/apps/files_sharing/tests/Service/NotificationPublisherTest.php @@ -36,25 +36,24 @@ */ class NotificationPublisherTest extends TestCase { /** @var IGroupManager | \PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var \OCP\Notification\IManager | \PHPUnit\Framework\MockObject\MockObject */ - private $notificationManager; + private \PHPUnit\Framework\MockObject\MockObject $notificationManager; /** @var IURLGenerator */ private $urlGenerator; - /** @var NotificationPublisher */ - private $publisher; + private \OCA\Files_Sharing\Service\NotificationPublisher $publisher; protected function setUp(): void { - $this->groupManager = $this->createMock('OCP\IGroupManager'); - $this->userManager = $this->createMock('OCP\IUserManager'); + $this->groupManager = $this->createMock(\OCP\IGroupManager::class); + $this->userManager = $this->createMock(\OCP\IUserManager::class); $this->notificationManager = $this->createMock(\OCP\Notification\IManager::class); - $this->urlGenerator = $this->createMock('OCP\IURLGenerator'); + $this->urlGenerator = $this->createMock(\OCP\IURLGenerator::class); $this->publisher = new NotificationPublisher( $this->notificationManager, diff --git a/apps/files_sharing/tests/SharedMountTest.php b/apps/files_sharing/tests/SharedMountTest.php index 99ddc4c8b555..4f1dd9ed00c3 100644 --- a/apps/files_sharing/tests/SharedMountTest.php +++ b/apps/files_sharing/tests/SharedMountTest.php @@ -440,7 +440,7 @@ public function testIsTargetAllowed() { $caught = $e; } - $this->assertInstanceOf('\OCP\Files\NotPermittedException', $e); + $this->assertInstanceOf('\\' . \OCP\Files\NotPermittedException::class, $e); } $this->shareManager->deleteShare($share); diff --git a/apps/files_sharing/tests/SharedStorageTest.php b/apps/files_sharing/tests/SharedStorageTest.php index d9731e8ce554..2c559c7087ad 100644 --- a/apps/files_sharing/tests/SharedStorageTest.php +++ b/apps/files_sharing/tests/SharedStorageTest.php @@ -100,7 +100,7 @@ public function testParentOfMountPointIsGone() { // delete the local folder /** @var \OC\Files\Storage\Storage $storage */ - list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/localfolder'); + [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/localfolder'); $storage->rmdir($internalPath); //enforce reload of the mount points @@ -436,8 +436,8 @@ public function testCopyFromStorage() { /** * @var \OCP\Files\Storage $sharedStorage */ - list($sharedStorage, ) = $view->resolvePath($this->folder); - $this->assertTrue($sharedStorage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')); + [$sharedStorage, ] = $view->resolvePath($this->folder); + $this->assertTrue($sharedStorage->instanceOfStorage(\OCA\Files_Sharing\ISharedStorage::class)); $sourceStorage = new \OC\Files\Storage\Temporary([]); $sourceStorage->file_put_contents('foo.txt', 'asd'); @@ -469,8 +469,8 @@ public function testMoveFromStorage() { /** * @var \OCP\Files\Storage $sharedStorage */ - list($sharedStorage, ) = $view->resolvePath($this->folder); - $this->assertTrue($sharedStorage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')); + [$sharedStorage, ] = $view->resolvePath($this->folder); + $this->assertTrue($sharedStorage->instanceOfStorage(\OCA\Files_Sharing\ISharedStorage::class)); $sourceStorage = new \OC\Files\Storage\Temporary([]); $sourceStorage->file_put_contents('foo.txt', 'asd'); @@ -523,7 +523,7 @@ public function testNameConflict() { $this->assertTrue($view2->file_exists('/foo (2)')); $mount = $view2->getMount('/foo'); - $this->assertInstanceOf('\OCA\Files_Sharing\SharedMount', $mount); + $this->assertInstanceOf('\\' . \OCA\Files_Sharing\SharedMount::class, $mount); /** @var \OCA\Files_Sharing\SharedStorage $storage */ $storage = $mount->getStorage(); @@ -555,7 +555,7 @@ public function testLongLock() { $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files'); $this->assertTrue($user2View->file_exists($fn . '/vincent/' . $fn)); - list($sharedStorage, $bla) = $user2View->resolvePath($fn . '/vincent/' . $fn); + [$sharedStorage, $bla] = $user2View->resolvePath($fn . '/vincent/' . $fn); $cache = $sharedStorage->getCache(); $scanner = $sharedStorage->getScanner(); $scanner->scan(''); diff --git a/apps/files_sharing/tests/SharingAllowlistTest.php b/apps/files_sharing/tests/SharingAllowlistTest.php index 0dd7ae5af017..1aa2e39b7c3e 100644 --- a/apps/files_sharing/tests/SharingAllowlistTest.php +++ b/apps/files_sharing/tests/SharingAllowlistTest.php @@ -28,13 +28,13 @@ class SharingAllowlistTest extends \Test\TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IGroupManager | \PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var SharingAllowlist | \PHPUnit\Framework\MockObject\MockObject */ - private $sharingAllowlist; + private \OCA\Files_Sharing\SharingAllowlist $sharingAllowlist; public function setUp(): void { $this->config = $this->getMockBuilder(IConfig::class) diff --git a/apps/files_sharing/tests/SharingBlacklistTest.php b/apps/files_sharing/tests/SharingBlacklistTest.php index dc0515d04a0f..3cb96b0b0704 100644 --- a/apps/files_sharing/tests/SharingBlacklistTest.php +++ b/apps/files_sharing/tests/SharingBlacklistTest.php @@ -27,10 +27,10 @@ class SharingBlacklistTest extends \Test\TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var SharingBlacklist | \PHPUnit\Framework\MockObject\MockObject */ - private $sharingBlacklist; + private \OCA\Files_Sharing\SharingBlacklist $sharingBlacklist; public function setUp(): void { $this->config = $this->getMockBuilder(IConfig::class) @@ -60,7 +60,7 @@ public function testSetGetBlacklistedReceiverGroups($ids) { $this->config->method('getAppValue') ->will($this->returnCallback(function ($app, $key, $default) use (&$keyValues) { - return (isset($keyValues[$key])) ? $keyValues[$key] : $default; + return $keyValues[$key] ?? $default; })); $this->sharingBlacklist->setBlacklistedReceiverGroups($ids); diff --git a/apps/files_sharing/tests/SizePropagationTest.php b/apps/files_sharing/tests/SizePropagationTest.php index 732db2791b05..a2d4918bfb7b 100644 --- a/apps/files_sharing/tests/SizePropagationTest.php +++ b/apps/files_sharing/tests/SizePropagationTest.php @@ -42,7 +42,7 @@ class SizePropagationTest extends TestCase { protected function setupUser($name) { $this->createUser($name); $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); + $this->registerMount($name, '\\' . \OC\Files\Storage\Local::class, '/' . $name, ['datadir' => $tmpFolder]); self::loginAsUser($name); return new View('/' . $name . '/files'); } diff --git a/apps/files_sharing/tests/TestCase.php b/apps/files_sharing/tests/TestCase.php index 0ab286ed7dfc..4bdfc2981499 100644 --- a/apps/files_sharing/tests/TestCase.php +++ b/apps/files_sharing/tests/TestCase.php @@ -69,7 +69,7 @@ abstract class TestCase extends \Test\TestCase { /** @var \OCP\Files\IRootFolder */ protected $rootFolder; - private static $alreadyRegistered = false; + private static bool $alreadyRegistered = false; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); @@ -85,7 +85,7 @@ public static function setUpBeforeClass(): void { \OC::$server->getGroupManager()->clearBackends(); // clear share hooks - \OC_Hook::clear('OCP\\Share'); + \OC_Hook::clear(\OCP\Share::class); \OC::registerShareHooks(); } diff --git a/apps/files_sharing/tests/UnshareChildrenTest.php b/apps/files_sharing/tests/UnshareChildrenTest.php index f40c29c27ebd..b089d539c879 100644 --- a/apps/files_sharing/tests/UnshareChildrenTest.php +++ b/apps/files_sharing/tests/UnshareChildrenTest.php @@ -43,7 +43,7 @@ class UnshareChildrenTest extends TestCase { protected function setUp(): void { parent::setUp(); - \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren'); + \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\\' . \OCA\Files_Sharing\Hooks::class, 'unshareChildren'); $this->folder = self::TEST_FOLDER_NAME; $this->subfolder = '/subfolder_share_api_test'; diff --git a/apps/files_sharing/tests/WatcherTest.php b/apps/files_sharing/tests/WatcherTest.php index a8c4bfe2a867..238ffdb19303 100644 --- a/apps/files_sharing/tests/WatcherTest.php +++ b/apps/files_sharing/tests/WatcherTest.php @@ -59,7 +59,7 @@ protected function setUp(): void { $this->view->mkdir('container/shareddir'); $this->view->mkdir('container/shareddir/subdir'); - list($this->ownerStorage, $internalPath) = $this->view->resolvePath(''); + [$this->ownerStorage, $internalPath] = $this->view->resolvePath(''); $this->ownerCache = $this->ownerStorage->getCache(); $this->ownerStorage->getScanner()->scan(''); @@ -77,7 +77,7 @@ protected function setUp(): void { // retrieve the shared storage $secondView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2); - list($this->sharedStorage, $internalPath) = $secondView->resolvePath('files/shareddir'); + [$this->sharedStorage, $internalPath] = $secondView->resolvePath('files/shareddir'); $this->sharedCache = $this->sharedStorage->getCache(); } diff --git a/apps/files_trashbin/ajax/delete.php b/apps/files_trashbin/ajax/delete.php index 7a12fcc326cf..e5b07097005d 100644 --- a/apps/files_trashbin/ajax/delete.php +++ b/apps/files_trashbin/ajax/delete.php @@ -28,7 +28,7 @@ OCP\JSON::callCheck(); \OC::$server->getSession()->close(); -$folder = isset($_POST['dir']) ? $_POST['dir'] : '/'; +$folder = $_POST['dir'] ?? '/'; // "empty trash" command if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true') { @@ -43,7 +43,7 @@ } else { $deleteAll = false; $files = (string)$_POST['files']; - $list = \json_decode($files); + $list = \json_decode($files, null, 512, JSON_THROW_ON_ERROR); } $folder = \rtrim($folder, '/') . '/'; diff --git a/apps/files_trashbin/ajax/undelete.php b/apps/files_trashbin/ajax/undelete.php index 4bf2a542ba69..f6c53f917715 100644 --- a/apps/files_trashbin/ajax/undelete.php +++ b/apps/files_trashbin/ajax/undelete.php @@ -49,7 +49,7 @@ $list[] = $fileName; } } else { - $list = \json_decode($files); + $list = \json_decode($files, null, 512, JSON_THROW_ON_ERROR); } $error = []; diff --git a/apps/files_trashbin/appinfo/app.php b/apps/files_trashbin/appinfo/app.php index 0e94d98178dc..2abd5331ea7e 100644 --- a/apps/files_trashbin/appinfo/app.php +++ b/apps/files_trashbin/appinfo/app.php @@ -28,7 +28,7 @@ // register hooks \OCA\Files_Trashbin\Trashbin::registerHooks(); -if (\class_exists('OCA\Files\App')) { +if (\class_exists(\OCA\Files\App::class)) { \OCA\Files\App::getNavigationManager()->add(function () { $l = \OC::$server->getL10N('files_trashbin'); return [ diff --git a/apps/files_trashbin/lib/AppInfo/Application.php b/apps/files_trashbin/lib/AppInfo/Application.php index f0c1a37bd04e..d141ab4cbe89 100644 --- a/apps/files_trashbin/lib/AppInfo/Application.php +++ b/apps/files_trashbin/lib/AppInfo/Application.php @@ -35,38 +35,32 @@ public function __construct(array $urlParams = []) { /* * Register capabilities */ - $container->registerCapability('OCA\Files_Trashbin\Capabilities'); + $container->registerCapability(\OCA\Files_Trashbin\Capabilities::class); /* * Register expiration */ - $container->registerService('Expiration', function ($c) { - return new Expiration( - $c->query('ServerContainer')->getConfig(), - $c->query('OCP\AppFramework\Utility\ITimeFactory') - ); - }); + $container->registerService('Expiration', fn ($c) => new Expiration( + $c->query('ServerContainer')->getConfig(), + $c->query(\OCP\AppFramework\Utility\ITimeFactory::class) + )); /* * Register quota */ - $container->registerService('Quota', function ($c) { - return new Quota( - $c->getServer()->getUserManager(), - $c->query('ServerContainer')->getConfig() - ); - }); + $container->registerService('Quota', fn ($c) => new Quota( + $c->getServer()->getUserManager(), + $c->query('ServerContainer')->getConfig() + )); /* * Register trashbin service */ - $container->registerService('Trashbin', function ($c) { - return new Trashbin( - $c->getServer()->getLazyRootFolder(), - $c->getServer()->getUrlGenerator(), - $c->getServer()->getEventDispatcher() - ); - }); + $container->registerService('Trashbin', fn ($c) => new Trashbin( + $c->getServer()->getLazyRootFolder(), + $c->getServer()->getUrlGenerator(), + $c->getServer()->getEventDispatcher() + )); } public function registerListeners() { diff --git a/apps/files_trashbin/lib/BackgroundJob/ExpireTrash.php b/apps/files_trashbin/lib/BackgroundJob/ExpireTrash.php index 778b79ae0e0b..fe35919d01d4 100644 --- a/apps/files_trashbin/lib/BackgroundJob/ExpireTrash.php +++ b/apps/files_trashbin/lib/BackgroundJob/ExpireTrash.php @@ -34,15 +34,9 @@ use OCP\IUserManager; class ExpireTrash extends TimedJob { - /** - * @var IConfig - */ - private $config; + private ?\OCP\IConfig $config = null; - /** - * @var TrashExpiryManager - */ - private $trashExpiryManager; + private ?\OCA\Files_Trashbin\TrashExpiryManager $trashExpiryManager = null; /** * @var IUserManager diff --git a/apps/files_trashbin/lib/Command/ExpireTrash.php b/apps/files_trashbin/lib/Command/ExpireTrash.php index 9e30990b350a..3bf307f97765 100644 --- a/apps/files_trashbin/lib/Command/ExpireTrash.php +++ b/apps/files_trashbin/lib/Command/ExpireTrash.php @@ -32,15 +32,9 @@ use Symfony\Component\Console\Output\OutputInterface; class ExpireTrash extends Command { - /** - * @var TrashExpiryManager - */ - private $trashExpiryManager; + private ?\OCA\Files_Trashbin\TrashExpiryManager $trashExpiryManager = null; - /** - * @var IUserManager - */ - private $userManager; + private ?\OCP\IUserManager $userManager = null; /** * @param IUserManager|null $userManager diff --git a/apps/files_trashbin/lib/Expiration.php b/apps/files_trashbin/lib/Expiration.php index 012a7db29567..155901c8b0cd 100644 --- a/apps/files_trashbin/lib/Expiration.php +++ b/apps/files_trashbin/lib/Expiration.php @@ -30,20 +30,16 @@ class Expiration { public const DEFAULT_RETENTION_OBLIGATION = 30; public const NO_OBLIGATION = -1; - /** @var ITimeFactory */ - private $timeFactory; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; /** @var string */ private $retentionObligation; - /** @var int */ - private $minAge; + private ?int $minAge = null; - /** @var int */ - private $maxAge; + private ?int $maxAge = null; - /** @var bool */ - private $canPurgeToSaveSpace; + private ?bool $canPurgeToSaveSpace = null; public function __construct(IConfig $config, ITimeFactory $timeFactory) { $this->timeFactory = $timeFactory; diff --git a/apps/files_trashbin/lib/Storage.php b/apps/files_trashbin/lib/Storage.php index 5012ce320655..15aeeb8e0be9 100644 --- a/apps/files_trashbin/lib/Storage.php +++ b/apps/files_trashbin/lib/Storage.php @@ -34,7 +34,7 @@ class Storage extends Wrapper { private $mountPoint; // remember already deleted files to avoid infinite loops if the trash bin // move files across storages - private $deletedFiles = []; + private array $deletedFiles = []; /** * Disable trash logic @@ -46,11 +46,9 @@ class Storage extends Wrapper { */ public static $disableTrash = false; - /** @var IUserManager */ - private $userManager; + private ?\OCP\IUserManager $userManager = null; - /** @var TrashbinSkipChecker */ - private $trashbinSkipChecker; + private ?\OCA\Files_Trashbin\TrashbinSkipChecker $trashbinSkipChecker = null; public function __construct($parameters, IUserManager $userManager = null, TrashbinSkipChecker $trashbinSkipChecker = null) { $this->mountPoint = $parameters['mountPoint']; @@ -79,7 +77,7 @@ public static function preRenameHook($params) { $targetStorage = $mount2->getStorage(); $sourceInternalPath = $mount1->getInternalPath($absolutePath1); // check whether this is a cross-storage move from a *local* shared storage - if ($sourceInternalPath !== '' && $sourceStorage !== $targetStorage && $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')) { + if ($sourceInternalPath !== '' && $sourceStorage !== $targetStorage && $sourceStorage->instanceOfStorage(\OCA\Files_Sharing\SharedStorage::class)) { '@phan-var \OCA\Files_Sharing\SharedStorage $sourceStorage'; $ownerPath = $sourceStorage->getSourcePath($sourceInternalPath); $owner = $sourceStorage->getOwner($sourceInternalPath); @@ -240,15 +238,13 @@ public function retainKeys($filename, $owner, $ownerPath, $timestamp, $sourceSto * Setup the storage wrapper callback */ public static function setupStorage() { - \OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) { - return new \OCA\Files_Trashbin\Storage( - ['storage' => $storage, 'mountPoint' => $mountPoint], - \OC::$server->getUserManager(), - new TrashbinSkipChecker( - \OC::$server->getLogger(), - \OC::$server->getConfig() - ) - ); - }, 1); + \OC\Files\Filesystem::addStorageWrapper('oc_trashbin', fn ($mountPoint, $storage) => new \OCA\Files_Trashbin\Storage( + ['storage' => $storage, 'mountPoint' => $mountPoint], + \OC::$server->getUserManager(), + new TrashbinSkipChecker( + \OC::$server->getLogger(), + \OC::$server->getConfig() + ) + ), 1); } } diff --git a/apps/files_trashbin/lib/TrashExpiryManager.php b/apps/files_trashbin/lib/TrashExpiryManager.php index 9499b7851b07..69a1e8353a6c 100644 --- a/apps/files_trashbin/lib/TrashExpiryManager.php +++ b/apps/files_trashbin/lib/TrashExpiryManager.php @@ -26,13 +26,13 @@ class TrashExpiryManager { /* @var Expiration */ - private $expiration; + private \OCA\Files_Trashbin\Expiration $expiration; /* @var Quota */ - private $quota; + private \OCA\Files_Trashbin\Quota $quota; /* @var ILogger */ - private $logger; + private \OCP\ILogger $logger; public function __construct( Expiration $expiration, diff --git a/apps/files_trashbin/lib/Trashbin.php b/apps/files_trashbin/lib/Trashbin.php index cf6514aec6d3..13e8835bec25 100644 --- a/apps/files_trashbin/lib/Trashbin.php +++ b/apps/files_trashbin/lib/Trashbin.php @@ -54,20 +54,11 @@ use Symfony\Component\EventDispatcher\EventDispatcher; class Trashbin { - /** - * @var IURLGenerator - */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; - /** - * @var IRootFolder - */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; - /** - * @var EventDispatcher - */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; public function __construct( IRootFolder $rootFolder, @@ -80,11 +71,9 @@ public function __construct( } /** - * Whether versions have already be rescanned during this PHP request - * - * @var bool - */ - private static $scannedVersions = false; + * Whether versions have already be rescanned during this PHP request + */ + private static bool $scannedVersions = false; /** * Ensure we don't need to scan the file during the move to trash @@ -280,8 +269,8 @@ public static function insertTrashEntry($user, $targetFilename, $targetLocation, public static function move2trash($file_path) { // get the user for which the filesystem is setup $root = Filesystem::getRoot(); - list(, $user) = \explode('/', $root); - list($owner, $ownerPath) = self::getUidAndFilename($file_path); + [, $user] = \explode('/', $root); + [$owner, $ownerPath] = self::getUidAndFilename($file_path); // if no owner found (ex: ext storage + share link), will use the current user's trashbin then if ($owner === null) { @@ -317,9 +306,9 @@ public static function move2trash($file_path) { $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp; /** @var \OC\Files\Storage\Storage $trashStorage */ - list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath); + [$trashStorage, $trashInternalPath] = $ownerView->resolvePath($trashPath); /** @var \OC\Files\Storage\Storage $sourceStorage */ - list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath); + [$sourceStorage, $sourceInternalPath] = $ownerView->resolvePath('/files/' . $ownerPath); try { $moveSuccessful = true; if ($trashStorage->file_exists($trashInternalPath)) { @@ -351,7 +340,7 @@ public static function move2trash($file_path) { if (!$result) { \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR); } - \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path), + \OCP\Util::emitHook('\\' . \OCA\Files_Trashbin\Trashbin::class, 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path), 'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)]); self::retainVersions($filename, $owner, $ownerPath, $timestamp, $sourceStorage); @@ -479,9 +468,9 @@ private static function retainVersions($filename, $owner, $ownerPath, $timestamp */ private static function move(View $view, $source, $target) { /** @var \OC\Files\Storage\Storage $sourceStorage */ - list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); + [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source); /** @var \OC\Files\Storage\Storage $targetStorage */ - list($targetStorage, $targetInternalPath) = $view->resolvePath($target); + [$targetStorage, $targetInternalPath] = $view->resolvePath($target); /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); @@ -501,9 +490,9 @@ private static function move(View $view, $source, $target) { */ private static function copy(View $view, $source, $target) { /** @var \OC\Files\Storage\Storage $sourceStorage */ - list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source); + [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source); /** @var \OC\Files\Storage\Storage $targetStorage */ - list($targetStorage, $targetInternalPath) = $view->resolvePath($target); + [$targetStorage, $targetInternalPath] = $view->resolvePath($target); /** @var \OC\Files\Storage\Storage $ownerTrashStorage */ $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath); @@ -592,7 +581,7 @@ public static function restore($filename, $targetLocation = null) { $view->chroot('/' . $user . '/files'); $view->touch('/' . $targetLocation, $mtime); $view->chroot($fakeRoot); - \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => Filesystem::normalizePath('/' . $targetLocation), + \OCP\Util::emitHook('\\' . \OCA\Files_Trashbin\Trashbin::class, 'post_restore', ['filePath' => Filesystem::normalizePath('/' . $targetLocation), 'trashPath' => Filesystem::normalizePath($filename)]); self::restoreVersionsFromTrashbin($view, $filename, $targetLocation); @@ -639,7 +628,7 @@ private static function restoreVersionsFromTrashbin(View $view, $filename, $targ $target = Filesystem::normalizePath('/' . $targetLocation); - list($owner, $ownerPath) = self::getUidAndFilename($target); + [$owner, $ownerPath] = self::getUidAndFilename($target); // file has been deleted in between if (empty($ownerPath)) { @@ -966,7 +955,7 @@ private static function getVersionsFromTrash($filename, $timestamp, $user) { //force rescan of versions, local storage may not have updated the cache if (!self::$scannedVersions) { /** @var \OC\Files\Storage\Storage $storage */ - list($storage, ) = $view->resolvePath('/'); + [$storage, ] = $view->resolvePath('/'); $storage->getScanner()->scan('files_trashbin/versions'); self::$scannedVersions = true; } @@ -1067,7 +1056,7 @@ private static function calculateSize($view) { public static function getTrashbinSize($user) { $view = new View('/' . $user); $fileInfo = $view->getFileInfo('/files_trashbin'); - return isset($fileInfo['size']) ? $fileInfo['size'] : 0; + return $fileInfo['size'] ?? 0; } /** @@ -1094,15 +1083,15 @@ function (GenericEvent $event) { */ public static function registerHooks() { // create storage wrapper on setup - \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage'); + \OCP\Util::connectHook('OC_Filesystem', 'preSetup', \OCA\Files_Trashbin\Storage::class, 'setupStorage'); //Listen to delete user signal - \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook'); + \OCP\Util::connectHook('OC_User', 'pre_deleteUser', \OCA\Files_Trashbin\Hooks::class, 'deleteUser_hook'); //Listen to post write hook - \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'post_write', \OCA\Files_Trashbin\Hooks::class, 'post_write_hook'); // pre and post-rename, disable trash logic for the copy+unlink case - \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook'); - \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook'); - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook'); + \OCP\Util::connectHook('OC_Filesystem', 'delete', \OCA\Files_Trashbin\Trashbin::class, 'ensureFileScannedHook'); + \OCP\Util::connectHook('OC_Filesystem', 'rename', \OCA\Files_Trashbin\Storage::class, 'preRenameHook'); + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', \OCA\Files_Trashbin\Storage::class, 'postRenameHook'); } /** diff --git a/apps/files_trashbin/lib/TrashbinSkipChecker.php b/apps/files_trashbin/lib/TrashbinSkipChecker.php index 714386efd410..9d981fa4522c 100644 --- a/apps/files_trashbin/lib/TrashbinSkipChecker.php +++ b/apps/files_trashbin/lib/TrashbinSkipChecker.php @@ -35,15 +35,9 @@ * @package OCA\Files_Trashbin */ class TrashbinSkipChecker { - /** - * @var ILogger - */ - private $logger; + private \OCP\ILogger $logger; - /** - * @var IConfig - */ - private $config; + private \OCP\IConfig $config; /** * @param ILogger $logger diff --git a/apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php b/apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php index 50e7f9f9bb53..a0efb7f3f1f9 100644 --- a/apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php +++ b/apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php @@ -40,22 +40,22 @@ class ExpireTrashTest extends TestCase { /** * @var TrashExpiryManager | \PHPUnit\Framework\MockObject\MockObject */ - private $trashExpiryManager; + private \PHPUnit\Framework\MockObject\MockObject $trashExpiryManager; /** * @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** * @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** * @var ExpireTrash | \PHPUnit\Framework\MockObject\MockObject */ - private $backgroundJob; + private \PHPUnit\Framework\MockObject\MockObject $backgroundJob; /** * Setup testcase diff --git a/apps/files_trashbin/tests/Command/CleanUpTest.php b/apps/files_trashbin/tests/Command/CleanUpTest.php index 41dcd2d934b7..1918df0d8a47 100644 --- a/apps/files_trashbin/tests/Command/CleanUpTest.php +++ b/apps/files_trashbin/tests/Command/CleanUpTest.php @@ -56,9 +56,9 @@ class CleanUpTest extends TestCase { public function setUp(): void { parent::setUp(); - $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder') + $this->rootFolder = $this->getMockBuilder(\OCP\Files\IRootFolder::class) ->disableOriginalConstructor()->getMock(); - $this->userManager = $this->getMockBuilder('OC\User\Manager') + $this->userManager = $this->getMockBuilder(\OC\User\Manager::class) ->disableOriginalConstructor()->getMock(); $this->dbConnection = \OC::$server->getDatabaseConnection(); @@ -146,7 +146,7 @@ public function dataTestRemoveDeletedFiles() { */ public function testExecuteDeleteListOfUsers() { $userIds = ['user1', 'user2', 'user3']; - $instance = $this->getMockBuilder('OCA\Files_Trashbin\Command\CleanUp') + $instance = $this->getMockBuilder(\OCA\Files_Trashbin\Command\CleanUp::class) ->setMethods(['removeDeletedFiles']) ->setConstructorArgs([$this->rootFolder, $this->userManager, $this->dbConnection]) ->getMock(); @@ -157,12 +157,12 @@ public function testExecuteDeleteListOfUsers() { }); $this->userManager->expects($this->exactly(\count($userIds))) ->method('userExists')->willReturn(true); - $inputInterface = $this->getMockBuilder('\Symfony\Component\Console\Input\InputInterface') + $inputInterface = $this->getMockBuilder('\\' . \Symfony\Component\Console\Input\InputInterface::class) ->disableOriginalConstructor()->getMock(); $inputInterface->expects($this->once())->method('getArgument') ->with('user_id') ->willReturn($userIds); - $outputInterface = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface') + $outputInterface = $this->getMockBuilder('\\' . \Symfony\Component\Console\Output\OutputInterface::class) ->disableOriginalConstructor()->getMock(); self::invokePrivate($instance, 'execute', [$inputInterface, $outputInterface]); } @@ -173,7 +173,7 @@ public function testExecuteDeleteListOfUsers() { public function testExecuteAllUsers() { $userIds = []; $backendUsers = ['user1', 'user2']; - $instance = $this->getMockBuilder('OCA\Files_Trashbin\Command\CleanUp') + $instance = $this->getMockBuilder(\OCA\Files_Trashbin\Command\CleanUp::class) ->setMethods(['removeDeletedFiles']) ->setConstructorArgs([$this->rootFolder, $this->userManager, $this->dbConnection]) ->getMock(); @@ -187,12 +187,12 @@ public function testExecuteAllUsers() { ->willReturnCallback(function ($user) use ($backendUsers) { $this->assertContains($user, $backendUsers); }); - $inputInterface = $this->getMockBuilder('\Symfony\Component\Console\Input\InputInterface') + $inputInterface = $this->getMockBuilder('\\' . \Symfony\Component\Console\Input\InputInterface::class) ->disableOriginalConstructor()->getMock(); $inputInterface->expects($this->once())->method('getArgument') ->with('user_id') ->willReturn($userIds); - $outputInterface = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface') + $outputInterface = $this->getMockBuilder('\\' . \Symfony\Component\Console\Output\OutputInterface::class) ->disableOriginalConstructor()->getMock(); $this->userManager->expects($this->once()) ->method('getBackends') diff --git a/apps/files_trashbin/tests/Command/ExpireTrashTest.php b/apps/files_trashbin/tests/Command/ExpireTrashTest.php index 311a92dbcd9b..579cc9c9f12d 100644 --- a/apps/files_trashbin/tests/Command/ExpireTrashTest.php +++ b/apps/files_trashbin/tests/Command/ExpireTrashTest.php @@ -35,12 +35,11 @@ * @package OCA\Files_Trashbin\Tests\Command */ class ExpireTrashTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; - private $expiration; + private \PHPUnit\Framework\MockObject\MockObject $expiration; public function setUp(): void { parent::setUp(); diff --git a/apps/files_trashbin/tests/ExpirationTest.php b/apps/files_trashbin/tests/ExpirationTest.php index d62088d21206..454f68b19375 100644 --- a/apps/files_trashbin/tests/ExpirationTest.php +++ b/apps/files_trashbin/tests/ExpirationTest.php @@ -25,7 +25,7 @@ class ExpirationTest extends \Test\TestCase { public const SECONDS_PER_DAY = 86400; //60*60*24 - public const FAKE_TIME_NOW = 1000000; + public const FAKE_TIME_NOW = 1_000_000; public function expirationData() { $today = 100*self::SECONDS_PER_DAY; @@ -156,7 +156,7 @@ public function testGetMaxAgeAsTimestamp($configValue, $expectedMaxAgeTimestamp) * @return \OCP\AppFramework\Utility\ITimeFactory */ private function getMockedTimeFactory($time) { - $mockedTimeFactory = $this->getMockBuilder('\OCP\AppFramework\Utility\ITimeFactory') + $mockedTimeFactory = $this->getMockBuilder('\\' . \OCP\AppFramework\Utility\ITimeFactory::class) ->disableOriginalConstructor() ->setMethods(['getTime']) ->getMock() @@ -174,7 +174,7 @@ private function getMockedTimeFactory($time) { * @return \OCP\IConfig */ private function getMockedConfig($returnValue) { - $mockedConfig = $this->getMockBuilder('\OCP\IConfig') + $mockedConfig = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->setMethods( [ diff --git a/apps/files_trashbin/tests/QuotaTest.php b/apps/files_trashbin/tests/QuotaTest.php index cd00b8345ca1..d904c5f6b1f5 100644 --- a/apps/files_trashbin/tests/QuotaTest.php +++ b/apps/files_trashbin/tests/QuotaTest.php @@ -25,7 +25,7 @@ class QuotaTest extends \Test\TestCase { /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ protected $config; diff --git a/apps/files_trashbin/tests/StorageTest.php b/apps/files_trashbin/tests/StorageTest.php index e9321713c42d..59969db66f0a 100644 --- a/apps/files_trashbin/tests/StorageTest.php +++ b/apps/files_trashbin/tests/StorageTest.php @@ -51,15 +51,9 @@ class StorageTest extends TestCase { */ private $user; - /** - * @var View - */ - private $rootView; + private \OC\Files\View $rootView; - /** - * @var View - */ - private $userView; + private \OC\Files\View $userView; protected function setUp(): void { parent::setUp(); @@ -101,7 +95,7 @@ protected function tearDown(): void { public function testSingleStorageDeleteFile() { $this->assertTrue($this->userView->file_exists('test.txt')); $this->userView->unlink('test.txt'); - list($storage, ) = $this->userView->resolvePath('test.txt'); + [$storage, ] = $this->userView->resolvePath('test.txt'); $storage->getScanner()->scan(''); // make sure we check the storage $this->assertFalse($this->userView->getFileInfo('test.txt')); @@ -118,7 +112,7 @@ public function testSingleStorageDeleteFile() { public function testSingleStorageDeleteFolder() { $this->assertTrue($this->userView->file_exists('folder/inside.txt')); $this->userView->rmdir('folder'); - list($storage, ) = $this->userView->resolvePath('folder/inside.txt'); + [$storage, ] = $this->userView->resolvePath('folder/inside.txt'); $storage->getScanner()->scan(''); // make sure we check the storage $this->assertFalse($this->userView->getFileInfo('folder')); @@ -311,7 +305,7 @@ public function testDeleteVersionsOfFile() { $this->userView->unlink('test.txt'); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // check if versions are in trashbin @@ -341,7 +335,7 @@ public function testDeleteVersionsOfFolder() { $this->userView->rmdir('folder'); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // check if versions are in trashbin @@ -377,7 +371,7 @@ public function testDeleteVersionsOfFilesInFolder() { $this->userView->unlink('folder/inside.txt'); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // check if versions are in trashbin @@ -409,7 +403,7 @@ public function testDeleteVersionsOfFilesInFolder2() { $this->userView->unlink('folder/inside.txt'); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // check if versions are in trashbin @@ -459,7 +453,7 @@ public function testDeleteVersionsOfFileAsRecipient() { $recipientView->unlink('share/test.txt'); // rescan trash storage for both users - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // check if versions are in trashbin for both users @@ -513,7 +507,7 @@ public function testDeleteVersionsOfFolderAsRecipient() { $recipientView->rmdir('share/folder'); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // check if versions are in trashbin for owner @@ -571,7 +565,7 @@ public function testKeepFileAndVersionsWhenMovingFileBetweenStorages() { $this->assertTrue($this->userView->file_exists('substorage/test.txt')); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // versions were moved too @@ -613,7 +607,7 @@ public function testKeepFileAndVersionsWhenMovingFolderBetweenStorages() { $this->assertTrue($this->userView->file_exists('substorage/folder/inside.txt')); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // versions were moved too @@ -651,7 +645,7 @@ public function testKeepFileAndVersionsWhenMovingFileInFolderBetweenStorages() { $this->assertTrue($this->userView->file_exists('substorage/folder/inside.txt')); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // versions were moved too @@ -697,7 +691,7 @@ public function testKeepFileAndVersionsWhenMovingFileInFolderBetweenStorages2() $this->assertTrue($this->userView->file_exists('substorage/folder/inside.txt')); // rescan trash storage - list($rootStorage, ) = $this->rootView->resolvePath($this->user . '/files_trashbin'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user . '/files_trashbin'); $rootStorage->getScanner()->scan(''); // versions were moved too @@ -799,7 +793,7 @@ public function testSingleStorageDeleteFileFail() { /** * @var \OC\Files\Storage\Temporary | \PHPUnit\Framework\MockObject\MockObject $storage */ - $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Temporary::class) ->setConstructorArgs([[]]) ->setMethods(['rename', 'unlink', 'moveFromStorage']) ->getMock(); @@ -836,7 +830,7 @@ public function testSingleStorageDeleteFolderFail() { /** * @var \OC\Files\Storage\Temporary | \PHPUnit\Framework\MockObject\MockObject $storage */ - $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Temporary::class) ->setConstructorArgs([[]]) ->setMethods(['rename', 'unlink', 'rmdir']) ->getMock(); @@ -867,9 +861,9 @@ public function testSingleStorageDeleteFolderFail() { * @dataProvider dataTestShouldMoveToTrash */ public function testShouldMoveToTrash($mountPoint, $path, $userExists, $expected) { - $tmpStorage = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $tmpStorage = $this->getMockBuilder('\\' . \OC\Files\Storage\Temporary::class) ->disableOriginalConstructor()->getMock(); - $userManager = $this->getMockBuilder('OCP\IUserManager') + $userManager = $this->getMockBuilder(\OCP\IUserManager::class) ->disableOriginalConstructor()->getMock(); $userManager->expects($this->any()) ->method('userExists')->willReturn($userExists); @@ -912,7 +906,7 @@ public function testSingleStorageDeleteFileLoggedOut() { private function markTestSkippedIfStorageHasOwnVersioning() { /** @var Storage $storage */ - list($storage, $internalPath) = $this->userView->resolvePath('folder/inside.txt'); + [$storage, $internalPath] = $this->userView->resolvePath('folder/inside.txt'); if ($storage->instanceOfStorage(ObjectStoreStorage::class)) { $this->markTestSkipped(); } diff --git a/apps/files_trashbin/tests/TestCase.php b/apps/files_trashbin/tests/TestCase.php index 08ac9738006b..bec00fba8972 100644 --- a/apps/files_trashbin/tests/TestCase.php +++ b/apps/files_trashbin/tests/TestCase.php @@ -59,7 +59,7 @@ public static function setUpBeforeClass(): void { self::$trashBinStatus = $appManager->isEnabledForUser('files_trashbin'); // clear share hooks - \OC_Hook::clear('OCP\\Share'); + \OC_Hook::clear(\OCP\Share::class); \OC::registerShareHooks(); $application = new Application(); $application->registerMountProviders(); @@ -109,7 +109,7 @@ protected function setUp(): void { \OC::$server->getAppManager()->enableApp('files_trashbin'); $config = \OC::$server->getConfig(); - $mockConfig = $this->createMock('\OCP\IConfig'); + $mockConfig = $this->createMock('\\' . \OCP\IConfig::class); $mockConfig->expects($this->any()) ->method('getSystemValue') ->will($this->returnCallback(function ($key, $default) use ($config) { diff --git a/apps/files_trashbin/tests/TrashbinExpiryManagerTest.php b/apps/files_trashbin/tests/TrashbinExpiryManagerTest.php index 60e3726cc6ad..cb9c2e167152 100644 --- a/apps/files_trashbin/tests/TrashbinExpiryManagerTest.php +++ b/apps/files_trashbin/tests/TrashbinExpiryManagerTest.php @@ -39,17 +39,14 @@ class TrashbinExpiryManagerTest extends TestCase { /** * @var Expiration| \PHPUnit\Framework\MockObject\MockObject */ - private $expiration; + private \PHPUnit\Framework\MockObject\MockObject $expiration; /** * @var Quota| \PHPUnit\Framework\MockObject\MockObject */ - private $quota; + private \PHPUnit\Framework\MockObject\MockObject $quota; - /** - * @var TrashExpiryManager - */ - private $trashExpiryManager; + private \OCA\Files_Trashbin\TrashExpiryManager $trashExpiryManager; protected function setUp(): void { parent::setUp(); @@ -86,7 +83,7 @@ public function testExpiryEnabled($expirationEnabled, $result) { public function providesRetentionEnabled() { return [ - [1000000, true], + [1_000_000, true], [false, false] ]; } diff --git a/apps/files_trashbin/tests/TrashbinTest.php b/apps/files_trashbin/tests/TrashbinTest.php index e4821de405f3..2d8c8e294ae7 100644 --- a/apps/files_trashbin/tests/TrashbinTest.php +++ b/apps/files_trashbin/tests/TrashbinTest.php @@ -489,7 +489,7 @@ public function testRestoreFileIntoReadOnlySourceFolder() { $trashedFile = $filesInTrash[0]; // delete source folder - list($storage, $internalPath) = $this->rootView->resolvePath('/' . self::TEST_TRASHBIN_USER1 . '/files/folder'); + [$storage, $internalPath] = $this->rootView->resolvePath('/' . self::TEST_TRASHBIN_USER1 . '/files/folder'); if ($storage instanceof Local) { $folderAbsPath = $storage->getSourcePath($internalPath); // make folder read-only @@ -524,19 +524,19 @@ public function testPrivateLink() { ->method('nodeExists') ->will($this->returnValue(true)); - $parentNode = $this->createMock('\OCP\Files\Folder'); + $parentNode = $this->createMock('\\' . \OCP\Files\Folder::class); $parentNode->expects($this->once()) ->method('getPath') ->will($this->returnValue('test@#?%test/files_trashbin/files/test.d1462861890/sub')); - $baseFolderTrash = $this->createMock('\OCP\Files\Folder'); + $baseFolderTrash = $this->createMock('\\' . \OCP\Files\Folder::class); $rootFolder->expects($this->once()) ->method('get') ->with('test@#?%test/files_trashbin/files/') ->will($this->returnValue($baseFolderTrash)); - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock('\\' . \OCP\Files\File::class); $node->expects($this->once()) ->method('getParent') ->will($this->returnValue($parentNode)); @@ -582,6 +582,6 @@ public function testDeleteKeys() { $sourceStorage->expects($this->once()) ->method('deleteAllFileKeys') ->with('//files/file1.txt'); - self::invokePrivate(Trashbin::class, 'retainVersions', ['file1.txt', 'test-trashbin-user1', 'file1.txt', 1529567106, $sourceStorage]); + self::invokePrivate(Trashbin::class, 'retainVersions', ['file1.txt', 'test-trashbin-user1', 'file1.txt', 1_529_567_106, $sourceStorage]); } } diff --git a/apps/files_versions/lib/AppInfo/Application.php b/apps/files_versions/lib/AppInfo/Application.php index dbbd75f699bf..59ed5ec79949 100644 --- a/apps/files_versions/lib/AppInfo/Application.php +++ b/apps/files_versions/lib/AppInfo/Application.php @@ -39,24 +39,20 @@ public function __construct(array $urlParams = []) { /* * Register capabilities */ - $container->registerCapability('OCA\Files_Versions\Capabilities'); + $container->registerCapability(\OCA\Files_Versions\Capabilities::class); /* * Register expiration */ - $container->registerService('Expiration', function ($c) { - return new Expiration( - $c->query('ServerContainer')->getConfig(), - $c->query('OCP\AppFramework\Utility\ITimeFactory') - ); - }); + $container->registerService('Expiration', fn ($c) => new Expiration( + $c->query('ServerContainer')->getConfig(), + $c->query(\OCP\AppFramework\Utility\ITimeFactory::class) + )); /* * Register FileHelper */ - $container->registerService('FileHelper', function ($c) { - return new FileHelper(); - }); + $container->registerService('FileHelper', fn ($c) => new FileHelper()); /** @var AllConfig $config */ $config = $container->query('ServerContainer')->getConfig(); @@ -64,12 +60,10 @@ public function __construct(array $urlParams = []) { if ($metaEnabled) { $container->registerService( MetaStorage::class, - function ($c) { - return new MetaStorage( - $c->query('ServerContainer')->getConfig()->getSystemValue('datadirectory'), - $c->query('FileHelper'), - ); - } + fn ($c) => new MetaStorage( + $c->query('ServerContainer')->getConfig()->getSystemValue('datadirectory'), + $c->query('FileHelper'), + ) ); Storage::enableMetaData($container->query(MetaStorage::class)); diff --git a/apps/files_versions/lib/Command/ExpireVersions.php b/apps/files_versions/lib/Command/ExpireVersions.php index 21228d50e710..c9f870a1d4a3 100644 --- a/apps/files_versions/lib/Command/ExpireVersions.php +++ b/apps/files_versions/lib/Command/ExpireVersions.php @@ -33,15 +33,9 @@ use Symfony\Component\Console\Output\OutputInterface; class ExpireVersions extends Command { - /** - * @var Expiration - */ - private $expiration; + private ?\OCA\Files_Versions\Expiration $expiration = null; - /** - * @var IUserManager - */ - private $userManager; + private ?\OCP\IUserManager $userManager = null; /** * @param IUserManager|null $userManager diff --git a/apps/files_versions/lib/Controller/VersionController.php b/apps/files_versions/lib/Controller/VersionController.php index e547f889acf9..f1c8aa21c042 100644 --- a/apps/files_versions/lib/Controller/VersionController.php +++ b/apps/files_versions/lib/Controller/VersionController.php @@ -35,8 +35,7 @@ * @package OCA\Files\Controller */ class VersionController extends Controller { - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; /** * @param string $appName diff --git a/apps/files_versions/lib/Expiration.php b/apps/files_versions/lib/Expiration.php index 7a2005fff580..14a923865707 100644 --- a/apps/files_versions/lib/Expiration.php +++ b/apps/files_versions/lib/Expiration.php @@ -28,20 +28,16 @@ class Expiration { // how long do we keep files a version if no other value is defined in the config file (unit: days) public const NO_OBLIGATION = -1; - /** @var ITimeFactory */ - private $timeFactory; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; /** @var string */ private $retentionObligation; - /** @var int */ - private $minAge; + private ?int $minAge = null; - /** @var int */ - private $maxAge; + private ?int $maxAge = null; - /** @var bool */ - private $canPurgeToSaveSpace; + private ?bool $canPurgeToSaveSpace = null; public function __construct(IConfig $config, ITimeFactory $timeFactory) { $this->timeFactory = $timeFactory; diff --git a/apps/files_versions/lib/FileHelper.php b/apps/files_versions/lib/FileHelper.php index f1839a7c29ae..f3d9a68d0821 100644 --- a/apps/files_versions/lib/FileHelper.php +++ b/apps/files_versions/lib/FileHelper.php @@ -58,7 +58,7 @@ public function createMissingDirectories(View $view, $path) { public function getVersionsSize($uid) { $view = $this->getUserView($uid); $fileInfo = $view->getFileInfo(self::VERSIONS_RELATIVE_PATH); - return isset($fileInfo['size']) ? $fileInfo['size'] : 0; + return $fileInfo['size'] ?? 0; } /** diff --git a/apps/files_versions/lib/Hooks.php b/apps/files_versions/lib/Hooks.php index 40a3128eb0c6..3d90477ee6e9 100644 --- a/apps/files_versions/lib/Hooks.php +++ b/apps/files_versions/lib/Hooks.php @@ -35,25 +35,25 @@ class Hooks { public static function connectHooks() { // Listen to write signals - \OCP\Util::connectHook('OC_Filesystem', 'write', 'OCA\Files_Versions\Hooks', 'write_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'write', \OCA\Files_Versions\Hooks::class, 'write_hook'); $config = \OC::$server->getConfig(); $metaEnabled = ($config->getSystemValue('file_storage.save_version_metadata', false) === true); if ($metaEnabled) { - \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Versions\Hooks', 'post_write_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'post_write', \OCA\Files_Versions\Hooks::class, 'post_write_hook'); } // Listen to delete and rename signals - \OCP\Util::connectHook('OC_Filesystem', 'post_delete', 'OCA\Files_Versions\Hooks', 'remove_hook'); - \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Versions\Hooks', 'pre_remove_hook'); - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Versions\Hooks', 'rename_hook'); - \OCP\Util::connectHook('OC_Filesystem', 'post_copy', 'OCA\Files_Versions\Hooks', 'copy_hook'); - \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Versions\Hooks', 'pre_renameOrCopy_hook'); - \OCP\Util::connectHook('OC_Filesystem', 'copy', 'OCA\Files_Versions\Hooks', 'pre_renameOrCopy_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'post_delete', \OCA\Files_Versions\Hooks::class, 'remove_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'delete', \OCA\Files_Versions\Hooks::class, 'pre_remove_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', \OCA\Files_Versions\Hooks::class, 'rename_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'post_copy', \OCA\Files_Versions\Hooks::class, 'copy_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'rename', \OCA\Files_Versions\Hooks::class, 'pre_renameOrCopy_hook'); + \OCP\Util::connectHook('OC_Filesystem', 'copy', \OCA\Files_Versions\Hooks::class, 'pre_renameOrCopy_hook'); $eventDispatcher = \OC::$server->getEventDispatcher(); - $eventDispatcher->addListener('OCA\Files::loadAdditionalScripts', ['OCA\Files_Versions\Hooks', 'onLoadFilesAppScripts']); + $eventDispatcher->addListener('OCA\Files::loadAdditionalScripts', [\OCA\Files_Versions\Hooks::class, 'onLoadFilesAppScripts']); } /** diff --git a/apps/files_versions/lib/MetaStorage.php b/apps/files_versions/lib/MetaStorage.php index e0d4644f67af..3b3b4fb22ad1 100644 --- a/apps/files_versions/lib/MetaStorage.php +++ b/apps/files_versions/lib/MetaStorage.php @@ -58,11 +58,9 @@ class MetaStorage { /** @var string File-extension of the metadata file for a specific version */ public const VERSION_FILE_EXT = ".json"; - /** @var string */ - private $dataDir; + private string $dataDir; - /** @var FileHelper */ - private $fileHelper; + private \OCA\Files_Versions\FileHelper $fileHelper; /** @var boolean */ private $objectStoreEnabled; @@ -332,7 +330,7 @@ private function pathToAbsDiskPath(string $uid, string $path) : string { * @return int|false */ private function writeMetaFile(array $metadata, string $diskPath) { - $metaJson = \json_encode($metadata); + $metaJson = \json_encode($metadata, JSON_THROW_ON_ERROR); return \file_put_contents($diskPath, $metaJson); } @@ -346,7 +344,7 @@ private function readMetaFile(string $diskPath) { } $json = \file_get_contents($diskPath); - if ($decoded = \json_decode($json, true)) { + if ($decoded = \json_decode($json, true, 512, JSON_THROW_ON_ERROR)) { $metadata = []; // handling for edited_by diff --git a/apps/files_versions/lib/Storage.php b/apps/files_versions/lib/Storage.php index 6233ee62900f..c059a5c4f665 100644 --- a/apps/files_versions/lib/Storage.php +++ b/apps/files_versions/lib/Storage.php @@ -62,11 +62,11 @@ class Storage { public const DELETE_TRIGGER_QUOTA_EXCEEDED = 2; // files for which we can remove the versions after the delete operation was successful - private static $deletedFiles = []; + private static array $deletedFiles = []; - private static $sourcePathAndUser = []; + private static array $sourcePathAndUser = []; - private static $max_versions_per_interval = [ + private static array $max_versions_per_interval = [ //first 10sec, one version every 2sec 1 => ['intervalEndsAfter' => 10, 'step' => 2], //next minute, one version every 10sec @@ -76,16 +76,14 @@ class Storage { //next 24h, one version every hour 4 => ['intervalEndsAfter' => 86400, 'step' => 3600], //next 30days, one version per day - 5 => ['intervalEndsAfter' => 2592000, 'step' => 86400], + 5 => ['intervalEndsAfter' => 2_592_000, 'step' => 86400], //until the end one version per week 6 => ['intervalEndsAfter' => -1, 'step' => 604800], ]; - /** @var \OCA\Files_Versions\AppInfo\Application */ - private static $application; + private static ?\OCA\Files_Versions\AppInfo\Application $application = null; - /** @var MetaStorage|null */ - private static $metaData = null; + private static ?\OCA\Files_Versions\MetaStorage $metaData = null; /** * Enables the "versioning-metadata" feature by receiving @@ -143,7 +141,7 @@ public static function getUidAndFilename($filename) { * @param string $source source path */ public static function setSourcePathAndUser($source) { - list($uid, $path) = self::getUidAndFilename($source); + [$uid, $path] = self::getUidAndFilename($source); self::$sourcePathAndUser[$source] = ['uid' => $uid, 'path' => $path]; } @@ -186,12 +184,12 @@ public static function store($filename) { return false; } - list($uid, $filename) = self::getUidAndFilename($filename); + [$uid, $filename] = self::getUidAndFilename($filename); // $filename is expected to start with "/" and be a // full path such as "/folder1/folder2/filename" $fullFileName = "/$uid/files$filename"; /** @var \OCP\Files\Storage\IStorage $storage */ - list($storage, $internalPath) = Filesystem::resolvePath($fullFileName); + [$storage, $internalPath] = Filesystem::resolvePath($fullFileName); if ($storage->instanceOfStorage(IVersionedStorage::class)) { /** @var IVersionedStorage $storage */ if ($storage->saveVersion($internalPath)) { @@ -250,7 +248,7 @@ public static function postStore(string $filename) { return false; } - list($uid, $currentFileName) = self::getUidAndFilename($filename); + [$uid, $currentFileName] = self::getUidAndFilename($filename); $versionMetadata = self::$metaData->getCurrentMetadata($currentFileName, $uid); if (!$versionMetadata) { // make sure metadata for current exists @@ -264,7 +262,7 @@ public static function postStore(string $filename) { * @param string $path */ public static function markDeletedFile($path) { - list($uid, $filename) = self::getUidAndFilename($path); + [$uid, $filename] = self::getUidAndFilename($path); self::$deletedFiles[$path] = [ 'uid' => $uid, 'filename' => $filename]; @@ -379,7 +377,7 @@ protected static function deleteVersion($view, $path) { * @var \OC\Files\Storage\Storage $storage * @var string $internalPath */ - list($storage, $internalPath) = $view->resolvePath($path); + [$storage, $internalPath] = $view->resolvePath($path); $cache = $storage->getCache($internalPath); $cache->remove($internalPath); @@ -434,7 +432,7 @@ public static function delete($path) { * @param string $operation can be 'copy' or 'rename' */ public static function renameOrCopy($sourcePath, $targetPath, $operation) { - list($sourceOwner, $sourcePath) = self::getSourcePathAndUser($sourcePath); + [$sourceOwner, $sourcePath] = self::getSourcePathAndUser($sourcePath); // it was a upload of a existing file if no old path exists // in this case the pre-hook already called the store method and we can @@ -443,7 +441,7 @@ public static function renameOrCopy($sourcePath, $targetPath, $operation) { return true; } - list($targetOwner, $targetPath) = self::getUidAndFilename($targetPath); + [$targetOwner, $targetPath] = self::getUidAndFilename($targetPath); $sourcePath = \ltrim($sourcePath, '/'); $targetPath = \ltrim($targetPath, '/'); @@ -579,17 +577,17 @@ public static function restoreVersion($uid, $filename, $fileToRestore, $revision */ private static function copyFileContents($view, $path1, $path2) { /** @var \OC\Files\Storage\Storage $storage1 */ - list($storage1, $internalPath1) = $view->resolvePath($path1); + [$storage1, $internalPath1] = $view->resolvePath($path1); /** @var \OC\Files\Storage\Storage $storage2 */ - list($storage2, $internalPath2) = $view->resolvePath($path2); + [$storage2, $internalPath2] = $view->resolvePath($path2); $view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE); $view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE); - if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) { + if ($storage1->instanceOfStorage('\\' . \OC\Files\ObjectStore\ObjectStoreStorage::class) || $storage2->instanceOfStorage('\\' . \OC\Files\ObjectStore\ObjectStoreStorage::class)) { $source = $storage1->fopen($internalPath1, 'r'); $target = $storage2->fopen($internalPath2, 'w'); - list(, $result) = \OC_Helper::streamCopy($source, $target); + [, $result] = \OC_Helper::streamCopy($source, $target); \fclose($source); \fclose($target); } else { @@ -636,7 +634,7 @@ public static function publishCurrentVersion($filename) { return false; } - list($uid, $currentFileName) = self::getUidAndFilename($filename); + [$uid, $currentFileName] = self::getUidAndFilename($filename); // overwrite current file metadata with minor=false to create new major version self::$metaData->createForCurrent($currentFileName, $uid, false); @@ -786,12 +784,12 @@ private static function getHumanReadableTimestamp($timestamp) { return \round($diff / 3600) . " hours ago"; } elseif ($diff < 604800) { //first week return \round($diff / 86400) . " days ago"; - } elseif ($diff < 2419200) { //first month + } elseif ($diff < 2_419_200) { //first month return \round($diff / 604800) . " weeks ago"; - } elseif ($diff < 29030400) { // first year - return \round($diff / 2419200) . " months ago"; + } elseif ($diff < 29_030_400) { // first year + return \round($diff / 2_419_200) . " months ago"; } else { - return \round($diff / 29030400) . " years ago"; + return \round($diff / 29_030_400) . " years ago"; } } @@ -806,7 +804,7 @@ protected static function getExpireList($time, $versions, $quotaExceeded = false $expiration = self::getExpiration(); if ($expiration->shouldAutoExpire() && \count($versions) > 0) { - list($toDelete, $size) = self::getAutoExpireList($time, $versions); + [$toDelete, $size] = self::getAutoExpireList($time, $versions); } else { $size = 0; $toDelete = []; // versions we want to delete @@ -913,7 +911,7 @@ public static function expire($filename, $uid) { if ($user === null) { $msg = "Backends provided no user object for $uid"; - \OC::$server->getLogger()->error($msg, ['app' => __CLASS__]); + \OC::$server->getLogger()->error($msg, ['app' => self::class]); throw new \OC\User\NoUserException($msg); } @@ -963,7 +961,7 @@ public static function expire($filename, $uid) { $allVersions = Storage::getVersions($uid, $filename); $time = \time(); - list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions, $availableSpace <= 0); + [$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0); $availableSpace = $availableSpace + $sizeOfDeletedVersions; $versionsSize = $versionsSize - $sizeOfDeletedVersions; @@ -975,7 +973,7 @@ public static function expire($filename, $uid) { $allVersions = $result['all']; foreach ($result['by_file'] as $versions) { - list($toDeleteNew, $size) = self::getExpireList($time, $versions, $availableSpace <= 0); + [$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0); $toDelete = \array_merge($toDelete, $toDeleteNew); $sizeOfDeletedVersions += $size; } diff --git a/apps/files_versions/tests/Command/CleanupTest.php b/apps/files_versions/tests/Command/CleanupTest.php index f94343e07709..a06b65346c5a 100644 --- a/apps/files_versions/tests/Command/CleanupTest.php +++ b/apps/files_versions/tests/Command/CleanupTest.php @@ -47,9 +47,9 @@ class CleanupTest extends TestCase { public function setUp(): void { parent::setUp(); - $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder') + $this->rootFolder = $this->getMockBuilder(\OCP\Files\IRootFolder::class) ->disableOriginalConstructor()->getMock(); - $this->userManager = $this->getMockBuilder('OC\User\Manager') + $this->userManager = $this->getMockBuilder(\OC\User\Manager::class) ->disableOriginalConstructor()->getMock(); $this->cleanup = new CleanUp($this->rootFolder, $this->userManager); @@ -95,7 +95,7 @@ public function dataTestDeleteVersions() { public function testExecuteDeleteListOfUsers() { $userIds = ['user1', 'user2', 'user3']; - $instance = $this->getMockBuilder('OCA\Files_Versions\Command\CleanUp') + $instance = $this->getMockBuilder(\OCA\Files_Versions\Command\CleanUp::class) ->setMethods(['deleteVersions']) ->setConstructorArgs([$this->rootFolder, $this->userManager]) ->getMock(); @@ -108,13 +108,13 @@ public function testExecuteDeleteListOfUsers() { $this->userManager->expects($this->exactly(\count($userIds))) ->method('userExists')->willReturn(true); - $inputInterface = $this->getMockBuilder('\Symfony\Component\Console\Input\InputInterface') + $inputInterface = $this->getMockBuilder('\\' . \Symfony\Component\Console\Input\InputInterface::class) ->disableOriginalConstructor()->getMock(); $inputInterface->expects($this->once())->method('getArgument') ->with('user_id') ->willReturn($userIds); - $outputInterface = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface') + $outputInterface = $this->getMockBuilder('\\' . \Symfony\Component\Console\Output\OutputInterface::class) ->disableOriginalConstructor()->getMock(); self::invokePrivate($instance, 'execute', [$inputInterface, $outputInterface]); @@ -127,7 +127,7 @@ public function testExecuteAllUsers() { $userIds = []; $backendUsers = ['user1', 'user2']; - $instance = $this->getMockBuilder('OCA\Files_Versions\Command\CleanUp') + $instance = $this->getMockBuilder(\OCA\Files_Versions\Command\CleanUp::class) ->setMethods(['deleteVersions']) ->setConstructorArgs([$this->rootFolder, $this->userManager]) ->getMock(); @@ -144,13 +144,13 @@ public function testExecuteAllUsers() { $this->assertContains($user, $backendUsers); }); - $inputInterface = $this->getMockBuilder('\Symfony\Component\Console\Input\InputInterface') + $inputInterface = $this->getMockBuilder('\\' . \Symfony\Component\Console\Input\InputInterface::class) ->disableOriginalConstructor()->getMock(); $inputInterface->expects($this->once())->method('getArgument') ->with('user_id') ->willReturn($userIds); - $outputInterface = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface') + $outputInterface = $this->getMockBuilder('\\' . \Symfony\Component\Console\Output\OutputInterface::class) ->disableOriginalConstructor()->getMock(); $this->userManager->expects($this->once()) diff --git a/apps/files_versions/tests/Command/ExpireVersionsTest.php b/apps/files_versions/tests/Command/ExpireVersionsTest.php index 9ae572bee80e..8c8edbe1119b 100644 --- a/apps/files_versions/tests/Command/ExpireVersionsTest.php +++ b/apps/files_versions/tests/Command/ExpireVersionsTest.php @@ -35,12 +35,11 @@ * @package OCA\Files_Versions\Tests\Command */ class ExpireVersionsTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; - private $expiration; + private \PHPUnit\Framework\MockObject\MockObject $expiration; public function setUp(): void { parent::setUp(); diff --git a/apps/files_versions/tests/ExpirationTest.php b/apps/files_versions/tests/ExpirationTest.php index 76f8f7ac5b7d..89d34a7b6d4b 100644 --- a/apps/files_versions/tests/ExpirationTest.php +++ b/apps/files_versions/tests/ExpirationTest.php @@ -181,7 +181,7 @@ public function testGetMaxAgeAsTimestamp($retentionObligation, $expectedResult) * @return \OCP\AppFramework\Utility\ITimeFactory */ private function getMockedTimeFactory($time) { - $mockedTimeFactory = $this->getMockBuilder('\OCP\AppFramework\Utility\ITimeFactory') + $mockedTimeFactory = $this->getMockBuilder('\\' . \OCP\AppFramework\Utility\ITimeFactory::class) ->disableOriginalConstructor() ->setMethods(['getTime']) ->getMock() @@ -199,7 +199,7 @@ private function getMockedTimeFactory($time) { * @return \OCP\IConfig */ private function getMockedConfig($returnValue) { - $mockedConfig = $this->getMockBuilder('\OCP\IConfig') + $mockedConfig = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->setMethods( [ diff --git a/apps/files_versions/tests/VersioningTest.php b/apps/files_versions/tests/VersioningTest.php index 92962fa06b38..6fec7c1bacd4 100644 --- a/apps/files_versions/tests/VersioningTest.php +++ b/apps/files_versions/tests/VersioningTest.php @@ -55,23 +55,17 @@ class VersioningTest extends TestCase { public const USERS_VERSIONS_ROOT = '/test-versions-user/files_versions'; - /** @var string */ - private $user1; - /** @var string */ - private $user2; - /** @var string */ - private $versionsRootOfUser1; + private string $user1; + private string $user2; + private string $versionsRootOfUser1; /** @var IConfig|MockObject */ - private $mockConfig; + private ?\PHPUnit\Framework\MockObject\MockObject $mockConfig = null; /** @var string */ private $dataDir; /** @var bool */ private $objectStoreEnabled; - /** - * @var \OC\Files\View - */ - private $rootView; + private \OC\Files\View $rootView; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); @@ -141,7 +135,7 @@ protected function tearDown(): void { */ private function overwriteConfig($saveVersionMetadata=false, $versionsRetentionObligation='auto') { $config = \OC::$server->getConfig(); - $this->mockConfig = $this->createMock('\OCP\IConfig'); + $this->mockConfig = $this->createMock('\\' . \OCP\IConfig::class); $this->mockConfig->expects($this->any()) ->method('getSystemValue') ->will($this->returnCallback( @@ -219,9 +213,9 @@ public function testMoveFileIntoSharedFolderAsRecipient(bool $metaDataEnabled) { $m1 = $versionsFolder2 . '/test.txt.v' . $t1 . MetaStorage::VERSION_FILE_EXT; $m2 = $versionsFolder2 . '/test.txt.v' . $t2 . MetaStorage::VERSION_FILE_EXT; - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user2])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user2])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user2])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); } // move file into the shared folder as recipient @@ -274,7 +268,7 @@ public function testPublishCurrentVersion(bool $metaDataEnabled) { if ($metaDataEnabled && !$this->objectStoreEnabled) { $m0 = $this->versionsRootOfUser1 . '/folder1/test.txt' . MetaStorage::CURRENT_FILE_PREFIX . MetaStorage::VERSION_FILE_EXT; - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.1'])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.1'], JSON_THROW_ON_ERROR)); } $current0 = \OCA\Files_Versions\Storage::getCurrentVersion($this->user1, '/folder1/test.txt'); @@ -333,12 +327,12 @@ public function testExpire(bool $metaDataEnabled) { $m3 = $this->versionsRootOfUser1 . '/test.txt.v' . $t3 . MetaStorage::VERSION_FILE_EXT; $m4 = $this->versionsRootOfUser1 . '/test.txt.v' . $t4 . MetaStorage::VERSION_FILE_EXT; $m5 = $this->versionsRootOfUser1 . '/test.txt.v' . $t5 . MetaStorage::VERSION_FILE_EXT; - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.2'])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.1'])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.0'])); // published - \file_put_contents("$this->dataDir/$m3", \json_encode(['edited_by' => $this->user1, 'version_tag' => '0.3'])); - \file_put_contents("$this->dataDir/$m4", \json_encode(['edited_by' => $this->user1, 'version_tag' => '0.2'])); - \file_put_contents("$this->dataDir/$m5", \json_encode(['edited_by' => $this->user1, 'version_tag' => '0.1'])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.2'], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.1'], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.0'], JSON_THROW_ON_ERROR)); // published + \file_put_contents("$this->dataDir/$m3", \json_encode(['edited_by' => $this->user1, 'version_tag' => '0.3'], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m4", \json_encode(['edited_by' => $this->user1, 'version_tag' => '0.2'], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m5", \json_encode(['edited_by' => $this->user1, 'version_tag' => '0.1'], JSON_THROW_ON_ERROR)); } $versions = \OCA\Files_Versions\Storage::getVersions($this->user1, '/test.txt'); @@ -397,9 +391,9 @@ public function testIsPublishedVersion(bool $metaDataEnabled) { $this->rootView->file_put_contents($v2, 'version2'); if ($metaDataEnabled && !$this->objectStoreEnabled) { - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.1'])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.0'])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1, 'version_tag' => '0.1'])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.1'], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1, 'version_tag' => '1.0'], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1, 'version_tag' => '0.1'], JSON_THROW_ON_ERROR)); } self::loginAsUser($this->user1); @@ -422,9 +416,9 @@ public function testGetExpireList($versions, $sizeOfAllDeletedFiles) { $this->overwriteConfig(); // last interval end at 2592000 - $startTime = 5000000; + $startTime = 5_000_000; - list($deleted, $size) = VersionStorageToTest::callProtectedGetExpireList($startTime, $versions); + [$deleted, $size] = VersionStorageToTest::callProtectedGetExpireList($startTime, $versions); // we should have deleted 16 files each of the size 1 $this->assertEquals($sizeOfAllDeletedFiles, $size); @@ -447,46 +441,46 @@ public function versionsProvider() { [ [ // first slice (10sec) keep one version every 2 seconds - ["version" => 4999999, "path" => "keep", "size" => 1], - ["version" => 4999998, "path" => "delete", "size" => 1], - ["version" => 4999997, "path" => "keep", "size" => 1], - ["version" => 4999995, "path" => "keep", "size" => 1], - ["version" => 4999994, "path" => "delete", "size" => 1], + ["version" => 4_999_999, "path" => "keep", "size" => 1], + ["version" => 4_999_998, "path" => "delete", "size" => 1], + ["version" => 4_999_997, "path" => "keep", "size" => 1], + ["version" => 4_999_995, "path" => "keep", "size" => 1], + ["version" => 4_999_994, "path" => "delete", "size" => 1], //next slice (60sec) starts at 4999990 keep one version every 10 seconds - ["version" => 4999988, "path" => "keep", "size" => 1], - ["version" => 4999978, "path" => "keep", "size" => 1], - ["version" => 4999975, "path" => "delete", "size" => 1], - ["version" => 4999972, "path" => "delete", "size" => 1], - ["version" => 4999967, "path" => "keep", "size" => 1], - ["version" => 4999958, "path" => "delete", "size" => 1], - ["version" => 4999957, "path" => "keep", "size" => 1], + ["version" => 4_999_988, "path" => "keep", "size" => 1], + ["version" => 4_999_978, "path" => "keep", "size" => 1], + ["version" => 4_999_975, "path" => "delete", "size" => 1], + ["version" => 4_999_972, "path" => "delete", "size" => 1], + ["version" => 4_999_967, "path" => "keep", "size" => 1], + ["version" => 4_999_958, "path" => "delete", "size" => 1], + ["version" => 4_999_957, "path" => "keep", "size" => 1], //next slice (3600sec) start at 4999940 keep one version every 60 seconds - ["version" => 4999900, "path" => "keep", "size" => 1], - ["version" => 4999841, "path" => "delete", "size" => 1], - ["version" => 4999840, "path" => "keep", "size" => 1], - ["version" => 4999780, "path" => "keep", "size" => 1], - ["version" => 4996401, "path" => "keep", "size" => 1], + ["version" => 4_999_900, "path" => "keep", "size" => 1], + ["version" => 4_999_841, "path" => "delete", "size" => 1], + ["version" => 4_999_840, "path" => "keep", "size" => 1], + ["version" => 4_999_780, "path" => "keep", "size" => 1], + ["version" => 4_996_401, "path" => "keep", "size" => 1], // next slice (86400sec) start at 4996400 keep one version every 3600 seconds - ["version" => 4996350, "path" => "delete", "size" => 1], - ["version" => 4992800, "path" => "keep", "size" => 1], - ["version" => 4989800, "path" => "delete", "size" => 1], - ["version" => 4989700, "path" => "delete", "size" => 1], - ["version" => 4989200, "path" => "keep", "size" => 1], + ["version" => 4_996_350, "path" => "delete", "size" => 1], + ["version" => 4_992_800, "path" => "keep", "size" => 1], + ["version" => 4_989_800, "path" => "delete", "size" => 1], + ["version" => 4_989_700, "path" => "delete", "size" => 1], + ["version" => 4_989_200, "path" => "keep", "size" => 1], // next slice (2592000sec) start at 4913600 keep one version every 86400 seconds - ["version" => 4913600, "path" => "keep", "size" => 1], - ["version" => 4852800, "path" => "delete", "size" => 1], - ["version" => 4827201, "path" => "delete", "size" => 1], - ["version" => 4827200, "path" => "keep", "size" => 1], - ["version" => 4777201, "path" => "delete", "size" => 1], - ["version" => 4777501, "path" => "delete", "size" => 1], - ["version" => 4740000, "path" => "keep", "size" => 1], + ["version" => 4_913_600, "path" => "keep", "size" => 1], + ["version" => 4_852_800, "path" => "delete", "size" => 1], + ["version" => 4_827_201, "path" => "delete", "size" => 1], + ["version" => 4_827_200, "path" => "keep", "size" => 1], + ["version" => 4_777_201, "path" => "delete", "size" => 1], + ["version" => 4_777_501, "path" => "delete", "size" => 1], + ["version" => 4_740_000, "path" => "keep", "size" => 1], // final slice starts at 2408000 keep one version every 604800 seconds - ["version" => 2408000, "path" => "keep", "size" => 1], - ["version" => 1803201, "path" => "delete", "size" => 1], - ["version" => 1803200, "path" => "keep", "size" => 1], - ["version" => 1800199, "path" => "delete", "size" => 1], - ["version" => 1800100, "path" => "delete", "size" => 1], - ["version" => 1198300, "path" => "keep", "size" => 1], + ["version" => 2_408_000, "path" => "keep", "size" => 1], + ["version" => 1_803_201, "path" => "delete", "size" => 1], + ["version" => 1_803_200, "path" => "keep", "size" => 1], + ["version" => 1_800_199, "path" => "delete", "size" => 1], + ["version" => 1_800_100, "path" => "delete", "size" => 1], + ["version" => 1_198_300, "path" => "keep", "size" => 1], ], 16 // size of all deleted files (every file has the size 1) ], @@ -497,28 +491,28 @@ public function versionsProvider() { // next slice (60sec) starts at 4999990 keep one version every 10 seconds // next slice (3600sec) start at 4999940 keep one version every 60 seconds // next slice (86400sec) start at 4996400 keep one version every 3600 seconds - ["version" => 4996400, "path" => "keep", "size" => 1], - ["version" => 4996350, "path" => "delete", "size" => 1], - ["version" => 4996350, "path" => "delete", "size" => 1], - ["version" => 4992800, "path" => "keep", "size" => 1], - ["version" => 4989800, "path" => "delete", "size" => 1], - ["version" => 4989700, "path" => "delete", "size" => 1], - ["version" => 4989200, "path" => "keep", "size" => 1], + ["version" => 4_996_400, "path" => "keep", "size" => 1], + ["version" => 4_996_350, "path" => "delete", "size" => 1], + ["version" => 4_996_350, "path" => "delete", "size" => 1], + ["version" => 4_992_800, "path" => "keep", "size" => 1], + ["version" => 4_989_800, "path" => "delete", "size" => 1], + ["version" => 4_989_700, "path" => "delete", "size" => 1], + ["version" => 4_989_200, "path" => "keep", "size" => 1], // next slice (2592000sec) start at 4913600 keep one version every 86400 seconds - ["version" => 4913600, "path" => "keep", "size" => 1], - ["version" => 4852800, "path" => "delete", "size" => 1], - ["version" => 4827201, "path" => "delete", "size" => 1], - ["version" => 4827200, "path" => "keep", "size" => 1], - ["version" => 4777201, "path" => "delete", "size" => 1], - ["version" => 4777501, "path" => "delete", "size" => 1], - ["version" => 4740000, "path" => "keep", "size" => 1], + ["version" => 4_913_600, "path" => "keep", "size" => 1], + ["version" => 4_852_800, "path" => "delete", "size" => 1], + ["version" => 4_827_201, "path" => "delete", "size" => 1], + ["version" => 4_827_200, "path" => "keep", "size" => 1], + ["version" => 4_777_201, "path" => "delete", "size" => 1], + ["version" => 4_777_501, "path" => "delete", "size" => 1], + ["version" => 4_740_000, "path" => "keep", "size" => 1], // final slice starts at 2408000 keep one version every 604800 seconds - ["version" => 2408000, "path" => "keep", "size" => 1], - ["version" => 1803201, "path" => "delete", "size" => 1], - ["version" => 1803200, "path" => "keep", "size" => 1], - ["version" => 1800199, "path" => "delete", "size" => 1], - ["version" => 1800100, "path" => "delete", "size" => 1], - ["version" => 1198300, "path" => "keep", "size" => 1], + ["version" => 2_408_000, "path" => "keep", "size" => 1], + ["version" => 1_803_201, "path" => "delete", "size" => 1], + ["version" => 1_803_200, "path" => "keep", "size" => 1], + ["version" => 1_800_199, "path" => "delete", "size" => 1], + ["version" => 1_800_100, "path" => "delete", "size" => 1], + ["version" => 1_198_300, "path" => "keep", "size" => 1], ], 11 // size of all deleted files (every file has the size 1) ], @@ -526,32 +520,32 @@ public function versionsProvider() { [ [ // first slice (10sec) keep one version every 2 seconds - ["version" => 4999999, "path" => "keep", "size" => 1], - ["version" => 4999998, "path" => "delete", "size" => 1], - ["version" => 4999997, "path" => "keep", "size" => 1], - ["version" => 4999995, "path" => "keep", "size" => 1], - ["version" => 4999994, "path" => "delete", "size" => 1], + ["version" => 4_999_999, "path" => "keep", "size" => 1], + ["version" => 4_999_998, "path" => "delete", "size" => 1], + ["version" => 4_999_997, "path" => "keep", "size" => 1], + ["version" => 4_999_995, "path" => "keep", "size" => 1], + ["version" => 4_999_994, "path" => "delete", "size" => 1], //next slice (60sec) starts at 4999990 keep one version every 10 seconds - ["version" => 4999988, "path" => "keep", "size" => 1], - ["version" => 4999978, "path" => "keep", "size" => 1], + ["version" => 4_999_988, "path" => "keep", "size" => 1], + ["version" => 4_999_978, "path" => "keep", "size" => 1], //next slice (3600sec) start at 4999940 keep one version every 60 seconds // next slice (86400sec) start at 4996400 keep one version every 3600 seconds - ["version" => 4989200, "path" => "keep", "size" => 1], + ["version" => 4_989_200, "path" => "keep", "size" => 1], // next slice (2592000sec) start at 4913600 keep one version every 86400 seconds - ["version" => 4913600, "path" => "keep", "size" => 1], - ["version" => 4852800, "path" => "delete", "size" => 1], - ["version" => 4827201, "path" => "delete", "size" => 1], - ["version" => 4827200, "path" => "keep", "size" => 1], - ["version" => 4777201, "path" => "delete", "size" => 1], - ["version" => 4777501, "path" => "delete", "size" => 1], - ["version" => 4740000, "path" => "keep", "size" => 1], + ["version" => 4_913_600, "path" => "keep", "size" => 1], + ["version" => 4_852_800, "path" => "delete", "size" => 1], + ["version" => 4_827_201, "path" => "delete", "size" => 1], + ["version" => 4_827_200, "path" => "keep", "size" => 1], + ["version" => 4_777_201, "path" => "delete", "size" => 1], + ["version" => 4_777_501, "path" => "delete", "size" => 1], + ["version" => 4_740_000, "path" => "keep", "size" => 1], // final slice starts at 2408000 keep one version every 604800 seconds - ["version" => 2408000, "path" => "keep", "size" => 1], - ["version" => 1803201, "path" => "delete", "size" => 1], - ["version" => 1803200, "path" => "keep", "size" => 1], - ["version" => 1800199, "path" => "delete", "size" => 1], - ["version" => 1800100, "path" => "delete", "size" => 1], - ["version" => 1198300, "path" => "keep", "size" => 1], + ["version" => 2_408_000, "path" => "keep", "size" => 1], + ["version" => 1_803_201, "path" => "delete", "size" => 1], + ["version" => 1_803_200, "path" => "keep", "size" => 1], + ["version" => 1_800_199, "path" => "delete", "size" => 1], + ["version" => 1_800_100, "path" => "delete", "size" => 1], + ["version" => 1_198_300, "path" => "keep", "size" => 1], ], 9 // size of all deleted files (every file has the size 1) ], @@ -588,9 +582,9 @@ public function testRename(bool $metaDataEnabled) { $this->rootView->file_put_contents($v2, 'version2'); if ($metaDataEnabled && !$this->objectStoreEnabled) { - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user2])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user2])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user2])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); } // execute rename hook of versions app @@ -648,9 +642,9 @@ public function testRenameInSharedFolder(bool $metaDataEnabled) { $this->rootView->file_put_contents($v2, 'version2'); if ($metaDataEnabled && !$this->objectStoreEnabled) { - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); } $node = \OC::$server->getUserFolder($this->user1)->get('folder1'); @@ -725,9 +719,9 @@ public function testMoveFolder(bool $metaDataEnabled) { $this->rootView->file_put_contents($v2, 'version2'); if ($metaDataEnabled && !$this->objectStoreEnabled) { - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); } // execute rename hook of versions app @@ -790,9 +784,9 @@ public function testMoveFolderIntoSharedFolderAsRecipient(bool $metaDataEnabled) $m0 = $versionsFolder2 . '/folder2/test.txt' . MetaStorage::CURRENT_FILE_PREFIX . MetaStorage::VERSION_FILE_EXT; $m1 = $v1 . MetaStorage::VERSION_FILE_EXT; $m2 = $v2 . MetaStorage::VERSION_FILE_EXT; - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user2])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user2])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user2])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user2], JSON_THROW_ON_ERROR)); } $this->rootView->file_put_contents($v1, 'version1'); @@ -858,9 +852,9 @@ public function testRenameSharedFile(bool $metaDataEnabled) { $this->rootView->file_put_contents($v2, 'version2'); if ($metaDataEnabled && !$this->objectStoreEnabled) { - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); } $node = \OC::$server->getUserFolder($this->user1)->get('test.txt'); @@ -931,9 +925,9 @@ public function testCopy(bool $metaDataEnabled) { $this->rootView->file_put_contents($v2, 'version2'); if ($metaDataEnabled && !$this->objectStoreEnabled) { - \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1])); + \file_put_contents("$this->dataDir/$m0", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); } // execute copy hook of versions app @@ -1003,8 +997,8 @@ public function testGetVersions(string $filepath, bool $enableMetadata) { $this->rootView->file_put_contents($v2, 'version2'); if ($enableMetadata && !$this->objectStoreEnabled) { - \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1])); - \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1])); + \file_put_contents("$this->dataDir/$m1", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); + \file_put_contents("$this->dataDir/$m2", \json_encode(['edited_by' => $this->user1], JSON_THROW_ON_ERROR)); } // execute copy hook of versions app @@ -1149,15 +1143,15 @@ private function doTestRestore(bool $metaDataEnabled) { \file_put_contents("$this->dataDir/$m0", \json_encode([ 'edited_by' => $this->user1, 'version_tag' => '0.3' - ])); + ], JSON_THROW_ON_ERROR)); \file_put_contents("$this->dataDir/$m1", \json_encode([ 'edited_by' => $this->user1, 'version_tag' => '0.2' - ])); + ], JSON_THROW_ON_ERROR)); \file_put_contents("$this->dataDir/$m2", \json_encode([ 'edited_by' => $this->user2, 'version_tag' => '0.1' - ])); + ], JSON_THROW_ON_ERROR)); } $oldVersions = \OCA\Files_Versions\Storage::getVersions( @@ -1371,7 +1365,7 @@ private function createAndCheckVersions(\OC\Files\View $view, $path) { self::loginAsUser($this->user1); // need to scan for the versions - list($rootStorage, ) = $this->rootView->resolvePath($this->user1 . '/files_versions'); + [$rootStorage, ] = $this->rootView->resolvePath($this->user1 . '/files_versions'); $rootStorage->getScanner()->scan('files_versions'); $versions = \OCA\Files_Versions\Storage::getVersions( @@ -1395,7 +1389,7 @@ public static function loginHelper($user, $create = false) { \OC::$server->getUserManager()->createUser($user, $user); } - $storage = new \ReflectionClass('\OCA\Files_Sharing\SharedStorage'); + $storage = new \ReflectionClass('\\' . \OCA\Files_Sharing\SharedStorage::class); $isInitialized = $storage->getProperty('initialized'); $isInitialized->setAccessible(true); $isInitialized->setValue($storage, false); @@ -1411,7 +1405,7 @@ public static function loginHelper($user, $create = false) { private function markTestSkippedIfStorageHasOwnVersioning() { /** @var Storage $storage */ - list($storage, $internalPath) = $this->rootView->resolvePath(self::USERS_VERSIONS_ROOT); + [$storage, $internalPath] = $this->rootView->resolvePath(self::USERS_VERSIONS_ROOT); if ($storage->instanceOfStorage(ObjectStoreStorage::class)) { $this->markTestSkipped(); } diff --git a/apps/provisioning_api/lib/Apps.php b/apps/provisioning_api/lib/Apps.php index 8a30a0a6e99e..36fc71404c72 100644 --- a/apps/provisioning_api/lib/Apps.php +++ b/apps/provisioning_api/lib/Apps.php @@ -30,8 +30,7 @@ use OC_OCS_Result; class Apps { - /** @var \OCP\App\IAppManager */ - private $appManager; + private \OCP\App\IAppManager $appManager; /** * @param \OCP\App\IAppManager $appManager @@ -50,7 +49,7 @@ public function getApps($parameters) { foreach ($apps as $app) { $list[] = $app['id']; } - $filter = isset($_GET['filter']) ? $_GET['filter'] : false; + $filter = $_GET['filter'] ?? false; if ($filter) { switch ($filter) { case 'enabled': diff --git a/apps/provisioning_api/lib/Groups.php b/apps/provisioning_api/lib/Groups.php index 2e2648394b98..9ad96424e26c 100644 --- a/apps/provisioning_api/lib/Groups.php +++ b/apps/provisioning_api/lib/Groups.php @@ -30,14 +30,11 @@ use OCP\IUser; class Groups { - /** @var \OCP\IGroupManager */ - private $groupManager; + private \OCP\IGroupManager $groupManager; - /** @var \OCP\IUserSession */ - private $userSession; + private \OCP\IUserSession $userSession; - /** @var \OCP\IRequest */ - private $request; + private \OCP\IRequest $request; /** * @param \OCP\IGroupManager $groupManager @@ -73,10 +70,9 @@ public function getGroups($parameters) { } $groups = $this->groupManager->search($search, $limit, $offset, 'management'); - $groups = \array_map(function ($group) { - /** @var IGroup $group */ - return $group->getGID(); - }, $groups); + $groups = \array_map(fn ($group) => + /** @var IGroup $group */ + $group->getGID(), $groups); return new OC_OCS_Result(['groups' => $groups]); } @@ -112,10 +108,9 @@ public function getGroup($parameters) { if ($this->groupManager->isAdmin($user->getUID()) || $isSubadminOfGroup) { $users = $this->groupManager->get($groupId)->getUsers(); - $users = \array_map(function ($user) { - /** @var IUser $user */ - return $user->getUID(); - }, $users); + $users = \array_map(fn ($user) => + /** @var IUser $user */ + $user->getUID(), $users); $users = \array_values($users); return new OC_OCS_Result(['users' => $users]); } diff --git a/apps/provisioning_api/lib/Users.php b/apps/provisioning_api/lib/Users.php index 248a15a406aa..d8ad6654c33b 100644 --- a/apps/provisioning_api/lib/Users.php +++ b/apps/provisioning_api/lib/Users.php @@ -29,6 +29,7 @@ namespace OCA\Provisioning_API; +use OC\Group\Manager; use OC\OCS\Result; use OC_Helper; use OCP\API; @@ -43,18 +44,12 @@ use OCP\Util; class Users { - /** @var IUserManager */ - private $userManager; - /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface - private $groupManager; - /** @var IUserSession */ - private $userSession; - /** @var ILogger */ - private $logger; - /** @var IConfig */ - private $config; - /** @var \OC\Authentication\TwoFactorAuth\Manager */ - private $twoFactorAuthManager; + private \OCP\IUserManager $userManager; + private Manager $groupManager; + private \OCP\IUserSession $userSession; + private \OCP\ILogger $logger; + private \OCP\IConfig $config; + private \OC\Authentication\TwoFactorAuth\Manager $twoFactorAuthManager; /** * @param IUserManager $userManager @@ -71,6 +66,9 @@ public function __construct( IConfig $config, \OC\Authentication\TwoFactorAuth\Manager $twoFactorAuthManager ) { + if (!$groupManager instanceof Manager) { + throw new \RuntimeException('Requires internal implementation of IGroupdManager'); + } $this->userManager = $userManager; $this->groupManager = $groupManager; $this->userSession = $userSession; @@ -130,9 +128,9 @@ public function getUsers() { * @return Result */ public function addUser() { - $userId = isset($_POST['userid']) ? $_POST['userid'] : null; - $password = isset($_POST['password']) ? $_POST['password'] : null; - $groups = isset($_POST['groups']) ? $_POST['groups'] : null; + $userId = $_POST['userid'] ?? null; + $password = $_POST['password'] ?? null; + $groups = $_POST['groups'] ?? null; $user = $this->userSession->getUser(); $isAdmin = $this->groupManager->isAdmin($user->getUID()); $subAdminManager = $this->groupManager->getSubAdmin(); @@ -491,7 +489,7 @@ public function addToGroup($parameters) { return new Result(null, API::RESPOND_UNAUTHORISED); } - $groupId = isset($_POST['groupid']) ? $_POST['groupid'] : null; + $groupId = $_POST['groupid'] ?? null; if (($groupId === '') || ($groupId === null) || ($groupId === false)) { return new Result(null, 101); } @@ -526,7 +524,7 @@ public function removeFromGroup($parameters) { return new Result(null, API::RESPOND_UNAUTHORISED); } - $group = isset($parameters['_delete']['groupid']) ? $parameters['_delete']['groupid'] : null; + $group = $parameters['_delete']['groupid'] ?? null; if (($group === '') || ($group === null) || ($group === false)) { return new Result(null, 101); } @@ -672,7 +670,7 @@ public function getUserSubAdminGroups($parameters) { $groups[$key] = $group->getGID(); } - return new Result($groups ? $groups : []); + return new Result($groups ?: []); } else { // No permission to access users groups return new Result(null, API::RESPOND_UNAUTHORISED); diff --git a/apps/provisioning_api/tests/AppsTest.php b/apps/provisioning_api/tests/AppsTest.php index be47d6cab324..65dee4937b71 100644 --- a/apps/provisioning_api/tests/AppsTest.php +++ b/apps/provisioning_api/tests/AppsTest.php @@ -40,8 +40,7 @@ class AppsTest extends TestCase { /** @var IAppManager */ private $appManager; - /** @var Apps */ - private $api; + private \OCA\Provisioning_API\Apps $api; /** @var IUserSession */ private $userSession; diff --git a/apps/provisioning_api/tests/GroupsTest.php b/apps/provisioning_api/tests/GroupsTest.php index a10d8814ae5e..803717ea050b 100644 --- a/apps/provisioning_api/tests/GroupsTest.php +++ b/apps/provisioning_api/tests/GroupsTest.php @@ -48,19 +48,19 @@ class GroupsTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->subAdminManager = $this->getMockBuilder('OC\SubAdmin') + $this->subAdminManager = $this->getMockBuilder(\OC\SubAdmin::class) ->disableOriginalConstructor() ->getMock(); - $this->groupManager = $this->getMockBuilder('OC\Group\Manager') + $this->groupManager = $this->getMockBuilder(\OC\Group\Manager::class) ->disableOriginalConstructor() ->getMock(); $this->groupManager ->method('getSubAdmin') ->willReturn($this->subAdminManager); - $this->userSession = $this->createMock('OCP\IUserSession'); - $this->request = $this->createMock('OCP\IRequest'); + $this->userSession = $this->createMock(\OCP\IUserSession::class); + $this->request = $this->createMock(\OCP\IRequest::class); $this->api = new Groups( $this->groupManager, $this->userSession, @@ -73,7 +73,7 @@ protected function setUp(): void { * @return \OCP\IGroup|\PHPUnit\Framework\MockObject\MockObject */ private function createGroup($gid) { - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(\OCP\IGroup::class); $group ->method('getGID') ->willReturn($gid); @@ -85,7 +85,7 @@ private function createGroup($gid) { * @return \OCP\IUser|\PHPUnit\Framework\MockObject\MockObject */ private function createUser($uid) { - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user ->method('getUID') ->willReturn($uid); @@ -156,7 +156,7 @@ public function testGetGroups($search, $limit, $offset) { $groups = [$this->createGroup('group1'), $this->createGroup('group2')]; - $search = $search === null ? '' : $search; + $search ??= ''; $this->groupManager ->expects($this->once()) diff --git a/apps/provisioning_api/tests/UsersTest.php b/apps/provisioning_api/tests/UsersTest.php index a88edac63c4f..38014fcc520b 100644 --- a/apps/provisioning_api/tests/UsersTest.php +++ b/apps/provisioning_api/tests/UsersTest.php @@ -57,7 +57,7 @@ class UsersTest extends OriginalTest { /** @var Users | MockObject */ protected $api; /** @var \OC\Authentication\TwoFactorAuth\Manager | MockObject */ - private $twoFactorAuthManager; + private \PHPUnit\Framework\MockObject\MockObject $twoFactorAuthManager; protected function tearDown(): void { $_GET = null; diff --git a/apps/systemtags/appinfo/app.php b/apps/systemtags/appinfo/app.php index 84d0e72460da..4b038b603d4f 100644 --- a/apps/systemtags/appinfo/app.php +++ b/apps/systemtags/appinfo/app.php @@ -50,14 +50,14 @@ function () { $activityManager->registerExtension(function () { $application = new \OCP\AppFramework\App('systemtags'); /** @var \OCA\SystemTags\Activity\Extension $extension */ - $extension = $application->getContainer()->query('OCA\SystemTags\Activity\Extension'); + $extension = $application->getContainer()->query(\OCA\SystemTags\Activity\Extension::class); return $extension; }); $managerListener = function (ManagerEvent $event) { $application = new \OCP\AppFramework\App('systemtags'); /** @var \OCA\SystemTags\Activity\Listener $listener */ - $listener = $application->getContainer()->query('OCA\SystemTags\Activity\Listener'); + $listener = $application->getContainer()->query(\OCA\SystemTags\Activity\Listener::class); $listener->event($event); }; @@ -68,14 +68,14 @@ function () { $mapperListener = function (MapperEvent $event) { $application = new \OCP\AppFramework\App('systemtags'); /** @var \OCA\SystemTags\Activity\Listener $listener */ - $listener = $application->getContainer()->query('OCA\SystemTags\Activity\Listener'); + $listener = $application->getContainer()->query(\OCA\SystemTags\Activity\Listener::class); $listener->mapperEvent($event); }; $eventDispatcher->addListener(MapperEvent::EVENT_ASSIGN, $mapperListener); $eventDispatcher->addListener(MapperEvent::EVENT_UNASSIGN, $mapperListener); -if (\class_exists('OCA\Files\App')) { +if (\class_exists(\OCA\Files\App::class)) { \OCA\Files\App::getNavigationManager()->add(function () { $l = \OC::$server->getL10N('systemtags'); return [ diff --git a/apps/systemtags/tests/unit/activity/ExtensionTest.php b/apps/systemtags/tests/unit/activity/ExtensionTest.php index 4bcf3b16ff19..7ae41e5c8253 100644 --- a/apps/systemtags/tests/unit/activity/ExtensionTest.php +++ b/apps/systemtags/tests/unit/activity/ExtensionTest.php @@ -34,13 +34,12 @@ */ class ExtensionTest extends TestCase { /** @var IFactory */ - private $languageFactory; + private \PHPUnit\Framework\MockObject\MockObject $languageFactory; /** @var IManager */ - private $activityManager; + private \PHPUnit\Framework\MockObject\MockObject $activityManager; - /** @var Extension */ - private $extension; + private \OCA\SystemTags\Activity\Extension $extension; public function setUp(): void { parent::setUp(); diff --git a/apps/systemtags/tests/unit/activity/ListenerTest.php b/apps/systemtags/tests/unit/activity/ListenerTest.php index 2133c79dea94..c05826415cdb 100644 --- a/apps/systemtags/tests/unit/activity/ListenerTest.php +++ b/apps/systemtags/tests/unit/activity/ListenerTest.php @@ -51,37 +51,37 @@ class ActivityListenerTest extends \Test\TestCase { /** * @var IGroupManager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** * @var ISystemTagManager */ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var Listener */ - private $listener; + private \PHPUnit\Framework\MockObject\MockObject $listener; /** * @var IUserMountCache */ - private $userMountCache; + private \PHPUnit\Framework\MockObject\MockObject $userMountCache; /** * @var IRootFolder */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; /** * @var IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** * @var IManager */ - private $activityManager; + private \PHPUnit\Framework\MockObject\MockObject $activityManager; protected function setUp(): void { parent::setUp(); diff --git a/apps/updatenotification/appinfo/app.php b/apps/updatenotification/appinfo/app.php index 4e1d654894ae..8d358d50d209 100644 --- a/apps/updatenotification/appinfo/app.php +++ b/apps/updatenotification/appinfo/app.php @@ -41,12 +41,10 @@ } $manager = \OC::$server->getNotificationManager(); - $manager->registerNotifier(function () use ($manager) { - return new \OCA\UpdateNotification\Notification\Notifier( - $manager, - \OC::$server->getL10NFactory() - ); - }, function () { + $manager->registerNotifier(fn () => new \OCA\UpdateNotification\Notification\Notifier( + $manager, + \OC::$server->getL10NFactory() + ), function () { $l = \OC::$server->getL10N('updatenotification'); return [ 'id' => 'updatenotification', diff --git a/apps/updatenotification/lib/Controller/AdminController.php b/apps/updatenotification/lib/Controller/AdminController.php index af0045da92ad..a55c573ebc66 100644 --- a/apps/updatenotification/lib/Controller/AdminController.php +++ b/apps/updatenotification/lib/Controller/AdminController.php @@ -38,20 +38,13 @@ use OCP\Settings\ISettings; class AdminController extends Controller implements ISettings { - /** @var IJobList */ - private $jobList; - /** @var ISecureRandom */ - private $secureRandom; - /** @var IConfig */ - private $config; - /** @var ITimeFactory */ - private $timeFactory; - /** @var UpdateChecker */ - private $updateChecker; - /** @var IL10N */ - private $l10n; - /** @var IDateTimeFormatter */ - private $dateTimeFormatter; + private \OCP\BackgroundJob\IJobList $jobList; + private \OCP\Security\ISecureRandom $secureRandom; + private \OCP\IConfig $config; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; + private \OCA\UpdateNotification\UpdateChecker $updateChecker; + private \OCP\IL10N $l10n; + private \OCP\IDateTimeFormatter $dateTimeFormatter; /** * @param string $appName @@ -134,7 +127,7 @@ public function displayPanel() { } $updateState = $this->updateChecker->getUpdateState(); - $notifyGroups = \json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true); + $notifyGroups = \json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true, 512, JSON_THROW_ON_ERROR); $isNewVersionAvailable = ($updateState === []) ? false : true; $newVersionString = ($updateState === []) ? '' : $updateState['updateVersion']; @@ -179,7 +172,7 @@ public function setChannel($channel) { */ public function createCredentials() { // Create a new job and store the creation date - $this->jobList->add('OCA\UpdateNotification\ResetTokenBackgroundJob'); + $this->jobList->add(\OCA\UpdateNotification\ResetTokenBackgroundJob::class); $this->config->setAppValue('core', 'updater.secret.created', $this->timeFactory->getTime()); // Create a new token diff --git a/apps/updatenotification/lib/Notification/BackgroundJob.php b/apps/updatenotification/lib/Notification/BackgroundJob.php index 67bd30ee87ae..a3e8267880e7 100644 --- a/apps/updatenotification/lib/Notification/BackgroundJob.php +++ b/apps/updatenotification/lib/Notification/BackgroundJob.php @@ -138,7 +138,7 @@ protected function getUsersToNotify() { return $this->users; } - $notifyGroups = \json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true); + $notifyGroups = \json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true, 512, JSON_THROW_ON_ERROR); $this->users = []; foreach ($notifyGroups as $group) { $groupToNotify = $this->groupManager->get($group); diff --git a/apps/updatenotification/lib/UpdateChecker.php b/apps/updatenotification/lib/UpdateChecker.php index 44d98c08621a..8f379dfda1eb 100644 --- a/apps/updatenotification/lib/UpdateChecker.php +++ b/apps/updatenotification/lib/UpdateChecker.php @@ -25,8 +25,7 @@ use OC\Updater\VersionCheck; class UpdateChecker { - /** @var VersionCheck */ - private $updater; + private \OC\Updater\VersionCheck $updater; /** * @param VersionCheck $updater @@ -62,7 +61,7 @@ public function getJavaScript(array $data) { $data['array']['oc_updateState'] = \json_encode([ 'updateAvailable' => true, 'updateVersion' => $this->getUpdateState()['updateVersion'], - 'updateLink' => isset($this->getUpdateState()['updateLink']) ? $this->getUpdateState()['updateLink'] : '', - ]); + 'updateLink' => $this->getUpdateState()['updateLink'] ?? '', + ], JSON_THROW_ON_ERROR); } } diff --git a/apps/updatenotification/tests/Controller/AdminControllerTest.php b/apps/updatenotification/tests/Controller/AdminControllerTest.php index 17a73c518653..8846362e3371 100644 --- a/apps/updatenotification/tests/Controller/AdminControllerTest.php +++ b/apps/updatenotification/tests/Controller/AdminControllerTest.php @@ -40,36 +40,35 @@ class AdminControllerTest extends TestCase { /** @var IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IJobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var ISecureRandom */ - private $secureRandom; + private \PHPUnit\Framework\MockObject\MockObject $secureRandom; /** @var IConfig */ - private $config; - /** @var AdminController */ - private $adminController; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OCA\UpdateNotification\Controller\AdminController $adminController; /** @var ITimeFactory */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** @var IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var UpdateChecker */ - private $updateChecker; + private \PHPUnit\Framework\MockObject\MockObject $updateChecker; /** @var IDateTimeFormatter */ - private $dateTimeFormatter; + private \PHPUnit\Framework\MockObject\MockObject $dateTimeFormatter; public function setUp(): void { parent::setUp(); - $this->request = $this->createMock('\\OCP\\IRequest'); - $this->jobList = $this->createMock('\\OCP\\BackgroundJob\\IJobList'); - $this->secureRandom = $this->createMock('\\OCP\\Security\\ISecureRandom'); - $this->config = $this->createMock('\\OCP\\IConfig'); - $this->timeFactory = $this->createMock('\\OCP\\AppFramework\\Utility\\ITimeFactory'); - $this->l10n = $this->createMock('\\OCP\\IL10N'); - $this->updateChecker = $this->getMockBuilder('\\OCA\\UpdateNotification\\UpdateChecker') + $this->request = $this->createMock('\\' . \OCP\IRequest::class); + $this->jobList = $this->createMock('\\' . \OCP\BackgroundJob\IJobList::class); + $this->secureRandom = $this->createMock('\\' . \OCP\Security\ISecureRandom::class); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->timeFactory = $this->createMock('\\' . \OCP\AppFramework\Utility\ITimeFactory::class); + $this->l10n = $this->createMock('\\' . \OCP\IL10N::class); + $this->updateChecker = $this->getMockBuilder('\\' . \OCA\UpdateNotification\UpdateChecker::class) ->disableOriginalConstructor()->getMock(); - $this->dateTimeFormatter = $this->createMock('\\OCP\\IDateTimeFormatter'); + $this->dateTimeFormatter = $this->createMock('\\' . \OCP\IDateTimeFormatter::class); $this->adminController = new AdminController( 'updatenotification', @@ -178,7 +177,7 @@ public function testCreateCredentials() { $this->jobList ->expects($this->once()) ->method('add') - ->with('OCA\UpdateNotification\ResetTokenBackgroundJob'); + ->with(\OCA\UpdateNotification\ResetTokenBackgroundJob::class); $this->secureRandom ->expects($this->once()) ->method('generate') diff --git a/apps/updatenotification/tests/Notification/BackgroundJobTest.php b/apps/updatenotification/tests/Notification/BackgroundJobTest.php index 46a731fe26c2..fcbdd020f58c 100644 --- a/apps/updatenotification/tests/Notification/BackgroundJobTest.php +++ b/apps/updatenotification/tests/Notification/BackgroundJobTest.php @@ -49,12 +49,12 @@ class BackgroundJobTest extends TestCase { public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('OCP\IConfig'); - $this->notificationManager = $this->createMock('OCP\Notification\IManager'); - $this->groupManager = $this->createMock('OCP\IGroupManager'); - $this->appManager = $this->createMock('OCP\App\IAppManager'); - $this->client = $this->createMock('OCP\Http\Client\IClientService'); - $this->urlGenerator = $this->createMock('OCP\IURLGenerator'); + $this->config = $this->createMock(\OCP\IConfig::class); + $this->notificationManager = $this->createMock(\OCP\Notification\IManager::class); + $this->groupManager = $this->createMock(\OCP\IGroupManager::class); + $this->appManager = $this->createMock(\OCP\App\IAppManager::class); + $this->client = $this->createMock(\OCP\Http\Client\IClientService::class); + $this->urlGenerator = $this->createMock(\OCP\IURLGenerator::class); } /** @@ -73,7 +73,7 @@ protected function getJob(array $methods = []) { ); } { - return $this->getMockBuilder('OCA\UpdateNotification\Notification\BackgroundJob') + return $this->getMockBuilder(\OCA\UpdateNotification\Notification\BackgroundJob::class) ->setConstructorArgs([ $this->config, $this->notificationManager, @@ -137,7 +137,7 @@ public function testCheckCoreUpdate($channel, $versionCheck, $notification) { $job->expects($this->never()) ->method('createVersionCheck'); } else { - $check = $this->getMockBuilder('OC\Updater\VersionCheck') + $check = $this->getMockBuilder(\OC\Updater\VersionCheck::class) ->disableOriginalConstructor() ->getMock(); $check->expects($this->once()) @@ -225,7 +225,7 @@ public function testCreateNotifications($app, $version, $url, $lastNotification, } if ($createNotification) { - $notification = $this->createMock('OCP\Notification\INotification'); + $notification = $this->createMock(\OCP\Notification\INotification::class); $notification->expects($this->once()) ->method('setApp') ->with('updatenotification') @@ -287,7 +287,7 @@ public function testGetUsersToNotify($groups, array $groupUsers, array $expected $this->config->expects($this->once()) ->method('getAppValue') ->with('updatenotification', 'notify_groups', '["admin"]') - ->willReturn(\json_encode($groups)); + ->willReturn(\json_encode($groups, JSON_THROW_ON_ERROR)); $groupMap = []; foreach ($groupUsers as $gid => $uids) { @@ -326,7 +326,7 @@ public function dataDeleteOutdatedNotifications() { * @param string $version */ public function testDeleteOutdatedNotifications($app, $version) { - $notification = $this->createMock('OCP\Notification\INotification'); + $notification = $this->createMock(\OCP\Notification\INotification::class); $notification->expects($this->once()) ->method('setApp') ->with('updatenotification') @@ -354,7 +354,7 @@ public function testDeleteOutdatedNotifications($app, $version) { protected function getUsers(array $userIds) { $users = []; foreach ($userIds as $uid) { - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn($uid); @@ -368,7 +368,7 @@ protected function getUsers(array $userIds) { * @return \OCP\IGroup|\PHPUnit\Framework\MockObject\MockObject */ protected function getGroup($gid) { - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(\OCP\IGroup::class); $group->expects($this->any()) ->method('getGID') ->willReturn($gid); diff --git a/apps/updatenotification/tests/Notification/NotifierTest.php b/apps/updatenotification/tests/Notification/NotifierTest.php index b4aa64bc11ee..55e63167fbd1 100644 --- a/apps/updatenotification/tests/Notification/NotifierTest.php +++ b/apps/updatenotification/tests/Notification/NotifierTest.php @@ -36,8 +36,8 @@ class NotifierTest extends TestCase { public function setUp(): void { parent::setUp(); - $this->notificationManager = $this->createMock('OCP\Notification\IManager'); - $this->l10nFactory = $this->createMock('OCP\L10n\IFactory'); + $this->notificationManager = $this->createMock(\OCP\Notification\IManager::class); + $this->l10nFactory = $this->createMock(\OCP\L10n\IFactory::class); } /** @@ -52,7 +52,7 @@ protected function getNotifier(array $methods = []) { ); } { - return $this->getMockBuilder('OCA\UpdateNotification\Notification\Notifier') + return $this->getMockBuilder(\OCA\UpdateNotification\Notification\Notifier::class) ->setConstructorArgs([ $this->notificationManager, $this->l10nFactory, @@ -80,7 +80,7 @@ public function dataUpdateAlreadyInstalledCheck() { public function testUpdateAlreadyInstalledCheck($versionNotification, $versionInstalled, $exception) { $notifier = $this->getNotifier(); - $notification = $this->createMock('OCP\Notification\INotification'); + $notification = $this->createMock(\OCP\Notification\INotification::class); $notification->expects($this->once()) ->method('getObjectId') ->willReturn($versionNotification); diff --git a/apps/updatenotification/tests/ResetTokenBackgroundJobTest.php b/apps/updatenotification/tests/ResetTokenBackgroundJobTest.php index 929a36183540..2fecac72c643 100644 --- a/apps/updatenotification/tests/ResetTokenBackgroundJobTest.php +++ b/apps/updatenotification/tests/ResetTokenBackgroundJobTest.php @@ -29,16 +29,15 @@ class ResetTokenBackgroundJobTest extends TestCase { /** @var IConfig */ - private $config; - /** @var ResetTokenBackgroundJob */ - private $resetTokenBackgroundJob; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OCA\UpdateNotification\ResetTokenBackgroundJob $resetTokenBackgroundJob; /** @var ITimeFactory */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('\\OCP\\IConfig'); - $this->timeFactory = $this->createMock('\\OCP\\AppFramework\\Utility\\ITimeFactory'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->timeFactory = $this->createMock('\\' . \OCP\AppFramework\Utility\ITimeFactory::class); $this->resetTokenBackgroundJob = new ResetTokenBackgroundJob($this->config, $this->timeFactory); } @@ -64,14 +63,14 @@ public function testRunWithExpiredToken() { ->expects($this->exactly(2)) ->method('getTime') ->willReturnOnConsecutiveCalls( - 1455131633, - 1455045234, + 1_455_131_633, + 1_455_045_234, ); $this->config ->expects($this->once()) ->method('getAppValue') - ->with('core', 'updater.secret.created', 1455045234); + ->with('core', 'updater.secret.created', 1_455_045_234); $this->config ->expects($this->once()) ->method('deleteSystemValue') diff --git a/apps/updatenotification/tests/UpdateCheckerTest.php b/apps/updatenotification/tests/UpdateCheckerTest.php index 2730eb58a849..345d3563faff 100644 --- a/apps/updatenotification/tests/UpdateCheckerTest.php +++ b/apps/updatenotification/tests/UpdateCheckerTest.php @@ -28,14 +28,13 @@ class UpdateCheckerTest extends TestCase { /** @var Updater */ - private $updater; - /** @var UpdateChecker */ - private $updateChecker; + private \PHPUnit\Framework\MockObject\MockObject $updater; + private \OCA\UpdateNotification\UpdateChecker $updateChecker; public function setUp(): void { parent::setUp(); - $this->updater = $this->getMockBuilder('\OC\Updater\VersionCheck') + $this->updater = $this->getMockBuilder('\\' . \OC\Updater\VersionCheck::class) ->disableOriginalConstructor()->getMock(); $this->updateChecker = new UpdateChecker($this->updater); } diff --git a/core/Application.php b/core/Application.php index 8b12fcc9d25a..7ffc17bb8fd8 100644 --- a/core/Application.php +++ b/core/Application.php @@ -70,44 +70,38 @@ public function __construct(array $urlParams= []) { /** * Controllers */ - $container->registerService('AppRegistryController', static function (SimpleContainer $c) use ($server) { - return new AppRegistryController( - $c->query('AppName'), - $server->getRequest(), - $server->getAppManager(), - $server->query('LazyRootFolder'), - $server->getURLGenerator(), - $server->getConfig(), - $server->getLogger() - ); - }); + $container->registerService('AppRegistryController', static fn (SimpleContainer $c) => new AppRegistryController( + $c->query('AppName'), + $server->getRequest(), + $server->getAppManager(), + $server->query('LazyRootFolder'), + $server->getURLGenerator(), + $server->getConfig(), + $server->getLogger() + )); - $container->registerService('LostController', static function (SimpleContainer $c) { - return new LostController( - $c->query('AppName'), - $c->query('Request'), - $c->query('URLGenerator'), - $c->query('UserManager'), - $c->query('Defaults'), - $c->query('L10N'), - $c->query('Config'), - $c->query('SecureRandom'), - $c->query('DefaultEmailAddress'), - $c->query('IsEncryptionEnabled'), - $c->query('Mailer'), - $c->query('TimeFactory'), - $c->query('Logger'), - $c->query('UserSession') - ); - }); - $container->registerService('UserController', static function (SimpleContainer $c) { - return new UserController( - $c->query('AppName'), - $c->query('Request'), - $c->query('UserManager'), - $c->query('Defaults') - ); - }); + $container->registerService('LostController', static fn (SimpleContainer $c) => new LostController( + $c->query('AppName'), + $c->query('Request'), + $c->query('URLGenerator'), + $c->query('UserManager'), + $c->query('Defaults'), + $c->query('L10N'), + $c->query('Config'), + $c->query('SecureRandom'), + $c->query('DefaultEmailAddress'), + $c->query('IsEncryptionEnabled'), + $c->query('Mailer'), + $c->query('TimeFactory'), + $c->query('Logger'), + $c->query('UserSession') + )); + $container->registerService('UserController', static fn (SimpleContainer $c) => new UserController( + $c->query('AppName'), + $c->query('Request'), + $c->query('UserManager'), + $c->query('Defaults') + )); $container->registerService('AvatarController', static function (SimpleContainer $c) { /** @var IServerContainer $server */ $server = $c->query('ServerContainer'); @@ -123,45 +117,37 @@ public function __construct(array $urlParams= []) { $c->query('Logger') ); }); - $container->registerService('LoginController', static function (SimpleContainer $c) { - return new LoginController( - $c->query('AppName'), - $c->query('Request'), - $c->query('UserManager'), - $c->query('Config'), - $c->query('Session'), - $c->query('UserSession'), - $c->query('URLGenerator'), - $c->query('TwoFactorAuthManager'), - $c->query('ServerContainer')->getLicenseManager() - ); - }); - $container->registerService('TwoFactorChallengeController', static function (SimpleContainer $c) { - return new TwoFactorChallengeController( - $c->query('AppName'), - $c->query('Request'), - $c->query('TwoFactorAuthManager'), - $c->query('UserSession'), - $c->query('Session'), - $c->query('URLGenerator') - ); - }); - $container->registerService('TokenController', static function (SimpleContainer $c) { - return new TokenController( - $c->query('AppName'), - $c->query('Request'), - $c->query('UserManager'), - $c->query('ServerContainer')->query('OC\Authentication\Token\IProvider'), - $c->query('TwoFactorAuthManager'), - $c->query('SecureRandom') - ); - }); - $container->registerService('CloudController', static function (SimpleContainer $c) { - return new CloudController( - $c->query('AppName'), - $c->query('Request') - ); - }); + $container->registerService('LoginController', static fn (SimpleContainer $c) => new LoginController( + $c->query('AppName'), + $c->query('Request'), + $c->query('UserManager'), + $c->query('Config'), + $c->query('Session'), + $c->query('UserSession'), + $c->query('URLGenerator'), + $c->query('TwoFactorAuthManager'), + $c->query('ServerContainer')->getLicenseManager() + )); + $container->registerService('TwoFactorChallengeController', static fn (SimpleContainer $c) => new TwoFactorChallengeController( + $c->query('AppName'), + $c->query('Request'), + $c->query('TwoFactorAuthManager'), + $c->query('UserSession'), + $c->query('Session'), + $c->query('URLGenerator') + )); + $container->registerService('TokenController', static fn (SimpleContainer $c) => new TokenController( + $c->query('AppName'), + $c->query('Request'), + $c->query('UserManager'), + $c->query('ServerContainer')->query(\OC\Authentication\Token\IProvider::class), + $c->query('TwoFactorAuthManager'), + $c->query('SecureRandom') + )); + $container->registerService('CloudController', static fn (SimpleContainer $c) => new CloudController( + $c->query('AppName'), + $c->query('Request') + )); $container->registerService('RolesController', static function (SimpleContainer $c) { /** @var IServerContainer $serverContainer */ $serverContainer = $c->query('ServerContainer'); @@ -185,15 +171,13 @@ public function __construct(array $urlParams= []) { $c->query('UserManager') ); }); - $container->registerService('CronController', static function (SimpleContainer $c) { - return new CronController( - $c->query('AppName'), - $c->query('Request'), - $c->query(IConfig::class), - $c->query(ILogger::class), - $c->query(IJobList::class) - ); - }); + $container->registerService('CronController', static fn (SimpleContainer $c) => new CronController( + $c->query('AppName'), + $c->query('Request'), + $c->query(IConfig::class), + $c->query(ILogger::class), + $c->query(IJobList::class) + )); $container->registerService('LicenseController', static function (SimpleContainer $c) { $server = $c->query('ServerContainer'); return new LicenseController( @@ -206,53 +190,21 @@ public function __construct(array $urlParams= []) { /** * Core class wrappers */ - $container->registerService('IsEncryptionEnabled', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getEncryptionManager()->isEnabled(); - }); - $container->registerService('URLGenerator', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getURLGenerator(); - }); - $container->registerService('UserManager', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getUserManager(); - }); - $container->registerService('Config', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getConfig(); - }); - $container->registerService('L10N', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getL10N('core'); - }); - $container->registerService('SecureRandom', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getSecureRandom(); - }); - $container->registerService('AvatarManager', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getAvatarManager(); - }); - $container->registerService('Session', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getSession(); - }); - $container->registerService('UserSession', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getUserSession(); - }); - $container->registerService('Cache', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getCache(); - }); - $container->registerService('Defaults', static function () { - return new OC_Defaults; - }); - $container->registerService('Mailer', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getMailer(); - }); - $container->registerService('Logger', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getLogger(); - }); - $container->registerService('TimeFactory', static function (SimpleContainer $c) { - return new TimeFactory(); - }); - $container->registerService('DefaultEmailAddress', static function () { - return Util::getDefaultEmailAddress('lostpassword-noreply'); - }); - $container->registerService('TwoFactorAuthManager', static function (SimpleContainer $c) { - return $c->query('ServerContainer')->getTwoFactorAuthManager(); - }); + $container->registerService('IsEncryptionEnabled', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getEncryptionManager()->isEnabled()); + $container->registerService('URLGenerator', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getURLGenerator()); + $container->registerService('UserManager', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getUserManager()); + $container->registerService('Config', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getConfig()); + $container->registerService('L10N', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getL10N('core')); + $container->registerService('SecureRandom', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getSecureRandom()); + $container->registerService('AvatarManager', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getAvatarManager()); + $container->registerService('Session', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getSession()); + $container->registerService('UserSession', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getUserSession()); + $container->registerService('Cache', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getCache()); + $container->registerService('Defaults', static fn () => new OC_Defaults); + $container->registerService('Mailer', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getMailer()); + $container->registerService('Logger', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getLogger()); + $container->registerService('TimeFactory', static fn (SimpleContainer $c) => new TimeFactory()); + $container->registerService('DefaultEmailAddress', static fn () => Util::getDefaultEmailAddress('lostpassword-noreply')); + $container->registerService('TwoFactorAuthManager', static fn (SimpleContainer $c) => $c->query('ServerContainer')->getTwoFactorAuthManager()); } } diff --git a/core/Command/App/CheckCode.php b/core/Command/App/CheckCode.php index c6b7f6c75410..ea19083b3d37 100644 --- a/core/Command/App/CheckCode.php +++ b/core/Command/App/CheckCode.php @@ -36,16 +36,14 @@ use Symfony\Component\Console\Output\OutputInterface; class CheckCode extends Command { - /** @var InfoParser */ - private $infoParser; + private \OC\App\InfoParser $infoParser; - /** @var IAppManager */ - private $appManager; + private \OCP\App\IAppManager $appManager; protected $checkers = [ - 'private' => '\OC\App\CodeChecker\PrivateCheck', - 'deprecation' => '\OC\App\CodeChecker\DeprecationCheck', - 'strong-comparison' => '\OC\App\CodeChecker\StrongComparisonCheck', + 'private' => '\\' . \OC\App\CodeChecker\PrivateCheck::class, + 'deprecation' => '\\' . \OC\App\CodeChecker\DeprecationCheck::class, + 'strong-comparison' => '\\' . \OC\App\CodeChecker\StrongComparisonCheck::class, ]; public function __construct(InfoParser $infoParser, IAppManager $appManager) { @@ -109,9 +107,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($count > 0 || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln(" {$count} errors"); } - \usort($errors, function ($a, $b) { - return $a['line'] - $b['line']; - }); + \usort($errors, fn ($a, $b) => $a['line'] - $b['line']); foreach ($errors as $p) { $line = \sprintf("%' 4d", $p['line']); diff --git a/core/Command/Background/Queue/Delete.php b/core/Command/Background/Queue/Delete.php index e0c35bdb2769..532159d4157c 100644 --- a/core/Command/Background/Queue/Delete.php +++ b/core/Command/Background/Queue/Delete.php @@ -28,8 +28,7 @@ use Symfony\Component\Console\Output\OutputInterface; class Delete extends Command { - /** @var \OCP\BackgroundJob\IJobList */ - private $jobList; + private \OCP\BackgroundJob\IJobList $jobList; public function __construct(IJobList $jobList) { $this->jobList = $jobList; diff --git a/core/Command/Background/Queue/Status.php b/core/Command/Background/Queue/Status.php index 2689415ef3ff..849fa2271169 100644 --- a/core/Command/Background/Queue/Status.php +++ b/core/Command/Background/Queue/Status.php @@ -30,8 +30,7 @@ use Symfony\Component\Console\Output\OutputInterface; class Status extends Command { - /** @var \OCP\BackgroundJob\IJobList */ - private $jobList; + private \OCP\BackgroundJob\IJobList $jobList; public function __construct(IJobList $jobList) { $this->jobList = $jobList; @@ -47,7 +46,7 @@ protected function configure() { private function getJobArgumentAsString($argument) { if (\is_array($argument)) { - $argument = \json_encode($argument); + $argument = \json_encode($argument, JSON_THROW_ON_ERROR); } return $argument; } diff --git a/core/Command/Base.php b/core/Command/Base.php index 00ffe872a3f5..a0bc53e70d71 100644 --- a/core/Command/Base.php +++ b/core/Command/Base.php @@ -35,11 +35,9 @@ class Base extends Command { protected $defaultOutputFormat = self::OUTPUT_FORMAT_PLAIN; - /** @var boolean */ - private $php_pcntl_signal = false; + private bool $php_pcntl_signal = false; - /** @var boolean */ - private $interrupted = false; + private bool $interrupted = false; protected function configure() { $this @@ -62,7 +60,7 @@ protected function configure() { protected function writeArrayInOutputFormat(InputInterface $input, OutputInterface $output, $items, $prefix = self::DEFAULT_OUTPUT_PREFIX, $showIntKeys = false) { switch ($input->getOption('output')) { case self::OUTPUT_FORMAT_JSON: - $output->writeln(\json_encode($items)); + $output->writeln(\json_encode($items, JSON_THROW_ON_ERROR)); break; case self::OUTPUT_FORMAT_JSON_PRETTY: $output->writeln(\json_encode($items, JSON_PRETTY_PRINT)); @@ -102,7 +100,7 @@ protected function writeMixedInOutputFormat(InputInterface $input, OutputInterfa switch ($input->getOption('output')) { case self::OUTPUT_FORMAT_JSON: - $output->writeln(\json_encode($item)); + $output->writeln(\json_encode($item, JSON_THROW_ON_ERROR)); break; case self::OUTPUT_FORMAT_JSON_PRETTY: $output->writeln(\json_encode($item, JSON_PRETTY_PRINT)); diff --git a/core/Command/Check.php b/core/Command/Check.php index 3f77ff7135be..a4f62fd1e68b 100644 --- a/core/Command/Check.php +++ b/core/Command/Check.php @@ -27,10 +27,7 @@ use Symfony\Component\Console\Output\OutputInterface; class Check extends Base { - /** - * @var IConfig - */ - private $config; + private \OCP\IConfig $config; public function __construct(IConfig $config) { parent::__construct(); @@ -49,9 +46,7 @@ protected function configure() { protected function execute(InputInterface $input, OutputInterface $output): int { $errors = \OC_Util::checkServer($this->config); if (!empty($errors)) { - $errors = \array_map(function ($item) { - return (string) $item['error']; - }, $errors); + $errors = \array_map(fn ($item) => (string) $item['error'], $errors); $this->writeArrayInOutputFormat($input, $output, $errors); return 1; diff --git a/core/Command/Config/Import.php b/core/Command/Config/Import.php index 2add77156e99..f371ce81d13a 100644 --- a/core/Command/Config/Import.php +++ b/core/Command/Config/Import.php @@ -119,7 +119,7 @@ protected function getArrayFromFile($importFile) { * @throws \UnexpectedValueException when the array is invalid */ protected function validateFileContent($content) { - $decodedContent = \json_decode($content, true); + $decodedContent = \json_decode($content, true, 512, JSON_THROW_ON_ERROR); if (!\is_array($decodedContent) || empty($decodedContent)) { throw new \UnexpectedValueException('The file must contain a valid json array'); } diff --git a/core/Command/Config/System/SetConfig.php b/core/Command/Config/System/SetConfig.php index 9f44fd36cd2a..8fe80ef7fd9c 100644 --- a/core/Command/Config/System/SetConfig.php +++ b/core/Command/Config/System/SetConfig.php @@ -171,7 +171,7 @@ protected function castValue($value, $type) { ]; case 'json': - $decodedJson = \json_decode($value, true); + $decodedJson = \json_decode($value, true, 512, JSON_THROW_ON_ERROR); if ($decodedJson === null) { throw new \InvalidArgumentException('Unable to parse value as json'); } diff --git a/core/Command/Db/ConvertMysqlToMB4.php b/core/Command/Db/ConvertMysqlToMB4.php index 37772f24589b..35ae76ec2190 100644 --- a/core/Command/Db/ConvertMysqlToMB4.php +++ b/core/Command/Db/ConvertMysqlToMB4.php @@ -33,14 +33,11 @@ use Symfony\Component\Console\Output\OutputInterface; class ConvertMysqlToMB4 extends Command { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; /** * @param IConfig $config diff --git a/core/Command/Db/ConvertType.php b/core/Command/Db/ConvertType.php index b51971858291..0e3224e44568 100644 --- a/core/Command/Db/ConvertType.php +++ b/core/Command/Db/ConvertType.php @@ -294,9 +294,7 @@ protected function getExistingApps($enabledOnly) { // filter apps with missing code $existingApps = \array_filter( $apps, - function ($appId) { - return $this->appManager->getAppPath($appId) !== false; - } + fn ($appId) => $this->appManager->getAppPath($appId) !== false ); return $existingApps; diff --git a/core/Command/Db/Migrations/ExecuteCommand.php b/core/Command/Db/Migrations/ExecuteCommand.php index dc7e62fe1515..14179a710d20 100644 --- a/core/Command/Db/Migrations/ExecuteCommand.php +++ b/core/Command/Db/Migrations/ExecuteCommand.php @@ -30,8 +30,7 @@ use Symfony\Component\Console\Output\OutputInterface; class ExecuteCommand extends Command { - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; /** * ExecuteCommand constructor. diff --git a/core/Command/Db/Migrations/GenerateCommand.php b/core/Command/Db/Migrations/GenerateCommand.php index 543043cf570b..ffffe023f44c 100644 --- a/core/Command/Db/Migrations/GenerateCommand.php +++ b/core/Command/Db/Migrations/GenerateCommand.php @@ -31,7 +31,7 @@ use Symfony\Component\Console\Output\OutputInterface; class GenerateCommand extends Command { - private static $_templateSimple = + private static string $_templateSimple = '; @@ -52,7 +52,7 @@ public function run(IOutput $out) { } '; - private static $_templateSchema = + private static string $_templateSchema = '; @@ -70,7 +70,7 @@ public function changeSchema(Schema $schema, array $options) { } '; - private static $_templateSql = + private static string $_templateSql = '; @@ -88,8 +88,7 @@ public function sql(IDBConnection $connection) { } '; - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; /** * @param IDBConnection $connection diff --git a/core/Command/Db/Migrations/MigrateCommand.php b/core/Command/Db/Migrations/MigrateCommand.php index 4940805f81d9..ec506b8404ad 100644 --- a/core/Command/Db/Migrations/MigrateCommand.php +++ b/core/Command/Db/Migrations/MigrateCommand.php @@ -30,8 +30,7 @@ use Symfony\Component\Console\Output\OutputInterface; class MigrateCommand extends Command { - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; /** * @param IDBConnection $connection diff --git a/core/Command/Db/Migrations/StatusCommand.php b/core/Command/Db/Migrations/StatusCommand.php index e98767ce3014..04adf4768d18 100644 --- a/core/Command/Db/Migrations/StatusCommand.php +++ b/core/Command/Db/Migrations/StatusCommand.php @@ -30,8 +30,7 @@ use Symfony\Component\Console\Output\OutputInterface; class StatusCommand extends Command { - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; /** * @param IDBConnection $connection diff --git a/core/Command/Db/RestoreDefaultRowFormat.php b/core/Command/Db/RestoreDefaultRowFormat.php index 84e9cad2b88d..80682c2a8ac8 100644 --- a/core/Command/Db/RestoreDefaultRowFormat.php +++ b/core/Command/Db/RestoreDefaultRowFormat.php @@ -29,11 +29,9 @@ use Symfony\Component\Console\Output\OutputInterface; class RestoreDefaultRowFormat extends Command { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; /** * @param IConfig $config diff --git a/core/Command/Group/AddMember.php b/core/Command/Group/AddMember.php index 1db11aa188cd..33e67fcfecb3 100644 --- a/core/Command/Group/AddMember.php +++ b/core/Command/Group/AddMember.php @@ -33,8 +33,7 @@ class AddMember extends Command { /** @var \OCP\IGroupManager */ protected $groupManager; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; /** * @param IGroupManager $groupManager diff --git a/core/Command/Group/ListGroups.php b/core/Command/Group/ListGroups.php index 09c43962c094..c8f600009d72 100644 --- a/core/Command/Group/ListGroups.php +++ b/core/Command/Group/ListGroups.php @@ -57,10 +57,9 @@ protected function configure() { protected function execute(InputInterface $input, OutputInterface $output): int { $groupNameSubString = $input->getArgument('search-pattern'); $groups = $this->groupManager->search($groupNameSubString, null, null, 'management', true); - $groups = \array_map(function ($group) { - /** @var IGroup $group */ - return $group->getGID(); - }, $groups); + $groups = \array_map(fn ($group) => + /** @var IGroup $group */ + $group->getGID(), $groups); parent::writeArrayInOutputFormat($input, $output, $groups); return 0; } diff --git a/core/Command/Group/RemoveMember.php b/core/Command/Group/RemoveMember.php index 894c32d0a6fe..4785accffbab 100644 --- a/core/Command/Group/RemoveMember.php +++ b/core/Command/Group/RemoveMember.php @@ -33,8 +33,7 @@ class RemoveMember extends Command { /** @var \OCP\IGroupManager */ protected $groupManager; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; /** * @param IGroupManager $groupManager diff --git a/core/Command/Integrity/CheckApp.php b/core/Command/Integrity/CheckApp.php index e72cf6b35f41..aa735012abd0 100644 --- a/core/Command/Integrity/CheckApp.php +++ b/core/Command/Integrity/CheckApp.php @@ -34,10 +34,7 @@ * @package OC\Core\Command\Integrity */ class CheckApp extends Base { - /** - * @var Checker - */ - private $checker; + private \OC\IntegrityCheck\Checker $checker; public function __construct(Checker $checker) { parent::__construct(); diff --git a/core/Command/Integrity/CheckCore.php b/core/Command/Integrity/CheckCore.php index 31d0df9888ca..bc7d1bc5c93c 100644 --- a/core/Command/Integrity/CheckCore.php +++ b/core/Command/Integrity/CheckCore.php @@ -33,10 +33,7 @@ * @package OC\Core\Command\Integrity */ class CheckCore extends Base { - /** - * @var Checker - */ - private $checker; + private \OC\IntegrityCheck\Checker $checker; public function __construct(Checker $checker) { parent::__construct(); diff --git a/core/Command/Integrity/SignApp.php b/core/Command/Integrity/SignApp.php index a68c47cf649c..8f3785df42e5 100644 --- a/core/Command/Integrity/SignApp.php +++ b/core/Command/Integrity/SignApp.php @@ -38,12 +38,9 @@ * @package OC\Core\Command\Integrity */ class SignApp extends Command { - /** @var Checker */ - private $checker; - /** @var FileAccessHelper */ - private $fileAccessHelper; - /** @var IURLGenerator */ - private $urlGenerator; + private \OC\IntegrityCheck\Checker $checker; + private \OC\IntegrityCheck\Helpers\FileAccessHelper $fileAccessHelper; + private \OCP\IURLGenerator $urlGenerator; /** * @param Checker $checker diff --git a/core/Command/Integrity/SignCore.php b/core/Command/Integrity/SignCore.php index a998adfcc29b..d5f5edbc6103 100644 --- a/core/Command/Integrity/SignCore.php +++ b/core/Command/Integrity/SignCore.php @@ -37,10 +37,8 @@ * @package OC\Core\Command\Integrity */ class SignCore extends Command { - /** @var Checker */ - private $checker; - /** @var FileAccessHelper */ - private $fileAccessHelper; + private \OC\IntegrityCheck\Checker $checker; + private \OC\IntegrityCheck\Helpers\FileAccessHelper $fileAccessHelper; /** * @param Checker $checker diff --git a/core/Command/L10n/CreateJs.php b/core/Command/L10n/CreateJs.php index db17d6201a14..a9b4d723a70d 100644 --- a/core/Command/L10n/CreateJs.php +++ b/core/Command/L10n/CreateJs.php @@ -86,7 +86,7 @@ private function getAllLanguages($path) { } private function writeFiles($app, $path, $lang, OutputInterface $output) { - list($translations, $plurals) = $this->loadTranslations($path, $lang); + [$translations, $plurals] = $this->loadTranslations($path, $lang); $this->writeJsFile($app, $path, $lang, $output, $translations, $plurals); $this->writeJsonFile($path, $lang, $output, $translations, $plurals); } @@ -119,7 +119,7 @@ private function writeJsonFile($path, $lang, OutputInterface $output, $translati return; } $content = ['translations' => $translations, 'pluralForm' => $plurals]; - \file_put_contents($jsFile, \json_encode($content)); + \file_put_contents($jsFile, \json_encode($content, JSON_THROW_ON_ERROR)); $output->writeln("Json translation file generated: $jsFile"); } diff --git a/core/Command/Maintenance/DataFingerprint.php b/core/Command/Maintenance/DataFingerprint.php index 665e90401b71..cbd1932a9e62 100644 --- a/core/Command/Maintenance/DataFingerprint.php +++ b/core/Command/Maintenance/DataFingerprint.php @@ -30,12 +30,9 @@ use Symfony\Component\Console\Style\SymfonyStyle; class DataFingerprint extends Command { - /** @var IConfig */ - private $config; - /** @var ITimeFactory */ - private $timeFactory; - /** @var ILogger */ - private $logger; + private \OCP\IConfig $config; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; + private \OCP\ILogger $logger; public function __construct( IConfig $config, diff --git a/core/Command/Maintenance/Install.php b/core/Command/Maintenance/Install.php index 79f1acf46ad7..5822afe22917 100644 --- a/core/Command/Maintenance/Install.php +++ b/core/Command/Maintenance/Install.php @@ -34,10 +34,7 @@ use Symfony\Component\Console\Question\Question; class Install extends Command { - /** - * @var IConfig - */ - private $config; + private \OCP\IConfig $config; public function __construct(IConfig $config) { parent::__construct(); diff --git a/core/Command/Maintenance/Repair.php b/core/Command/Maintenance/Repair.php index e30370a0ee5a..74ede69ffbee 100644 --- a/core/Command/Maintenance/Repair.php +++ b/core/Command/Maintenance/Repair.php @@ -43,14 +43,10 @@ class Repair extends Command { protected $repair; /** @var IConfig $config */ protected $config; - /** @var EventDispatcherInterface $dispatcher */ - private $dispatcher; - /** @var IAppManager $appManager */ - private $appManager; - /** @var ProgressBar */ - private $progress; - /** @var OutputInterface $output */ - private $output; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher; + private \OCP\App\IAppManager $appManager; + private ?\Symfony\Component\Console\Helper\ProgressBar $progress = null; + private ?\Symfony\Component\Console\Output\OutputInterface $output = null; /** * @param \OC\Repair $repair diff --git a/core/Command/Previews/Cleanup.php b/core/Command/Previews/Cleanup.php index 1560c3b6e237..30b7455f7c4d 100644 --- a/core/Command/Previews/Cleanup.php +++ b/core/Command/Previews/Cleanup.php @@ -28,10 +28,7 @@ use Symfony\Component\Console\Output\OutputInterface; class Cleanup extends Base { - /** - * @var IDBConnection - */ - private $connection; + private \OCP\IDBConnection $connection; public function __construct(IDBConnection $connection) { parent::__construct(); diff --git a/core/Command/Security/CreateSignKey.php b/core/Command/Security/CreateSignKey.php index dbe0a43aed02..4732819de845 100644 --- a/core/Command/Security/CreateSignKey.php +++ b/core/Command/Security/CreateSignKey.php @@ -31,18 +31,9 @@ use Symfony\Component\Console\Question\ConfirmationQuestion; class CreateSignKey extends Base { - /** - * @var IUserManager - */ - private $userManager; - /** - * @var IConfig - */ - private $config; - /** - * @var ISecureRandom - */ - private $secureRandom; + private \OCP\IUserManager $userManager; + private \OCP\IConfig $config; + private \OCP\Security\ISecureRandom $secureRandom; public function __construct(IUserManager $userManager, IConfig $config, ISecureRandom $secureRandom) { parent::__construct(); diff --git a/core/Command/Security/ListCertificates.php b/core/Command/Security/ListCertificates.php index f2bee52ba4fd..8991915e2939 100644 --- a/core/Command/Security/ListCertificates.php +++ b/core/Command/Security/ListCertificates.php @@ -51,8 +51,7 @@ protected function configure() { protected function execute(InputInterface $input, OutputInterface $output): int { $outputType = $input->getOption('output'); if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) { - $certificates = \array_map(function (ICertificate $certificate) { - return [ + $certificates = \array_map(fn (ICertificate $certificate) => [ 'name' => $certificate->getName(), 'common_name' => $certificate->getCommonName(), 'organization' => $certificate->getOrganization(), @@ -60,10 +59,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int 'issuer' => $certificate->getIssuerName(), 'issuer_organization' => $certificate->getIssuerOrganization(), 'issue_date' => $certificate->getIssueDate()->format(\DateTime::ATOM) - ]; - }, $this->certificateManager->listCertificates()); + ], $this->certificateManager->listCertificates()); if ($outputType === self::OUTPUT_FORMAT_JSON) { - $output->writeln(\json_encode(\array_values($certificates))); + $output->writeln(\json_encode(\array_values($certificates), JSON_THROW_ON_ERROR)); } else { $output->writeln(\json_encode(\array_values($certificates), JSON_PRETTY_PRINT)); } @@ -77,15 +75,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int 'Issued By' ]); - $rows = \array_map(function (ICertificate $certificate) { - return [ + $rows = \array_map(fn (ICertificate $certificate) => [ $certificate->getName(), $certificate->getCommonName(), $certificate->getOrganization(), $this->l->l('date', $certificate->getExpireDate()), $certificate->getIssuerName() - ]; - }, $this->certificateManager->listCertificates()); + ], $this->certificateManager->listCertificates()); $table->setRows($rows); $table->render(); } diff --git a/core/Command/Security/ListRoutes.php b/core/Command/Security/ListRoutes.php index f82ec91253d7..c58dd5e2b509 100644 --- a/core/Command/Security/ListRoutes.php +++ b/core/Command/Security/ListRoutes.php @@ -99,16 +99,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int } } } - \usort($rows, function ($a, $b) { - return \strcmp($a['path'], $b['path']); - }); + \usort($rows, fn ($a, $b) => \strcmp($a['path'], $b['path'])); $rows = \array_map(function ($row) { $row['methods'] = \implode(',', $row['methods']); return $row; }, $rows); if ($outputType === self::OUTPUT_FORMAT_JSON) { - $output->write(\json_encode($rows)); + $output->write(\json_encode($rows, JSON_THROW_ON_ERROR)); } elseif ($outputType === self::OUTPUT_FORMAT_JSON_PRETTY) { $output->writeln(\json_encode($rows, JSON_PRETTY_PRINT)); } else { @@ -183,9 +181,7 @@ private function listControllerNames($appName, $controllerName) { yield $appNameSpace . $namespace . \ucfirst(\strtolower($controllerName)); yield $appNameSpace . $namespace . $controllerName . 'Controller'; yield $appNameSpace . $namespace . \ucfirst(\strtolower($controllerName)) . 'Controller'; - $controllerName = \implode('', \array_map(function ($word) { - return \ucfirst($word); - }, \explode('_', $controllerName))); + $controllerName = \implode('', \array_map(fn ($word) => \ucfirst($word), \explode('_', $controllerName))); yield $appNameSpace . $namespace . $controllerName; yield $appNameSpace . $namespace . \ucfirst(\strtolower($controllerName)); yield $appNameSpace . $namespace . $controllerName . 'Controller'; diff --git a/core/Command/System/Cron.php b/core/Command/System/Cron.php index 81f1bb19c83c..3767f2b3d278 100644 --- a/core/Command/System/Cron.php +++ b/core/Command/System/Cron.php @@ -32,14 +32,10 @@ use Symfony\Component\Console\Output\OutputInterface; class Cron extends Command { - /** @var \OCP\BackgroundJob\IJobList */ - private $jobList; - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; - /** @var ITempManager */ - private $tempManager; + private \OCP\BackgroundJob\IJobList $jobList; + private \OCP\IConfig $config; + private \OCP\ILogger $logger; + private \OCP\ITempManager $tempManager; /** * Cron constructor. diff --git a/core/Command/TwoFactorAuth/Disable.php b/core/Command/TwoFactorAuth/Disable.php index e1ca2b29363b..16b946120b57 100644 --- a/core/Command/TwoFactorAuth/Disable.php +++ b/core/Command/TwoFactorAuth/Disable.php @@ -29,11 +29,9 @@ use Symfony\Component\Console\Output\OutputInterface; class Disable extends Base { - /** @var Manager */ - private $manager; + private \OC\Authentication\TwoFactorAuth\Manager $manager; - /** @var UserManager */ - private $userManager; + private \OC\User\Manager $userManager; public function __construct(Manager $manager, UserManager $userManager) { parent::__construct('twofactorauth:disable'); diff --git a/core/Command/TwoFactorAuth/Enable.php b/core/Command/TwoFactorAuth/Enable.php index 6fec24df3a66..5cbaf02dcbef 100644 --- a/core/Command/TwoFactorAuth/Enable.php +++ b/core/Command/TwoFactorAuth/Enable.php @@ -29,11 +29,9 @@ use Symfony\Component\Console\Output\OutputInterface; class Enable extends Base { - /** @var Manager */ - private $manager; + private \OC\Authentication\TwoFactorAuth\Manager $manager; - /** @var UserManager */ - private $userManager; + private \OC\User\Manager $userManager; public function __construct(Manager $manager, UserManager $userManager) { parent::__construct('twofactorauth:enable'); diff --git a/core/Command/Upgrade.php b/core/Command/Upgrade.php index 19d529975f2f..d13a4cf460c7 100644 --- a/core/Command/Upgrade.php +++ b/core/Command/Upgrade.php @@ -49,14 +49,11 @@ class Upgrade extends Command { public const ERROR_INVALID_ARGUMENTS = 4; public const ERROR_FAILURE = 5; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var ICacheFactory */ - private $cacheFactory; + private \OCP\ICacheFactory $cacheFactory; /** * @param IConfig $config @@ -198,17 +195,17 @@ protected function execute(InputInterface $input, OutputInterface $output): int $dispatcher->addListener('\OC\Repair::warning', $repairListener); $dispatcher->addListener('\OC\Repair::error', $repairListener); - $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'maintenanceEnabled', function () use ($output) { $output->writeln('Turned on maintenance mode'); }); - $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'maintenanceDisabled', function () use ($output) { $output->writeln('Turned off maintenance mode'); }); - $updater->listen('\OC\Updater', 'maintenanceActive', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'maintenanceActive', function () use ($output) { $output->writeln('Maintenance mode is kept active'); }); $updater->listen( - '\OC\Updater', + '\\' . \OC\Updater::class, 'updateEnd', function ($success) use ($output) { if ($success) { @@ -219,52 +216,52 @@ function ($success) use ($output) { $output->writeln($message); } ); - $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'dbUpgradeBefore', function () use ($output) { $output->writeln('Updating database schema'); }); - $updater->listen('\OC\Updater', 'dbUpgrade', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'dbUpgrade', function () use ($output) { $output->writeln('Updated database'); }); - $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'dbSimulateUpgradeBefore', function () use ($output) { $output->writeln('Checking whether the database schema can be updated (this can take a long time depending on the database size)'); }); - $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'dbSimulateUpgrade', function () use ($output) { $output->writeln('Checked database schema update'); }); - $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'incompatibleAppDisabled', function ($app) use ($output) { $output->writeln('Disabled incompatible app: ' . $app . ''); }); - $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'upgradeAppStoreApp', function ($app) use ($output) { $output->writeln('Update 3rd-party app: ' . $app . ''); }); - $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'appUpgradeCheckBefore', function () use ($output) { $output->writeln('Checking updates of apps'); }); - $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'appSimulateUpdate', function ($app) use ($output) { $output->writeln("Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)"); }); - $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'appUpgradeCheck', function () use ($output) { $output->writeln('Checked database schema update for apps'); }); - $updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'appUpgradeStarted', function ($app, $version) use ($output) { $output->writeln("Updating <$app> ..."); }); - $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'appUpgrade', function ($app, $version) use ($output) { $output->writeln("Updated <$app> to $version"); }); - $updater->listen('\OC\Updater', 'failure', function ($message) use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'failure', function ($message) use ($output) { $output->writeln("$message"); }); - $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'setDebugLogLevel', function ($logLevel, $logLevelName) use ($output) { $output->writeln("Set log level to debug"); }); - $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'resetLogLevel', function ($logLevel, $logLevelName) use ($output) { $output->writeln("Reset log level"); }); - $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'startCheckCodeIntegrity', function () use ($output) { $output->writeln("Starting code integrity check..."); }); - $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($output) { + $updater->listen('\\' . \OC\Updater::class, 'finishedCheckCodeIntegrity', function () use ($output) { $output->writeln("Finished code integrity check"); }); diff --git a/core/Command/User/Delete.php b/core/Command/User/Delete.php index 47e4cf20f44c..5973ebf90b4e 100644 --- a/core/Command/User/Delete.php +++ b/core/Command/User/Delete.php @@ -32,8 +32,7 @@ use Symfony\Component\Console\Input\InputArgument; class Delete extends Command { - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; /** * @param IUserManager $userManager diff --git a/core/Command/User/Modify.php b/core/Command/User/Modify.php index f856fb1fcd8d..9690368c327b 100644 --- a/core/Command/User/Modify.php +++ b/core/Command/User/Modify.php @@ -29,14 +29,11 @@ use Symfony\Component\Console\Output\OutputInterface; class Modify extends Base { - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IMailer */ - private $mailer; + private \OCP\Mail\IMailer $mailer; - /** @var array */ - private $allowedKeys = ['email', 'displayname']; + private array $allowedKeys = ['email', 'displayname']; /** * Modify constructor. diff --git a/core/Command/User/MoveHome.php b/core/Command/User/MoveHome.php index 40d6a2b49d88..a2e5a65c74ac 100644 --- a/core/Command/User/MoveHome.php +++ b/core/Command/User/MoveHome.php @@ -33,10 +33,7 @@ use Symfony\Component\Console\Output\OutputInterface; class MoveHome extends Command { - /** - * @var IUserManager - */ - private $userManager; + private \OCP\IUserManager $userManager; public function __construct( IUserManager $userManager diff --git a/core/Command/User/Report.php b/core/Command/User/Report.php index dab8f80517b1..09eda5d6e91c 100644 --- a/core/Command/User/Report.php +++ b/core/Command/User/Report.php @@ -93,7 +93,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $rows[] = ['user directories', $this->countUserDirectories()]; $table->setRows($rows); - $table->render($output); + $table->render(); return 0; } diff --git a/core/Command/User/ResetPassword.php b/core/Command/User/ResetPassword.php index 2feaff69d0b1..9ca60b59a156 100644 --- a/core/Command/User/ResetPassword.php +++ b/core/Command/User/ResetPassword.php @@ -44,14 +44,10 @@ class ResetPassword extends Command { /** @var IUserManager */ protected $userManager; - /** @var IConfig */ - private $config; - /** @var ITimeFactory */ - private $timeFactory; - /** @var EnvironmentHelper */ - private $environmentHelper; - /** @var LostController */ - private $lostController; + private \OCP\IConfig $config; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; + private \OC\Helper\EnvironmentHelper $environmentHelper; + private \OC\Core\Controller\LostController $lostController; public function __construct( IUserManager $userManager, @@ -118,7 +114,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } } elseif ($emailLink || $displayLink) { $userId = $user->getUID(); - list($link, $token) = $this->lostController->generateTokenAndLink($userId); + [$link, $token] = $this->lostController->generateTokenAndLink($userId); if ($emailLink && $this->hasValidEmailAddress($user->getEMailAddress())) { try { @@ -174,7 +170,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($emailLink) { $userId = $user->getUID(); - list(, $token) = $this->lostController->generateTokenAndLink($userId); + [, $token] = $this->lostController->generateTokenAndLink($userId); if (!$this->hasValidEmailAddress($user->getEMailAddress())) { $output->writeln('Email address is not set for the user ' . $user->getUID() . ''); return 1; diff --git a/core/Command/User/SyncBackend.php b/core/Command/User/SyncBackend.php index 6889aaa3145d..1f3e6727e3f3 100644 --- a/core/Command/User/SyncBackend.php +++ b/core/Command/User/SyncBackend.php @@ -160,7 +160,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $helper = $this->getHelper('question'); $question = new ChoiceQuestion( 'If unknown users are found, what do you want to do with their accounts? (removing the account will also remove its data)', - \array_merge(self::VALID_ACTIONS, ['ask later']), + [...self::VALID_ACTIONS, 'ask later'], 0 ); $missingAccountsAction = $helper->ask($input, $output, $question); @@ -344,9 +344,7 @@ private function getBackend($backend): ?UserInterface { break; } $backends = $this->userManager->getBackends(); - $match = \array_filter($backends, static function ($b) use ($backend) { - return \get_class($b) === $backend; - }); + $match = \array_filter($backends, static fn ($b) => \get_class($b) === $backend); if (empty($match)) { return null; } diff --git a/core/Controller/AppRegistryController.php b/core/Controller/AppRegistryController.php index cc618187e83d..6bb6ca592a97 100644 --- a/core/Controller/AppRegistryController.php +++ b/core/Controller/AppRegistryController.php @@ -314,7 +314,7 @@ private function buildWebUri(array $app_info, string $fileId): ?string { 'ios' => 'https://' ]); foreach ($clientRules as $client => $rule) { - if (strpos($userAgent, $rule) !== false) { + if (strpos($userAgent, (string) $rule) !== false) { return str_replace('https://', $schema[$client], $uri); } } diff --git a/core/Controller/CloudController.php b/core/Controller/CloudController.php index ddded5f0644e..c7f48138d4e3 100644 --- a/core/Controller/CloudController.php +++ b/core/Controller/CloudController.php @@ -42,7 +42,7 @@ public function __construct($appName, IRequest $request) { public function getCapabilities() { $result = []; $defaults = new \OCP\Defaults(); - list($major, $minor, $micro) = \OCP\Util::getVersion(); + [$major, $minor, $micro] = \OCP\Util::getVersion(); $result['version'] = [ 'major' => $major, 'minor' => $minor, diff --git a/core/Controller/CronController.php b/core/Controller/CronController.php index c709c445531b..54260f4cfe99 100644 --- a/core/Controller/CronController.php +++ b/core/Controller/CronController.php @@ -29,12 +29,9 @@ use OCP\ILogger; class CronController extends Controller { - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; - /** @var IJobList */ - private $jobList; + private \OCP\IConfig $config; + private \OCP\ILogger $logger; + private \OCP\BackgroundJob\IJobList $jobList; /** * CronController constructor. diff --git a/core/Controller/LicenseController.php b/core/Controller/LicenseController.php index d3dc7d5ad9d3..44b4636a6904 100644 --- a/core/Controller/LicenseController.php +++ b/core/Controller/LicenseController.php @@ -26,8 +26,7 @@ use OCP\License\ILicenseManager; class LicenseController extends Controller { - /** @var ILicenseManager */ - private $licenseManager; + private \OCP\License\ILicenseManager $licenseManager; /** * @param ILicenseManager $licenseManager diff --git a/core/Controller/LoginController.php b/core/Controller/LoginController.php index f89ecf4a09e9..b7ed70fe5b54 100644 --- a/core/Controller/LoginController.php +++ b/core/Controller/LoginController.php @@ -42,26 +42,19 @@ use OCP\IUserManager; class LoginController extends Controller { - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var ISession */ - private $session; + private \OCP\ISession $session; - /** @var Session */ - private $userSession; + private \OC\User\Session $userSession; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; - /** @var Manager */ - private $twoFactorManager; + private \OC\Authentication\TwoFactorAuth\Manager $twoFactorManager; - /** @var ILicenseManager */ - private $licenseManager; + private \OCP\License\ILicenseManager $licenseManager; /** * @param string $appName @@ -153,7 +146,7 @@ public function showLoginForm($user, $redirect_url, $remember_login) { $errors = []; $messages = []; if (\is_array($loginMessages)) { - list($errors, $messages) = $loginMessages; + [$errors, $messages] = $loginMessages; } $this->session->remove('loginMessages'); foreach ($errors as $value) { diff --git a/core/Controller/LostController.php b/core/Controller/LostController.php index 3155711e6749..95625bd7954d 100644 --- a/core/Controller/LostController.php +++ b/core/Controller/LostController.php @@ -74,8 +74,7 @@ class LostController extends Controller { protected $timeFactory; /** @var ILogger */ protected $logger; - /** @var Session */ - private $userSession; + private \OC\User\Session $userSession; /** * @param string $appName @@ -225,7 +224,7 @@ public function email($user) { } // FIXME: use HTTP error codes try { - list($link, $token) = $this->generateTokenAndLink($user); + [$link, $token] = $this->generateTokenAndLink($user); $this->sendEmail($user, $token, $link); } catch (\Exception $e) { return $this->error($e->getMessage()); diff --git a/core/Controller/OccController.php b/core/Controller/OccController.php index 2e0e7e29716f..c2f19be2bfc7 100644 --- a/core/Controller/OccController.php +++ b/core/Controller/OccController.php @@ -31,8 +31,7 @@ use Symfony\Component\Console\Output\BufferedOutput; class OccController extends Controller { - /** @var array */ - private $allowedCommands = [ + private array $allowedCommands = [ 'app:disable', 'app:enable', 'app:getpath', @@ -45,12 +44,9 @@ class OccController extends Controller { 'upgrade' ]; - /** @var IConfig */ - private $config; - /** @var Application */ - private $console; - /** @var ILogger */ - private $logger; + private \OCP\IConfig $config; + private \OC\Console\Application $console; + private \OCP\ILogger $logger; /** * OccController constructor. diff --git a/core/Controller/OcsController.php b/core/Controller/OcsController.php index e2b2e2e136cc..06b2bb93f3c1 100644 --- a/core/Controller/OcsController.php +++ b/core/Controller/OcsController.php @@ -35,14 +35,11 @@ class OcsController extends \OCP\AppFramework\OCSController { public const SELECT_SINGLE_STMT = 'SELECT `key`, `app`, `value` FROM `*PREFIX*privatedata` WHERE `user` = ? AND `app` = ? AND `key` = ? '; public const DELETE_STMT = 'DELETE FROM `*PREFIX*privatedata` WHERE `user` = ? AND `app` = ? AND `key` = ? '; - /** @var IDBConnection */ - private $dbConnection; + private \OCP\IDBConnection $dbConnection; - /** @var IUserSession */ - private $userSession; + private \OCP\IUserSession $userSession; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; /** * OccController constructor. diff --git a/core/Controller/RolesController.php b/core/Controller/RolesController.php index 48827a5adf39..b1b581d950b4 100644 --- a/core/Controller/RolesController.php +++ b/core/Controller/RolesController.php @@ -28,14 +28,8 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; class RolesController extends OCSController { - /** - * @var IL10N - */ - private $l10n; - /** - * @var EventDispatcherInterface - */ - private $dispatcher; + private \OCP\IL10N $l10n; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher; public function __construct( $appName, diff --git a/core/Controller/SetupController.php b/core/Controller/SetupController.php index 8bf74e75d876..d1e5ad4aaf88 100644 --- a/core/Controller/SetupController.php +++ b/core/Controller/SetupController.php @@ -32,8 +32,7 @@ class SetupController { /** @var Setup */ protected $setupHelper; - /** @var string */ - private $autoConfigFile; + private string $autoConfigFile; /** * @param Setup $setupHelper diff --git a/core/Controller/TokenController.php b/core/Controller/TokenController.php index da97d738cc20..3ee106117151 100644 --- a/core/Controller/TokenController.php +++ b/core/Controller/TokenController.php @@ -34,17 +34,13 @@ use OCP\Security\ISecureRandom; class TokenController extends Controller { - /** @var UserManager */ - private $userManager; + private \OC\User\Manager $userManager; - /** @var IProvider */ - private $tokenProvider; + private \OC\Authentication\Token\IProvider $tokenProvider; - /** @var TwoFactorAuthManager */ - private $twoFactorAuthManager; + private \OC\Authentication\TwoFactorAuth\Manager $twoFactorAuthManager; - /** @var ISecureRandom */ - private $secureRandom; + private \OCP\Security\ISecureRandom $secureRandom; /** * @param string $appName diff --git a/core/Controller/TwoFactorChallengeController.php b/core/Controller/TwoFactorChallengeController.php index 20c2c629962b..a9a495d04b46 100644 --- a/core/Controller/TwoFactorChallengeController.php +++ b/core/Controller/TwoFactorChallengeController.php @@ -38,17 +38,13 @@ use OCP\IUserSession; class TwoFactorChallengeController extends Controller { - /** @var Manager */ - private $twoFactorManager; + private \OC\Authentication\TwoFactorAuth\Manager $twoFactorManager; - /** @var IUserSession */ - private $userSession; + private \OCP\IUserSession $userSession; - /** @var ISession */ - private $session; + private \OCP\ISession $session; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; /** * @param string $appName diff --git a/core/Controller/UserSyncController.php b/core/Controller/UserSyncController.php index 6be29478515a..197ef2c4be42 100644 --- a/core/Controller/UserSyncController.php +++ b/core/Controller/UserSyncController.php @@ -45,14 +45,8 @@ * @package OC\Core\Controller */ class UserSyncController extends OCSController { - /** - * @var SyncService - */ - private $syncService; - /** - * @var IUserManager - */ - private $userManager; + private \OC\User\SyncService $syncService; + private \OCP\IUserManager $userManager; /** * UserSyncController constructor. diff --git a/core/Middleware/AccountModuleMiddleware.php b/core/Middleware/AccountModuleMiddleware.php index d8a10a03e472..eb74e1b2d48d 100644 --- a/core/Middleware/AccountModuleMiddleware.php +++ b/core/Middleware/AccountModuleMiddleware.php @@ -43,17 +43,13 @@ * @package OC\Core\Middleware */ class AccountModuleMiddleware extends Middleware { - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var Manager */ - private $manager; + private \OC\Authentication\AccountModule\Manager $manager; - /** @var IUserSession */ - private $session; + private \OCP\IUserSession $session; - /** @var IControllerMethodReflector */ - private $reflector; + private \OCP\AppFramework\Utility\IControllerMethodReflector $reflector; /** * @param ILogger $logger diff --git a/core/Middleware/TwoFactorMiddleware.php b/core/Middleware/TwoFactorMiddleware.php index 9c0707a7b9be..90cb497e3357 100644 --- a/core/Middleware/TwoFactorMiddleware.php +++ b/core/Middleware/TwoFactorMiddleware.php @@ -38,20 +38,15 @@ use OCP\IUserSession; class TwoFactorMiddleware extends Middleware { - /** @var Manager */ - private $twoFactorManager; + private \OC\Authentication\TwoFactorAuth\Manager $twoFactorManager; - /** @var IUserSession */ - private $session; + private \OCP\IUserSession $session; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; - /** @var IControllerMethodReflector */ - private $reflector; + private \OCP\AppFramework\Utility\IControllerMethodReflector $reflector; - /** @var IRequest */ - private $request; + private \OCP\IRequest $request; /** * @param Manager $twoFactorManager diff --git a/core/ajax/appconfig.php b/core/ajax/appconfig.php index 99d119fada59..f9ec9d0954f1 100644 --- a/core/ajax/appconfig.php +++ b/core/ajax/appconfig.php @@ -25,7 +25,7 @@ OC_Util::checkAdminUser(); OCP\JSON::callCheck(); -$action=isset($_POST['action'])?$_POST['action']:$_GET['action']; +$action=$_POST['action'] ?? $_GET['action']; if (isset($_POST['app']) || isset($_GET['app'])) { $app=OC_App::cleanAppId(isset($_POST['app'])? (string)$_POST['app']: (string)$_GET['app']); diff --git a/core/ajax/share.php b/core/ajax/share.php index 9c63d986df98..50fd2af5a2ea 100644 --- a/core/ajax/share.php +++ b/core/ajax/share.php @@ -158,9 +158,7 @@ function displayNamesInGroups($gids, $search = '', $limit = -1, $offset = 0) { $groups = getGroups((string)$_GET['search']); if ($shareWithinGroupOnly) { $usergroups = \OC::$server->getGroupManager()->getUserIdGroups(OC_User::getUser()); - $usergroups = \array_values(\array_map(function (\OCP\IGroup $g) { - return $g->getGID(); - }, $usergroups)); + $usergroups = \array_values(\array_map(fn (\OCP\IGroup $g) => $g->getGID(), $usergroups)); $groups = \array_intersect($groups, $usergroups); } @@ -275,10 +273,8 @@ function displayNamesInGroups($gids, $search = '', $limit = -1, $offset = 0) { if ($sharingAutocompletion !== 'yes') { $searchTerm = \strtolower($_GET['search']); - $shareWith = \array_filter($shareWith, function ($user) use ($searchTerm) { - return \strtolower($user['label']) === $searchTerm - || \strtolower($user['value']['shareWith']) === $searchTerm; - }); + $shareWith = \array_filter($shareWith, fn ($user) => \strtolower($user['label']) === $searchTerm + || \strtolower($user['value']['shareWith']) === $searchTerm); } $sorter = new \OC\Share\SearchResultSorter( diff --git a/core/ajax/update.php b/core/ajax/update.php index 57f251c72f31..9fbf2d5ba56a 100644 --- a/core/ajax/update.php +++ b/core/ajax/update.php @@ -47,8 +47,7 @@ class FeedBackHandler { public IL10N $l10n; /** @var integer */ private $progressStateMax = 100; - /** @var integer */ - private $progressStateStep = 0; + private int $progressStateStep = 0; /** @var string */ private $currentStep; @@ -136,57 +135,57 @@ public function handleRepairFeedback($event) { $dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']); $dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']); - $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'maintenanceEnabled', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Turned on maintenance mode')); }); - $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'maintenanceDisabled', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Turned off maintenance mode')); }); - $updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'maintenanceActive', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Maintenance mode is kept active')); }); - $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'dbUpgradeBefore', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Updating database schema')); }); - $updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'dbUpgrade', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Updated database')); }); - $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'dbSimulateUpgradeBefore', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)')); }); - $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'dbSimulateUpgrade', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Checked database schema update')); }); - $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'appUpgradeCheckBefore', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Checking updates of apps')); }); - $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'appSimulateUpdate', function ($app) use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app])); }); - $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'appUpgradeCheck', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Checked database schema update for apps')); }); - $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'appUpgrade', function ($app, $version) use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Updated "%s" to %s', [$app, $version])); }); - $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) { + $updater->listen('\\' . \OC\Updater::class, 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) { $incompatibleApps[]= $app; }); - $updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) { + $updater->listen('\\' . \OC\Updater::class, 'failure', function ($message) use ($eventSource, $config) { $eventSource->send('failure', $message); $eventSource->close(); $config->setSystemValue('maintenance', false); }); - $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'setDebugLogLevel', function ($logLevel, $logLevelName) use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Set log level to debug')); }); - $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'resetLogLevel', function ($logLevel, $logLevelName) use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Reset log level')); }); - $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'startCheckCodeIntegrity', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Starting code integrity check')); }); - $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($eventSource, $l) { + $updater->listen('\\' . \OC\Updater::class, 'finishedCheckCodeIntegrity', function () use ($eventSource, $l) { $eventSource->send('success', (string)$l->t('Finished code integrity check')); }); diff --git a/core/js/config.php b/core/js/config.php index 43a9e4baea9a..cbded01b8bf8 100644 --- a/core/js/config.php +++ b/core/js/config.php @@ -114,8 +114,8 @@ "oc_isadmin" => OC_User::isAdminUser(OC_User::getUser()) ? 'true' : 'false', "oc_dataURL" => \is_string($dataLocation) ? "\"".$dataLocation."\"" : 'false', "oc_webroot" => "\"".OC::$WEBROOT."\"", - "oc_appswebroots" => \str_replace('\\/', '/', \json_encode($apps_paths)), // Ugly unescape slashes waiting for better solution - "datepickerFormatDate" => \json_encode($l->l('jsdate', null)), + "oc_appswebroots" => \str_replace('\\/', '/', \json_encode($apps_paths, JSON_THROW_ON_ERROR)), // Ugly unescape slashes waiting for better solution + "datepickerFormatDate" => \json_encode($l->l('jsdate', null), JSON_THROW_ON_ERROR), "dayNames" => \json_encode( [ (string)$l->t('Sunday'), @@ -125,7 +125,8 @@ (string)$l->t('Thursday'), (string)$l->t('Friday'), (string)$l->t('Saturday') - ] + ], + JSON_THROW_ON_ERROR ), "dayNamesShort" => \json_encode( [ @@ -136,7 +137,8 @@ (string)$l->t('Thu.'), (string)$l->t('Fri.'), (string)$l->t('Sat.') - ] + ], + JSON_THROW_ON_ERROR ), "dayNamesMin" => \json_encode( [ @@ -147,7 +149,8 @@ (string)$l->t('Th'), (string)$l->t('Fr'), (string)$l->t('Sa') - ] + ], + JSON_THROW_ON_ERROR ), "monthNames" => \json_encode( [ @@ -163,7 +166,8 @@ (string)$l->t('October'), (string)$l->t('November'), (string)$l->t('December') - ] + ], + JSON_THROW_ON_ERROR ), "monthNamesShort" => \json_encode( [ @@ -179,9 +183,10 @@ (string)$l->t('Oct.'), (string)$l->t('Nov.'), (string)$l->t('Dec.') - ] + ], + JSON_THROW_ON_ERROR ), - "firstDay" => \json_encode($l->l('firstday', null)) , + "firstDay" => \json_encode($l->l('firstday', null), JSON_THROW_ON_ERROR) , "oc_config" => [ 'session_lifetime' => \min(\OC::$server->getConfig()->getSystemValue('session_lifetime', OC::$server->getIniWrapper()->getNumeric('session.gc_maxlifetime')), OC::$server->getIniWrapper()->getNumeric('session.gc_maxlifetime')), 'session_keepalive' => \OC::$server->getConfig()->getSystemValue('session_keepalive', true), @@ -237,7 +242,8 @@ [ 'name' => OC_Util::getTheme()->getName(), 'directory' => OC_Util::getTheme()->getDirectory() - ] + ], + JSON_THROW_ON_ERROR ) ]; @@ -250,7 +256,7 @@ $caps = \OC::$server->getCapabilitiesManager()->getCapabilities(); // remove status.php info as we already have the version above unset($caps['core']['status']); - $array['oc_capabilities'] = \json_encode($caps); + $array['oc_capabilities'] = \json_encode($caps, JSON_THROW_ON_ERROR); $user = \OC::$server->getUserSession()->getUser(); if ($user !== null) { @@ -261,7 +267,7 @@ 'displayName' => $user->getDisplayName(), 'email' => $user->getEMailAddress(), 'groups' => $groups, - ]); + ], JSON_THROW_ON_ERROR); } } @@ -269,8 +275,8 @@ OC_Hook::emit('\OCP\Config', 'js', ['array' => &$array]); $array['oc_appconfig'] = \json_encode($array['oc_appconfig']); -$array['oc_config'] = \json_encode($array['oc_config']); -$array['oc_defaults'] = \json_encode($array['oc_defaults']); +$array['oc_config'] = \json_encode($array['oc_config'], JSON_THROW_ON_ERROR); +$array['oc_defaults'] = \json_encode($array['oc_defaults'], JSON_THROW_ON_ERROR); // Echo it foreach ($array as $setting => $value) { diff --git a/lib/kernel.php b/lib/kernel.php index 4455b7f2c040..e0bcb2a157b0 100644 --- a/lib/kernel.php +++ b/lib/kernel.php @@ -115,10 +115,7 @@ class OC { */ public static $server = null; - /** - * @var \OC\Config - */ - private static $config = null; + private static ?\OC\Config $config = null; /** * @throws \RuntimeException when the app path list is empty or contains an invalid path @@ -461,7 +458,7 @@ public static function initSession() { // session timeout \OC::$server->getUserSession()->logout(); if (isset($_COOKIE[\session_name()])) { - \setcookie(\session_name(), null, -1, self::$WEBROOT ? : '/'); + \setcookie(\session_name(), null, ['expires' => -1, 'path' => self::$WEBROOT ? : '/']); } } } @@ -581,10 +578,10 @@ public static function init() { } // register the stream wrappers - \stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir'); - \stream_wrapper_register('static', 'OC\Files\Stream\StaticStream'); - \stream_wrapper_register('close', 'OC\Files\Stream\Close'); - \stream_wrapper_register('quota', 'OC\Files\Stream\Quota'); + \stream_wrapper_register('fakedir', \OC\Files\Stream\Dir::class); + \stream_wrapper_register('static', \OC\Files\Stream\StaticStream::class); + \stream_wrapper_register('close', \OC\Files\Stream\Close::class); + \stream_wrapper_register('quota', \OC\Files\Stream\Quota::class); \OC::$server->getEventLogger()->start('init_session', 'Initialize session'); OC_App::loadApps(['session', 'theme']); @@ -620,7 +617,7 @@ public static function init() { } try { - \OC::$server->getConfig()->setAppValue('core', 'cronErrors', \json_encode($staticErrors)); + \OC::$server->getConfig()->setAppValue('core', 'cronErrors', \json_encode($staticErrors, JSON_THROW_ON_ERROR)); } catch (\Exception $e) { echo('Writing to database failed'); } @@ -652,7 +649,7 @@ public static function init() { \OCP\Util::connectHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', - '\OC\User\Database', + '\\' . \OC\User\Database::class, 'preLoginNameUsedAsUserName' ); @@ -667,7 +664,7 @@ public static function init() { self::registerCacheHooks(); self::registerFilesystemHooks(); if ($systemConfig->getValue('enable_previews', true)) { - OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write'); + OC_Hook::connect('OC_Filesystem', 'post_write', \OC\Preview::class, 'post_write'); } self::registerShareHooks(); self::registerLogRotate(); @@ -766,10 +763,10 @@ private static function registerEncryptionHooks() { //Call share hooks if they are not masterkey if ($enabled && (\OC::$server->getConfig()->getAppValue('encryption', 'useMasterKey', '0') === '0')) { - \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared'); - \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared'); - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename'); - \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_shared', \OC\Encryption\HookManager::class, 'postShared'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_unshare', \OC\Encryption\HookManager::class, 'postUnshared'); + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', \OC\Encryption\HookManager::class, 'postRename'); + \OCP\Util::connectHook('\\' . \OCA\Files_Trashbin\Trashbin::class, 'post_restore', \OC\Encryption\HookManager::class, 'postRestore'); } } @@ -781,7 +778,7 @@ public static function registerLogRotate() { if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) { //don't try to do this before we are properly setup //use custom logfile path if defined, otherwise use default of owncloud.log in data directory - \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log')); + \OCP\BackgroundJob::registerJob(\OC\Log\Rotate::class, $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/owncloud.log')); } } @@ -790,8 +787,8 @@ public static function registerLogRotate() { */ public static function registerFilesystemHooks() { // Check for blacklisted files - OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isForbiddenFileOrDir_Hook'); - OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isForbiddenFileOrDir_Hook'); + OC_Hook::connect('OC_Filesystem', 'write', \OC\Files\Filesystem::class, 'isForbiddenFileOrDir_Hook'); + OC_Hook::connect('OC_Filesystem', 'rename', \OC\Files\Filesystem::class, 'isForbiddenFileOrDir_Hook'); } /** @@ -799,9 +796,9 @@ public static function registerFilesystemHooks() { */ public static function registerShareHooks() { if (\OC::$server->getSystemConfig()->getValue('installed')) { - OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser'); - OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup'); - OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup'); + OC_Hook::connect('OC_User', 'post_deleteUser', \OC\Share20\Hooks::class, 'post_deleteUser'); + OC_Hook::connect('OC_User', 'post_removeFromGroup', \OC\Share20\Hooks::class, 'post_removeFromGroup'); + OC_Hook::connect('OC_User', 'post_deleteGroup', \OC\Share20\Hooks::class, 'post_deleteGroup'); } } @@ -988,7 +985,7 @@ protected static function handleAuthHeaders() { ]; foreach ($vars as $var) { if (isset($_SERVER[$var]) && \preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { - list($name, $password) = \explode(':', \base64_decode($matches[1]), 2); + [$name, $password] = \explode(':', \base64_decode($matches[1]), 2); $_SERVER['PHP_AUTH_USER'] = $name; $_SERVER['PHP_AUTH_PW'] = $password; break; diff --git a/lib/private/Activity/Manager.php b/lib/private/Activity/Manager.php index 86830ee17141..90351f5566c3 100644 --- a/lib/private/Activity/Manager.php +++ b/lib/private/Activity/Manager.php @@ -71,13 +71,13 @@ public function __construct( } /** @var \Closure[] */ - private $consumersClosures = []; + private array $consumersClosures = []; /** @var IConsumer[] */ private $consumers = []; /** @var \Closure[] */ - private $extensionsClosures = []; + private array $extensionsClosures = []; /** @var IExtension[] */ private $extensions = []; @@ -262,11 +262,11 @@ public function getNotificationTypes($languageCode) { foreach ($this->getExtensions() as $c) { $result = $c->getNotificationTypes($languageCode); if (\is_array($result)) { - if (\class_exists('\OCA\Files\Activity', false) && $c instanceof \OCA\Files\Activity) { + if (\class_exists('\\' . \OCA\Files\Activity::class, false) && $c instanceof \OCA\Files\Activity) { $filesNotificationTypes = $result; continue; } - if (\class_exists('\OCA\Files_Sharing\Activity', false) && $c instanceof \OCA\Files_Sharing\Activity) { + if (\class_exists('\\' . \OCA\Files_Sharing\Activity::class, false) && $c instanceof \OCA\Files_Sharing\Activity) { $sharingNotificationTypes = $result; continue; } @@ -466,7 +466,7 @@ public function getQueryForFilter($filter) { foreach ($this->getExtensions() as $c) { $result = $c->getQueryForFilter($filter); if (\is_array($result)) { - list($condition, $parameter) = $result; + [$condition, $parameter] = $result; if ($condition && \is_array($parameter)) { $conditions[] = $condition; $parameters = \array_merge($parameters, $parameter); diff --git a/lib/private/AllConfig.php b/lib/private/AllConfig.php index 30e7fa0b626b..455d498a6300 100644 --- a/lib/private/AllConfig.php +++ b/lib/private/AllConfig.php @@ -39,14 +39,12 @@ * Class to combine all the configuration options ownCloud offers */ class AllConfig implements IConfig { - /** @var SystemConfig */ - private $systemConfig; + private \OC\SystemConfig $systemConfig; /** @var IDBConnection */ private $connection; - /** @var EventDispatcher */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; /** * 3 dimensional array with the following structure: diff --git a/lib/private/App/AppManager.php b/lib/private/App/AppManager.php index fc55894f9289..061b4913ca29 100644 --- a/lib/private/App/AppManager.php +++ b/lib/private/App/AppManager.php @@ -62,26 +62,20 @@ class AppManager implements IAppManager { 'theme', ]; - /** @var \OCP\IUserSession */ - private $userSession; - /** @var \OCP\IAppConfig */ - private $appConfig; + private ?\OCP\IUserSession $userSession = null; + private ?\OCP\IAppConfig $appConfig = null; /** @var \OCP\ICache */ private $appInfo; - /** @var \OCP\IGroupManager */ - private $groupManager; - /** @var \OCP\ICacheFactory */ - private $memCacheFactory; + private ?\OCP\IGroupManager $groupManager = null; + private \OCP\ICacheFactory $memCacheFactory; /** @var string[] $appId => $enabled */ - private $installedAppsCache; + private ?array $installedAppsCache = null; /** @var string[] */ private $shippedApps; /** @var string[] */ private $alwaysEnabled; - /** @var EventDispatcherInterface */ - private $dispatcher; - /** @var IConfig */ - private $config; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher; + private \OCP\IConfig $config; /** * Apps as 'appId' => [ @@ -90,7 +84,7 @@ class AppManager implements IAppManager { * ] * @var string[][] */ - private $appDirs = []; + private array $appDirs = []; /** * @param IUserSession $userSession @@ -137,9 +131,7 @@ private function getInstalledAppsValues() { $values[$appId] = 'yes'; } - $this->installedAppsCache = \array_filter($values, function ($value) { - return $value !== 'no'; - }); + $this->installedAppsCache = \array_filter($values, fn ($value) => $value !== 'no'); \ksort($this->installedAppsCache); } return $this->installedAppsCache; @@ -162,9 +154,7 @@ public function getInstalledApps() { */ public function getEnabledAppsForUser(IUser $user = null) { $apps = $this->getInstalledAppsValues(); - $appsForUser = \array_filter($apps, function ($enabled, $appName) use ($user) { - return $this->checkAppForUser($enabled, $appName, $user); - }, ARRAY_FILTER_USE_BOTH); + $appsForUser = \array_filter($apps, fn ($enabled, $appName) => $this->checkAppForUser($enabled, $appName, $user), ARRAY_FILTER_USE_BOTH); return \array_keys($appsForUser); } @@ -334,12 +324,11 @@ public function enableAppForGroups($appId, $groups) { Installer::installShippedApp($appId); } - $groupIds = \array_map(function ($group) { - /** @var \OCP\IGroup $group */ - return $group->getGID(); - }, $groups); - $this->installedAppsCache[$appId] = \json_encode($groupIds); - $this->appConfig->setValue($appId, 'enabled', \json_encode($groupIds)); + $groupIds = \array_map(fn ($group) => + /** @var \OCP\IGroup $group */ + $group->getGID(), $groups); + $this->installedAppsCache[$appId] = \json_encode($groupIds, JSON_THROW_ON_ERROR); + $this->appConfig->setValue($appId, 'enabled', \json_encode($groupIds, JSON_THROW_ON_ERROR)); $this->dispatcher->dispatch( new ManagerEvent(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups), ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS @@ -501,10 +490,7 @@ public function getAppInfoByPath($path, $etag = null) { $parser = new InfoParser(); try { $info = $parser->parse($file); - } catch (\InvalidArgumentException $e) { - \OC::$server->getLogger()->logException($e); - throw $e; - } catch (AppNotFoundException $e) { + } catch (\InvalidArgumentException|AppNotFoundException $e) { \OC::$server->getLogger()->logException($e); throw $e; } @@ -580,7 +566,7 @@ private function loadShippedJson() { if (!\file_exists($shippedJson)) { throw new \Exception("File not found: $shippedJson"); } - $content = \json_decode(\file_get_contents($shippedJson), true); + $content = \json_decode(\file_get_contents($shippedJson), true, 512, JSON_THROW_ON_ERROR); $this->shippedApps = $content['shippedApps']; $this->alwaysEnabled = $content['alwaysEnabled']; } @@ -639,7 +625,7 @@ public function readAppPackage($path) { 'source' => 'path', 'path' => $path, ]; - list($appCodeDir, $path) = Installer::downloadApp($data); + [$appCodeDir, $path] = Installer::downloadApp($data); $appInfo = Installer::checkAppsIntegrity($data, $appCodeDir, $path); Files::rmdirr($appCodeDir); return $appInfo; @@ -794,6 +780,6 @@ protected function getAppRoots() { public function getAppVersionByPath($path) { $infoFile = "{$path}/appinfo/info.xml"; $appData = $this->getAppInfoByPath($infoFile); - return isset($appData['version']) ? $appData['version'] : ''; + return $appData['version'] ?? ''; } } diff --git a/lib/private/App/CodeChecker/CodeChecker.php b/lib/private/App/CodeChecker/CodeChecker.php index b13059f5eab9..1474b6f82e67 100644 --- a/lib/private/App/CodeChecker/CodeChecker.php +++ b/lib/private/App/CodeChecker/CodeChecker.php @@ -42,8 +42,7 @@ class CodeChecker extends BasicEmitter { public const CLASS_USE_NOT_ALLOWED = 1006; public const CLASS_METHOD_CALL_NOT_ALLOWED = 1007; - /** @var Parser */ - private $parser; + private \PhpParser\Parser $parser; /** @var ICheck */ protected $checkList; @@ -73,9 +72,7 @@ public function analyse($appId) { public function analyseFolder($folder) { $errors = []; - $excludes = \array_map(function ($item) use ($folder) { - return $folder . '/' . $item; - }, ['vendor', '.git', 'l10n', 'tests', 'test']); + $excludes = \array_map(fn ($item) => $folder . '/' . $item, ['vendor', '.git', 'l10n', 'tests', 'test']); $iterator = new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS); $iterator = new RecursiveCallbackFilterIterator($iterator, function ($item) use ($folder, $excludes) { diff --git a/lib/private/App/CodeChecker/DeprecationCheck.php b/lib/private/App/CodeChecker/DeprecationCheck.php index 3b41de33ca61..cda8a94bb6b5 100644 --- a/lib/private/App/CodeChecker/DeprecationCheck.php +++ b/lib/private/App/CodeChecker/DeprecationCheck.php @@ -37,12 +37,12 @@ protected function getLocalClasses() { 'OC_JSON' => '8.2.0', 'OCP\Config' => '8.0.0', - 'OCP\Contacts' => '8.1.0', - 'OCP\DB' => '8.1.0', - 'OCP\IHelper' => '8.1.0', - 'OCP\JSON' => '8.1.0', - 'OCP\Response' => '8.1.0', - 'OCP\AppFramework\IApi' => '8.0.0', + \OCP\Contacts::class => '8.1.0', + \OCP\DB::class => '8.1.0', + \OCP\IHelper::class => '8.1.0', + \OCP\JSON::class => '8.1.0', + \OCP\Response::class => '8.1.0', + \OCP\AppFramework\IApi::class => '8.0.0', ]; } diff --git a/lib/private/App/CodeChecker/InfoChecker.php b/lib/private/App/CodeChecker/InfoChecker.php index 2ab78797f94f..17e629132207 100644 --- a/lib/private/App/CodeChecker/InfoChecker.php +++ b/lib/private/App/CodeChecker/InfoChecker.php @@ -27,13 +27,11 @@ use OCP\App\IAppManager; class InfoChecker extends BasicEmitter { - /** @var InfoParser */ - private $infoParser; + private \OC\App\InfoParser $infoParser; - /** @var IAppManager */ - private $appManager; + private \OCP\App\IAppManager $appManager; - private $mandatoryFields = [ + private array $mandatoryFields = [ 'author', 'description', 'id', @@ -41,7 +39,7 @@ class InfoChecker extends BasicEmitter { 'name', 'version', ]; - private $optionalFields = [ + private array $optionalFields = [ 'bugs', 'category', 'default_enable', @@ -54,7 +52,7 @@ class InfoChecker extends BasicEmitter { 'types', 'website', ]; - private $deprecatedFields = [ + private array $deprecatedFields = [ 'info', 'require', 'requiremax', @@ -115,7 +113,7 @@ public function analyse($appId) { foreach ($info as $key => $value) { if (\is_array($value)) { - $value = \json_encode($value); + $value = \json_encode($value, JSON_THROW_ON_ERROR); } if (\in_array($key, $this->mandatoryFields)) { $this->emit('InfoChecker', 'mandatoryFieldFound', [$key, $value]); diff --git a/lib/private/App/DependencyAnalyzer.php b/lib/private/App/DependencyAnalyzer.php index 4acbc9b181dc..377c34ab19dc 100644 --- a/lib/private/App/DependencyAnalyzer.php +++ b/lib/private/App/DependencyAnalyzer.php @@ -29,12 +29,9 @@ use OCP\IL10N; class DependencyAnalyzer { - /** @var Platform */ - private $platform; - /** @var \OCP\IL10N */ - private $l; - /** @var array */ - private $appInfo; + private \OC\App\Platform $platform; + private \OCP\IL10N $l; + private ?array $appInfo = null; /** * @param Platform $platform @@ -101,7 +98,7 @@ private function compare($first, $second, $operator) { // version string but null. In case one parameter is null normalization // will therefore be skipped if ($first !== null && $second !== null) { - list($first, $second) = $this->normalizeVersions($first, $second); + [$first, $second] = $this->normalizeVersions($first, $second); } return \version_compare($first, $second, $operator); @@ -171,9 +168,7 @@ private function analyzeDatabases(array $dependencies) { if (!\is_array($supportedDatabases)) { $supportedDatabases = [$supportedDatabases]; } - $supportedDatabases = \array_map(function ($db) { - return $this->getValue($db); - }, $supportedDatabases); + $supportedDatabases = \array_map(fn ($db) => $this->getValue($db), $supportedDatabases); $currentDatabase = $this->platform->getDatabase(); if (!\in_array($currentDatabase, $supportedDatabases)) { $missing[] = (string)$this->l->t('Following databases are supported: %s', \join(', ', $supportedDatabases)); @@ -275,9 +270,7 @@ private function analyzeOS(array $dependencies) { return $missing; } if (\is_array($oss)) { - $oss = \array_map(function ($os) { - return $this->getValue($os); - }, $oss); + $oss = \array_map(fn ($os) => $this->getValue($os), $oss); } else { $oss = [$oss]; } @@ -328,9 +321,6 @@ private function analyzeOC(array $dependencies, array $appInfo) { * @return mixed */ private function getValue($element) { - if (isset($element['@value'])) { - return $element['@value']; - } - return (string)$element; + return $element['@value'] ?? (string)$element; } } diff --git a/lib/private/App/Platform.php b/lib/private/App/Platform.php index 1ef9268ab443..ad19d2ff5457 100644 --- a/lib/private/App/Platform.php +++ b/lib/private/App/Platform.php @@ -33,8 +33,7 @@ * @package OC\App */ class Platform { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** * @param IConfig $config diff --git a/lib/private/App/PlatformRepository.php b/lib/private/App/PlatformRepository.php index 911fe0b5127b..78b78aff40ab 100644 --- a/lib/private/App/PlatformRepository.php +++ b/lib/private/App/PlatformRepository.php @@ -91,9 +91,7 @@ protected function initialize() { break; case 'openssl': - $prettyVersion = \preg_replace_callback('{^(?:OpenSSL\s*)?([0-9.]+)([a-z]?).*}', function ($match) { - return $match[1] . (empty($match[2]) ? '' : '.' . (\ord($match[2]) - 96)); - }, OPENSSL_VERSION_TEXT); + $prettyVersion = \preg_replace_callback('{^(?:OpenSSL\s*)?([0-9.]+)([a-z]?).*}', fn ($match) => $match[1] . (empty($match[2]) ? '' : '.' . (\ord($match[2]) - 96)), OPENSSL_VERSION_TEXT); break; case 'pcre': @@ -135,13 +133,10 @@ private function buildPackageName($name) { */ public function findLibrary($name) { $extName = $this->buildPackageName($name); - if (isset($this->packages[$extName])) { - return $this->packages[$extName]; - } - return null; + return $this->packages[$extName] ?? null; } - private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)(?:[.-]?(\d+))?)?([.-]?dev)?'; + private static string $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)(?:[.-]?(\d+))?)?([.-]?dev)?'; /** * Normalizes a version string to be able to perform comparisons on it diff --git a/lib/private/AppConfig.php b/lib/private/AppConfig.php index e40e9d31f8a3..92a41d3b4610 100644 --- a/lib/private/AppConfig.php +++ b/lib/private/AppConfig.php @@ -44,7 +44,7 @@ class AppConfig implements IAppConfig { private $cache = []; - private $configLoaded; + private bool $configLoaded; /** * @param IDBConnection $conn @@ -61,11 +61,7 @@ public function __construct(IDBConnection $conn) { private function getAppValues($app) { $this->loadConfigValues(); - if (isset($this->cache[$app])) { - return $this->cache[$app]; - } - - return []; + return $this->cache[$app] ?? []; } /** @@ -287,9 +283,7 @@ public function getValues($app, $key) { return $this->getAppValues($app); } else { $appIds = $this->getApps(); - $values = \array_map(function ($appId) use ($key) { - return isset($this->cache[$appId][$key]) ? $this->cache[$appId][$key] : null; - }, $appIds); + $values = \array_map(fn ($appId) => $this->cache[$appId][$key] ?? null, $appIds); $result = \array_combine($appIds, $values); return \array_filter($result); @@ -325,7 +319,7 @@ protected function loadConfigValues() { ) { $row['configvalue'] = '0.0.1'; } - $this->cache[$row['appid']][$row['configkey']] = ($row['configvalue'] === null) ? '' : $row['configvalue']; + $this->cache[$row['appid']][$row['configkey']] = $row['configvalue'] ?? ''; } $result->closeCursor(); diff --git a/lib/private/AppFramework/App.php b/lib/private/AppFramework/App.php index 79d9dfc431cf..011fa840eb5f 100644 --- a/lib/private/AppFramework/App.php +++ b/lib/private/AppFramework/App.php @@ -65,9 +65,9 @@ public static function buildAppNamespace($appId, $topNamespace='OCA\\') { */ public static function main($controllerName, $methodName, DIContainer $container, array $urlParams = null) { if ($urlParams !== null) { - $container['OCP\\IRequest']->setUrlParameters($urlParams); + $container[\OCP\IRequest::class]->setUrlParameters($urlParams); } elseif (isset($container['urlParams']) && $container['urlParams'] !== null) { - $container['OCP\\IRequest']->setUrlParameters($container['urlParams']); + $container[\OCP\IRequest::class]->setUrlParameters($container['urlParams']); } $appName = $container['AppName']; @@ -90,15 +90,9 @@ public static function main($controllerName, $methodName, DIContainer $container /** @var Dispatcher $dispatcher */ $dispatcher = $container['Dispatcher']; - list( - $httpHeaders, - $responseHeaders, - $responseCookies, - $output, - $response - ) = $dispatcher->dispatch($controller, $methodName); + [$httpHeaders, $responseHeaders, $responseCookies, $output, $response] = $dispatcher->dispatch($controller, $methodName); - $io = $container['OCP\\AppFramework\\Http\\IOutput']; + $io = $container[\OCP\AppFramework\Http\IOutput::class]; if ($httpHeaders !== null) { $io->setHeader($httpHeaders); @@ -155,7 +149,7 @@ public static function part( $dispatcher = $container['Dispatcher']; - list(, , $output) = $dispatcher->dispatch($controller, $methodName); + [, , $output] = $dispatcher->dispatch($controller, $methodName); return $output; } } diff --git a/lib/private/AppFramework/DependencyInjection/DIContainer.php b/lib/private/AppFramework/DependencyInjection/DIContainer.php index 86cdf5606520..583c8c841389 100644 --- a/lib/private/AppFramework/DependencyInjection/DIContainer.php +++ b/lib/private/AppFramework/DependencyInjection/DIContainer.php @@ -49,10 +49,7 @@ use OCP\IDateTimeFormatter; class DIContainer extends SimpleContainer implements IAppContainer { - /** - * @var array - */ - private $middleWares = []; + private array $middleWares = []; /** * Put your class dependencies in here @@ -76,250 +73,138 @@ public function __construct($appName, $urlParams = []) { /** * Core services */ - $this->registerService('OCP\\IAppConfig', function ($c) { - return $this->getServer()->getAppConfig(); - }); + $this->registerService(\OCP\IAppConfig::class, fn ($c) => $this->getServer()->getAppConfig()); - $this->registerService('OCP\\App\\IAppManager', function ($c) { - return $this->getServer()->getAppManager(); - }); + $this->registerService(\OCP\App\IAppManager::class, fn ($c) => $this->getServer()->getAppManager()); - $this->registerService('OCP\\License\\ILicenseManager', function ($c) { - return $this->getServer()->getLicenseManager(); - }); + $this->registerService(\OCP\License\ILicenseManager::class, fn ($c) => $this->getServer()->getLicenseManager()); - $this->registerService('OCP\\AppFramework\\Http\\IOutput', function ($c) { - return new Output($this->getServer()->getWebRoot()); - }); + $this->registerService(\OCP\AppFramework\Http\IOutput::class, fn ($c) => new Output($this->getServer()->getWebRoot())); - $this->registerService('OCP\\IAvatarManager', function ($c) { - return $this->getServer()->getAvatarManager(); - }); + $this->registerService(\OCP\IAvatarManager::class, fn ($c) => $this->getServer()->getAvatarManager()); - $this->registerService('OCP\\Activity\\IManager', function ($c) { - return $this->getServer()->getActivityManager(); - }); + $this->registerService(\OCP\Activity\IManager::class, fn ($c) => $this->getServer()->getActivityManager()); - $this->registerService('OCP\\ICache', function ($c) { - return $this->getServer()->getCache(); - }); + $this->registerService(\OCP\ICache::class, fn ($c) => $this->getServer()->getCache()); - $this->registerService('OCP\\ICacheFactory', function ($c) { - return $this->getServer()->getMemCacheFactory(); - }); + $this->registerService(\OCP\ICacheFactory::class, fn ($c) => $this->getServer()->getMemCacheFactory()); - $this->registerService('OC\\CapabilitiesManager', function ($c) { + $this->registerService(\OC\CapabilitiesManager::class, function ($c) { $server = $this->getServer(); '@phan-var \OC\Server $server'; return $server->getCapabilitiesManager(); }); - $this->registerService('OCP\Comments\ICommentsManager', function ($c) { - return $this->getServer()->getCommentsManager(); - }); + $this->registerService(\OCP\Comments\ICommentsManager::class, fn ($c) => $this->getServer()->getCommentsManager()); - $this->registerService('OCP\\IConfig', function ($c) { - return $this->getServer()->getConfig(); - }); + $this->registerService(\OCP\IConfig::class, fn ($c) => $this->getServer()->getConfig()); - $this->registerService('OCP\\Contacts\\IManager', function ($c) { - return $this->getServer()->getContactsManager(); - }); + $this->registerService(\OCP\Contacts\IManager::class, fn ($c) => $this->getServer()->getContactsManager()); - $this->registerService('OCP\\IDateTimeZone', function ($c) { - return $this->getServer()->getDateTimeZone(); - }); + $this->registerService(\OCP\IDateTimeZone::class, fn ($c) => $this->getServer()->getDateTimeZone()); - $this->registerService('OCP\\IDb', function ($c) { - return $this->getServer()->getDb(); - }); + $this->registerService(\OCP\IDb::class, fn ($c) => $this->getServer()->getDb()); - $this->registerService('OCP\\IDBConnection', function ($c) { - return $this->getServer()->getDatabaseConnection(); - }); + $this->registerService(\OCP\IDBConnection::class, fn ($c) => $this->getServer()->getDatabaseConnection()); - $this->registerService('OCP\\Diagnostics\\IEventLogger', function ($c) { - return $this->getServer()->getEventLogger(); - }); + $this->registerService(\OCP\Diagnostics\IEventLogger::class, fn ($c) => $this->getServer()->getEventLogger()); - $this->registerService('OCP\\Diagnostics\\IQueryLogger', function ($c) { - return $this->getServer()->getQueryLogger(); - }); + $this->registerService(\OCP\Diagnostics\IQueryLogger::class, fn ($c) => $this->getServer()->getQueryLogger()); - $this->registerService('OCP\\Files\\IMimeTypeDetector', function ($c) { - return $this->getServer()->getMimeTypeDetector(); - }); + $this->registerService(\OCP\Files\IMimeTypeDetector::class, fn ($c) => $this->getServer()->getMimeTypeDetector()); - $this->registerService('OCP\\Files\\Config\\IMountProviderCollection', function ($c) { - return $this->getServer()->getMountProviderCollection(); - }); + $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, fn ($c) => $this->getServer()->getMountProviderCollection()); - $this->registerService('OCP\\Files\\IRootFolder', function ($c) { - return $this->getServer()->getRootFolder(); - }); + $this->registerService(\OCP\Files\IRootFolder::class, fn ($c) => $this->getServer()->getRootFolder()); - $this->registerService('OCP\\Http\\Client\\IClientService', function ($c) { - return $this->getServer()->getHTTPClientService(); - }); + $this->registerService(\OCP\Http\Client\IClientService::class, fn ($c) => $this->getServer()->getHTTPClientService()); - $this->registerService('OCP\\IGroupManager', function ($c) { - return $this->getServer()->getGroupManager(); - }); + $this->registerService(\OCP\IGroupManager::class, fn ($c) => $this->getServer()->getGroupManager()); - $this->registerService('OCP\\Http\\Client\\IClientService', function () { - return $this->getServer()->getHTTPClientService(); - }); + $this->registerService(\OCP\Http\Client\IClientService::class, fn () => $this->getServer()->getHTTPClientService()); - $this->registerService('OCP\\IL10N', function ($c) { - return $this->getServer()->getL10N($c->query('AppName')); - }); + $this->registerService(\OCP\IL10N::class, fn ($c) => $this->getServer()->getL10N($c->query('AppName'))); - $this->registerService('OCP\\L10N\\IFactory', function ($c) { - return $this->getServer()->getL10NFactory(); - }); + $this->registerService(\OCP\L10N\IFactory::class, fn ($c) => $this->getServer()->getL10NFactory()); - $this->registerService('OCP\\ILogger', function ($c) { - return $this->getServer()->getLogger(); - }); + $this->registerService(\OCP\ILogger::class, fn ($c) => $this->getServer()->getLogger()); - $this->registerService('OCP\\BackgroundJob\\IJobList', function ($c) { - return $this->getServer()->getJobList(); - }); + $this->registerService(\OCP\BackgroundJob\IJobList::class, fn ($c) => $this->getServer()->getJobList()); - $this->registerAlias('OCP\\AppFramework\\Utility\\IControllerMethodReflector', 'OC\AppFramework\Utility\ControllerMethodReflector'); - $this->registerAlias('ControllerMethodReflector', 'OCP\\AppFramework\\Utility\\IControllerMethodReflector'); + $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class); + $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class); - $this->registerService('OCP\\Files\\IMimeTypeDetector', function ($c) { - return $this->getServer()->getMimeTypeDetector(); - }); + $this->registerService(\OCP\Files\IMimeTypeDetector::class, fn ($c) => $this->getServer()->getMimeTypeDetector()); - $this->registerService('OCP\\Mail\\IMailer', function () { - return $this->getServer()->getMailer(); - }); + $this->registerService(\OCP\Mail\IMailer::class, fn () => $this->getServer()->getMailer()); - $this->registerService('OCP\\INavigationManager', function ($c) { - return $this->getServer()->getNavigationManager(); - }); + $this->registerService(\OCP\INavigationManager::class, fn ($c) => $this->getServer()->getNavigationManager()); - $this->registerService('OCP\\Notification\IManager', function ($c) { - return $this->getServer()->getNotificationManager(); - }); + $this->registerService(\OCP\Notification\IManager::class, fn ($c) => $this->getServer()->getNotificationManager()); - $this->registerService('OCP\\IPreview', function ($c) { - return $this->getServer()->getPreviewManager(); - }); + $this->registerService(\OCP\IPreview::class, fn ($c) => $this->getServer()->getPreviewManager()); - $this->registerService('OCP\\IRequest', function () { - return $this->getServer()->getRequest(); - }); - $this->registerAlias('Request', 'OCP\\IRequest'); + $this->registerService(\OCP\IRequest::class, fn () => $this->getServer()->getRequest()); + $this->registerAlias('Request', \OCP\IRequest::class); - $this->registerService('OCP\\ITagManager', function ($c) { - return $this->getServer()->getTagManager(); - }); + $this->registerService(\OCP\ITagManager::class, fn ($c) => $this->getServer()->getTagManager()); - $this->registerService('OCP\\ITempManager', function ($c) { - return $this->getServer()->getTempManager(); - }); + $this->registerService(\OCP\ITempManager::class, fn ($c) => $this->getServer()->getTempManager()); - $this->registerAlias('OCP\\AppFramework\\Utility\\ITimeFactory', 'OC\AppFramework\Utility\TimeFactory'); - $this->registerAlias('TimeFactory', 'OCP\\AppFramework\\Utility\\ITimeFactory'); + $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class); + $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class); - $this->registerService('OCP\\Route\\IRouter', function ($c) { - return $this->getServer()->getRouter(); - }); + $this->registerService(\OCP\Route\IRouter::class, fn ($c) => $this->getServer()->getRouter()); - $this->registerService('OCP\\ISearch', function ($c) { - return $this->getServer()->getSearch(); - }); + $this->registerService(\OCP\ISearch::class, fn ($c) => $this->getServer()->getSearch()); - $this->registerService('OCP\\ISearch', function ($c) { - return $this->getServer()->getSearch(); - }); + $this->registerService(\OCP\ISearch::class, fn ($c) => $this->getServer()->getSearch()); - $this->registerService('OCP\\Security\\ICrypto', function ($c) { - return $this->getServer()->getCrypto(); - }); + $this->registerService(\OCP\Security\ICrypto::class, fn ($c) => $this->getServer()->getCrypto()); - $this->registerService('OCP\\Security\\IHasher', function ($c) { - return $this->getServer()->getHasher(); - }); + $this->registerService(\OCP\Security\IHasher::class, fn ($c) => $this->getServer()->getHasher()); - $this->registerService('OCP\\Security\\ICredentialsManager', function ($c) { - return $this->getServer()->getCredentialsManager(); - }); + $this->registerService(\OCP\Security\ICredentialsManager::class, fn ($c) => $this->getServer()->getCredentialsManager()); - $this->registerService('OCP\\Security\\ISecureRandom', function ($c) { - return $this->getServer()->getSecureRandom(); - }); + $this->registerService(\OCP\Security\ISecureRandom::class, fn ($c) => $this->getServer()->getSecureRandom()); - $this->registerService('OCP\\Share\\IManager', function ($c) { - return $this->getServer()->getShareManager(); - }); + $this->registerService(\OCP\Share\IManager::class, fn ($c) => $this->getServer()->getShareManager()); - $this->registerService('OCP\\SystemTag\\ISystemTagManager', function () { - return $this->getServer()->getSystemTagManager(); - }); + $this->registerService(\OCP\SystemTag\ISystemTagManager::class, fn () => $this->getServer()->getSystemTagManager()); - $this->registerService('OCP\\SystemTag\\ISystemTagObjectMapper', function () { - return $this->getServer()->getSystemTagObjectMapper(); - }); + $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, fn () => $this->getServer()->getSystemTagObjectMapper()); - $this->registerService('OCP\\IURLGenerator', function ($c) { - return $this->getServer()->getURLGenerator(); - }); + $this->registerService(\OCP\IURLGenerator::class, fn ($c) => $this->getServer()->getURLGenerator()); - $this->registerService('OCP\\IUserManager', function ($c) { - return $this->getServer()->getUserManager(); - }); + $this->registerService(\OCP\IUserManager::class, fn ($c) => $this->getServer()->getUserManager()); - $this->registerService('OCP\\IUserSession', function ($c) { - return $this->getServer()->getUserSession(); - }); + $this->registerService(\OCP\IUserSession::class, fn ($c) => $this->getServer()->getUserSession()); - $this->registerService('OCP\\ISession', function ($c) { - return $this->getServer()->getSession(); - }); + $this->registerService(\OCP\ISession::class, fn ($c) => $this->getServer()->getSession()); - $this->registerService('OCP\\Security\\IContentSecurityPolicyManager', function ($c) { - return $this->getServer()->getContentSecurityPolicyManager(); - }); + $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, fn ($c) => $this->getServer()->getContentSecurityPolicyManager()); - $this->registerService('ServerContainer', function ($c) { - return $this->getServer(); - }); - $this->registerAlias('OCP\\IServerContainer', 'ServerContainer'); + $this->registerService('ServerContainer', fn ($c) => $this->getServer()); + $this->registerAlias(\OCP\IServerContainer::class, 'ServerContainer'); $this->registerAlias(IServiceLoader::class, 'ServerContainer'); - $this->registerService('Symfony\Component\EventDispatcher\EventDispatcherInterface', function ($c) { - return $this->getServer()->getEventDispatcher(); - }); + $this->registerService(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class, fn ($c) => $this->getServer()->getEventDispatcher()); - $this->registerService('OCP\\AppFramework\\IAppContainer', function ($c) { - return $c; - }); + $this->registerService(\OCP\AppFramework\IAppContainer::class, fn ($c) => $c); - $this->registerService(IDateTimeFormatter::class, function () { - return $this->getServer()->getDateTimeFormatter(); - }); - $this->registerService(IMountManager::class, function () { - return $this->getServer()->getMountManager(); - }); + $this->registerService(IDateTimeFormatter::class, fn () => $this->getServer()->getDateTimeFormatter()); + $this->registerService(IMountManager::class, fn () => $this->getServer()->getMountManager()); // commonly used attributes - $this->registerService('UserId', function ($c) { - return $c->query('OCP\\IUserSession')->getSession()->get('user_id'); - }); + $this->registerService('UserId', fn ($c) => $c->query(\OCP\IUserSession::class)->getSession()->get('user_id')); - $this->registerService('WebRoot', function ($c) { - return $c->query('ServerContainer')->getWebRoot(); - }); + $this->registerService('WebRoot', fn ($c) => $c->query('ServerContainer')->getWebRoot()); /** * App Framework APIs */ $this->registerService('API', function ($c) { - $c->query('OCP\\ILogger')->debug( + $c->query(\OCP\ILogger::class)->debug( 'Accessing the API class is deprecated! Use the appropriate ' . 'services instead!' ); @@ -333,53 +218,43 @@ public function __construct($appName, $urlParams = []) { return new Http($_SERVER, $protocol); }); - $this->registerService('Dispatcher', function ($c) { - return new Dispatcher( - $c['Protocol'], - $c['MiddlewareDispatcher'], - $c['ControllerMethodReflector'], - $c['Request'] - ); - }); + $this->registerService('Dispatcher', fn ($c) => new Dispatcher( + $c['Protocol'], + $c['MiddlewareDispatcher'], + $c['ControllerMethodReflector'], + $c['Request'] + )); - $this->registerService('OCP\Theme\IThemeService', function ($c) { - return $this->getServer()->getThemeService(); - }); + $this->registerService(\OCP\Theme\IThemeService::class, fn ($c) => $this->getServer()->getThemeService()); /** * Middleware */ $app = $this; - $this->registerService('SecurityMiddleware', function ($c) use ($app) { - return new SecurityMiddleware( - $c['Request'], - $c['ControllerMethodReflector'], - $app->getServer()->getNavigationManager(), - $app->getServer()->getURLGenerator(), - $app->getServer()->getLogger(), - $app->getServer()->getUserSession(), - $c['AppName'], - $app->isAdminUser(), - $app->getServer()->getContentSecurityPolicyManager() - ); - }); - - $this->registerService('CORSMiddleware', function ($c) { - return new CORSMiddleware( - $c['Request'], - $c['ControllerMethodReflector'], - $c['OCP\IUserSession'], - $c['OCP\IConfig'] - ); - }); - - $this->registerService('SessionMiddleware', function ($c) use ($app) { - return new SessionMiddleware( - $c['Request'], - $c['ControllerMethodReflector'], - $app->getServer()->getSession() - ); - }); + $this->registerService('SecurityMiddleware', fn ($c) => new SecurityMiddleware( + $c['Request'], + $c['ControllerMethodReflector'], + $app->getServer()->getNavigationManager(), + $app->getServer()->getURLGenerator(), + $app->getServer()->getLogger(), + $app->getServer()->getUserSession(), + $c['AppName'], + $app->isAdminUser(), + $app->getServer()->getContentSecurityPolicyManager() + )); + + $this->registerService('CORSMiddleware', fn ($c) => new CORSMiddleware( + $c['Request'], + $c['ControllerMethodReflector'], + $c[\OCP\IUserSession::class], + $c[\OCP\IConfig::class] + )); + + $this->registerService('SessionMiddleware', fn ($c) => new SessionMiddleware( + $c['Request'], + $c['ControllerMethodReflector'], + $app->getServer()->getSession() + )); $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) { // ToDo: DIServer is in DIContainer and not in SimpleContainer @@ -494,8 +369,6 @@ public function log($message, $level) { * @param string $serviceName e.g. 'OCA\Files\Capabilities' */ public function registerCapability($serviceName) { - $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) { - return $this->query($serviceName); - }); + $this->query(\OC\CapabilitiesManager::class)->registerCapability(fn () => $this->query($serviceName)); } } diff --git a/lib/private/AppFramework/Http/Dispatcher.php b/lib/private/AppFramework/Http/Dispatcher.php index 98666bc2dc7b..828b10c131ab 100644 --- a/lib/private/AppFramework/Http/Dispatcher.php +++ b/lib/private/AppFramework/Http/Dispatcher.php @@ -39,10 +39,10 @@ * Class to dispatch the request to the middleware dispatcher */ class Dispatcher { - private $middlewareDispatcher; - private $protocol; - private $reflector; - private $request; + private \OC\AppFramework\Middleware\MiddlewareDispatcher $middlewareDispatcher; + private \OC\AppFramework\Http $protocol; + private \OC\AppFramework\Utility\ControllerMethodReflector $reflector; + private \OCP\IRequest $request; /** * @param Http $protocol the http protocol with contains all status headers diff --git a/lib/private/AppFramework/Http/Output.php b/lib/private/AppFramework/Http/Output.php index 8ca47240da24..77d7b755f097 100644 --- a/lib/private/AppFramework/Http/Output.php +++ b/lib/private/AppFramework/Http/Output.php @@ -87,6 +87,6 @@ public function getHttpResponseCode() { */ public function setCookie($name, $value, $expire, $path, $domain, $secure, $httpOnly) { $localPath = $this->webRoot ? : '/'; - \setcookie($name, $value, $expire, $localPath, $domain, $secure, $httpOnly); + \setcookie($name, $value, ['expires' => $expire, 'path' => $localPath, 'domain' => $domain, 'secure' => $secure, 'httponly' => $httpOnly]); } } diff --git a/lib/private/AppFramework/Http/Request.php b/lib/private/AppFramework/Http/Request.php index 61f27d152f04..a3b093964d89 100644 --- a/lib/private/AppFramework/Http/Request.php +++ b/lib/private/AppFramework/Http/Request.php @@ -135,9 +135,7 @@ public function __construct( } foreach ($this->allowedKeys as $name) { - $this->items[$name] = isset($vars[$name]) - ? $vars[$name] - : []; + $this->items[$name] = $vars[$name] ?? []; } $this->items['parameters'] = \array_merge( @@ -194,9 +192,7 @@ public function offsetExists($offset) { * @see offsetExists */ public function offsetGet($offset) { - return isset($this->items['parameters'][$offset]) - ? $this->items['parameters'][$offset] - : null; + return $this->items['parameters'][$offset] ?? null; } /** @@ -253,16 +249,12 @@ public function __get($name) { case 'cookies': case 'urlParams': case 'method': - return isset($this->items[$name]) - ? $this->items[$name] - : null; + return $this->items[$name] ?? null; case 'parameters': case 'params': return $this->getContent(); default: - return isset($this[$name]) - ? $this[$name] - : null; + return $this[$name] ?? null; } } @@ -326,9 +318,7 @@ public function getHeader(string $name): ?string { * @return mixed the content of the array */ public function getParam($key, $default = null) { - return isset($this->parameters[$key]) - ? $this->parameters[$key] - : $default; + return $this->parameters[$key] ?? $default; } /** @@ -354,7 +344,7 @@ public function getMethod() { * @return array|null the file in the $_FILES element */ public function getUploadedFile($key) { - return isset($this->files[$key]) ? $this->files[$key] : null; + return $this->files[$key] ?? null; } /** @@ -363,7 +353,7 @@ public function getUploadedFile($key) { * @return array|null the value in the $_ENV element */ public function getEnv($key) { - return isset($this->env[$key]) ? $this->env[$key] : null; + return $this->env[$key] ?? null; } /** @@ -372,7 +362,7 @@ public function getEnv($key) { * @return string|null the value in the $_COOKIE element */ public function getCookie($key) { - return isset($this->cookies[$key]) ? $this->cookies[$key] : null; + return $this->cookies[$key] ?? null; } /** @@ -419,7 +409,7 @@ protected function decodeContent() { // 'application/json' must be decoded manually. if (\strpos($this->getHeader('Content-Type') ?? '', 'application/json') !== false) { - $params = \json_decode(\file_get_contents($this->inputStream), true); + $params = \json_decode(\file_get_contents($this->inputStream), true, 512, JSON_THROW_ON_ERROR); if (\is_array($params) && \count($params) > 0) { $this->items['params'] = $params; if ($this->method === 'POST') { @@ -511,7 +501,7 @@ public function getId() { * @return string IP address */ public function getRemoteAddress() { - $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : ''; + $remoteAddress = $this->server['REMOTE_ADDR'] ?? ''; $trustedProxies = $this->config->getSystemValue('trusted_proxies', []); if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) { @@ -542,7 +532,7 @@ public function getRemoteAddress() { */ private function isOverwriteCondition($type = '') { $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '') . '/'; - $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : ''; + $remoteAddr = $this->server['REMOTE_ADDR'] ?? ''; return $regex === '//' || \preg_match($regex, $remoteAddr) === 1 || $type !== 'protocol'; } @@ -608,7 +598,7 @@ public function getHttpProtocol() { * @return string */ public function getRequestUri() { - $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : ''; + $uri = $this->server['REQUEST_URI'] ?? ''; // remove too many leading slashes - can be caused by reverse proxy configuration if (\strpos($uri, '/') === 0) { $uri = '/' . \ltrim($uri, '/'); @@ -639,7 +629,7 @@ public function getRequestUri() { * @return string Path info */ public function getRawPathInfo() { - $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : ''; + $requestUri = $this->server['REQUEST_URI'] ?? ''; // remove too many leading slashes - can be caused by reverse proxy configuration if (\strpos($requestUri, '/') === 0) { $requestUri = '/' . \ltrim($requestUri, '/'); @@ -658,7 +648,7 @@ public function getRawPathInfo() { // strip off the script name's dir and file name // FIXME: Sabre does not really belong here - list($path, $name) = \Sabre\Uri\split($scriptName); + [$path, $name] = \Sabre\Uri\split($scriptName); if (!empty($path)) { if ($path === $pathInfo || \strpos($pathInfo, $path.'/') === 0) { $pathInfo = \substr($pathInfo, \strlen($path)); @@ -686,7 +676,7 @@ public function getRawPathInfo() { * @return string|false Path info or false when not found */ public function getPathInfo() { - $pathInfo = isset($this->server['PATH_INFO']) ? $this->server['PATH_INFO'] : ''; + $pathInfo = $this->server['PATH_INFO'] ?? ''; if ($pathInfo !== '') { return $pathInfo; } diff --git a/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php b/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php index 3f744d4e27fc..930cd7c40ae4 100644 --- a/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php +++ b/lib/private/AppFramework/Middleware/MiddlewareDispatcher.php @@ -37,13 +37,13 @@ class MiddlewareDispatcher { /** * @var array array containing all the middlewares */ - private $middlewares; + private array $middlewares; /** * @var int counter which tells us what middleware was executed once an * exception occurs */ - private $middlewareCounter; + private int $middlewareCounter; /** * Constructor diff --git a/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php b/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php index a55b6f4b21ce..71e85bfded97 100644 --- a/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/CORSMiddleware.php @@ -44,25 +44,13 @@ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS */ class CORSMiddleware extends Middleware { - /** - * @var IRequest - */ - private $request; + private \OCP\IRequest $request; - /** - * @var ControllerMethodReflector - */ - private $reflector; + private \OC\AppFramework\Utility\ControllerMethodReflector $reflector; - /** - * @var IUserSession - */ - private $session; + private \OCP\IUserSession $session; - /** - * @var IConfig - */ - private $config; + private \OCP\IConfig $config; /** * @param IRequest $request diff --git a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php index 6b50ec41a6b3..663570614bf5 100644 --- a/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php @@ -60,24 +60,17 @@ * check fails */ class SecurityMiddleware extends Middleware { - /** @var INavigationManager */ - private $navigationManager; - /** @var IRequest */ - private $request; - /** @var ControllerMethodReflector */ - private $reflector; + private \OCP\INavigationManager $navigationManager; + private \OCP\IRequest $request; + private \OC\AppFramework\Utility\ControllerMethodReflector $reflector; /** @var string */ private $appName; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var ILogger */ - private $logger; + private \OCP\IURLGenerator $urlGenerator; + private \OCP\ILogger $logger; /** @var bool */ private $isAdminUser; - /** @var ContentSecurityPolicyManager */ - private $contentSecurityPolicyManager; - /** @var IUserSession */ - private $session; + private \OC\Security\CSP\ContentSecurityPolicyManager $contentSecurityPolicyManager; + private \OCP\IUserSession $session; /** * @param IRequest $request @@ -169,7 +162,7 @@ public function beforeController($controller, $methodName) { * @return Response */ public function afterController($controller, $methodName, Response $response) { - $policy = $response->getContentSecurityPolicy() !== null ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy(); + $policy = $response->getContentSecurityPolicy() ?? new ContentSecurityPolicy(); $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy(); $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy); diff --git a/lib/private/AppFramework/Middleware/SessionMiddleware.php b/lib/private/AppFramework/Middleware/SessionMiddleware.php index fc50b9a1a54d..d8bc05e2fcdb 100644 --- a/lib/private/AppFramework/Middleware/SessionMiddleware.php +++ b/lib/private/AppFramework/Middleware/SessionMiddleware.php @@ -30,14 +30,11 @@ use OCP\ISession; class SessionMiddleware extends Middleware { - /** @var IRequest */ - private $request; + private \OCP\IRequest $request; - /** @var ControllerMethodReflector */ - private $reflector; + private \OC\AppFramework\Utility\ControllerMethodReflector $reflector; - /** @var ISession */ - private $session; + private \OCP\ISession $session; /** * @param IRequest $request diff --git a/lib/private/AppFramework/Routing/RouteActionHandler.php b/lib/private/AppFramework/Routing/RouteActionHandler.php index ae87cd6c659a..cd0041b24bb3 100644 --- a/lib/private/AppFramework/Routing/RouteActionHandler.php +++ b/lib/private/AppFramework/Routing/RouteActionHandler.php @@ -30,7 +30,7 @@ class RouteActionHandler { private $controllerName; private $actionName; - private $container; + private \OC\AppFramework\DependencyInjection\DIContainer $container; /** * @param DIContainer $container diff --git a/lib/private/AppFramework/Routing/RouteConfig.php b/lib/private/AppFramework/Routing/RouteConfig.php index dd9e86e9ff27..53f0e9955fc5 100644 --- a/lib/private/AppFramework/Routing/RouteConfig.php +++ b/lib/private/AppFramework/Routing/RouteConfig.php @@ -36,10 +36,8 @@ * @package OC\AppFramework\routing */ class RouteConfig { - /** @var DIContainer */ - private $container; - /** @var IRouter */ - private $router; + private \OC\AppFramework\DependencyInjection\DIContainer $container; + private \OCP\Route\IRouter $router; /** @var array */ private $routes; /** @var string */ @@ -81,7 +79,7 @@ public function register() { } private function processOCS(array $routes) { - $ocsRoutes = isset($routes['ocs']) ? $routes['ocs'] : []; + $ocsRoutes = $routes['ocs'] ?? []; foreach ($ocsRoutes as $ocsRoute) { $name = $ocsRoute['name']; $postFix = ''; @@ -90,9 +88,7 @@ private function processOCS(array $routes) { $postFix = $ocsRoute['postfix']; } - $root = (isset($ocsRoute['root'])) - ? $ocsRoute['root'] - : '/apps/' . $this->appName; + $root = $ocsRoute['root'] ?? '/apps/' . $this->appName; $url = $root . $ocsRoute['url']; $verb = isset($ocsRoute['verb']) ? \strtoupper($ocsRoute['verb']) : 'GET'; @@ -133,7 +129,7 @@ private function processOCS(array $routes) { * @throws \UnexpectedValueException */ private function processSimpleRoutes($routes) { - $simpleRoutes = isset($routes['routes']) ? $routes['routes'] : []; + $simpleRoutes = $routes['routes'] ?? []; foreach ($simpleRoutes as $simpleRoute) { $name = $simpleRoute['name']; $postfix = ''; @@ -196,14 +192,14 @@ private function processResources($routes) { ['name' => 'destroy', 'verb' => 'DELETE'], ]; - $resources = isset($routes['resources']) ? $routes['resources'] : []; + $resources = $routes['resources'] ?? []; foreach ($resources as $resource => $config) { // the url parameter used as id to the resource foreach ($actions as $action) { $url = $config['url']; $method = $action['name']; $verb = isset($action['verb']) ? \strtoupper($action['verb']) : 'GET'; - $collectionAction = isset($action['on-collection']) ? $action['on-collection'] : false; + $collectionAction = $action['on-collection'] ?? false; if (!$collectionAction) { $url = $url . '/{id}'; } @@ -252,9 +248,7 @@ private function underScoreToCamelCase($str) { $pattern = "/_[a-z]?/"; return \preg_replace_callback( $pattern, - function ($matches) { - return \strtoupper(\ltrim($matches[0], "_")); - }, + fn ($matches) => \strtoupper(\ltrim($matches[0], "_")), $str ); } diff --git a/lib/private/AppFramework/Utility/SimpleContainer.php b/lib/private/AppFramework/Utility/SimpleContainer.php index 91d7b1a15484..9c2687eec266 100644 --- a/lib/private/AppFramework/Utility/SimpleContainer.php +++ b/lib/private/AppFramework/Utility/SimpleContainer.php @@ -107,9 +107,7 @@ public function query($name) { return $this->offsetGet($name); } catch (\InvalidArgumentException $ex) { $object = $this->resolve($name); - $this->registerService($name, function () use ($object) { - return $object; - }); + $this->registerService($name, fn () => $object); return $object; } } @@ -151,9 +149,7 @@ public function registerService($name, Closure $closure, $shared = true) { * @param string $target the target that should be resolved instead */ public function registerAlias($alias, $target) { - $this->registerService($alias, function (IContainer $container) use ($target) { - return $container->query($target); - }, false); + $this->registerService($alias, fn (IContainer $container) => $container->query($target), false); } /* diff --git a/lib/private/Archive/TAR.php b/lib/private/Archive/TAR.php index dde64126dea3..c9d4b5913f4f 100644 --- a/lib/private/Archive/TAR.php +++ b/lib/private/Archive/TAR.php @@ -42,7 +42,7 @@ class TAR extends Archive { /** * @var \Archive_Tar tar */ - private $tar = null; + private ?\Archive_Tar $tar = null; private $path; /** @@ -363,7 +363,7 @@ public function getStream($path, $mode) { } } - private static $tempFiles = []; + private static array $tempFiles = []; /** * write back temporary files diff --git a/lib/private/Archive/ZIP.php b/lib/private/Archive/ZIP.php index 897d6f671221..70ce6d29b75a 100644 --- a/lib/private/Archive/ZIP.php +++ b/lib/private/Archive/ZIP.php @@ -34,7 +34,7 @@ class ZIP extends Archive { /** * @var \ZipArchive zip */ - private $zip=null; + private ?\ZipArchive $zip=null; private $path; /** @@ -209,7 +209,7 @@ public function getStream($path, $mode) { } } - private static $tempFiles= []; + private static array $tempFiles= []; /** * write back temporary files */ diff --git a/lib/private/Authentication/AccountModule/Manager.php b/lib/private/Authentication/AccountModule/Manager.php index a0f59645f315..bf12a9324cb8 100644 --- a/lib/private/Authentication/AccountModule/Manager.php +++ b/lib/private/Authentication/AccountModule/Manager.php @@ -29,14 +29,11 @@ use OCP\IUser; class Manager { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var IServiceLoader */ - private $loader; + private \OCP\App\IServiceLoader $loader; /** * @param IConfig $config @@ -61,7 +58,7 @@ public function getAccountModules(IUser $user) { // load order from appconfig $rawOrder = $this->config->getAppValue('core', 'account-module-order', '[]'); - $order = \json_decode($rawOrder); + $order = \json_decode($rawOrder, null, 512, JSON_THROW_ON_ERROR); if (!\is_array($order)) { $order = []; } diff --git a/lib/private/Authentication/LoginPolicies/GroupLoginPolicy.php b/lib/private/Authentication/LoginPolicies/GroupLoginPolicy.php index c282f98c0dfb..04db57881102 100644 --- a/lib/private/Authentication/LoginPolicies/GroupLoginPolicy.php +++ b/lib/private/Authentication/LoginPolicies/GroupLoginPolicy.php @@ -48,12 +48,9 @@ * ``` */ class GroupLoginPolicy implements ILoginPolicy { - /** @var IGroupManager */ - private $groupManager; - /** @var IConfig */ - private $config; - /** @var IL10N */ - private $l10n; + private \OCP\IGroupManager $groupManager; + private \OCP\IConfig $config; + private \OCP\IL10N $l10n; public function __construct(IGroupManager $groupManager, IConfig $config, IL10N $l10n) { $this->groupManager = $groupManager; diff --git a/lib/private/Authentication/LoginPolicies/LoginPolicyManager.php b/lib/private/Authentication/LoginPolicies/LoginPolicyManager.php index ce953f009b6c..dfa5b64f816e 100644 --- a/lib/private/Authentication/LoginPolicies/LoginPolicyManager.php +++ b/lib/private/Authentication/LoginPolicies/LoginPolicyManager.php @@ -27,14 +27,11 @@ use OC\User\LoginException; class LoginPolicyManager { - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; - /** @var IL10N */ - private $l10n; + private \OCP\IConfig $config; + private \OCP\ILogger $logger; + private \OCP\IL10N $l10n; /** @var Array */ - private $registeredPolicies = []; + private array $registeredPolicies = []; public function __construct(IConfig $config, ILogger $logger, IL10N $l10n) { $this->config = $config; diff --git a/lib/private/Authentication/Token/DefaultTokenCleanupJob.php b/lib/private/Authentication/Token/DefaultTokenCleanupJob.php index 4a98e9d58f22..51f301002e1c 100644 --- a/lib/private/Authentication/Token/DefaultTokenCleanupJob.php +++ b/lib/private/Authentication/Token/DefaultTokenCleanupJob.php @@ -28,7 +28,7 @@ class DefaultTokenCleanupJob extends Job { protected function run($argument) { /* @var $provider DefaultTokenProvider */ // TODO: add OC\Authentication\Token\IProvider::invalidateOldTokens and query interface - $provider = OC::$server->query('OC\Authentication\Token\DefaultTokenProvider'); + $provider = OC::$server->query(\OC\Authentication\Token\DefaultTokenProvider::class); $provider->invalidateOldTokens(); } } diff --git a/lib/private/Authentication/Token/DefaultTokenMapper.php b/lib/private/Authentication/Token/DefaultTokenMapper.php index 345a79e4d095..dbab11b982e2 100644 --- a/lib/private/Authentication/Token/DefaultTokenMapper.php +++ b/lib/private/Authentication/Token/DefaultTokenMapper.php @@ -103,9 +103,7 @@ public function getTokenByUser(IUser $user) { $data = $result->fetchAll(); $result->closeCursor(); - $entities = \array_map(function ($row) { - return DefaultToken::fromRow($row); - }, $data); + $entities = \array_map(fn ($row) => DefaultToken::fromRow($row), $data); return $entities; } diff --git a/lib/private/Authentication/Token/DefaultTokenProvider.php b/lib/private/Authentication/Token/DefaultTokenProvider.php index 541eeb165e89..8166fedd96f8 100644 --- a/lib/private/Authentication/Token/DefaultTokenProvider.php +++ b/lib/private/Authentication/Token/DefaultTokenProvider.php @@ -32,20 +32,15 @@ use OCP\Security\ICrypto; class DefaultTokenProvider implements IProvider { - /** @var DefaultTokenMapper */ - private $mapper; + private \OC\Authentication\Token\DefaultTokenMapper $mapper; - /** @var ICrypto */ - private $crypto; + private \OCP\Security\ICrypto $crypto; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var ILogger $logger */ - private $logger; + private \OCP\ILogger $logger; - /** @var ITimeFactory $time */ - private $time; + private \OCP\AppFramework\Utility\ITimeFactory $time; /** * @param DefaultTokenMapper $mapper diff --git a/lib/private/Authentication/TwoFactorAuth/Manager.php b/lib/private/Authentication/TwoFactorAuth/Manager.php index 2f3ac967e7ce..67ba9f55d0f9 100644 --- a/lib/private/Authentication/TwoFactorAuth/Manager.php +++ b/lib/private/Authentication/TwoFactorAuth/Manager.php @@ -38,23 +38,17 @@ class Manager { public const SESSION_UID_KEY = 'two_factor_auth_uid'; - /** @var AppManager */ - private $appManager; + private \OC\App\AppManager $appManager; - /** @var ISession */ - private $session; + private \OCP\ISession $session; - /** @var IGroupManager */ - private $groupManager; + private \OCP\IGroupManager $groupManager; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var IRequest */ - private $request; + private \OCP\IRequest $request; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; /** * @param AppManager $appManager @@ -92,7 +86,7 @@ public function isTwoFactorEnforcedForUser(IUser $user) { return false; } - $enforce2faExcludedGroups = \json_decode($this->config->getAppValue('core', 'enforce_2fa_excluded_groups', '[]'), true); + $enforce2faExcludedGroups = \json_decode($this->config->getAppValue('core', 'enforce_2fa_excluded_groups', '[]'), true, 512, JSON_THROW_ON_ERROR); if (!empty($enforce2faExcludedGroups)) { foreach ($enforce2faExcludedGroups as $group) { if ($this->groupManager->isInGroup($user->getUID(), $group)) { @@ -130,7 +124,7 @@ public function enableTwoFactorAuthentication(IUser $user) { */ public function getProvider(IUser $user, $challengeProviderId) { $providers = $this->getProviders($user); - return isset($providers[$challengeProviderId]) ? $providers[$challengeProviderId] : null; + return $providers[$challengeProviderId] ?? null; } /** @@ -168,10 +162,9 @@ public function getProviders(IUser $user) { return $providers; } - return \array_filter($providers, function ($provider) use ($user) { - /* @var $provider IProvider */ - return $provider->isTwoFactorAuthEnabledForUser($user); - }); + return \array_filter($providers, fn ($provider) => + /* @var $provider IProvider */ + $provider->isTwoFactorAuthEnabledForUser($user)); } /** diff --git a/lib/private/Autoloader.php b/lib/private/Autoloader.php index 315f4d0c9141..028deebfab62 100644 --- a/lib/private/Autoloader.php +++ b/lib/private/Autoloader.php @@ -34,8 +34,7 @@ use \OCP\AutoloadNotAllowedException; class Autoloader { - /** @var array */ - private $validRoots = []; + private array $validRoots = []; /** * Optional low-latency memory cache for class to path mapping. @@ -76,7 +75,7 @@ public function findClass($class) { $paths = []; if (\strpos($class, 'OCA\\') === 0) { - list(, $app, $rest) = \explode('\\', $class, 3); + [, $app, $rest] = \explode('\\', $class, 3); $app = \strtolower($app); $appPath = \OC_App::getAppPath($app); if ($appPath && \stream_resolve_include_path($appPath)) { diff --git a/lib/private/Avatar.php b/lib/private/Avatar.php index 293499b3464c..c5d26ff6abff 100644 --- a/lib/private/Avatar.php +++ b/lib/private/Avatar.php @@ -45,14 +45,10 @@ */ class Avatar implements IAvatar { - /** @var IStorage */ - private $storage; - /** @var IL10N */ - private $l; - /** @var User */ - private $user; - /** @var ILogger */ - private $logger; + private \OCP\Files\Storage\IStorage $storage; + private \OCP\IL10N $l; + private \OC\User\User $user; + private \OCP\ILogger $logger; /** @var string */ private $path; diff --git a/lib/private/AvatarManager.php b/lib/private/AvatarManager.php index 14f0bd048e49..8e1c6c469fa7 100644 --- a/lib/private/AvatarManager.php +++ b/lib/private/AvatarManager.php @@ -40,20 +40,16 @@ * This class implements methods to access Avatar functionality */ class AvatarManager implements IAvatarManager { - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; /** @var IStorage */ private $storage; - /** @var IL10N */ - private $l; + private \OCP\IL10N $l; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; /** * AvatarManager constructor. diff --git a/lib/private/BackgroundJob/JobList.php b/lib/private/BackgroundJob/JobList.php index 967238cff57b..27a885f29682 100644 --- a/lib/private/BackgroundJob/JobList.php +++ b/lib/private/BackgroundJob/JobList.php @@ -68,7 +68,7 @@ public function add($job, $argument = null) { $class = $job; } - $argument = \json_encode($argument); + $argument = \json_encode($argument, JSON_THROW_ON_ERROR); if (\strlen($argument) > 4000) { throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)'); } @@ -102,7 +102,7 @@ public function remove($job, $argument = null) { $query->delete('jobs') ->where($query->expr()->eq('class', $query->createNamedParameter($class))); if ($argument !== null) { - $argument = \json_encode($argument); + $argument = \json_encode($argument, JSON_THROW_ON_ERROR); $query->andWhere($query->expr()->eq('argument', $query->createNamedParameter($argument))); } $query->execute(); @@ -131,7 +131,7 @@ public function has($job, $argument) { } else { $class = $job; } - $argument = \json_encode($argument); + $argument = \json_encode($argument, JSON_THROW_ON_ERROR); $query = $this->connection->getQueryBuilder(); $query->select('id') @@ -293,7 +293,7 @@ private function buildJob($row) { $job->setId($row['id']); $job->setLastRun($row['last_run']); - $job->setArgument(\json_decode($row['argument'], true)); + $job->setArgument(\json_decode($row['argument'], true, 512, JSON_THROW_ON_ERROR)); $job->setLastChecked($row['last_checked']); $job->setReservedAt($row['reserved_at']); $job->setExecutionDuration($row['execution_duration']); diff --git a/lib/private/Cache/CappedMemoryCache.php b/lib/private/Cache/CappedMemoryCache.php index 1e0b9eddef3c..3e79f1efa47e 100644 --- a/lib/private/Cache/CappedMemoryCache.php +++ b/lib/private/Cache/CappedMemoryCache.php @@ -30,7 +30,7 @@ */ class CappedMemoryCache implements ICache, \ArrayAccess { private $capacity; - private $cache = []; + private array $cache = []; public function __construct($capacity = 512) { $this->capacity = $capacity; @@ -41,7 +41,7 @@ public function hasKey($key) { } public function get($key) { - return isset($this->cache[$key]) ? $this->cache[$key] : null; + return $this->cache[$key] ?? null; } public function set($key, $value, $ttl = 0) { @@ -78,8 +78,7 @@ public function offsetUnset($offset) { private function garbageCollect() { while (\count($this->cache) > $this->capacity) { - \reset($this->cache); - $key = \key($this->cache); + $key = array_key_first($this->cache); $this->remove($key); } } diff --git a/lib/private/CapabilitiesManager.php b/lib/private/CapabilitiesManager.php index 6f63c3adf263..3e0c08b8e15e 100644 --- a/lib/private/CapabilitiesManager.php +++ b/lib/private/CapabilitiesManager.php @@ -27,7 +27,7 @@ class CapabilitiesManager { /** * @var \Closure[] */ - private $capabilities = []; + private array $capabilities = []; /** * Get an array of al the capabilities that are registered at this manager diff --git a/lib/private/Command/AsyncBus.php b/lib/private/Command/AsyncBus.php index e9c6d8707ced..adabae74a8e2 100644 --- a/lib/private/Command/AsyncBus.php +++ b/lib/private/Command/AsyncBus.php @@ -44,7 +44,7 @@ class AsyncBus implements IBus { * * @var string[] */ - private $syncTraits = []; + private array $syncTraits = []; /** * @param IJobList $jobList @@ -92,15 +92,15 @@ private function runCommand($command) { */ private function getJobClass($command) { if ($command instanceof Closure) { - return 'OC\Command\ClosureJob'; + return \OC\Command\ClosureJob::class; } if (\is_callable($command)) { - return 'OC\Command\CallableJob'; + return \OC\Command\CallableJob::class; } if ($command instanceof ICommand) { - return 'OC\Command\CommandJob'; + return \OC\Command\CommandJob::class; } throw new InvalidArgumentException('Invalid command'); diff --git a/lib/private/Command/QueueBus.php b/lib/private/Command/QueueBus.php index 1145becb6e52..040dc8b9a3ee 100644 --- a/lib/private/Command/QueueBus.php +++ b/lib/private/Command/QueueBus.php @@ -28,7 +28,7 @@ class QueueBus implements IBus { /** * @var (ICommand|callable)[] */ - private $queue = []; + private array $queue = []; /** * Schedule a command to be fired diff --git a/lib/private/Comments/Manager.php b/lib/private/Comments/Manager.php index 2a968f1928a6..a437ee1b339c 100644 --- a/lib/private/Comments/Manager.php +++ b/lib/private/Comments/Manager.php @@ -594,9 +594,7 @@ protected function insert(IComment &$comment) { new CommentsEvent(CommentsEvent::EVENT_ADD, $comment), CommentsEvent::EVENT_ADD ); - return $this->emittingCall(function () use ($affectedRows) { - return $affectedRows > 0; - }, [ + return $this->emittingCall(fn () => $affectedRows > 0, [ 'before' => ['objectId' => $comment->getObjectId(), 'message' => $comment->getMessage()], 'after' => ['commentId' => $comment->getId(), 'objectId' => $comment->getObjectId(), 'message' => $comment->getMessage()] ], 'comment', 'create'); diff --git a/lib/private/Comments/ManagerFactory.php b/lib/private/Comments/ManagerFactory.php index 19e732a7452d..81bb39cd9455 100644 --- a/lib/private/Comments/ManagerFactory.php +++ b/lib/private/Comments/ManagerFactory.php @@ -29,11 +29,9 @@ class ManagerFactory implements ICommentsManagerFactory { /** - * Server container - * - * @var IServerContainer - */ - private $serverContainer; + * Server container + */ + private \OCP\IServerContainer $serverContainer; /** * Constructor for the comments manager factory diff --git a/lib/private/Config.php b/lib/private/Config.php index 2e7ff9357c53..b17f92fc31a0 100644 --- a/lib/private/Config.php +++ b/lib/private/Config.php @@ -92,11 +92,7 @@ public function getValue($key, $default = null) { return $envValue; } - if (isset($this->cache[$key])) { - return $this->cache[$key]; - } - - return $default; + return $this->cache[$key] ?? $default; } /** @@ -231,7 +227,7 @@ private function readData() { $extra = \glob($this->configDir.'*.'.$this->configFileName); if (\is_array($extra)) { \natsort($extra); - $configFiles = \array_merge($configFiles, $extra); + $configFiles = [...$configFiles, ...$extra]; } // Include file and merge config diff --git a/lib/private/Console/Application.php b/lib/private/Console/Application.php index ff61a9a590ad..e48fc3fc2164 100644 --- a/lib/private/Console/Application.php +++ b/lib/private/Console/Application.php @@ -40,15 +40,11 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; class Application { - /** @var IConfig */ - private $config; - /** @var EventDispatcherInterface */ - private $dispatcher; - /** @var IRequest */ - private $request; + private \OCP\IConfig $config; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher; + private \OCP\IRequest $request; - /** @var SymfonyApplication */ - private $application; + private \Symfony\Component\Console\Application $application; /** * @param IConfig $config @@ -157,7 +153,7 @@ public function setAutoExit($boolean) { * @throws \Exception */ public function run(InputInterface $input = null, OutputInterface $output = null) { - $args = isset($this->request->server['argv']) ? $this->request->server['argv'] : []; + $args = $this->request->server['argv'] ?? []; $this->dispatcher->dispatch( new ConsoleEvent(ConsoleEvent::EVENT_RUN, $args), ConsoleEvent::EVENT_RUN diff --git a/lib/private/Console/TimestampFormatter.php b/lib/private/Console/TimestampFormatter.php index d92c9af8265f..a75d4a6cd0f2 100644 --- a/lib/private/Console/TimestampFormatter.php +++ b/lib/private/Console/TimestampFormatter.php @@ -29,8 +29,7 @@ class TimestampFormatter implements OutputFormatterInterface { /** @var IConfig */ protected $config; - /** @var OutputFormatterInterface */ - private $formatter; + private \Symfony\Component\Console\Formatter\OutputFormatterInterface $formatter; /** * @param IConfig $config diff --git a/lib/private/ContactsManager.php b/lib/private/ContactsManager.php index 5f8a89c22d5d..b4c7d6e19506 100644 --- a/lib/private/ContactsManager.php +++ b/lib/private/ContactsManager.php @@ -49,7 +49,7 @@ public function search($pattern, $searchProperties = [], $options = [], $limit = $c['addressbook-key'] = $addressBook->getKey(); $contacts[] = $c; } - $result = \array_merge($result, $contacts); + $result = [...$result, ...$contacts]; } return $result; diff --git a/lib/private/DB/ConnectionFactory.php b/lib/private/DB/ConnectionFactory.php index b4665bdf0fa6..07c620117b7a 100644 --- a/lib/private/DB/ConnectionFactory.php +++ b/lib/private/DB/ConnectionFactory.php @@ -43,30 +43,29 @@ class ConnectionFactory { */ protected $defaultConnectionParams = [ 'mysql' => [ - 'adapter' => '\OC\DB\AdapterMySQL', + 'adapter' => '\\' . \OC\DB\AdapterMySQL::class, 'charset' => 'UTF8', 'driver' => 'pdo_mysql', - 'wrapperClass' => 'OC\DB\Connection', + 'wrapperClass' => \OC\DB\Connection::class, ], 'oci' => [ - 'adapter' => '\OC\DB\AdapterOCI8', + 'adapter' => '\\' . \OC\DB\AdapterOCI8::class, 'charset' => 'AL32UTF8', 'driver' => 'oci8', - 'wrapperClass' => 'OC\DB\OracleConnection', + 'wrapperClass' => \OC\DB\OracleConnection::class, ], 'pgsql' => [ - 'adapter' => '\OC\DB\AdapterPgSql', + 'adapter' => '\\' . \OC\DB\AdapterPgSql::class, 'driver' => 'pdo_pgsql', - 'wrapperClass' => 'OC\DB\Connection', + 'wrapperClass' => \OC\DB\Connection::class, ], 'sqlite3' => [ - 'adapter' => '\OC\DB\AdapterSqlite', + 'adapter' => '\\' . \OC\DB\AdapterSqlite::class, 'driver' => 'pdo_sqlite', - 'wrapperClass' => 'OC\DB\Connection', + 'wrapperClass' => \OC\DB\Connection::class, ], ]; - /** @var SystemConfig */ - private $config; + private \OC\SystemConfig $config; /** * ConnectionFactory constructor. @@ -188,7 +187,7 @@ public function createConnectionParams() { $host = $this->config->getValue('dbhost', ''); if (\strpos($host, ':')) { // Host variable may carry a port or socket. - list($host, $portOrSocket) = \explode(':', $host, 2); + [$host, $portOrSocket] = \explode(':', $host, 2); if (\ctype_digit($portOrSocket)) { $connectionParams['port'] = $portOrSocket; } else { diff --git a/lib/private/DB/MigrationService.php b/lib/private/DB/MigrationService.php index d579173c75dd..ef025aa44473 100644 --- a/lib/private/DB/MigrationService.php +++ b/lib/private/DB/MigrationService.php @@ -36,22 +36,19 @@ use OCP\ILogger; class MigrationService { - /** @var boolean */ - private $migrationTableCreated; + private ?bool $migrationTableCreated = null; /** @var array */ private $migrations; /** @var IOutput */ private $output; /** @var Connection */ - private $connection; + private \OCP\IDBConnection $connection; /** @var string */ private $appName; /** @var ILogger */ private $logger; - /** @var string */ - private $migrationsPath; - /** @var string */ - private $migrationsNamespace; + private ?string $migrationsPath = null; + private ?string $migrationsNamespace = null; /** * MigrationService constructor. @@ -194,9 +191,7 @@ protected function findMigrations() { ); $files = \array_keys(\iterator_to_array($iterator)); - \uasort($files, function ($a, $b) { - return \strcmp(\basename($a), \basename($b)); - }); + \uasort($files, fn ($a, $b) => \strcmp(\basename($a), \basename($b))); $migrations = []; diff --git a/lib/private/DB/Migrator.php b/lib/private/DB/Migrator.php index db8fdd4d69e1..a55598e52fe5 100644 --- a/lib/private/DB/Migrator.php +++ b/lib/private/DB/Migrator.php @@ -43,17 +43,14 @@ class Migrator { /** @var \Doctrine\DBAL\Connection $connection */ protected $connection; - /** @var ISecureRandom */ - private $random; + private \OCP\Security\ISecureRandom $random; /** @var IConfig */ protected $config; - /** @var EventDispatcher */ - private $dispatcher; + private ?\Symfony\Component\EventDispatcher\EventDispatcher $dispatcher = null; - /** @var bool */ - private $noEmit = false; + private bool $noEmit = false; /** * @param \Doctrine\DBAL\Connection|Connection $connection diff --git a/lib/private/DB/OracleMigrator.php b/lib/private/DB/OracleMigrator.php index 4b529dfe152c..2d675ad7201b 100644 --- a/lib/private/DB/OracleMigrator.php +++ b/lib/private/DB/OracleMigrator.php @@ -69,9 +69,7 @@ protected function quoteIndex($index) { return new Index( //TODO migrate existing uppercase indexes, then $this->connection->quoteIdentifier($index->getName()), $index->getName(), - \array_map(function ($columnName) { - return $this->connection->quoteIdentifier($columnName); - }, $index->getColumns()), + \array_map(fn ($columnName) => $this->connection->quoteIdentifier($columnName), $index->getColumns()), $index->isUnique(), $index->isPrimary(), $index->getFlags(), @@ -88,13 +86,9 @@ protected function quoteIndex($index) { */ protected function quoteForeignKeyConstraint($fkc) { return new ForeignKeyConstraint( - \array_map(function ($columnName) { - return $this->connection->quoteIdentifier($columnName); - }, $fkc->getLocalColumns()), + \array_map(fn ($columnName) => $this->connection->quoteIdentifier($columnName), $fkc->getLocalColumns()), $this->connection->quoteIdentifier($fkc->getForeignTableName()), - \array_map(function ($columnName) { - return $this->connection->quoteIdentifier($columnName); - }, $fkc->getForeignColumns()), + \array_map(fn ($columnName) => $this->connection->quoteIdentifier($columnName), $fkc->getForeignColumns()), $fkc->getName(), $fkc->getOptions() ); @@ -109,40 +103,28 @@ protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $conn $schemaDiff = parent::getDiff($targetSchema, $connection); // oracle forces us to quote the identifiers - $schemaDiff->newTables = \array_map(function (Table $table) { - return new Table( - $this->connection->quoteIdentifier($table->getName()), - \array_map(function (Column $column) { - return $this->quoteColumn($column); - }, $table->getColumns()), - \array_map(function (Index $index) { - return $this->quoteIndex($index); - }, $table->getIndexes()), - \array_map(function (ForeignKeyConstraint $fck) { - return $this->quoteForeignKeyConstraint($fck); - }, $table->getForeignKeys()), - 0, - $table->getOptions() - ); - }, $schemaDiff->newTables); - - $schemaDiff->removedTables = \array_map(function (Table $table) { - return new Table( - $this->connection->quoteIdentifier($table->getName()), - $table->getColumns(), - $table->getIndexes(), - $table->getForeignKeys(), - 0, - $table->getOptions() - ); - }, $schemaDiff->removedTables); + $schemaDiff->newTables = \array_map(fn (Table $table) => new Table( + $this->connection->quoteIdentifier($table->getName()), + \array_map(fn (Column $column) => $this->quoteColumn($column), $table->getColumns()), + \array_map(fn (Index $index) => $this->quoteIndex($index), $table->getIndexes()), + \array_map(fn (ForeignKeyConstraint $fck) => $this->quoteForeignKeyConstraint($fck), $table->getForeignKeys()), + 0, + $table->getOptions() + ), $schemaDiff->newTables); + + $schemaDiff->removedTables = \array_map(fn (Table $table) => new Table( + $this->connection->quoteIdentifier($table->getName()), + $table->getColumns(), + $table->getIndexes(), + $table->getForeignKeys(), + 0, + $table->getOptions() + ), $schemaDiff->removedTables); foreach ($schemaDiff->changedTables as $tableDiff) { $tableDiff->name = $this->connection->quoteIdentifier($tableDiff->name); - $tableDiff->addedColumns = \array_map(function (Column $column) { - return $this->quoteColumn($column); - }, $tableDiff->addedColumns); + $tableDiff->addedColumns = \array_map(fn (Column $column) => $this->quoteColumn($column), $tableDiff->addedColumns); foreach ($tableDiff->changedColumns as $column) { $column->oldColumnName = $this->connection->quoteIdentifier($column->oldColumnName); @@ -150,45 +132,25 @@ protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $conn $column->changedProperties = \array_diff($column->changedProperties, ['autoincrement', 'unsigned']); } // remove columns that no longer have changed (because autoincrement and unsigned are not supported) - $tableDiff->changedColumns = \array_filter($tableDiff->changedColumns, function (ColumnDiff $column) { - return \count($column->changedProperties) > 0; - }); + $tableDiff->changedColumns = \array_filter($tableDiff->changedColumns, fn (ColumnDiff $column) => \count($column->changedProperties) > 0); - $tableDiff->removedColumns = \array_map(function (Column $column) { - return $this->quoteColumn($column); - }, $tableDiff->removedColumns); + $tableDiff->removedColumns = \array_map(fn (Column $column) => $this->quoteColumn($column), $tableDiff->removedColumns); - $tableDiff->renamedColumns = \array_map(function (Column $column) { - return $this->quoteColumn($column); - }, $tableDiff->renamedColumns); + $tableDiff->renamedColumns = \array_map(fn (Column $column) => $this->quoteColumn($column), $tableDiff->renamedColumns); - $tableDiff->addedIndexes = \array_map(function (Index $index) { - return $this->quoteIndex($index); - }, $tableDiff->addedIndexes); + $tableDiff->addedIndexes = \array_map(fn (Index $index) => $this->quoteIndex($index), $tableDiff->addedIndexes); - $tableDiff->changedIndexes = \array_map(function (Index $index) { - return $this->quoteIndex($index); - }, $tableDiff->changedIndexes); + $tableDiff->changedIndexes = \array_map(fn (Index $index) => $this->quoteIndex($index), $tableDiff->changedIndexes); - $tableDiff->removedIndexes = \array_map(function (Index $index) { - return $this->quoteIndex($index); - }, $tableDiff->removedIndexes); + $tableDiff->removedIndexes = \array_map(fn (Index $index) => $this->quoteIndex($index), $tableDiff->removedIndexes); - $tableDiff->renamedIndexes = \array_map(function (Index $index) { - return $this->quoteIndex($index); - }, $tableDiff->renamedIndexes); + $tableDiff->renamedIndexes = \array_map(fn (Index $index) => $this->quoteIndex($index), $tableDiff->renamedIndexes); - $tableDiff->addedForeignKeys = \array_map(function (ForeignKeyConstraint $fkc) { - return $this->quoteForeignKeyConstraint($fkc); - }, $tableDiff->addedForeignKeys); + $tableDiff->addedForeignKeys = \array_map(fn (ForeignKeyConstraint $fkc) => $this->quoteForeignKeyConstraint($fkc), $tableDiff->addedForeignKeys); - $tableDiff->changedForeignKeys = \array_map(function (ForeignKeyConstraint $fkc) { - return $this->quoteForeignKeyConstraint($fkc); - }, $tableDiff->changedForeignKeys); + $tableDiff->changedForeignKeys = \array_map(fn (ForeignKeyConstraint $fkc) => $this->quoteForeignKeyConstraint($fkc), $tableDiff->changedForeignKeys); - $tableDiff->removedForeignKeys = \array_map(function (ForeignKeyConstraint $fkc) { - return $this->quoteForeignKeyConstraint($fkc); - }, $tableDiff->removedForeignKeys); + $tableDiff->removedForeignKeys = \array_map(fn (ForeignKeyConstraint $fkc) => $this->quoteForeignKeyConstraint($fkc), $tableDiff->removedForeignKeys); } return $schemaDiff; diff --git a/lib/private/DB/PgSqlTools.php b/lib/private/DB/PgSqlTools.php index d0f992bf273e..184713b79a5b 100644 --- a/lib/private/DB/PgSqlTools.php +++ b/lib/private/DB/PgSqlTools.php @@ -29,8 +29,7 @@ * Various PostgreSQL specific helper functions. */ class PgSqlTools { - /** @var \OCP\IConfig */ - private $config; + private \OCP\IConfig $config; /** * @param \OCP\IConfig $config diff --git a/lib/private/DB/QueryBuilder/QueryBuilder.php b/lib/private/DB/QueryBuilder/QueryBuilder.php index 33f0246f62b3..426441476b12 100644 --- a/lib/private/DB/QueryBuilder/QueryBuilder.php +++ b/lib/private/DB/QueryBuilder/QueryBuilder.php @@ -37,17 +37,13 @@ use OCP\IDBConnection; class QueryBuilder implements IQueryBuilder { - /** @var \OCP\IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; - /** @var \Doctrine\DBAL\Query\QueryBuilder */ - private $queryBuilder; + private \Doctrine\DBAL\Query\QueryBuilder $queryBuilder; - /** @var QuoteHelper */ - private $helper; + private \OC\DB\QueryBuilder\QuoteHelper $helper; - /** @var bool */ - private $automaticTablePrefix = true; + private bool $automaticTablePrefix = true; /** @var string */ protected $lastInsertedTable; diff --git a/lib/private/DB/QueryBuilder/QuoteHelper.php b/lib/private/DB/QueryBuilder/QuoteHelper.php index 3cbb128bb728..8c94b201b804 100644 --- a/lib/private/DB/QueryBuilder/QuoteHelper.php +++ b/lib/private/DB/QueryBuilder/QuoteHelper.php @@ -61,7 +61,7 @@ public function quoteColumnName($string) { } if (\substr_count($string, '.')) { - list($alias, $columnName) = \explode('.', $string, 2); + [$alias, $columnName] = \explode('.', $string, 2); if ($columnName === '*') { return $string; diff --git a/lib/private/Diagnostics/EventLogger.php b/lib/private/Diagnostics/EventLogger.php index 9edcac47a959..11b17bc4af39 100644 --- a/lib/private/Diagnostics/EventLogger.php +++ b/lib/private/Diagnostics/EventLogger.php @@ -30,12 +30,12 @@ class EventLogger implements IEventLogger { /** * @var \OC\Diagnostics\Event[] */ - private $events = []; + private array $events = []; /** * @var bool - Module needs to be activated by some app */ - private $activated = false; + private bool $activated = false; /** * @inheritdoc diff --git a/lib/private/Diagnostics/QueryLogger.php b/lib/private/Diagnostics/QueryLogger.php index e98d47eb5836..89414df12eb8 100644 --- a/lib/private/Diagnostics/QueryLogger.php +++ b/lib/private/Diagnostics/QueryLogger.php @@ -40,7 +40,7 @@ class QueryLogger implements IQueryLogger { /** * @var bool - Module needs to be activated by some app */ - private $activated = false; + private bool $activated = false; /** * @inheritdoc diff --git a/lib/private/Encryption/DecryptAll.php b/lib/private/Encryption/DecryptAll.php index ea4a80218e76..4b34a21094ef 100644 --- a/lib/private/Encryption/DecryptAll.php +++ b/lib/private/Encryption/DecryptAll.php @@ -220,7 +220,7 @@ protected function decryptUsersFiles($uid, ProgressBar $progress, $userCount) { $content = $this->rootView->getDirectoryContent($root); foreach ($content as $file) { // only decrypt files owned by the user, exclude incoming local shares, and incoming federated shares - if ($file->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { + if ($file->getStorage()->instanceOfStorage('\\' . \OCA\Files_Sharing\ISharedStorage::class)) { continue; } $path = $root . '/' . $file['name']; @@ -243,7 +243,7 @@ protected function decryptUsersFiles($uid, ProgressBar $progress, $userCount) { } catch (\Exception $e) { $this->logger->logException($e, [ 'message' => "Exception trying to decrypt file <$path> for user <$uid>", - 'app' => __CLASS__ + 'app' => self::class ]); if (isset($this->failed[$uid])) { $this->failed[$uid][] = ['path' => $path, 'exception' => $e]; @@ -273,7 +273,7 @@ protected function decryptFile($path) { View::setIgnorePartFile(true); $this->rootView->rename($target, $source); View::setIgnorePartFile(false); - list($storage, $internalPath) = $this->rootView->resolvePath($source); + [$storage, $internalPath] = $this->rootView->resolvePath($source); //Update the encrypted column in file cache to zero, as the file is decrypted $storage->getCache()->put($internalPath, ['encrypted' => 0]); } catch (DecryptionFailedException $e) { diff --git a/lib/private/Encryption/EncryptionWrapper.php b/lib/private/Encryption/EncryptionWrapper.php index 95309c9ad529..498b1745fb4a 100644 --- a/lib/private/Encryption/EncryptionWrapper.php +++ b/lib/private/Encryption/EncryptionWrapper.php @@ -38,14 +38,11 @@ * @package OC\Encryption */ class EncryptionWrapper { - /** @var ArrayCache */ - private $arrayCache; + private \OC\Memcache\ArrayCache $arrayCache; - /** @var Manager */ - private $manager; + private \OC\Encryption\Manager $manager; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; /** * EncryptionWrapper constructor. @@ -79,8 +76,8 @@ public function wrapStorage($mountPoint, Storage $storage, IMountPoint $mount) { 'mount' => $mount ]; - if (!$storage->instanceOfStorage('OCA\Files_Sharing\SharedStorage') - && !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') + if (!$storage->instanceOfStorage(\OCA\Files_Sharing\SharedStorage::class) + && !$storage->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class) && !$storage->instanceOfStorage('OC\Files\Storage\OwnCloud')) { $user = \OC::$server->getUserSession()->getUser(); $mountManager = Filesystem::getMountManager(); diff --git a/lib/private/Encryption/File.php b/lib/private/Encryption/File.php index 340a9a8ca589..05c910bd280e 100644 --- a/lib/private/Encryption/File.php +++ b/lib/private/Encryption/File.php @@ -50,7 +50,7 @@ public function __construct(Util $util) { */ public function getAccessList($path) { // Make sure that a share key is generated for the owner too - list($owner, $ownerPath) = $this->util->getUidAndFilename($path); + [$owner, $ownerPath] = $this->util->getUidAndFilename($path); // always add owner to the list of users with access to the file $userIds = [$owner]; diff --git a/lib/private/Encryption/HookManager.php b/lib/private/Encryption/HookManager.php index c5fbae390129..61a339077ca2 100644 --- a/lib/private/Encryption/HookManager.php +++ b/lib/private/Encryption/HookManager.php @@ -26,10 +26,7 @@ use OC\Files\View; class HookManager { - /** - * @var Update - */ - private static $updater; + private static ?\OC\Encryption\Update $updater = null; public static function postShared($params) { self::getUpdate()->postShared($params); diff --git a/lib/private/Encryption/Keys/Storage.php b/lib/private/Encryption/Keys/Storage.php index 045f7d5d75b6..094b81d0bff0 100644 --- a/lib/private/Encryption/Keys/Storage.php +++ b/lib/private/Encryption/Keys/Storage.php @@ -36,25 +36,20 @@ class Storage implements IStorage { // hidden file which indicate that the folder is a valid key storage public const KEY_STORAGE_MARKER = '.oc_key_storage'; - /** @var View */ - private $view; + private \OC\Files\View $view; - /** @var Util */ - private $util; + private \OC\Encryption\Util $util; // base dir where all the file related keys are stored - /** @var string */ - private $keys_base_dir; + private string $keys_base_dir; // root of the key storage default is empty which means that we use the data folder /** @var string */ private $root_dir; - /** @var string */ - private $encryption_base_dir; + private string $encryption_base_dir; - /** @var array */ - private $keyCache = []; + private array $keyCache = []; /** @var string */ private $currentUser = null; @@ -274,7 +269,7 @@ private function setKey($path, $key) { * @return string */ private function getFileKeyDir($encryptionModuleId, $path) { - list($owner, $filename) = $this->util->getUidAndFilename($path); + [$owner, $filename] = $this->util->getUidAndFilename($path); // in case of system wide mount points the keys are stored directly in the data directory if ($this->util->isSystemWideMountPoint($filename, $owner)) { @@ -332,7 +327,7 @@ public function copyKeys($source, $target) { * @return string */ protected function getPathToKeys($path) { - list($owner, $relativePath) = $this->util->getUidAndFilename($path); + [$owner, $relativePath] = $this->util->getUidAndFilename($path); $systemWideMountPoint = $this->util->isSystemWideMountPoint($relativePath, $owner); if ($systemWideMountPoint) { diff --git a/lib/private/Encryption/Update.php b/lib/private/Encryption/Update.php index b3a2fbb9482d..01ff66618fa6 100644 --- a/lib/private/Encryption/Update.php +++ b/lib/private/Encryption/Update.php @@ -83,7 +83,7 @@ public function postShared($params) { if ($this->encryptionManager->isEnabled()) { if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { $path = Filesystem::getPath($params['fileSource']); - list($owner, $ownerPath) = $this->getOwnerPath($path); + [$owner, $ownerPath] = $this->getOwnerPath($path); $absPath = '/' . $owner . '/files/' . $ownerPath; $this->update($absPath); } @@ -99,7 +99,7 @@ public function postUnshared($params) { if ($this->encryptionManager->isEnabled()) { if ($params['itemType'] === 'file' || $params['itemType'] === 'folder') { $path = Filesystem::getPath($params['fileSource']); - list($owner, $ownerPath) = $this->getOwnerPath($path); + [$owner, $ownerPath] = $this->getOwnerPath($path); $absPath = '/' . $owner . '/files/' . $ownerPath; $this->update($absPath); } @@ -132,7 +132,7 @@ public function postRename($params) { $this->encryptionManager->isEnabled() && \dirname($source) !== \dirname($target) ) { - list($owner, $ownerPath) = $this->getOwnerPath($target); + [$owner, $ownerPath] = $this->getOwnerPath($target); $absPath = '/' . $owner . '/files/' . $ownerPath; $this->update($absPath); } diff --git a/lib/private/Encryption/Util.php b/lib/private/Encryption/Util.php index 814324243285..35d3d89213a5 100644 --- a/lib/private/Encryption/Util.php +++ b/lib/private/Encryption/Util.php @@ -227,7 +227,7 @@ public function getBlockSize() { * @throws \BadMethodCallException */ public function getUidAndFilename($path) { - list($storage, $internalPath) = $this->rootView->resolvePath($path); + [$storage, $internalPath] = $this->rootView->resolvePath($path); $absMountPoint = $this->rootView->getMountPoint($path); $parts = \explode('/', $absMountPoint); @@ -240,10 +240,10 @@ public function getUidAndFilename($path) { $originalPath = "/{$internalPath}"; } - if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { + if ($storage->instanceOfStorage('\\' . \OCA\Files_Sharing\ISharedStorage::class)) { // TODO: Improve sharedStorage detection. // Note that ISharedStorage doesn't enforce any method - if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) { + if ($storage->instanceOfStorage('\\' . \OCA\Files_Sharing\SharedStorage::class)) { // local sharing $share = $storage->getShare(); $node = $share->getNode(); @@ -283,9 +283,7 @@ public function getUserWithAccessToMountPoint($users, $groups) { foreach ($groups as $group) { $g = \OC::$server->getGroupManager()->get($group); if ($g !== null) { - $users = \array_values(\array_map(function (IUser $u) { - return $u->getUID(); - }, $g->getUsers())); + $users = \array_values(\array_map(fn (IUser $u) => $u->getUID(), $g->getUsers())); $result = \array_merge($result, $users); } } diff --git a/lib/private/Files/Cache/Cache.php b/lib/private/Files/Cache/Cache.php index 5dc8a1a9bd01..7ba5e68b3eb4 100644 --- a/lib/private/Files/Cache/Cache.php +++ b/lib/private/Files/Cache/Cache.php @@ -256,9 +256,7 @@ private function getChildrenWithFilter($fileId, $mimetypeFilter = null) { $file['storage_mtime'] = (int)$file['storage_mtime']; $file['size'] = 0 + $file['size']; } - return \array_map(function (array $data) { - return new CacheEntry($data); - }, $files); + return \array_map(fn (array $data) => new CacheEntry($data), $files); } else { return []; } @@ -312,13 +310,11 @@ public function insert($file, array $data) { $data['parent'] = $this->getParentId($file); $data['name'] = \OC_Util::basename($file); - list($queryParts, $params) = $this->buildParts($data); + [$queryParts, $params] = $this->buildParts($data); $queryParts[] = '`storage`'; $params[] = $this->getNumericStorageId(); - $queryParts = \array_map(function ($item) { - return \trim($item, "`"); - }, $queryParts); + $queryParts = \array_map(fn ($item) => \trim($item, "`"), $queryParts); $values = \array_combine($queryParts, $params); // Update or insert this to the filecache \OC::$server->getDatabaseConnection()->upsert( @@ -362,7 +358,7 @@ public function update($id, array $data) { } } - list($queryParts, $params) = $this->buildParts($data); + [$queryParts, $params] = $this->buildParts($data); // don't update if the data we try to set is the same as the one in the record // some databases (Postgres) don't like superfluous updates @@ -382,12 +378,10 @@ public function update($id, array $data) { $whereClause = \implode(' OR ', $whereParts); // remove null values from the $params - $params = \array_values(\array_filter($params, function ($v) { - return $v !== null; - })); + $params = \array_values(\array_filter($params, fn ($v) => $v !== null)); // duplicate $params because we need the parts twice in the SQL statement // once for the SET part, once in the WHERE clause - $params = \array_merge($params, $params); + $params = [...$params, ...$params]; $params[] = $id; $sql = "UPDATE `*PREFIX*filecache` SET $setClause WHERE ($whereClause) AND `fileid` = ?"; @@ -600,8 +594,8 @@ public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) { $sourceId = $sourceData['fileid']; $newParentId = $this->getParentId($targetPath); - list($sourceStorageId, $sourcePath) = $sourceCache->getMoveInfo($sourcePath); - list($targetStorageId, $targetPath) = $this->getMoveInfo($targetPath); + [$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath); + [$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath); if ($sourceStorageId === null || $sourceStorageId === false) { throw new \Exception('Invalid source storage id: ' . $sourceStorageId); @@ -762,9 +756,7 @@ public function search($pattern) { $row['mimepart'] = $this->mimetypeLoader->getMimetypeById($row['mimepart']); $files[] = $row; } - return \array_map(function (array $data) { - return new CacheEntry($data); - }, $files); + return \array_map(fn (array $data) => new CacheEntry($data), $files); } /** @@ -790,9 +782,7 @@ public function searchByMime($mimetype) { $row['mimepart'] = $this->mimetypeLoader->getMimetypeById($row['mimepart']); $files[] = $row; } - return \array_map(function (array $data) { - return new CacheEntry($data); - }, $files); + return \array_map(fn (array $data) => new CacheEntry($data), $files); } /** @@ -837,9 +827,7 @@ public function searchByTag($tag, $userId) { while ($row = $result->fetch()) { $files[] = $row; } - return \array_map(function (array $data) { - return new CacheEntry($data); - }, $files); + return \array_map(fn (array $data) => new CacheEntry($data), $files); } /** @@ -886,7 +874,7 @@ public function calculateFolderSize($path, $entry = null) { $result = $this->connection->executeQuery($sql, [$id, $this->getNumericStorageId()]); if ($row = $result->fetch()) { $result->closeCursor(); - list($sum, $min) = \array_values($row); + [$sum, $min] = \array_values($row); if ($min === null && $entry['size'] < 0) { // could happen if the folder hasn't been scanned. // we don't have any data, so return the SIZE_NEEDS_SCAN diff --git a/lib/private/Files/Cache/HomeCache.php b/lib/private/Files/Cache/HomeCache.php index 19341b0ce2b6..cadea24b91b3 100644 --- a/lib/private/Files/Cache/HomeCache.php +++ b/lib/private/Files/Cache/HomeCache.php @@ -57,7 +57,7 @@ public function calculateFolderSize($path, $entry = null) { $result = \OC_DB::executeAudited($sql, [$id, $this->getNumericStorageId()]); if ($row = $result->fetchRow()) { $result->closeCursor(); - list($sum) = \array_values($row); + [$sum] = \array_values($row); $totalSize = 0 + $sum; $entry['size'] += 0; if ($entry['size'] !== $totalSize) { diff --git a/lib/private/Files/Cache/HomePropagator.php b/lib/private/Files/Cache/HomePropagator.php index f5f12dc65401..bf66fd100708 100644 --- a/lib/private/Files/Cache/HomePropagator.php +++ b/lib/private/Files/Cache/HomePropagator.php @@ -40,7 +40,7 @@ public function __construct(\OC\Files\Storage\Storage $storage, IDBConnection $c * @param int $sizeDifference number of bytes the file has grown */ public function propagateChange($internalPath, $time, $sizeDifference = 0) { - list($baseFolder) = \explode('/', $internalPath, 2); + [$baseFolder] = \explode('/', $internalPath, 2); if (\in_array($baseFolder, $this->ignoredBaseFolders)) { return []; } else { diff --git a/lib/private/Files/Cache/Propagator.php b/lib/private/Files/Cache/Propagator.php index bf2013771182..4ff74de23fc4 100644 --- a/lib/private/Files/Cache/Propagator.php +++ b/lib/private/Files/Cache/Propagator.php @@ -29,7 +29,7 @@ * Propagate etags and mtimes within the storage */ class Propagator implements IPropagator { - private $inBatch = false; + private bool $inBatch = false; private $batch = []; @@ -38,10 +38,7 @@ class Propagator implements IPropagator { */ protected $storage; - /** - * @var IDBConnection - */ - private $connection; + private \OCP\IDBConnection $connection; /** * @param \OC\Files\Storage\Storage $storage @@ -77,9 +74,7 @@ public function propagateChange($internalPath, $time, $sizeDifference = 0) { $etag = \uniqid(); // since we give all folders the same etag we don't ask the storage for the etag $builder = $this->connection->getQueryBuilder(); - $hashParams = \array_map(function ($hash) use ($builder) { - return $builder->expr()->literal($hash); - }, $parentHashes); + $hashParams = \array_map(fn ($hash) => $builder->expr()->literal($hash), $parentHashes); $builder->update('filecache') ->set('mtime', $builder->createFunction('GREATEST(`mtime`, ' . $builder->createNamedParameter($time, IQueryBuilder::PARAM_INT) . ')')) diff --git a/lib/private/Files/Cache/Scanner.php b/lib/private/Files/Cache/Scanner.php index e58fd6fd4e30..ea22b246c251 100644 --- a/lib/private/Files/Cache/Scanner.php +++ b/lib/private/Files/Cache/Scanner.php @@ -151,8 +151,8 @@ public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = if ($data) { // pre-emit only if it was a file. By that we avoid counting/treating folders as files if ($data['mimetype'] !== 'httpd/unix-directory') { - $this->emit('\OC\Files\Cache\Scanner', 'scanFile', [$file, $this->storageId]); - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', ['path' => $file, 'storage' => $this->storageId]); + $this->emit('\\' . \OC\Files\Cache\Scanner::class, 'scanFile', [$file, $this->storageId]); + \OC_Hook::emit('\\' . \OC\Files\Cache\Scanner::class, 'scan_file', ['path' => $file, 'storage' => $this->storageId]); } $parent = \dirname($file); @@ -229,8 +229,8 @@ public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = // post-emit only if it was a file. By that we avoid counting/treating folders as files if ($data['mimetype'] !== 'httpd/unix-directory') { - $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]); - \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]); + $this->emit('\\' . \OC\Files\Cache\Scanner::class, 'postScanFile', [$file, $this->storageId]); + \OC_Hook::emit('\\' . \OC\Files\Cache\Scanner::class, 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]); } } else { $this->removeFromCache($file); @@ -255,7 +255,7 @@ public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = protected function removeFromCache($path) { \OC_Hook::emit('Scanner', 'removeFromCache', ['file' => $path]); - $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', [$path]); + $this->emit('\\' . \OC\Files\Cache\Scanner::class, 'removeFromCache', [$path]); if ($this->cacheActive) { $this->cache->remove($path); } @@ -271,7 +271,7 @@ protected function removeFromCache($path) { */ protected function addToCache($path, $data, $fileId = -1) { \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]); - $this->emit('\OC\Files\Cache\Scanner', 'addToCache', [$path, $this->storageId, $data]); + $this->emit('\\' . \OC\Files\Cache\Scanner::class, 'addToCache', [$path, $this->storageId, $data]); if ($this->cacheActive) { if ($fileId !== -1) { $this->cache->update($fileId, $data); @@ -293,7 +293,7 @@ protected function addToCache($path, $data, $fileId = -1) { */ protected function updateCache($path, $data, $fileId = -1) { \OC_Hook::emit('Scanner', 'updateCache', ['file' => $path, 'data' => $data]); - $this->emit('\OC\Files\Cache\Scanner', 'updateCache', [$path, $this->storageId, $data]); + $this->emit('\\' . \OC\Files\Cache\Scanner::class, 'updateCache', [$path, $this->storageId, $data]); if ($this->cacheActive) { if ($fileId !== -1) { $this->cache->update($fileId, $data); @@ -388,7 +388,7 @@ protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse if ($reuse === -1) { $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG; } - $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', [$path, $this->storageId]); + $this->emit('\\' . \OC\Files\Cache\Scanner::class, 'scanFolder', [$path, $this->storageId]); $size = 0; if ($folderId !== null) { $folderId = $this->cache->getId($path); @@ -413,7 +413,7 @@ protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse if ($this->cacheActive) { $this->cache->update($folderId, ['size' => $size]); } - $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', [$path, $this->storageId]); + $this->emit('\\' . \OC\Files\Cache\Scanner::class, 'postScanFolder', [$path, $this->storageId]); return $size; } @@ -431,7 +431,7 @@ private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$s foreach ($newChildren as $file) { $child = $path ? $path . '/' . $file : $file; try { - $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null; + $existingData = $existingChildren[$file] ?? null; $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock); if ($data) { if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) { @@ -519,14 +519,10 @@ private function runBackgroundScanJob(callable $callback, $path) { if ($this->cacheActive && $this->cache instanceof Cache) { $this->cache->correctFolderSize($path); } - } catch (\OCP\Files\StorageInvalidException $e) { - // skip unavailable storages - } catch (\OCP\Files\StorageNotAvailableException $e) { + } catch (\OCP\Files\StorageInvalidException|\OCP\Files\StorageNotAvailableException|\OCP\Lock\LockedException $e) { // skip unavailable storages } catch (\OCP\Files\ForbiddenException $e) { // skip forbidden storages - } catch (\OCP\Lock\LockedException $e) { - // skip unavailable storages } } diff --git a/lib/private/Files/Cache/Storage.php b/lib/private/Files/Cache/Storage.php index de0997d71d1a..971c2402b790 100644 --- a/lib/private/Files/Cache/Storage.php +++ b/lib/private/Files/Cache/Storage.php @@ -42,7 +42,7 @@ */ class Storage { private $storageId; - private $numericId; + private ?int $numericId = null; /** @var CappedMemoryCache */ protected static $localCache = null; @@ -50,7 +50,7 @@ class Storage { /** @var ICache */ private static $distributedCache = null; - private static $distributedCacheTTL = 300; // 5 Min + private static int $distributedCacheTTL = 300; // 5 Min /** * @param \OC\Files\Storage\Storage|string $storage diff --git a/lib/private/Files/Cache/Wrapper/ReadOnlyCachePermissionsMask.php b/lib/private/Files/Cache/Wrapper/ReadOnlyCachePermissionsMask.php index 7af2ecfafbdd..c552e9aa1846 100644 --- a/lib/private/Files/Cache/Wrapper/ReadOnlyCachePermissionsMask.php +++ b/lib/private/Files/Cache/Wrapper/ReadOnlyCachePermissionsMask.php @@ -38,10 +38,9 @@ class ReadOnlyCachePermissionsMask extends CacheWrapper { protected $mask; /** - * System internal paths which should not be protected - * @var array - */ - private $whitelist = [ + * System internal paths which should not be protected + */ + private array $whitelist = [ 'uploads', 'cache', 'files_zsync' @@ -90,6 +89,6 @@ private function isHomeStorage($storageId) { } private function startsWith($haystack, $needle) { - return (\strpos($haystack, $needle) === 0); + return (\strpos($haystack, (string) $needle) === 0); } } diff --git a/lib/private/Files/Config/LazyStorageMountInfo.php b/lib/private/Files/Config/LazyStorageMountInfo.php index 8019cb942195..27cc0eeed48e 100644 --- a/lib/private/Files/Config/LazyStorageMountInfo.php +++ b/lib/private/Files/Config/LazyStorageMountInfo.php @@ -26,8 +26,7 @@ use OCP\IUser; class LazyStorageMountInfo extends CachedMountInfo { - /** @var IMountPoint */ - private $mount; + private \OCP\Files\Mount\IMountPoint $mount; /** * CachedMountInfo constructor. diff --git a/lib/private/Files/Config/MountProviderCollection.php b/lib/private/Files/Config/MountProviderCollection.php index cfd7d3294c24..89c31f67d55e 100644 --- a/lib/private/Files/Config/MountProviderCollection.php +++ b/lib/private/Files/Config/MountProviderCollection.php @@ -44,22 +44,16 @@ class MountProviderCollection implements IMountProviderCollection, Emitter { /** * @var \OCP\Files\Config\IHomeMountProvider[] */ - private $homeProviders = []; + private array $homeProviders = []; /** * @var \OCP\Files\Config\IMountProvider[] */ - private $providers = []; + private array $providers = []; - /** - * @var \OCP\Files\Storage\IStorageFactory - */ - private $loader; + private \OCP\Files\Storage\IStorageFactory $loader; - /** - * @var \OCP\Files\Config\IUserMountCache - */ - private $mountCache; + private \OCP\Files\Config\IUserMountCache $mountCache; /** * @param \OCP\Files\Storage\IStorageFactory $loader @@ -78,12 +72,8 @@ public function __construct(IStorageFactory $loader, IUserMountCache $mountCache */ public function getMountsForUser(IUser $user) { $loader = $this->loader; - $mounts = \array_map(function (IMountProvider $provider) use ($user, $loader) { - return $provider->getMountsForUser($user, $loader); - }, $this->providers); - $mounts = \array_filter($mounts, function ($result) { - return \is_array($result); - }); + $mounts = \array_map(fn (IMountProvider $provider) => $provider->getMountsForUser($user, $loader), $this->providers); + $mounts = \array_filter($mounts, fn ($result) => \is_array($result)); $mergedMounts = []; $takenMountpoints = []; diff --git a/lib/private/Files/Config/UserMountCache.php b/lib/private/Files/Config/UserMountCache.php index 4ebc5852d436..86e4cd00098f 100644 --- a/lib/private/Files/Config/UserMountCache.php +++ b/lib/private/Files/Config/UserMountCache.php @@ -39,15 +39,9 @@ * Cache mounts points per user in the cache so we can easily look them up */ class UserMountCache implements IUserMountCache { - /** - * @var IDBConnection - */ - private $connection; + private \OCP\IDBConnection $connection; - /** - * @var IUserManager - */ - private $userManager; + private \OCP\IUserManager $userManager; /** * Cached mount info. @@ -57,10 +51,7 @@ class UserMountCache implements IUserMountCache { **/ private $mountsForUsers; - /** - * @var ILogger - */ - private $logger; + private \OCP\ILogger $logger; /** * @var CappedMemoryCache @@ -95,10 +86,9 @@ public function registerMounts(IUser $user, array $mounts) { $newMounts = \array_values(\array_filter($newMounts)); $cachedMounts = $this->getMountsForUser($user); - $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) { - // since we are only looking for mounts for a specific user comparing on root id is enough - return $mount1->getRootId() - $mount2->getRootId(); - }; + $mountDiff = fn (ICachedMountInfo $mount1, ICachedMountInfo $mount2) => + // since we are only looking for mounts for a specific user comparing on root id is enough + $mount1->getRootId() - $mount2->getRootId(); /** @var ICachedMountInfo[] $addedMounts */ $addedMounts = \array_udiff($newMounts, $cachedMounts, $mountDiff); @@ -291,7 +281,7 @@ private function getCacheInfoFromFileId($fileId) { */ public function getMountsForFileId($fileId) { try { - list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId); + [$storageId, $internalPath] = $this->getCacheInfoFromFileId($fileId); } catch (NotFoundException $e) { return []; } @@ -303,7 +293,7 @@ public function getMountsForFileId($fileId) { return true; } try { - list(, $internalMountPath) = $this->getCacheInfoFromFileId($mount->getRootId()); + [, $internalMountPath] = $this->getCacheInfoFromFileId($mount->getRootId()); } catch (NotFoundException $e) { return false; } diff --git a/lib/private/Files/Config/UserMountCacheListener.php b/lib/private/Files/Config/UserMountCacheListener.php index 295ba65cb3f7..f67ee3c3469e 100644 --- a/lib/private/Files/Config/UserMountCacheListener.php +++ b/lib/private/Files/Config/UserMountCacheListener.php @@ -28,10 +28,7 @@ * Listen to hooks and update the mount cache as needed */ class UserMountCacheListener { - /** - * @var IUserMountCache - */ - private $userMountCache; + private \OCP\Files\Config\IUserMountCache $userMountCache; /** * UserMountCacheListener constructor. diff --git a/lib/private/Files/External/Auth/CoreAuthMechanismProvider.php b/lib/private/Files/External/Auth/CoreAuthMechanismProvider.php index 6e0dd1809418..3af1cd955c88 100644 --- a/lib/private/Files/External/Auth/CoreAuthMechanismProvider.php +++ b/lib/private/Files/External/Auth/CoreAuthMechanismProvider.php @@ -28,11 +28,10 @@ * @package OC\Files\External */ class CoreAuthMechanismProvider implements IAuthMechanismProvider { - /** @var ServerContainer */ - private $server; + private \OC\ServerContainer $server; /** @var array class names */ - private $classNames; + private array $classNames; /** * Constructs a new provider @@ -48,8 +47,6 @@ public function __construct(ServerContainer $server, array $classNames = []) { * @{inheritdoc} */ public function getAuthMechanisms() { - return \array_map(function ($className) { - return $this->server->query($className); - }, $this->classNames); + return \array_map(fn ($className) => $this->server->query($className), $this->classNames); } } diff --git a/lib/private/Files/External/Auth/Password/SessionCredentials.php b/lib/private/Files/External/Auth/Password/SessionCredentials.php index 51d4615c0f24..7cd116fbcb34 100644 --- a/lib/private/Files/External/Auth/Password/SessionCredentials.php +++ b/lib/private/Files/External/Auth/Password/SessionCredentials.php @@ -64,7 +64,7 @@ public function __construct(ISession $session, ICrypto $crypto) { * @param array $params */ public function authenticate(array $params) { - $this->session->set('password::sessioncredentials/credentials', $this->crypto->encrypt(\json_encode($params))); + $this->session->set('password::sessioncredentials/credentials', $this->crypto->encrypt(\json_encode($params, JSON_THROW_ON_ERROR))); } public function manipulateStorageConfig(IStorageConfig &$storage, IUser $user = null) { @@ -73,7 +73,7 @@ public function manipulateStorageConfig(IStorageConfig &$storage, IUser $user = throw new InsufficientDataForMeaningfulAnswerException('No session credentials saved'); } - $credentials = \json_decode($this->crypto->decrypt($encrypted), true); + $credentials = \json_decode($this->crypto->decrypt($encrypted), true, 512, JSON_THROW_ON_ERROR); if ($user !== null) { $storage->setBackendOption('user', $user->getUserName()); } else { diff --git a/lib/private/Files/External/ConfigAdapter.php b/lib/private/Files/External/ConfigAdapter.php index 448b0e018adf..3cb0d7da27b1 100644 --- a/lib/private/Files/External/ConfigAdapter.php +++ b/lib/private/Files/External/ConfigAdapter.php @@ -40,17 +40,13 @@ * Make the old files_external config work with the new public mount config api */ class ConfigAdapter implements IMountProvider { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var IUserStoragesService */ - private $userStoragesService; + private \OCP\Files\External\Service\IUserStoragesService $userStoragesService; - /** @var IUserGlobalStoragesService */ - private $userGlobalStoragesService; + private \OCP\Files\External\Service\IUserGlobalStoragesService $userGlobalStoragesService; - /** @var ISession */ - private $session; + private \OCP\ISession $session; /** * @param IUserStoragesService $userStoragesService @@ -85,7 +81,7 @@ private function prepareStorageConfig(IStorageConfig &$storage, IUser $user) { $objectStore = $storage->getBackendOption('objectstore'); if ($objectStore) { $objectClass = $objectStore['class']; - if (!\is_subclass_of($objectClass, '\OCP\Files\ObjectStore\IObjectStore')) { + if (!\is_subclass_of($objectClass, '\\' . \OCP\Files\ObjectStore\IObjectStore::class)) { throw new \InvalidArgumentException('Invalid object store'); } $storage->setBackendOption('objectstore', new $objectClass($objectStore)); diff --git a/lib/private/Files/External/LegacyUtil.php b/lib/private/Files/External/LegacyUtil.php index c34b5b8d859a..0b831c9f05d1 100644 --- a/lib/private/Files/External/LegacyUtil.php +++ b/lib/private/Files/External/LegacyUtil.php @@ -203,7 +203,7 @@ public static function getBackendStatus($class, $options, $isPersonal, $testOnly $storage = new $class($options); try { - $result = $storage->test($isPersonal, $testOnly); + $result = $storage->test(); $storage->setAvailability($result); if ($result) { return StorageNotAvailableException::STATUS_SUCCESS; @@ -235,7 +235,7 @@ public function readData($user = null) { $jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json'); } if (\is_file($jsonFile)) { - $mountPoints = \json_decode(\file_get_contents($jsonFile), true); + $mountPoints = \json_decode(\file_get_contents($jsonFile), true, 512, JSON_THROW_ON_ERROR); if (\is_array($mountPoints)) { return $mountPoints; } @@ -328,9 +328,10 @@ public static function makeConfigHash($config) { 'a' => $config['authMechanism'], 'm' => $config['mountpoint'], 'o' => $config['options'], - 'p' => isset($config['priority']) ? $config['priority'] : -1, - 'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [], - ] + 'p' => $config['priority'] ?? -1, + 'mo' => $config['mountOptions'] ?? [], + ], + JSON_THROW_ON_ERROR ); return \hash('md5', $data); } diff --git a/lib/private/Files/External/Service/DBConfigService.php b/lib/private/Files/External/Service/DBConfigService.php index 360540631c67..840e42c02ece 100644 --- a/lib/private/Files/External/Service/DBConfigService.php +++ b/lib/private/Files/External/Service/DBConfigService.php @@ -40,15 +40,9 @@ class DBConfigService { public const APPLICABLE_TYPE_GROUP = 2; public const APPLICABLE_TYPE_USER = 3; - /** - * @var IDBConnection - */ - private $connection; + private \OCP\IDBConnection $connection; - /** - * @var ICrypto - */ - private $crypto; + private \OCP\Security\ICrypto $crypto; /** * DBConfigService constructor. @@ -156,9 +150,7 @@ public function getAdminMountsFor($type, $value) { */ public function getAdminMountsForMultiple($type, array $values) { $builder = $this->connection->getQueryBuilder(); - $params = \array_map(function ($value) use ($builder) { - return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR); - }, $values); + $params = \array_map(fn ($value) => $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR), $values); $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type']) ->from('external_mounts', 'm') @@ -294,12 +286,12 @@ public function setOption($mountId, $key, $value) { $count = $this->connection->insertIfNotExist('*PREFIX*external_options', [ 'mount_id' => $mountId, 'key' => $key, - 'value' => \json_encode($value) + 'value' => \json_encode($value, JSON_THROW_ON_ERROR) ], ['mount_id', 'key']); if ($count === 0) { $builder = $this->connection->getQueryBuilder(); $query = $builder->update('external_options') - ->set('value', $builder->createNamedParameter(\json_encode($value), IQueryBuilder::PARAM_STR)) + ->set('value', $builder->createNamedParameter(\json_encode($value, JSON_THROW_ON_ERROR), IQueryBuilder::PARAM_STR)) ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT))) ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR))); $query->execute(); @@ -341,9 +333,7 @@ private function getMountsFromQuery(IQueryBuilder $query) { } $uniqueMounts = \array_values($uniqueMounts); - $mountIds = \array_map(function ($mount) { - return $mount['mount_id']; - }, $uniqueMounts); + $mountIds = \array_map(fn ($mount) => $mount['mount_id'], $uniqueMounts); $mountIds = \array_values(\array_unique($mountIds)); $applicable = $this->getApplicableForMounts($mountIds); @@ -374,9 +364,7 @@ private function selectForMounts($table, array $fields, array $mountIds) { } $builder = $this->connection->getQueryBuilder(); $fields[] = 'mount_id'; - $placeHolders = \array_map(function ($id) use ($builder) { - return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT); - }, $mountIds); + $placeHolders = \array_map(fn ($id) => $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT), $mountIds); $query = $builder->select($fields) ->from($table) ->where($builder->expr()->in('mount_id', $placeHolders)); @@ -419,11 +407,7 @@ public function getConfigForMounts($mountIds) { public function getOptionsForMounts($mountIds) { $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds); $optionsMap = \array_map([$this, 'createKeyValueMap'], $mountOptions); - return \array_map(function (array $options) { - return \array_map(function ($option) { - return \json_decode($option); - }, $options); - }, $optionsMap); + return \array_map(fn (array $options) => \array_map(fn ($option) => \json_decode($option, null, 512, JSON_THROW_ON_ERROR), $options), $optionsMap); } /** @@ -431,12 +415,8 @@ public function getOptionsForMounts($mountIds) { * @return array ['key1' => $value1, ...] */ private function createKeyValueMap(array $keyValuePairs) { - $keys = \array_map(function ($pair) { - return $pair['key']; - }, $keyValuePairs); - $values = \array_map(function ($pair) { - return $pair['value']; - }, $keyValuePairs); + $keys = \array_map(fn ($pair) => $pair['key'], $keyValuePairs); + $values = \array_map(fn ($pair) => $pair['value'], $keyValuePairs); return \array_combine($keys, $values); } diff --git a/lib/private/Files/External/Service/GlobalStoragesService.php b/lib/private/Files/External/Service/GlobalStoragesService.php index 23f874349bbf..d8c1c45750e6 100644 --- a/lib/private/Files/External/Service/GlobalStoragesService.php +++ b/lib/private/Files/External/Service/GlobalStoragesService.php @@ -173,13 +173,9 @@ protected function isApplicable(IStorageConfig $config) { public function getStorageForAllUsers() { $mounts = $this->dbConfig->getAllMounts(); $configs = \array_map([$this, 'getStorageConfigFromDBMount'], $mounts); - $configs = \array_filter($configs, function ($config) { - return $config instanceof IStorageConfig; - }); + $configs = \array_filter($configs, fn ($config) => $config instanceof IStorageConfig); - $keys = \array_map(function (IStorageConfig $config) { - return $config->getId(); - }, $configs); + $keys = \array_map(fn (IStorageConfig $config) => $config->getId(), $configs); return \array_combine($keys, $configs); } diff --git a/lib/private/Files/External/Service/LegacyStoragesService.php b/lib/private/Files/External/Service/LegacyStoragesService.php index 954062812ece..af0008326f48 100644 --- a/lib/private/Files/External/Service/LegacyStoragesService.php +++ b/lib/private/Files/External/Service/LegacyStoragesService.php @@ -34,10 +34,7 @@ class LegacyStoragesService { */ protected $backendService; - /** - * @var LegacyUtil - */ - private $legacyUtil; + private \OC\Files\External\LegacyUtil $legacyUtil; /** * @param IStoragesBackendService $backendService diff --git a/lib/private/Files/External/Service/StoragesService.php b/lib/private/Files/External/Service/StoragesService.php index 60ff8105cd9c..c93d2c8dc22f 100644 --- a/lib/private/Files/External/Service/StoragesService.php +++ b/lib/private/Files/External/Service/StoragesService.php @@ -83,19 +83,11 @@ protected function readDBConfig() { } protected function getStorageConfigFromDBMount(array $mount) { - $applicableUsers = \array_filter($mount['applicable'], function ($applicable) { - return $applicable['type'] === DBConfigService::APPLICABLE_TYPE_USER; - }); - $applicableUsers = \array_map(function ($applicable) { - return $applicable['value']; - }, $applicableUsers); - - $applicableGroups = \array_filter($mount['applicable'], function ($applicable) { - return $applicable['type'] === DBConfigService::APPLICABLE_TYPE_GROUP; - }); - $applicableGroups = \array_map(function ($applicable) { - return $applicable['value']; - }, $applicableGroups); + $applicableUsers = \array_filter($mount['applicable'], fn ($applicable) => $applicable['type'] === DBConfigService::APPLICABLE_TYPE_USER); + $applicableUsers = \array_map(fn ($applicable) => $applicable['value'], $applicableUsers); + + $applicableGroups = \array_filter($mount['applicable'], fn ($applicable) => $applicable['type'] === DBConfigService::APPLICABLE_TYPE_GROUP); + $applicableGroups = \array_map(fn ($applicable) => $applicable['value'], $applicableGroups); try { $config = $this->createStorage( @@ -145,13 +137,9 @@ protected function getStorageConfigFromDBMount(array $mount) { protected function readConfig() { $mounts = $this->readDBConfig(); $configs = \array_map([$this, 'getStorageConfigFromDBMount'], $mounts); - $configs = \array_filter($configs, function ($config) { - return $config instanceof IStorageConfig; - }); + $configs = \array_filter($configs, fn ($config) => $config instanceof IStorageConfig); - $keys = \array_map(function (IStorageConfig $config) { - return $config->getId(); - }, $configs); + $keys = \array_map(fn (IStorageConfig $config) => $config->getId(), $configs); return \array_combine($keys, $configs); } diff --git a/lib/private/Files/External/StorageConfig.php b/lib/private/Files/External/StorageConfig.php index 936f5628ef0c..007c43f5e260 100644 --- a/lib/private/Files/External/StorageConfig.php +++ b/lib/private/Files/External/StorageConfig.php @@ -42,25 +42,19 @@ class StorageConfig implements IStorageConfig { private $id; /** - * Backend - * - * @var Backend - */ - private $backend; + * Backend + */ + private ?\OCP\Files\External\Backend\Backend $backend = null; /** - * Authentication mechanism - * - * @var AuthMechanism - */ - private $authMechanism; + * Authentication mechanism + */ + private ?\OCP\Files\External\Auth\AuthMechanism $authMechanism = null; /** - * Backend options - * - * @var array - */ - private $backendOptions = []; + * Backend options + */ + private array $backendOptions = []; /** * Mount point path, relative to the user's "files" folder @@ -91,25 +85,19 @@ class StorageConfig implements IStorageConfig { private $priority; /** - * List of users who have access to this storage - * - * @var array - */ - private $applicableUsers = []; + * List of users who have access to this storage + */ + private array $applicableUsers = []; /** - * List of groups that have access to this storage - * - * @var array - */ - private $applicableGroups = []; + * List of groups that have access to this storage + */ + private array $applicableGroups = []; /** - * Mount-specific options - * - * @var array - */ - private $mountOptions = []; + * Mount-specific options + */ + private array $mountOptions = []; /** * Whether it's a personal or admin mount @@ -232,10 +220,7 @@ public function setBackendOptions($backendOptions) { * @return mixed */ public function getBackendOption($key) { - if (isset($this->backendOptions[$key])) { - return $this->backendOptions[$key]; - } - return null; + return $this->backendOptions[$key] ?? null; } /** @@ -332,10 +317,7 @@ public function setMountOptions($mountOptions) { * @return mixed */ public function getMountOption($key) { - if (isset($this->mountOptions[$key])) { - return $this->mountOptions[$key]; - } - return null; + return $this->mountOptions[$key] ?? null; } /** diff --git a/lib/private/Files/External/StoragesBackendService.php b/lib/private/Files/External/StoragesBackendService.php index fc7a2664abb6..72b261a057d3 100644 --- a/lib/private/Files/External/StoragesBackendService.php +++ b/lib/private/Files/External/StoragesBackendService.php @@ -38,20 +38,19 @@ class StoragesBackendService implements IStoragesBackendService { /** @var IConfig */ protected $config; - /** @var bool */ - private $userMountingAllowed = true; + private bool $userMountingAllowed = true; /** @var string[] */ - private $userMountingBackends = []; + private array $userMountingBackends = []; /** @var Backend[] */ - private $backends = []; + private array $backends = []; /** @var IBackendProvider[] */ private $backendProviders = []; /** @var AuthMechanism[] */ - private $authMechanisms = []; + private array $authMechanisms = []; /** @var IAuthMechanismProvider[] */ private $authMechanismProviders = []; @@ -183,9 +182,7 @@ public function getBackends() { * @return Backend[] */ public function getAvailableBackends() { - return \array_filter($this->getBackends(), function ($backend) { - return !($backend->checkDependencies()); - }); + return \array_filter($this->getBackends(), fn ($backend) => !($backend->checkDependencies())); } /** @@ -194,10 +191,7 @@ public function getAvailableBackends() { */ public function getBackend($identifier) { $this->loadBackendProviders(); - if (isset($this->backends[$identifier])) { - return $this->backends[$identifier]; - } - return null; + return $this->backends[$identifier] ?? null; } /** @@ -222,9 +216,7 @@ public function getAuthMechanisms() { * @return AuthMechanism[] */ public function getAuthMechanismsByScheme(array $schemes) { - return \array_filter($this->getAuthMechanisms(), function ($authMech) use ($schemes) { - return \in_array($authMech->getScheme(), $schemes, true); - }); + return \array_filter($this->getAuthMechanisms(), fn ($authMech) => \in_array($authMech->getScheme(), $schemes, true)); } /** @@ -233,10 +225,7 @@ public function getAuthMechanismsByScheme(array $schemes) { */ public function getAuthMechanism($identifier) { $this->loadAuthMechanismProviders(); - if (isset($this->authMechanisms[$identifier])) { - return $this->authMechanisms[$identifier]; - } - return null; + return $this->authMechanisms[$identifier] ?? null; } /** diff --git a/lib/private/Files/FileInfo.php b/lib/private/Files/FileInfo.php index 1a3d927e566d..88ba840d8e1d 100644 --- a/lib/private/Files/FileInfo.php +++ b/lib/private/Files/FileInfo.php @@ -66,7 +66,7 @@ class FileInfo implements \OCP\Files\FileInfo, \ArrayAccess { /** * @var string[] */ - private $childEtags = []; + private array $childEtags = []; /** * @param string|boolean $path @@ -176,7 +176,7 @@ public function getEtag() { * @return int|float */ public function getSize() { - return isset($this->data['size']) ? $this->data['size'] : 0; + return $this->data['size'] ?? 0; } /** @@ -324,7 +324,7 @@ public function getOwner() { * @param string $entryPath full path of the child entry */ public function addSubEntry($data, $entryPath) { - $this->data['size'] += isset($data['size']) ? $data['size'] : 0; + $this->data['size'] += $data['size'] ?? 0; if (isset($data['mtime'])) { $this->data['mtime'] = \max($this->data['mtime'], $data['mtime']); } @@ -332,7 +332,7 @@ public function addSubEntry($data, $entryPath) { // prefix the etag with the relative path of the subentry to propagate etag on mount moves $relativeEntryPath = \substr($entryPath, \strlen($this->getPath())); // attach the permissions to propagate etag on permission changes of submounts - $permissions = isset($data['permissions']) ? $data['permissions'] : 0; + $permissions = $data['permissions'] ?? 0; $this->childEtags[] = $relativeEntryPath . '/' . $data['etag'] . $permissions; } } diff --git a/lib/private/Files/Filesystem.php b/lib/private/Files/Filesystem.php index 6ba1ce1f7fe4..0d589fdb5ec8 100644 --- a/lib/private/Files/Filesystem.php +++ b/lib/private/Files/Filesystem.php @@ -73,16 +73,13 @@ class Filesystem { private static $mounts; public static $loaded = false; - /** - * @var \OC\Files\View $defaultInstance - */ - private static $defaultInstance; + private static ?\OC\Files\View $defaultInstance = null; private static $usersSetup = []; private static $normalizedPathCache = null; - private static $listeningForProviders = false; + private static bool $listeningForProviders = false; /** * classname which used for hooks handling @@ -201,13 +198,9 @@ class Filesystem { public const signal_param_mount_type = 'mounttype'; public const signal_param_users = 'users'; - /** - * @var \OC\Files\Storage\StorageFactory $loader - */ - private static $loader; + private static ?\OC\Files\Storage\StorageFactory $loader = null; - /** @var bool */ - private static $logWarningWhenAddingStorageWrapper = true; + private static bool $logWarningWhenAddingStorageWrapper = true; /** * @param bool $shouldLog @@ -407,7 +400,7 @@ public static function initMountPoints($user = '', $fullInit = true) { if ($userObject === null) { $msg = "Backends provided no user object for $user"; - \OC::$server->getLogger()->error($msg, ['app' => __CLASS__]); + \OC::$server->getLogger()->error($msg, ['app' => self::class]); // reset flag, this will make it possible to rethrow the exception if called again unset(self::$usersSetup[$user]); throw new \OC\User\NoUserException($msg); @@ -416,7 +409,7 @@ public static function initMountPoints($user = '', $fullInit = true) { $realUid = $userObject->getUID(); // workaround in case of different casings if ($user !== $realUid) { - $stack = \json_encode(\debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50)); + $stack = \json_encode(\debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50), JSON_THROW_ON_ERROR); \OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::DEBUG); $user = $realUid; @@ -654,7 +647,7 @@ private static function regexValidityCheck($regexToBeChecked, $callerMessage = ' if (\preg_last_error() !== PREG_NO_ERROR) { \OC::$server->getLogger()->error( 'Regex error: ' . $regexToBeChecked . ' - ' . $callerMessage . ': ' . self::pregErrorText(), - ['app' => __CLASS__] + ['app' => self::class] ); return false; } @@ -752,7 +745,7 @@ public static function isForbiddenFileOrDir($FileOrDir, $excluded = []) { // further explode each array element with '\' and add to result array if found foreach ($ppx as $pp) { // only add an array element if strlen != 0 - $pathParts = \array_merge($pathParts, \array_filter(\explode('\\', $pp), 'strlen')); + $pathParts = [...$pathParts, ...\array_filter(\explode('\\', $pp), 'strlen')]; } // force that the last element (possibly the filename) is an entry in an array @@ -969,7 +962,7 @@ public static function normalizePath($path, $stripTrailingSlash = true, $isAbsol */ $path = (string)$path; - $cacheKey = \json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]); + $cacheKey = \json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode], JSON_THROW_ON_ERROR); if (isset(self::$normalizedPathCache[$cacheKey])) { return self::$normalizedPathCache[$cacheKey]; diff --git a/lib/private/Files/Meta/MetaFileIdNode.php b/lib/private/Files/Meta/MetaFileIdNode.php index 5aff55a986a9..1df8de4ddce5 100644 --- a/lib/private/Files/Meta/MetaFileIdNode.php +++ b/lib/private/Files/Meta/MetaFileIdNode.php @@ -35,12 +35,9 @@ * @package OC\Files\Meta */ class MetaFileIdNode extends AbstractFolder { - /** @var \OCP\Files\Node */ - private $node; - /** @var MetaRootNode */ - private $parentNode; - /** @var IRootFolder */ - private $root; + private \OCP\Files\Node $node; + private \OC\Files\Meta\MetaRootNode $parentNode; + private \OCP\Files\IRootFolder $root; /** * MetaFileIdNode constructor. diff --git a/lib/private/Files/Meta/MetaFileVersionNode.php b/lib/private/Files/Meta/MetaFileVersionNode.php index c2eeb8821295..0cd4d0f6c914 100644 --- a/lib/private/Files/Meta/MetaFileVersionNode.php +++ b/lib/private/Files/Meta/MetaFileVersionNode.php @@ -44,16 +44,13 @@ class MetaFileVersionNode extends AbstractFile implements IPreviewNode, IProvidesAdditionalHeaders, IProvidesVersionAuthor, IProvidesVersionTag { /** @var string */ private $versionId; - /** @var MetaVersionCollection */ - private $parent; + private \OC\Files\Meta\MetaVersionCollection $parent; /** @var IStorage|IVersionedStorage|SharedStorage */ - private $storage; + private \OCP\Files\Storage\IStorage $storage; /** @var string */ private $internalPath; - /** @var IRootFolder */ - private $root; - /** @var array */ - private $versionInfo; + private \OCP\Files\IRootFolder $root; + private array $versionInfo; /** * MetaFileVersionNode constructor. @@ -108,7 +105,7 @@ public function getVersionTag() : string { * @inheritdoc */ public function getSize() { - return isset($this->versionInfo['size']) ? $this->versionInfo['size'] : null; + return $this->versionInfo['size'] ?? null; } /** @@ -139,15 +136,15 @@ public function copy($targetPath) { } public function getMTime() { - return isset($this->versionInfo['timestamp']) ? $this->versionInfo['timestamp'] : null; + return $this->versionInfo['timestamp'] ?? null; } public function getMimetype() { - return isset($this->versionInfo['mimetype']) ? $this->versionInfo['mimetype'] : 'application/octet-stream'; + return $this->versionInfo['mimetype'] ?? 'application/octet-stream'; } public function getEtag() { - return isset($this->versionInfo['etag']) ? $this->versionInfo['etag'] : null; + return $this->versionInfo['etag'] ?? null; } public function fopen($mode) { diff --git a/lib/private/Files/Meta/MetaRootNode.php b/lib/private/Files/Meta/MetaRootNode.php index 3ad09814464b..e58a22c09ed6 100644 --- a/lib/private/Files/Meta/MetaRootNode.php +++ b/lib/private/Files/Meta/MetaRootNode.php @@ -34,14 +34,8 @@ * @package OC\Files\Meta */ class MetaRootNode extends AbstractFolder { - /** - * @var IRootFolder - */ - private $rootFolder; - /** - * @var IUserSession - */ - private $userSession; + private \OCP\Files\IRootFolder $rootFolder; + private \OCP\IUserSession $userSession; public function __construct(IRootFolder $rootFolder, IUserSession $userSession) { $this->rootFolder = $rootFolder; diff --git a/lib/private/Files/Meta/MetaVersionCollection.php b/lib/private/Files/Meta/MetaVersionCollection.php index c4d48f319ad0..cb48a1d1c3cc 100644 --- a/lib/private/Files/Meta/MetaVersionCollection.php +++ b/lib/private/Files/Meta/MetaVersionCollection.php @@ -37,10 +37,8 @@ * @package OC\Files\Meta */ class MetaVersionCollection extends AbstractFolder implements IProvidesVersionAuthor, IProvidesVersionTag { - /** @var IRootFolder */ - private $root; - /** @var \OCP\Files\Node */ - private $node; + private \OCP\Files\IRootFolder $root; + private \OCP\Files\Node $node; /** @var array */ private $versionInfo; diff --git a/lib/private/Files/Mount/CacheMountProvider.php b/lib/private/Files/Mount/CacheMountProvider.php index 83158a19c7b2..42e9749d76fc 100644 --- a/lib/private/Files/Mount/CacheMountProvider.php +++ b/lib/private/Files/Mount/CacheMountProvider.php @@ -30,10 +30,7 @@ * Mount provider for custom cache storages */ class CacheMountProvider implements IMountProvider { - /** - * @var IConfig - */ - private $config; + private \OCP\IConfig $config; /** * CacheMountProvider constructor. @@ -60,7 +57,7 @@ public function getMountsForUser(IUser $user, IStorageFactory $loader) { } return [ - new MountPoint('\OC\Files\Storage\Local', '/' . $user->getUID() . '/cache', ['datadir' => $cacheDir], $loader) + new MountPoint('\\' . \OC\Files\Storage\Local::class, '/' . $user->getUID() . '/cache', ['datadir' => $cacheDir], $loader) ]; } else { return []; diff --git a/lib/private/Files/Mount/LocalHomeMountProvider.php b/lib/private/Files/Mount/LocalHomeMountProvider.php index b56ff622e738..93ac5c5bebd4 100644 --- a/lib/private/Files/Mount/LocalHomeMountProvider.php +++ b/lib/private/Files/Mount/LocalHomeMountProvider.php @@ -38,6 +38,6 @@ class LocalHomeMountProvider implements IHomeMountProvider { */ public function getHomeMountForUser(IUser $user, IStorageFactory $loader) { $arguments = ['user' => $user]; - return new MountPoint('\OC\Files\Storage\Home', '/' . $user->getUID(), $arguments, $loader); + return new MountPoint('\\' . \OC\Files\Storage\Home::class, '/' . $user->getUID(), $arguments, $loader); } } diff --git a/lib/private/Files/Mount/Manager.php b/lib/private/Files/Mount/Manager.php index f485a5a2ef85..f58ba702a055 100644 --- a/lib/private/Files/Mount/Manager.php +++ b/lib/private/Files/Mount/Manager.php @@ -76,7 +76,7 @@ public function find($path) { $foundMountPoint = ''; $mountPoints = \array_keys($this->mounts); foreach ($mountPoints as $mountpoint) { - if (\strpos($path, $mountpoint) === 0 and \strlen($mountpoint) > \strlen($foundMountPoint)) { + if (\strpos($path, (string) $mountpoint) === 0 and \strlen($mountpoint) > \strlen($foundMountPoint)) { $foundMountPoint = $mountpoint; } } diff --git a/lib/private/Files/Mount/MountPoint.php b/lib/private/Files/Mount/MountPoint.php index 8dccd4d4439f..cb7f1c632f1b 100644 --- a/lib/private/Files/Mount/MountPoint.php +++ b/lib/private/Files/Mount/MountPoint.php @@ -62,12 +62,10 @@ class MountPoint implements IMountPoint { private $loader; /** - * Specified whether the storage is invalid after failing to - * instantiate it. - * - * @var bool - */ - private $invalidStorage = false; + * Specified whether the storage is invalid after failing to + * instantiate it. + */ + private bool $invalidStorage = false; /** * @param string|\OC\Files\Storage\Storage $storage @@ -234,7 +232,7 @@ public function wrapStorage($wrapper) { * @return mixed */ public function getOption($name, $default) { - return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default; + return $this->mountOptions[$name] ?? $default; } /** diff --git a/lib/private/Files/Mount/ObjectHomeMountProvider.php b/lib/private/Files/Mount/ObjectHomeMountProvider.php index 614fda70606e..15ef139f668b 100644 --- a/lib/private/Files/Mount/ObjectHomeMountProvider.php +++ b/lib/private/Files/Mount/ObjectHomeMountProvider.php @@ -31,10 +31,7 @@ * Mount provider for object store home storages */ class ObjectHomeMountProvider implements IHomeMountProvider { - /** - * @var IConfig - */ - private $config; + private \OCP\IConfig $config; /** * ObjectStoreHomeMountProvider constructor. @@ -62,7 +59,7 @@ public function getHomeMountForUser(IUser $user, IStorageFactory $loader) { return null; } - return new MountPoint('\OC\Files\ObjectStore\HomeObjectStoreStorage', '/' . $user->getUID(), $config['arguments'], $loader); + return new MountPoint('\\' . \OC\Files\ObjectStore\HomeObjectStoreStorage::class, '/' . $user->getUID(), $config['arguments'], $loader); } /** diff --git a/lib/private/Files/Mount/PreviewsMountProvider.php b/lib/private/Files/Mount/PreviewsMountProvider.php index 56acfb556c0b..a2d19fb0d283 100644 --- a/lib/private/Files/Mount/PreviewsMountProvider.php +++ b/lib/private/Files/Mount/PreviewsMountProvider.php @@ -30,10 +30,7 @@ * Mount provider for custom preview storages */ class PreviewsMountProvider implements IMountProvider { - /** - * @var IConfig - */ - private $config; + private \OCP\IConfig $config; /** * PreviewsMountProvider constructor. @@ -60,7 +57,7 @@ public function getMountsForUser(IUser $user, IStorageFactory $loader) { } return [ - new MountPoint('\OC\Files\Storage\Local', '/' . $user->getUID() . '/thumbnails', ['datadir' => $previewsDir], $loader) + new MountPoint('\\' . \OC\Files\Storage\Local::class, '/' . $user->getUID() . '/thumbnails', ['datadir' => $previewsDir], $loader) ]; } else { return []; diff --git a/lib/private/Files/Node/Folder.php b/lib/private/Files/Node/Folder.php index fe80a19bfc01..669309aefc3c 100644 --- a/lib/private/Files/Node/Folder.php +++ b/lib/private/Files/Node/Folder.php @@ -263,9 +263,7 @@ private function searchCommon($method, $args) { } } - return \array_map(function (FileInfo $file) { - return $this->createNode($file->getPath(), $file); - }, $files); + return \array_map(fn (FileInfo $file) => $this->createNode($file->getPath(), $file), $files); } /** diff --git a/lib/private/Files/Node/HookConnector.php b/lib/private/Files/Node/HookConnector.php index 19a617ab8997..3978e7fe986c 100644 --- a/lib/private/Files/Node/HookConnector.php +++ b/lib/private/Files/Node/HookConnector.php @@ -27,20 +27,14 @@ use OCP\Util; class HookConnector { - /** - * @var Root - */ - private $root; + private \OC\Files\Node\Root $root; - /** - * @var View - */ - private $view; + private \OC\Files\View $view; /** * @var FileInfo[] */ - private $deleteMetaCache = []; + private array $deleteMetaCache = []; /** * HookConnector constructor. diff --git a/lib/private/Files/Node/LazyRoot.php b/lib/private/Files/Node/LazyRoot.php index 02992f505cc5..48cc4c2b0901 100644 --- a/lib/private/Files/Node/LazyRoot.php +++ b/lib/private/Files/Node/LazyRoot.php @@ -33,8 +33,7 @@ * @package OC\Files\Node */ class LazyRoot implements IRootFolder { - /** @var \Closure */ - private $rootFolderClosure; + private \Closure $rootFolderClosure; /** @var IRootFolder */ private $rootFolder; diff --git a/lib/private/Files/Node/Node.php b/lib/private/Files/Node/Node.php index 66aa2fe90d7d..447902a1a85c 100644 --- a/lib/private/Files/Node/Node.php +++ b/lib/private/Files/Node/Node.php @@ -146,7 +146,7 @@ public function touch($mtime = null) { * @throws \OCP\Files\NotFoundException */ public function getStorage() { - list($storage, ) = $this->view->resolvePath($this->path); + [$storage, ] = $this->view->resolvePath($this->path); return $storage; } @@ -161,7 +161,7 @@ public function getPath() { * @return string */ public function getInternalPath() { - list(, $internalPath) = $this->view->resolvePath($this->path); + [, $internalPath] = $this->view->resolvePath($this->path); return $internalPath; } diff --git a/lib/private/Files/Node/Root.php b/lib/private/Files/Node/Root.php index b3e18c564f33..d3a88673b3ad 100644 --- a/lib/private/Files/Node/Root.php +++ b/lib/private/Files/Node/Root.php @@ -63,10 +63,7 @@ class Root extends Folder implements IRootFolder { */ private $mountManager; - /** - * @var \OC\Hooks\PublicEmitter - */ - private $emitter; + private \OC\Hooks\PublicEmitter $emitter; /** * @var \OC\User\User $user @@ -357,7 +354,7 @@ public function getUserFolder($userId) { if ($userObject === null) { $msg = "Backends provided no user object for $userId"; - \OC::$server->getLogger()->error($msg, ['app' => __CLASS__]); + \OC::$server->getLogger()->error($msg, ['app' => self::class]); throw new NoUserException($msg); } diff --git a/lib/private/Files/ObjectStore/Mapper.php b/lib/private/Files/ObjectStore/Mapper.php index 6b557c1c582b..63ea297a4fdb 100644 --- a/lib/private/Files/ObjectStore/Mapper.php +++ b/lib/private/Files/ObjectStore/Mapper.php @@ -30,8 +30,7 @@ * Map a user to a bucket. */ class Mapper { - /** @var IUser */ - private $user; + private \OCP\IUser $user; /** * Mapper constructor. diff --git a/lib/private/Files/ObjectStore/ObjectStoreStorage.php b/lib/private/Files/ObjectStore/ObjectStoreStorage.php index 4caed7400877..2508837ad57d 100644 --- a/lib/private/Files/ObjectStore/ObjectStoreStorage.php +++ b/lib/private/Files/ObjectStore/ObjectStoreStorage.php @@ -36,10 +36,7 @@ use OCP\IUser; class ObjectStoreStorage extends \OC\Files\Storage\Common { - /** - * @var array - */ - private static $tmpFiles = []; + private static array $tmpFiles = []; /** @var array */ private $movingBetweenBuckets = []; /** @@ -589,7 +586,7 @@ public function getVersions($internalPath) { throw new NotFoundException(); } $versions = $this->objectStore->getVersions($this->getURN($stat['fileid'])); - list($uid, $path) = $this->convertInternalPathToGlobalPath($internalPath); + [$uid, $path] = $this->convertInternalPathToGlobalPath($internalPath); return \array_map(function (array $version) use ($uid, $path) { $version['path'] = $path; $version['owner'] = $uid; @@ -606,7 +603,7 @@ public function getVersion($internalPath, $versionId) { throw new NotFoundException(); } $version = $this->objectStore->getVersion($this->getURN($stat['fileid']), $versionId); - list($uid, $path) = $this->convertInternalPathToGlobalPath($internalPath); + [$uid, $path] = $this->convertInternalPathToGlobalPath($internalPath); if (!empty($version)) { $version['path'] = $path; $version['owner'] = $uid; diff --git a/lib/private/Files/Storage/CacheableFlysystem.php b/lib/private/Files/Storage/CacheableFlysystem.php index 073de9691e12..be9e6cca1885 100644 --- a/lib/private/Files/Storage/CacheableFlysystem.php +++ b/lib/private/Files/Storage/CacheableFlysystem.php @@ -108,9 +108,7 @@ public function opendir($path) { } catch (FileNotFoundException $e) { return false; } - $names = \array_map(function ($object) { - return $object['basename']; - }, $content); + $names = \array_map(fn ($object) => $object['basename'], $content); return IteratorDirectory::wrap($names); } diff --git a/lib/private/Files/Storage/Common.php b/lib/private/Files/Storage/Common.php index 82248d7149cd..f2d57a748f67 100644 --- a/lib/private/Files/Storage/Common.php +++ b/lib/private/Files/Storage/Common.php @@ -232,7 +232,7 @@ public function copy($path1, $path2) { } else { $source = $this->fopen($path1, 'r'); $target = $this->fopen($path2, 'w'); - list(, $result) = \OC_Helper::streamCopy($source, $target); + [, $result] = \OC_Helper::streamCopy($source, $target); $this->removeCachedFile($path2); return $result; } @@ -482,7 +482,7 @@ public function isLocal() { public function instanceOfStorage($class) { if (\ltrim($class, '\\') === 'OC\Files\Storage\Shared') { // FIXME Temporary fix to keep existing checks working - $class = '\OCA\Files_Sharing\SharedStorage'; + $class = '\\' . \OCA\Files_Sharing\SharedStorage::class; } return \is_a($this, $class); } @@ -554,7 +554,7 @@ public function setMountOptions(array $options) { * @return mixed */ public function getMountOption($name, $default = null) { - return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default; + return $this->mountOptions[$name] ?? $default; } /** @@ -587,7 +587,7 @@ public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceIntern // are not the same as the original one.Once this is fixed we also // need to adjust the encryption wrapper. $target = $this->fopen($targetInternalPath, 'w'); - list(, $result) = \OC_Helper::streamCopy($source, $target); + [, $result] = \OC_Helper::streamCopy($source, $target); if ($result and $preserveMtime) { $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath)); } @@ -706,7 +706,7 @@ public function getVersions($internalPath) { if (!\OC_App::isEnabled('files_versions')) { return []; } - list($uid, $filename) = $this->convertInternalPathToGlobalPath($internalPath); + [$uid, $filename] = $this->convertInternalPathToGlobalPath($internalPath); return \array_map(function ($version) use ($internalPath) { $version['mimetype'] = $this->getMimeType($internalPath); @@ -721,7 +721,7 @@ public function getCurrentVersion($internalPath) { if (!\OC_App::isEnabled('files_versions')) { return []; } - list($uid, $filename) = $this->convertInternalPathToGlobalPath($internalPath); + [$uid, $filename] = $this->convertInternalPathToGlobalPath($internalPath); return \OCA\Files_Versions\Storage::getCurrentVersion($uid, $filename); } @@ -753,9 +753,7 @@ public function convertInternalPathToGlobalPath($internalPath) { public function getVersion($internalPath, $versionId) { $versions = $this->getVersions($internalPath); - $versions = \array_filter($versions, function ($version) use ($versionId) { - return $version['version'] === $versionId; - }); + $versions = \array_filter($versions, fn ($version) => $version['version'] === $versionId); return \array_shift($versions); } @@ -800,7 +798,7 @@ public function getLocks($internalPath, $returnChildLocks = false) { $locks = $locksManager->getLocks($storageId, $internalPath, $returnChildLocks); return \array_map(function (Lock $lock) { - list($uid, $fileName) = $this->convertInternalPathToGlobalPath($lock->getPath()); + [$uid, $fileName] = $this->convertInternalPathToGlobalPath($lock->getPath()); $lock->setDavUserId($uid); $lock->setAbsoluteDavPath($fileName); return $lock; diff --git a/lib/private/Files/Storage/CommonTest.php b/lib/private/Files/Storage/CommonTest.php index c9156f5687a5..b0813033d428 100644 --- a/lib/private/Files/Storage/CommonTest.php +++ b/lib/private/Files/Storage/CommonTest.php @@ -33,10 +33,9 @@ class CommonTest extends \OC\Files\Storage\Common { /** - * underlying local storage used for missing functions - * @var \OC\Files\Storage\Local - */ - private $storage; + * underlying local storage used for missing functions + */ + private \OC\Files\Storage\Local $storage; public function __construct($params) { $this->storage=new \OC\Files\Storage\Local($params); diff --git a/lib/private/Files/Storage/DAV.php b/lib/private/Files/Storage/DAV.php index 71dbea5ea04c..c0c37ebf1dcd 100644 --- a/lib/private/Files/Storage/DAV.php +++ b/lib/private/Files/Storage/DAV.php @@ -74,10 +74,8 @@ class DAV extends Common { protected $ready; /** @var Client */ private $client; - /** @var ArrayCache */ - private $statCache; - /** @var array */ - private static $tempFiles = []; + private \OC\Memcache\ArrayCache $statCache; + private static array $tempFiles = []; /** @var \OCP\Http\Client\IClientService */ private $httpClientService; @@ -115,7 +113,7 @@ public function __construct($params) { } else { $this->secure = false; } - $this->root = isset($params['root']) ? $params['root'] : '/'; + $this->root = $params['root'] ?? '/'; if (!$this->root || $this->root[0] != '/') { $this->root = '/' . $this->root; } diff --git a/lib/private/Files/Storage/Flysystem.php b/lib/private/Files/Storage/Flysystem.php index a6b581620e0f..f613ac46adee 100644 --- a/lib/private/Files/Storage/Flysystem.php +++ b/lib/private/Files/Storage/Flysystem.php @@ -162,9 +162,7 @@ public function opendir($path) { } catch (FileNotFoundException $e) { return false; } - $names = \array_map(function ($object) { - return $object['basename']; - }, $content); + $names = \array_map(fn ($object) => $object['basename'], $content); return IteratorDirectory::wrap($names); } diff --git a/lib/private/Files/Storage/Local.php b/lib/private/Files/Storage/Local.php index 454e4062ac41..71fd250f5f2b 100644 --- a/lib/private/Files/Storage/Local.php +++ b/lib/private/Files/Storage/Local.php @@ -440,7 +440,7 @@ public function getETag($path) { * @throws ForbiddenException */ public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) { - if ($sourceStorage->instanceOfStorage(__CLASS__)) { + if ($sourceStorage->instanceOfStorage(self::class)) { /** * @var \OC\Files\Storage\Local $sourceStorage */ @@ -460,7 +460,7 @@ public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceIntern * @throws \InvalidArgumentException */ public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) { - if ($sourceStorage->instanceOfStorage(__CLASS__)) { + if ($sourceStorage->instanceOfStorage(self::class)) { /** * @var \OC\Files\Storage\Local $sourceStorage */ diff --git a/lib/private/Files/Storage/StorageFactory.php b/lib/private/Files/Storage/StorageFactory.php index dc08eb172a00..527c3de4e645 100644 --- a/lib/private/Files/Storage/StorageFactory.php +++ b/lib/private/Files/Storage/StorageFactory.php @@ -31,7 +31,7 @@ class StorageFactory implements IStorageFactory { /** * @var array[] [$name=>['priority'=>$priority, 'wrapper'=>$callable] $storageWrappers */ - private $storageWrappers = []; + private array $storageWrappers = []; /** * allow modifier storage behaviour by adding wrappers around storages @@ -89,13 +89,9 @@ public function getInstance(IMountPoint $mountPoint, $class, $arguments) { */ public function wrap(IMountPoint $mountPoint, $storage) { $wrappers = \array_values($this->storageWrappers); - \usort($wrappers, function ($a, $b) { - return $b['priority'] - $a['priority']; - }); + \usort($wrappers, fn ($a, $b) => $b['priority'] - $a['priority']); /** @var callable[] $wrappers */ - $wrappers = \array_map(function ($wrapper) { - return $wrapper['wrapper']; - }, $wrappers); + $wrappers = \array_map(fn ($wrapper) => $wrapper['wrapper'], $wrappers); foreach ($wrappers as $wrapper) { $storage = $wrapper($mountPoint->getMountPoint(), $storage, $mountPoint); if (!($storage instanceof \OCP\Files\Storage)) { diff --git a/lib/private/Files/Storage/Wrapper/Checksum.php b/lib/private/Files/Storage/Wrapper/Checksum.php index b405f14ad1f6..ab2a3669a3f9 100644 --- a/lib/private/Files/Storage/Wrapper/Checksum.php +++ b/lib/private/Files/Storage/Wrapper/Checksum.php @@ -46,8 +46,7 @@ class Checksum extends Wrapper { /** File needs to be checksummed on first read because it is already in cache but has no checksum */ public const PATH_IN_CACHE_WITHOUT_CHECKSUM = 2; - /** @var array */ - private $pathsInCacheWithoutChecksum = []; + private array $pathsInCacheWithoutChecksum = []; /** * @param string $path diff --git a/lib/private/Files/Storage/Wrapper/DirMask.php b/lib/private/Files/Storage/Wrapper/DirMask.php index 0b963013dc4f..7cf289a49249 100644 --- a/lib/private/Files/Storage/Wrapper/DirMask.php +++ b/lib/private/Files/Storage/Wrapper/DirMask.php @@ -35,7 +35,7 @@ class DirMask extends PermissionsMask { /** * @var int remember length */ - private $pathLength; + private int $pathLength; /** * @param array $arguments ['storage' => $storage, 'mask' => $mask, 'path' => $path] * diff --git a/lib/private/Files/Storage/Wrapper/Encryption.php b/lib/private/Files/Storage/Wrapper/Encryption.php index 906568d088da..2b422e65366d 100644 --- a/lib/private/Files/Storage/Wrapper/Encryption.php +++ b/lib/private/Files/Storage/Wrapper/Encryption.php @@ -50,14 +50,11 @@ class Encryption extends Wrapper { /** @var string */ private $mountPoint; - /** @var \OC\Encryption\Util */ - private $util; + private ?\OC\Encryption\Util $util = null; - /** @var \OCP\Encryption\IManager */ - private $encryptionManager; + private ?\OCP\Encryption\IManager $encryptionManager = null; - /** @var \OCP\ILogger */ - private $logger; + private ?\OCP\ILogger $logger = null; /** @var string */ private $uid; @@ -65,31 +62,26 @@ class Encryption extends Wrapper { /** @var array */ protected $unencryptedSize; - /** @var \OCP\Encryption\IFile */ - private $fileHelper; + private ?\OCP\Encryption\IFile $fileHelper = null; /** @var IMountPoint */ private $mount; - /** @var IStorage */ - private $keyStorage; + private ?\OCP\Encryption\Keys\IStorage $keyStorage = null; - /** @var Update */ - private $update; + private ?\OC\Encryption\Update $update = null; - /** @var Manager */ - private $mountManager; + private ?\OC\Files\Mount\Manager $mountManager = null; /** @var array remember for which path we execute the repair step to avoid recursions */ - private $fixUnencryptedSizeOf = []; + private array $fixUnencryptedSizeOf = []; - /** @var ArrayCache */ - private $arrayCache; + private ?\OC\Memcache\ArrayCache $arrayCache = null; /** @var array which has information of sourcePath during rename operation */ - private $sourcePath; + private ?array $sourcePath = null; - private static $disableWriteEncryption = false; + private static bool $disableWriteEncryption = false; /** * @param array $parameters @@ -850,7 +842,7 @@ private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, unset($this->sourcePath[$targetInternalPath]); } $target = $this->fopen($targetInternalPath, 'w'); - list(, $result) = \OC_Helper::streamCopy($source, $target); + [, $result] = \OC_Helper::streamCopy($source, $target); \fclose($source); \fclose($target); } catch (\Exception $e) { diff --git a/lib/private/Files/Storage/Wrapper/Quota.php b/lib/private/Files/Storage/Wrapper/Quota.php index 1fc504277ffe..d4c2178483a2 100644 --- a/lib/private/Files/Storage/Wrapper/Quota.php +++ b/lib/private/Files/Storage/Wrapper/Quota.php @@ -49,7 +49,7 @@ class Quota extends Wrapper { public function __construct($parameters) { parent::__construct($parameters); $this->quota = $parameters['quota']; - $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : ''; + $this->sizeRoot = $parameters['root'] ?? ''; $this->mountPoint = $parameters['mountPoint'] ?? ''; } diff --git a/lib/private/Files/Storage/Wrapper/Wrapper.php b/lib/private/Files/Storage/Wrapper/Wrapper.php index 0482d222857d..d292d7e9dc6b 100644 --- a/lib/private/Files/Storage/Wrapper/Wrapper.php +++ b/lib/private/Files/Storage/Wrapper/Wrapper.php @@ -494,7 +494,7 @@ public function isLocal() { public function instanceOfStorage($class) { if (\ltrim($class, '\\') === 'OC\Files\Storage\Shared') { // FIXME Temporary fix to keep existing checks working - $class = '\OCA\Files_Sharing\SharedStorage'; + $class = '\\' . \OCA\Files_Sharing\SharedStorage::class; } return \is_a($this, $class) or $this->getWrapperStorage()->instanceOfStorage($class); } diff --git a/lib/private/Files/Stream/Checksum.php b/lib/private/Files/Stream/Checksum.php index 49e2f7c78a06..bac99c29c3f4 100644 --- a/lib/private/Files/Stream/Checksum.php +++ b/lib/private/Files/Stream/Checksum.php @@ -44,15 +44,15 @@ class Checksum extends Wrapper { * * @var resource[] */ - private $hashingContexts; + private ?array $hashingContexts = null; /** * Check if the stream has been read or written from the beginning. * If `fseek` is called, this flag should be false unless the target * position of the beginning of the stream */ - private $fromBeginning = true; - private $reading = false; + private bool $fromBeginning = true; + private bool $reading = false; /** @var CappedMemoryCache Key is path, value is array of checksums */ private static $checksums; @@ -271,11 +271,8 @@ public static function getChecksums($path) { } $pathToCheck = "{$pathPieces[0]}/" . \md5("/{$pathPieces[1]}"); - if (isset(self::$checksums[$pathToCheck])) { - return self::$checksums[$pathToCheck]; - } - return []; + return self::$checksums[$pathToCheck] ?? []; } /** diff --git a/lib/private/Files/Stream/Close.php b/lib/private/Files/Stream/Close.php index 4810d01150a8..dd22a1b2ae8f 100644 --- a/lib/private/Files/Stream/Close.php +++ b/lib/private/Files/Stream/Close.php @@ -28,11 +28,11 @@ * stream wrapper that provides a callback on stream close */ class Close { - private static $callBacks = []; - private $path = ''; + private static array $callBacks = []; + private string $path = ''; private $source; - private static $open = []; - private $meta; + private static array $open = []; + private ?array $meta = null; public function stream_open($path, $mode, $options, &$opened_path) { $path = \substr($path, \strlen('close://')); diff --git a/lib/private/Files/Stream/Dir.php b/lib/private/Files/Stream/Dir.php index 8b0034e0fb81..0c89a09bf883 100644 --- a/lib/private/Files/Stream/Dir.php +++ b/lib/private/Files/Stream/Dir.php @@ -25,9 +25,9 @@ namespace OC\Files\Stream; class Dir { - private static $dirs = []; - private $name; - private $index; + private static array $dirs = []; + private ?string $name = null; + private ?int $index = null; public function dir_opendir($path, $options) { $this->name = \substr($path, \strlen('fakedir://')); diff --git a/lib/private/Files/Stream/Encryption.php b/lib/private/Files/Stream/Encryption.php index 7ec3b2d6cccd..d78d77cb7ed7 100644 --- a/lib/private/Files/Stream/Encryption.php +++ b/lib/private/Files/Stream/Encryption.php @@ -160,7 +160,7 @@ public static function wrap( $headerSize, $signed, $sourceFileOfRename = null, - $wrapper = 'OC\Files\Stream\Encryption' + $wrapper = \OC\Files\Stream\Encryption::class ) { $context = \stream_context_create([ 'ocencryption' => [ diff --git a/lib/private/Files/Stream/Quota.php b/lib/private/Files/Stream/Quota.php index 1cb7c4c77370..d00e857721e7 100644 --- a/lib/private/Files/Stream/Quota.php +++ b/lib/private/Files/Stream/Quota.php @@ -75,7 +75,7 @@ public static function wrap($stream, $limit) { public function stream_open($path, $mode, $options, &$opened_path) { $id = \substr($path, \strlen('quota://')); if (isset(self::$streams[$id])) { - list($this->source, $this->limit) = self::$streams[$id]; + [$this->source, $this->limit] = self::$streams[$id]; return true; } else { return false; diff --git a/lib/private/Files/Type/Detection.php b/lib/private/Files/Type/Detection.php index 5992caebb3f7..bfe641b56437 100644 --- a/lib/private/Files/Type/Detection.php +++ b/lib/private/Files/Type/Detection.php @@ -49,8 +49,7 @@ class Detection implements IMimeTypeDetector { /** @var string[] */ protected $mimeTypeAlias = []; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; /** @var string */ private $customConfigDir; @@ -107,7 +106,7 @@ public function registerTypeArray($types) { // Update the alternative mimetypes to avoid having to look them up each time. foreach ($this->mimetypes as $mimeType) { - $this->secureMimeTypes[$mimeType[0]] = isset($mimeType[1]) ? $mimeType[1]: $mimeType[0]; + $this->secureMimeTypes[$mimeType[0]] = $mimeType[1] ?? $mimeType[0]; } } @@ -119,10 +118,10 @@ private function loadAliases() { return; } - $this->mimeTypeAlias = \json_decode(\file_get_contents($this->defaultConfigDir . '/mimetypealiases.dist.json'), true); + $this->mimeTypeAlias = \json_decode(\file_get_contents($this->defaultConfigDir . '/mimetypealiases.dist.json'), true, 512, JSON_THROW_ON_ERROR); if (\file_exists($this->customConfigDir . '/mimetypealiases.json')) { - $custom = \json_decode(\file_get_contents($this->customConfigDir . '/mimetypealiases.json'), true); + $custom = \json_decode(\file_get_contents($this->customConfigDir . '/mimetypealiases.json'), true, 512, JSON_THROW_ON_ERROR); $this->mimeTypeAlias = \array_merge($this->mimeTypeAlias, $custom); } } @@ -143,11 +142,11 @@ private function loadMappings() { return; } - $mimetypeMapping = \json_decode(\file_get_contents($this->defaultConfigDir . '/mimetypemapping.dist.json'), true); + $mimetypeMapping = \json_decode(\file_get_contents($this->defaultConfigDir . '/mimetypemapping.dist.json'), true, 512, JSON_THROW_ON_ERROR); //Check if need to load custom mappings if (\file_exists($this->customConfigDir . '/mimetypemapping.json')) { - $custom = \json_decode(\file_get_contents($this->customConfigDir . '/mimetypemapping.json'), true); + $custom = \json_decode(\file_get_contents($this->customConfigDir . '/mimetypemapping.json'), true, 512, JSON_THROW_ON_ERROR); $mimetypeMapping = \array_merge($mimetypeMapping, $custom); } @@ -285,9 +284,7 @@ public function detectString($data) { public function getSecureMimeType($mimeType) { $this->loadMappings(); - return isset($this->secureMimeTypes[$mimeType]) - ? $this->secureMimeTypes[$mimeType] - : 'application/octet-stream'; + return $this->secureMimeTypes[$mimeType] ?? 'application/octet-stream'; } /** diff --git a/lib/private/Files/Type/Loader.php b/lib/private/Files/Type/Loader.php index d710b66319e6..0a2ea6119099 100644 --- a/lib/private/Files/Type/Loader.php +++ b/lib/private/Files/Type/Loader.php @@ -37,8 +37,7 @@ class Loader implements IMimeTypeLoader { public const CACHE_PREFIX_FOR_ID = ':id:'; public const CACHE_PREFIX_FOR_MIME = ':mime:'; - /** @var IDBConnection */ - private $dbConnection; + private \OCP\IDBConnection $dbConnection; /** @var ICache */ private $memcache; diff --git a/lib/private/Files/Utils/Scanner.php b/lib/private/Files/Utils/Scanner.php index 27b03de8b199..58e47d068abe 100644 --- a/lib/private/Files/Utils/Scanner.php +++ b/lib/private/Files/Utils/Scanner.php @@ -116,17 +116,17 @@ protected function getMounts($dir) { protected function attachListener($mount) { $scanner = $mount->getStorage()->getScanner(); $emitter = $this; - $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount, $emitter) { - $emitter->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]); + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'scanFile', function ($path) use ($mount, $emitter) { + $emitter->emit('\\' . \OC\Files\Utils\Scanner::class, 'scanFile', [$mount->getMountPoint() . $path]); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount, $emitter) { - $emitter->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]); + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'scanFolder', function ($path) use ($mount, $emitter) { + $emitter->emit('\\' . \OC\Files\Utils\Scanner::class, 'scanFolder', [$mount->getMountPoint() . $path]); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount, $emitter) { - $emitter->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]); + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'postScanFile', function ($path) use ($mount, $emitter) { + $emitter->emit('\\' . \OC\Files\Utils\Scanner::class, 'postScanFile', [$mount->getMountPoint() . $path]); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount, $emitter) { - $emitter->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]); + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'postScanFolder', function ($path) use ($mount, $emitter) { + $emitter->emit('\\' . \OC\Files\Utils\Scanner::class, 'postScanFolder', [$mount->getMountPoint() . $path]); }); } @@ -143,20 +143,20 @@ public function backgroundScan($dir) { $storage = $mount->getStorage(); // don't scan the root storage - if ($storage->instanceOfStorage('\OC\Files\Storage\Local') && $mount->getMountPoint() === '/') { + if ($storage->instanceOfStorage('\\' . \OC\Files\Storage\Local::class) && $mount->getMountPoint() === '/') { continue; } $scanner = $storage->getScanner(); $this->attachListener($mount); - $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) { + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'removeFromCache', function ($path) use ($storage) { $this->triggerPropagator($storage, $path); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) { + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'updateCache', function ($path) use ($storage) { $this->triggerPropagator($storage, $path); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) { + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'addToCache', function ($path) use ($storage) { $this->triggerPropagator($storage, $path); }); @@ -180,13 +180,13 @@ private function shouldScan($mount) { } // don't bother scanning failed storages (shortcut for same result) - if ($storage->instanceOfStorage('OC\Files\Storage\FailedStorage')) { + if ($storage->instanceOfStorage(\OC\Files\Storage\FailedStorage::class)) { return false; } // if the home storage isn't readable then the scanner is run as the wrong user // (guests will have a read-only home storage) - if ($storage->instanceOfStorage('\OC\Files\Storage\Home') and + if ($storage->instanceOfStorage('\\' . \OC\Files\Storage\Home::class) and (!$storage->isReadable('') or !$storage->isReadable('files')) ) { if ($storage->file_exists('') or $storage->getCache()->inCache('')) { @@ -197,7 +197,7 @@ private function shouldScan($mount) { } // don't scan received local shares, these can be scanned when scanning the owner's storage - if ($storage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) { + if ($storage->instanceOfStorage(\OCA\Files_Sharing\ISharedStorage::class)) { return false; } @@ -220,20 +220,20 @@ public function scan($dir = '') { $storage = $mount->getStorage(); - $this->emit('\OC\Files\Utils\Scanner', 'beforeScanStorage', [$storage]); + $this->emit('\\' . \OC\Files\Utils\Scanner::class, 'beforeScanStorage', [$storage]); $relativePath = $mount->getInternalPath($dir); $scanner = $storage->getScanner(); $scanner->setUseTransactions(false); $this->attachListener($mount); - $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) { + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'removeFromCache', function ($path) use ($storage) { $this->postProcessEntry($storage, $path); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) { + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'updateCache', function ($path) use ($storage) { $this->postProcessEntry($storage, $path); }); - $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) { + $scanner->listen('\\' . \OC\Files\Cache\Scanner::class, 'addToCache', function ($path) use ($storage) { $this->postProcessEntry($storage, $path); }); @@ -253,12 +253,12 @@ public function scan($dir = '') { } catch (StorageNotAvailableException $e) { $this->logger->error('Storage ' . $storage->getId() . ' not available'); $this->logger->logException($e); - $this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]); + $this->emit('\\' . \OC\Files\Utils\Scanner::class, 'StorageNotAvailable', [$e]); } if ($this->useTransaction) { $this->db->commit(); } - $this->emit('\OC\Files\Utils\Scanner', 'afterScanStorage', [$storage]); + $this->emit('\\' . \OC\Files\Utils\Scanner::class, 'afterScanStorage', [$storage]); } } diff --git a/lib/private/Files/View.php b/lib/private/Files/View.php index 9bd55a420c3b..76126c0f62f7 100644 --- a/lib/private/Files/View.php +++ b/lib/private/Files/View.php @@ -84,19 +84,16 @@ */ class View { use EventEmitterTrait; - /** @var string */ - private $fakeRoot = ''; + private string $fakeRoot = ''; /** * @var \OCP\Lock\ILockingProvider */ private $lockingProvider; - /** @var bool */ - private $lockingEnabled; + private bool $lockingEnabled; - /** @var bool */ - private $updaterEnabled = true; + private bool $updaterEnabled = true; /** @var \OC\User\Manager */ private $userManager; @@ -107,7 +104,7 @@ class View { /** @var \OCP\IConfig */ private $config; - private static $ignorePartFile = false; + private static bool $ignorePartFile = false; /** * @param string $root @@ -247,7 +244,7 @@ public function resolvePath($path) { public function getLocalFile($path) { $parent = \substr($path, 0, \strrpos($path, '/')); $path = $this->getAbsolutePath($path); - list($storage, $internalPath) = Filesystem::resolvePath($path); + [$storage, $internalPath] = Filesystem::resolvePath($path); if (Filesystem::isValidPath($parent) and $storage) { return $storage->getLocalFile($internalPath); } else { @@ -262,7 +259,7 @@ public function getLocalFile($path) { public function getLocalFolder($path) { $parent = \substr($path, 0, \strrpos($path, '/')); $path = $this->getAbsolutePath($path); - list($storage, $internalPath) = Filesystem::resolvePath($path); + [$storage, $internalPath] = Filesystem::resolvePath($path); if (Filesystem::isValidPath($parent) and $storage) { return $storage->getLocalFolder($internalPath); } else { @@ -722,10 +719,10 @@ public function file_put_contents($path, $data) { $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE); /** @var \OC\Files\Storage\Storage $storage */ - list($storage, $internalPath) = $this->resolvePath($path); + [$storage, $internalPath] = $this->resolvePath($path); $target = $storage->fopen($internalPath, 'w'); if ($target) { - list(, $result) = \OC_Helper::streamCopy($data, $target); + [, $result] = \OC_Helper::streamCopy($data, $target); \fclose($target); \fclose($data); @@ -1162,7 +1159,7 @@ public function hash($type, $path, $raw = false) { [Filesystem::signal_param_path => $this->getHookPath($path)] ); } - list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix); + [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix); if ($storage) { $result = $storage->hash($type, $internalPath, $raw); return $result; @@ -1213,7 +1210,7 @@ private function basicOperation($operation, $path, $hooks = [], $extraParam = nu $run = $this->runHooks($hooks, $path); /** @var \OC\Files\Storage\Storage $storage */ - list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix); + [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix); if ($run and $storage) { if (\in_array('write', $hooks) || \in_array('delete', $hooks)) { $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE); @@ -1535,9 +1532,7 @@ public function getDirectoryContent($directory, $mimetype_filter = '') { /** * @var \OC\Files\FileInfo[] $files */ - $files = \array_filter($contents, function (ICacheEntry $content) { - return (!\OC\Files\Filesystem::isForbiddenFileOrDir($content['path'])); - }); + $files = \array_filter($contents, fn (ICacheEntry $content) => !\OC\Files\Filesystem::isForbiddenFileOrDir($content['path'])); $files = \array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) { try { $itemPath = $this->getPath($content['fileid'], false); @@ -1570,9 +1565,7 @@ public function getDirectoryContent($directory, $mimetype_filter = '') { $subScanner = $subStorage->getScanner(''); try { $subScanner->scanFile(''); - } catch (\OCP\Files\StorageNotAvailableException $e) { - continue; - } catch (\OCP\Files\StorageInvalidException $e) { + } catch (\OCP\Files\StorageNotAvailableException|\OCP\Files\StorageInvalidException $e) { continue; } catch (\Exception $e) { // sometimes when the storage is not available it can be any exception @@ -1665,7 +1658,7 @@ public function putFileInfo($path, $data) { * @var \OC\Files\Storage\Storage $storage * @var string $internalPath */ - list($storage, $internalPath) = Filesystem::resolvePath($path); + [$storage, $internalPath] = Filesystem::resolvePath($path); if ($storage) { $cache = $storage->getCache($path); @@ -1797,7 +1790,7 @@ public function getETag($path) { * @var Storage\Storage $storage * @var string $internalPath */ - list($storage, $internalPath) = $this->resolvePath($path); + [$storage, $internalPath] = $this->resolvePath($path); if ($storage) { return $storage->getETag($internalPath); } else { @@ -1873,8 +1866,8 @@ private function assertPathLength($path) { * @return boolean */ private function canMove(MoveableMount $mount1, $target) { - list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target); - if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) { + [$targetStorage, $targetInternalPath] = \OC\Files\Filesystem::resolvePath($target); + if (!$targetStorage->instanceOfStorage('\\' . \OCP\Files\IHomeStorage::class)) { Util::writeLog( 'files', 'It is not allowed to move one mount point into another one', @@ -1954,7 +1947,7 @@ public function verifyPath($path, $fileName) { try { /** @type \OCP\Files\Storage $storage */ - list($storage, $internalPath) = $this->resolvePath($path); + [$storage, $internalPath] = $this->resolvePath($path); $storage->verifyPath($internalPath, $fileName); } catch (ReservedWordException $ex) { throw new InvalidPathException($l10n->t('File name is a reserved word')); @@ -2040,7 +2033,7 @@ private function lockPath($path, $type, $lockMountPoint = false) { if ($mount) { try { $storage = $mount->getStorage(); - if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { + if ($storage->instanceOfStorage('\\' . \OCP\Files\Storage\ILockingStorage::class)) { $storage->acquireLock( $mount->getInternalPath($absolutePath), $type, @@ -2081,7 +2074,7 @@ public function changeLock($path, $type, $lockMountPoint = false) { if ($mount) { try { $storage = $mount->getStorage(); - if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { + if ($storage->instanceOfStorage('\\' . \OCP\Files\Storage\ILockingStorage::class)) { $storage->changeLock( $mount->getInternalPath($absolutePath), $type, @@ -2119,7 +2112,7 @@ private function unlockPath($path, $type, $lockMountPoint = false) { $mount = $this->getMountForLock($absolutePath, $lockMountPoint); if ($mount) { $storage = $mount->getStorage(); - if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) { + if ($storage && $storage->instanceOfStorage('\\' . \OCP\Files\Storage\ILockingStorage::class)) { $storage->releaseLock( $mount->getInternalPath($absolutePath), $type, @@ -2220,10 +2213,7 @@ public function getPathRelativeToFiles($absolutePath) { if (!isset($parts[1]) || $parts[1] !== 'files') { throw new \InvalidArgumentException('"' . $absolutePath . '" must be relative to "files"'); } - if (isset($parts[2])) { - return $parts[2]; - } - return ''; + return $parts[2] ?? ''; } /** diff --git a/lib/private/Group/Database.php b/lib/private/Group/Database.php index 4b8eb79de3dd..afd9afc11f3d 100644 --- a/lib/private/Group/Database.php +++ b/lib/private/Group/Database.php @@ -44,7 +44,7 @@ */ class Database extends \OC\Group\Backend { /** @var string[] */ - private $groupCache = []; + private array $groupCache = []; /** @var \OCP\IDBConnection */ private $dbConn; diff --git a/lib/private/Group/Group.php b/lib/private/Group/Group.php index 6cdfd190da7a..08b479eae0c4 100644 --- a/lib/private/Group/Group.php +++ b/lib/private/Group/Group.php @@ -43,12 +43,9 @@ class Group implements IGroup { /** * @var \OC\User\User[] $users */ - private $users = []; + private array $users = []; - /** - * @var bool $usersLoaded - */ - private $usersLoaded; + private ?bool $usersLoaded = null; /** * @var \OC\Group\Backend[]|\OC\Group\Database[] $backend @@ -65,8 +62,7 @@ class Group implements IGroup { */ private $userManager; - /** @var EventDispatcherInterface */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher; /** @var null|string */ private $displayName; diff --git a/lib/private/Group/Manager.php b/lib/private/Group/Manager.php index 049d3937f646..078de8a3edf5 100644 --- a/lib/private/Group/Manager.php +++ b/lib/private/Group/Manager.php @@ -62,17 +62,11 @@ class Manager extends PublicEmitter implements IGroupManager { /** * @var GroupInterface[] $backends */ - private $backends = []; + private array $backends = []; - /** - * @var UserManager $userManager - */ - private $userManager; + private \OC\User\Manager $userManager; - /** - * @var UserSearch $userSearch - */ - private $userSearch; + private \OCP\Util\UserSearch $userSearch; /** * @var \OC\Group\Group[] @@ -84,11 +78,9 @@ class Manager extends PublicEmitter implements IGroupManager { */ private $cachedUserGroups = []; - /** @var \OC\SubAdmin */ - private $subAdmin = null; + private ?\OC\SubAdmin $subAdmin = null; - /** @var EventDispatcherInterface */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher; /** * @param \OC\User\Manager $userManager @@ -162,10 +154,7 @@ protected function clearCaches() { * @return \OC\Group\Group|null */ public function get($gid) { - if (isset($this->cachedGroups[$gid])) { - return $this->cachedGroups[$gid]; - } - return $this->getGroupObject($gid); + return $this->cachedGroups[$gid] ?? $this->getGroupObject($gid); } /** @@ -302,9 +291,7 @@ private function getExcludedBackendsForScope($scope) { private function filterExcludedBackendsForScope($groups, $scope) { $excludedBackendsForScope = $this->getExcludedBackendsForScope($scope); if (!empty($excludedBackendsForScope)) { - return \array_filter($groups, function ($group) use ($excludedBackendsForScope) { - return !\in_array($group->getBackend(), $excludedBackendsForScope); - }); + return \array_filter($groups, fn ($group) => !\in_array($group->getBackend(), $excludedBackendsForScope)); } return $groups; } @@ -366,9 +353,7 @@ public function isInGroup($userId, $group) { * @return array with group ids */ public function getUserGroupIds($user, $scope = null) { - return \array_map(function ($value) { - return (string) $value; - }, \array_keys($this->getUserGroups($user, $scope))); + return \array_map(fn ($value) => (string) $value, \array_keys($this->getUserGroups($user, $scope))); } /** diff --git a/lib/private/HTTPHelper.php b/lib/private/HTTPHelper.php index 1d339f4c8133..fdec553e1130 100644 --- a/lib/private/HTTPHelper.php +++ b/lib/private/HTTPHelper.php @@ -35,10 +35,8 @@ class HTTPHelper { public const USER_AGENT = 'ownCloud Server Crawler'; - /** @var \OCP\IConfig */ - private $config; - /** @var IClientService */ - private $clientService; + private \OCP\IConfig $config; + private \OCP\Http\Client\IClientService $clientService; /** * @param IConfig $config diff --git a/lib/private/Helper/LocaleHelper.php b/lib/private/Helper/LocaleHelper.php index 7231a1055f85..a58c7229df0b 100644 --- a/lib/private/Helper/LocaleHelper.php +++ b/lib/private/Helper/LocaleHelper.php @@ -27,7 +27,7 @@ class LocaleHelper { /** * @var string[] */ - private $commonLanguages = [ + private array $commonLanguages = [ 'en', 'es', 'fr', @@ -52,7 +52,7 @@ class LocaleHelper { /** * @var string[] */ - private $languageCodes = [ + private array $languageCodes = [ 'el' => 'Ελληνικά', 'en' => 'English', 'fa' => 'فارسى', @@ -164,9 +164,7 @@ public function getCommonLanguageWeight($languageCode) { * @return string */ public function getLanguageNameByCode($code) { - return (isset($this->languageCodes[$code])) - ? $this->languageCodes[$code] - : $code; + return $this->languageCodes[$code] ?? $code; } /** diff --git a/lib/private/HintException.php b/lib/private/HintException.php index 603f1b1f4623..e1f6871c0add 100644 --- a/lib/private/HintException.php +++ b/lib/private/HintException.php @@ -34,7 +34,7 @@ public function __construct($message, $hint = '', $code = 0, \Exception $previou } public function __toString() { - return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n"; + return self::class . ": [{$this->code}]: {$this->message} ({$this->hint})\n"; } public function getHint() { diff --git a/lib/private/Hooks/ForwardingEmitter.php b/lib/private/Hooks/ForwardingEmitter.php index de2f722e5c3e..61e55b1d11a7 100644 --- a/lib/private/Hooks/ForwardingEmitter.php +++ b/lib/private/Hooks/ForwardingEmitter.php @@ -34,7 +34,7 @@ abstract class ForwardingEmitter extends BasicEmitter { /** * @var \OC\Hooks\Emitter[] array */ - private $forwardEmitters = []; + private array $forwardEmitters = []; /** * @param string $scope @@ -56,7 +56,7 @@ protected function forward(Emitter $emitter) { //forward all previously connected hooks foreach ($this->listeners as $key => $listeners) { - list($scope, $method) = \explode('::', $key, 2); + [$scope, $method] = \explode('::', $key, 2); foreach ($listeners as $listener) { $emitter->listen($scope, $method, $listener); } diff --git a/lib/private/Http/Client/Client.php b/lib/private/Http/Client/Client.php index 54fcd46498a0..f7542cc71063 100644 --- a/lib/private/Http/Client/Client.php +++ b/lib/private/Http/Client/Client.php @@ -34,14 +34,10 @@ * @package OC\Http */ class Client implements IClient { - /** @var GuzzleClient */ - private $client; - /** @var IConfig */ - private $config; - /** @var ICertificateManager */ - private $certificateManager; - /** @var array */ - private $defaultOptions; + private \GuzzleHttp\Client $client; + private \OCP\IConfig $config; + private \OCP\ICertificateManager $certificateManager; + private ?array $defaultOptions = null; /** * @param IConfig $config diff --git a/lib/private/Http/Client/ClientService.php b/lib/private/Http/Client/ClientService.php index 6e5651b42a2d..6099f1f7dc91 100644 --- a/lib/private/Http/Client/ClientService.php +++ b/lib/private/Http/Client/ClientService.php @@ -32,10 +32,8 @@ * @package OC\Http */ class ClientService implements IClientService { - /** @var IConfig */ - private $config; - /** @var ICertificateManager */ - private $certificateManager; + private \OCP\IConfig $config; + private \OCP\ICertificateManager $certificateManager; /** * @param IConfig $config diff --git a/lib/private/Http/Client/Response.php b/lib/private/Http/Client/Response.php index 103de87e84f2..54f7d717b032 100644 --- a/lib/private/Http/Client/Response.php +++ b/lib/private/Http/Client/Response.php @@ -31,8 +31,7 @@ * @package OC\Http */ class Response implements IResponse { - /** @var GuzzleResponse */ - private $response; + private \GuzzleHttp\Psr7\Response $response; /** * @var bool diff --git a/lib/private/Http/Client/WebDavClientService.php b/lib/private/Http/Client/WebDavClientService.php index 786f619ef3d9..9107c63781c2 100644 --- a/lib/private/Http/Client/WebDavClientService.php +++ b/lib/private/Http/Client/WebDavClientService.php @@ -31,10 +31,8 @@ * @package OC\Http */ class WebDavClientService implements IWebDavClientService { - /** @var IConfig */ - private $config; - /** @var ICertificateManager */ - private $certificateManager; + private \OCP\IConfig $config; + private \OCP\ICertificateManager $certificateManager; /** * @param IConfig $config diff --git a/lib/private/Image/BmpToResource.php b/lib/private/Image/BmpToResource.php index 4eb87814aa61..167298792458 100644 --- a/lib/private/Image/BmpToResource.php +++ b/lib/private/Image/BmpToResource.php @@ -34,8 +34,7 @@ class BmpToResource { public const COMPRESSION_BI_RGB = 0; public const COMPRESSION_BI_BITFIELDS = 3; - /** @var \SplFileObject $file */ - private $file; + private ?\SplFileObject $file = null; /** @var array $header */ private $header = []; @@ -49,8 +48,7 @@ class BmpToResource { /** @var resource $resource */ private $resource; - /** @var array $bytesPerDepth */ - private $bytesPerDepth = [ + private array $bytesPerDepth = [ 1 => 1, 4 => 1, 8 => 1, @@ -137,7 +135,7 @@ private function readDibHeader() { $dibHeader = @\unpack('Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', $rawDibHeader); // fixup colors - $dibHeader['colors'] = $dibHeader['colors'] === 0 ? \pow(2, $dibHeader['bits']) : $dibHeader['colors']; + $dibHeader['colors'] = $dibHeader['colors'] === 0 ? 2 ** $dibHeader['bits'] : $dibHeader['colors']; // fixup imagesize - it can be zero if ($dibHeader['imagesize'] < 1) { @@ -257,9 +255,7 @@ private function getColors($raw) { } } elseif (\in_array($this->header['bits'], [8, 4, 1])) { $colors = \array_map( - function ($i) { - return $this->palette[ \bindec($i) ]; - }, + fn ($i) => $this->palette[ \bindec($i) ], $this->splitByteIntoArray($raw, $this->header['bits']) ); } diff --git a/lib/private/Installer.php b/lib/private/Installer.php index c6c724d85474..e996df2023ed 100644 --- a/lib/private/Installer.php +++ b/lib/private/Installer.php @@ -85,7 +85,7 @@ class Installer { public static function installApp($data = []) { $l = \OC::$server->getL10N('lib'); - list($extractDir, $path) = self::downloadApp($data); + [$extractDir, $path] = self::downloadApp($data); $info = self::checkAppsIntegrity($data, $extractDir, $path); $appId = OC_App::cleanAppId($info['id']); @@ -214,7 +214,7 @@ public static function isInstalled($app) { * "\OC::$server->getAppConfig()->getValue($appid, 'installed_version')" */ public static function updateApp($info= [], $isShipped=false) { - list($extractDir, $path) = self::downloadApp($info); + [$extractDir, $path] = self::downloadApp($info); $info = self::checkAppsIntegrity($info, $extractDir, $path, $isShipped); $currentDir = OC_App::getAppPath($info['id']); @@ -491,7 +491,7 @@ public static function installShippedApps($softErrors = false) { try { Installer::installShippedApp($appToInstall); } catch (TableExistsException $e) { - \OC::$server->getLogger()->logException($e, ['app' => __CLASS__]); + \OC::$server->getLogger()->logException($e, ['app' => self::class]); $errors[$appToInstall] = $e; continue; } diff --git a/lib/private/IntegrityCheck/Checker.php b/lib/private/IntegrityCheck/Checker.php index f69de935766f..6f32c9dc6f67 100644 --- a/lib/private/IntegrityCheck/Checker.php +++ b/lib/private/IntegrityCheck/Checker.php @@ -52,20 +52,14 @@ */ class Checker { public const CACHE_KEY = 'oc.integritycheck.checker'; - /** @var EnvironmentHelper */ - private $environmentHelper; - /** @var AppLocator */ - private $appLocator; - /** @var FileAccessHelper */ - private $fileAccessHelper; - /** @var IConfig */ - private $config; + private \OC\IntegrityCheck\Helpers\EnvironmentHelper $environmentHelper; + private \OC\IntegrityCheck\Helpers\AppLocator $appLocator; + private \OC\IntegrityCheck\Helpers\FileAccessHelper $fileAccessHelper; + private ?\OCP\IConfig $config = null; /** @var ICache */ private $cache; - /** @var IAppManager */ - private $appManager; - /** @var ITempManager */ - private $tempManager; + private ?\OCP\App\IAppManager $appManager = null; + private \OCP\ITempManager $tempManager; /** * @param EnvironmentHelper $environmentHelper @@ -246,7 +240,7 @@ private function createSignatureData( ->withSaltLength(0) ->withPadding(RSA::SIGNATURE_PSS); - $signature = $privateKey->sign(\json_encode($hashes)); + $signature = $privateKey->sign(\json_encode($hashes, JSON_THROW_ON_ERROR)); return [ 'hashes' => $hashes, @@ -342,7 +336,7 @@ private function verify($signaturePath, $basePath, $certificateCN, $force = fals return []; } - $signatureData = \json_decode($this->fileAccessHelper->file_get_contents($signaturePath), true); + $signatureData = \json_decode($this->fileAccessHelper->file_get_contents($signaturePath), true, 512, JSON_THROW_ON_ERROR); if (!\is_array($signatureData)) { throw new MissingSignatureException('Signature data not found.'); } @@ -395,7 +389,7 @@ private function verify($signaturePath, $basePath, $certificateCN, $force = fals ->withPadding(RSA::SIGNATURE_PSS) ->withSaltLength(0); - if (!$rsa->verify(\json_encode($expectedHashes), $signature)) { + if (!$rsa->verify(\json_encode($expectedHashes, JSON_THROW_ON_ERROR), $signature)) { throw new InvalidSignatureException('Signature could not get verified.'); } @@ -461,10 +455,10 @@ public function hasPassedCheck() { public function getResults() { $cachedResults = $this->cache->get(self::CACHE_KEY); if ($cachedResults !== null) { - return \json_decode($cachedResults, true); + return \json_decode($cachedResults, true, 512, JSON_THROW_ON_ERROR); } - return \json_decode($this->getAppValue(self::CACHE_KEY, '{}'), true); + return \json_decode($this->getAppValue(self::CACHE_KEY, '{}'), true, 512, JSON_THROW_ON_ERROR); } /** @@ -480,10 +474,10 @@ private function storeResults($scope, array $result) { $resultArray[$scope] = $result; } - $this->setAppValue(self::CACHE_KEY, \json_encode($resultArray)); + $this->setAppValue(self::CACHE_KEY, \json_encode($resultArray, JSON_THROW_ON_ERROR)); //Set cache for each app - $this->cache->set($scope, \json_encode($resultArray)); - $this->cache->set(self::CACHE_KEY, \json_encode($resultArray)); + $this->cache->set($scope, \json_encode($resultArray, JSON_THROW_ON_ERROR)); + $this->cache->set(self::CACHE_KEY, \json_encode($resultArray, JSON_THROW_ON_ERROR)); } /** diff --git a/lib/private/IntegrityCheck/Iterator/ExcludeFileByNameFilterIterator.php b/lib/private/IntegrityCheck/Iterator/ExcludeFileByNameFilterIterator.php index 1d6e78bdcec5..e43b37efab3b 100644 --- a/lib/private/IntegrityCheck/Iterator/ExcludeFileByNameFilterIterator.php +++ b/lib/private/IntegrityCheck/Iterator/ExcludeFileByNameFilterIterator.php @@ -30,13 +30,11 @@ */ class ExcludeFileByNameFilterIterator extends \RecursiveFilterIterator { /** - * Array of excluded file names. Those are not scanned by the integrity checker. - * This is used to exclude files which administrators could upload by mistakes - * such as .DS_Store files. - * - * @var array - */ - private $excludedFilenames = [ + * Array of excluded file names. Those are not scanned by the integrity checker. + * This is used to exclude files which administrators could upload by mistakes + * such as .DS_Store files. + */ + private array $excludedFilenames = [ '.DS_Store', // Mac OS X 'Thumbs.db', // Microsoft Windows '.directory', // Dolphin (KDE) @@ -44,24 +42,20 @@ class ExcludeFileByNameFilterIterator extends \RecursiveFilterIterator { ]; /** - * Array of excluded file name parts. Those are not scanned by the integrity checker. - * These strings are regular expressions and any file names - * matching these expressions are ignored. - * - * @var array - */ - private $excludedFileNamePatterns = [ + * Array of excluded file name parts. Those are not scanned by the integrity checker. + * These strings are regular expressions and any file names + * matching these expressions are ignored. + */ + private array $excludedFileNamePatterns = [ '/^\.webapp-owncloud-.*/', // Gentoo/Funtoo & derivatives use a tool known as webapp-config to manage wep-apps. ]; /** - * Array of excluded path and file name parts. Those are not scanned by the integrity checker. - * These strings are regular expressions and any filepath - * matching these expressions are ignored. - * - * @var array - */ - private $excludedFilePathPatterns = [ + * Array of excluded path and file name parts. Those are not scanned by the integrity checker. + * These strings are regular expressions and any filepath + * matching these expressions are ignored. + */ + private array $excludedFilePathPatterns = [ '|/core/js/mimetypelist.js$|', // this file can be regenerated with additional entries with occ maintenance:mimetype:update-js ]; diff --git a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php index b3030f6b74f8..e3818f3a4e4f 100644 --- a/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php +++ b/lib/private/IntegrityCheck/Iterator/ExcludeFoldersByPathFilterIterator.php @@ -23,7 +23,7 @@ namespace OC\IntegrityCheck\Iterator; class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator { - private $excludedFolders = []; + private array $excludedFolders = []; public function __construct(\RecursiveIterator $iterator, $root = '') { parent::__construct($iterator); diff --git a/lib/private/L10N/Factory.php b/lib/private/L10N/Factory.php index 59bdf33a7975..4c962404feca 100644 --- a/lib/private/L10N/Factory.php +++ b/lib/private/L10N/Factory.php @@ -227,7 +227,7 @@ public function setLanguageFromRequest($app = null) { $preferences = \preg_split('/,\s*/', \strtolower($header)); foreach ($preferences as $preference) { - list($preferred_language) = \explode(';', $preference); + [$preferred_language] = \explode(';', $preference); $preferred_language = \str_replace('-', '_', $preferred_language); foreach ($available as $available_language) { diff --git a/lib/private/License/BasicLicense.php b/lib/private/License/BasicLicense.php index 3a8e4d4fc06a..849d222fbeca 100644 --- a/lib/private/License/BasicLicense.php +++ b/lib/private/License/BasicLicense.php @@ -22,12 +22,12 @@ use OCP\License\AbstractLicense; class BasicLicense extends AbstractLicense { - private $rawLicense; - private $org; + private string $rawLicense; + private ?string $org = null; private $expirationDateTimestamp = 0; // to ensure an integer as expiration value - private $rawCodes; - private $codes; - private $checksum; + private ?string $rawCodes = null; + private ?array $codes = null; + private ?string $checksum = null; public function __construct(string $licenseKey) { $this->rawLicense = $licenseKey; diff --git a/lib/private/License/LicenseFetcher.php b/lib/private/License/LicenseFetcher.php index 719b6a2a5195..88548def3b5c 100644 --- a/lib/private/License/LicenseFetcher.php +++ b/lib/private/License/LicenseFetcher.php @@ -30,10 +30,8 @@ * and also per-app licenses (not planned for now) */ class LicenseFetcher { - /** @var IConfig */ - private $config; - /** @var ITimeFactory */ - private $timeFactory; + private \OCP\IConfig $config; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; public function __construct(IConfig $config, ITimeFactory $timeFactory) { $this->config = $config; diff --git a/lib/private/License/LicenseManager.php b/lib/private/License/LicenseManager.php index 364b71d7f006..de4799447825 100644 --- a/lib/private/License/LicenseManager.php +++ b/lib/private/License/LicenseManager.php @@ -29,19 +29,12 @@ class LicenseManager implements ILicenseManager { public const GRACE_PERIOD = 60 * 60 * 24; // 24h - - /** @var LicenseFetcher */ - private $licenseFetcher; - /** @var MessageService */ - private $messageService; - /** @var IConfig */ - private $config; - /** @var IAppManager */ - private $appManager; - /** @var ITimeFactory */ - private $timeFactory; - /** @var ILogger */ - private $logger; + private \OC\License\LicenseFetcher $licenseFetcher; + private \OC\License\MessageService $messageService; + private \OCP\IConfig $config; + private \OCP\App\IAppManager $appManager; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; + private \OCP\ILogger $logger; public function __construct( LicenseFetcher $licenseFetcher, @@ -246,9 +239,7 @@ public function askLicenseFor(string $appid, string $method, array $params = []) } // function names are case-insensitive... - $lowerCaseMethods = \array_map(function ($value) { - return \strtolower($value); - }, $licenseObj->getProtectedMethods()); + $lowerCaseMethods = \array_map(fn ($value) => \strtolower($value), $licenseObj->getProtectedMethods()); if (\in_array(\strtolower($method), $lowerCaseMethods, true)) { throw new LicenseManagerException("License doesn't allow method $method to be called", 3); diff --git a/lib/private/License/MessageService.php b/lib/private/License/MessageService.php index 81e86cdc3615..6fdea27bedad 100644 --- a/lib/private/License/MessageService.php +++ b/lib/private/License/MessageService.php @@ -26,8 +26,7 @@ * This class will provide translated messages based on the current license status */ class MessageService { - /** @var IFactory */ - private $l10nFactory; + private \OCP\L10N\IFactory $l10nFactory; public function __construct(IFactory $l10nFactory) { $this->l10nFactory = $l10nFactory; diff --git a/lib/private/Lock/AbstractLockingProvider.php b/lib/private/Lock/AbstractLockingProvider.php index 3234311c2a6e..2a8bbfe8ce4c 100644 --- a/lib/private/Lock/AbstractLockingProvider.php +++ b/lib/private/Lock/AbstractLockingProvider.php @@ -126,6 +126,6 @@ public function releaseAll() { } protected function getOwnSharedLockCount($path) { - return isset($this->acquiredLocks['shared'][$path]) ? $this->acquiredLocks['shared'][$path] : 0; + return $this->acquiredLocks['shared'][$path] ?? 0; } } diff --git a/lib/private/Lock/DBLockingProvider.php b/lib/private/Lock/DBLockingProvider.php index 470b4f7cf248..ce6f34ff2d72 100644 --- a/lib/private/Lock/DBLockingProvider.php +++ b/lib/private/Lock/DBLockingProvider.php @@ -38,20 +38,11 @@ * Locking provider that stores the locks in the database */ class DBLockingProvider extends AbstractLockingProvider { - /** - * @var \OCP\IDBConnection - */ - private $connection; + private \OCP\IDBConnection $connection; - /** - * @var \OCP\ILogger - */ - private $logger; + private \OCP\ILogger $logger; - /** - * @var \OCP\AppFramework\Utility\ITimeFactory - */ - private $timeFactory; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; private $sharedLocks = []; @@ -287,9 +278,7 @@ public function releaseAll() { // since we keep shared locks we need to manually clean those $lockedPaths = \array_keys($this->sharedLocks); - $lockedPaths = \array_filter($lockedPaths, function ($path) { - return $this->sharedLocks[$path]; - }); + $lockedPaths = \array_filter($lockedPaths, fn ($path) => $this->sharedLocks[$path]); $chunkedPaths = \array_chunk($lockedPaths, 100); diff --git a/lib/private/Lock/MemcacheLockingProvider.php b/lib/private/Lock/MemcacheLockingProvider.php index 27bd5b66f372..c0ff26728830 100644 --- a/lib/private/Lock/MemcacheLockingProvider.php +++ b/lib/private/Lock/MemcacheLockingProvider.php @@ -27,10 +27,7 @@ use OCP\IMemcache; class MemcacheLockingProvider extends AbstractLockingProvider { - /** - * @var \OCP\IMemcache - */ - private $memcache; + private \OCP\IMemcache $memcache; /** * @param \OCP\IMemcache $memcache diff --git a/lib/private/Lock/Persistent/LockManager.php b/lib/private/Lock/Persistent/LockManager.php index 3a7c7ed6fdde..37761421ae16 100644 --- a/lib/private/Lock/Persistent/LockManager.php +++ b/lib/private/Lock/Persistent/LockManager.php @@ -27,14 +27,10 @@ class LockManager { public const LOCK_TIMEOUT_DEFAULT = 30 * 60; // default 30 minutes public const LOCK_TIMEOUT_MAX = 24 * 60 * 60; // max 1 day - /** @var LockMapper */ - private $lockMapper; - /** @var IUserSession */ - private $userSession; - /** @var ITimeFactory */ - private $timeFactory; - /** @var IConfig */ - private $config; + private \OC\Lock\Persistent\LockMapper $lockMapper; + private \OCP\IUserSession $userSession; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; + private \OCP\IConfig $config; public function __construct( LockMapper $lockMapper, @@ -73,7 +69,7 @@ public function lock($storageId, $internalPath, $fileId, array $lockInfo) { $timeout = $maxTimeout; } - $owner = isset($lockInfo['owner']) ? $lockInfo['owner'] : null; + $owner = $lockInfo['owner'] ?? null; if ($owner === null && $this->userSession->isLoggedIn()) { $user = $this->userSession->getUser(); if ($user !== null) { diff --git a/lib/private/Lock/Persistent/LockMapper.php b/lib/private/Lock/Persistent/LockMapper.php index c4e1f27e8fb4..510fbf11862d 100644 --- a/lib/private/Lock/Persistent/LockMapper.php +++ b/lib/private/Lock/Persistent/LockMapper.php @@ -27,8 +27,7 @@ use OCP\Lock\Persistent\ILock; class LockMapper extends Mapper { - /** @var ITimeFactory */ - private $timeFactory; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; public function __construct(IDBConnection $db, ITimeFactory $timeFactory) { parent::__construct($db, 'persistent_locks', null); diff --git a/lib/private/Log.php b/lib/private/Log.php index 6739d7c09088..cb8301127f98 100644 --- a/lib/private/Log.php +++ b/lib/private/Log.php @@ -61,17 +61,15 @@ class Log implements ILogger { private $eventDispatcher; /** @var boolean|null cache the result of the log condition check for the request */ - private $logConditionSatisfied; + private ?bool $logConditionSatisfied = null; /** @var Normalizer */ private $normalizer; /** - * Flag whether we are within the event block - * - * @var bool - */ - private $inEvent = false; + * Flag whether we are within the event block + */ + private bool $inEvent = false; protected static $methodsWithSensitiveParameters = [ // Session/User @@ -442,8 +440,8 @@ public function logException($exception, array $context = []) { if (\OC::$server->getUserSession() && \OC::$server->getUserSession()->isLoggedIn()) { $context['userid'] = \OC::$server->getUserSession()->getUser()->getUID(); } - $msg = isset($context['message']) ? $context['message'] : 'Exception'; - $msg .= ': ' . \json_encode($exception); + $msg = $context['message'] ?? 'Exception'; + $msg .= ': ' . \json_encode($exception, JSON_THROW_ON_ERROR); $this->log($level, $msg, $context); // also log previous exception if ($context['exception']->getPrevious()) { diff --git a/lib/private/Log/CommandLogger.php b/lib/private/Log/CommandLogger.php index 606410311ac1..3a9343de4d8a 100644 --- a/lib/private/Log/CommandLogger.php +++ b/lib/private/Log/CommandLogger.php @@ -26,8 +26,7 @@ use Symfony\Component\Console\Output\OutputInterface; class CommandLogger implements ILogger { - /** @var OutputInterface */ - private $output; + private \Symfony\Component\Console\Output\OutputInterface $output; /** * CommandLogger constructor. @@ -196,8 +195,8 @@ public function logException($exception, array $context = []) { 'Line' => $exception->getLine(), ]; $exception['Trace'] = \preg_replace('!(login|checkPassword|updatePrivateKeyPassword)\(.*\)!', '$1(*** username and password replaced ***)', $exception['Trace']); - $msg = isset($context['message']) ? $context['message'] : 'Exception'; - $msg .= ': ' . \json_encode($exception); + $msg = $context['message'] ?? 'Exception'; + $msg .= ': ' . \json_encode($exception, JSON_THROW_ON_ERROR); $this->error($msg, $context); } } diff --git a/lib/private/Log/ErrorHandler.php b/lib/private/Log/ErrorHandler.php index 7c0075cc786d..6dcb8d85f110 100644 --- a/lib/private/Log/ErrorHandler.php +++ b/lib/private/Log/ErrorHandler.php @@ -27,8 +27,7 @@ use OCP\ILogger; class ErrorHandler { - /** @var ILogger */ - private static $logger; + private static ?\OCP\ILogger $logger = null; /** * remove password in URLs diff --git a/lib/private/Log/Owncloud.php b/lib/private/Log/Owncloud.php index 54f21dadde46..1d2dd41a023b 100644 --- a/lib/private/Log/Owncloud.php +++ b/lib/private/Log/Owncloud.php @@ -93,7 +93,7 @@ public static function writeExtra($app, $message, $level, $conditionalLogFile, $ $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--'; $method = \is_string($request->getMethod()) ? $request->getMethod() : '--'; if (\OC::$server->getConfig()->getSystemValue('installed', false)) { - $user = (\OC_User::getUser()) ? \OC_User::getUser() : '--'; + $user = \OC_User::getUser() ?: '--'; } else { $user = '--'; } @@ -114,7 +114,7 @@ public static function writeExtra($app, $message, $level, $conditionalLogFile, $ $entry = \array_merge($entry, $extraFields); } - $entry = \json_encode($entry); + $entry = \json_encode($entry, JSON_THROW_ON_ERROR); if ($conditionalLogFile !== null) { if ($conditionalLogFile[0] !== '/') { $conditionalLogFile = \OC::$server->getConfig()->getSystemValue('datadirectory') . "/" . $conditionalLogFile; diff --git a/lib/private/Log/Rotate.php b/lib/private/Log/Rotate.php index d10c0b383922..61238b0bd8ba 100644 --- a/lib/private/Log/Rotate.php +++ b/lib/private/Log/Rotate.php @@ -45,6 +45,6 @@ protected function rotate($logfile) { $rotatedLogfile = $logfile.'.1'; \rename($logfile, $rotatedLogfile); $msg = 'Log file "'.$logfile.'" was over '.$this->max_log_size.' bytes, moved to "'.$rotatedLogfile.'"'; - \OCP\Util::writeLog('OC\Log\Rotate', $msg, \OCP\Util::WARN); + \OCP\Util::writeLog(\OC\Log\Rotate::class, $msg, \OCP\Util::WARN); } } diff --git a/lib/private/Log/Syslog.php b/lib/private/Log/Syslog.php index de96f7dbf64a..238caff51260 100644 --- a/lib/private/Log/Syslog.php +++ b/lib/private/Log/Syslog.php @@ -57,7 +57,7 @@ public static function write($app, $message, $level) { $request = \OC::$server->getRequest(); if (\OC::$server->getConfig()->getSystemValue('installed', false)) { - $user = (\OC_User::getUser()) ? \OC_User::getUser() : '--'; + $user = \OC_User::getUser() ?: '--'; } else { $user = '--'; } diff --git a/lib/private/Mail/Mailer.php b/lib/private/Mail/Mailer.php index 62b33d89f22d..7235c72466f9 100644 --- a/lib/private/Mail/Mailer.php +++ b/lib/private/Mail/Mailer.php @@ -48,12 +48,9 @@ class Mailer implements IMailer { /** @var \Swift_SmtpTransport|\Swift_SendmailTransport Cached transport */ private $instance = null; - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; - /** @var \OC_Defaults */ - private $defaults; + private \OCP\IConfig $config; + private \OCP\ILogger $logger; + private \OC_Defaults $defaults; /** * @param IConfig $config @@ -117,8 +114,8 @@ public function send(Message $message) { $logMessage = 'Sent mail from "{from}" to "{recipients}" with subject "{subject}"'; $this->logger->debug($logMessage, [ 'app' => 'core', - 'from' => \json_encode($message->getFrom()), - 'recipients' => \json_encode($allRecipients), + 'from' => \json_encode($message->getFrom(), JSON_THROW_ON_ERROR), + 'recipients' => \json_encode($allRecipients, JSON_THROW_ON_ERROR), 'subject' => $message->getSubject() ]); @@ -149,7 +146,7 @@ protected function convertEmail($email) { return $email; } - list($name, $domain) = \explode('@', $email, 2); + [$name, $domain] = \explode('@', $email, 2); if (\defined('INTL_IDNA_VARIANT_UTS46')) { $domain = \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); } else { diff --git a/lib/private/Mail/Message.php b/lib/private/Mail/Message.php index 12633ff76ad6..a854977e0265 100644 --- a/lib/private/Mail/Message.php +++ b/lib/private/Mail/Message.php @@ -30,8 +30,7 @@ * @package OC\Mail */ class Message { - /** @var Swift_Message */ - private $swiftMessage; + private \Swift_Message $swiftMessage; /** * @param Swift_Message $swiftMessage @@ -56,7 +55,7 @@ protected function convertAddresses($addresses) { foreach ($addresses as $email => $readableName) { if (!\is_numeric($email)) { - list($name, $domain) = \explode('@', $email, 2); + [$name, $domain] = \explode('@', $email, 2); if (\defined('INTL_IDNA_VARIANT_UTS46')) { $domain = \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); } else { @@ -64,7 +63,7 @@ protected function convertAddresses($addresses) { } $convertedAddresses[$name.'@'.$domain] = $readableName; } else { - list($name, $domain) = \explode('@', $readableName, 2); + [$name, $domain] = \explode('@', $readableName, 2); if (\defined('INTL_IDNA_VARIANT_UTS46')) { $domain = \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); } else { diff --git a/lib/private/Memcache/Factory.php b/lib/private/Memcache/Factory.php index 5e490486f221..914df371f03e 100644 --- a/lib/private/Memcache/Factory.php +++ b/lib/private/Memcache/Factory.php @@ -40,10 +40,7 @@ class Factory implements ICacheFactory { */ private $globalPrefix; - /** - * @var ILogger $logger - */ - private $logger; + private \OCP\ILogger $logger; /** * @var string $localCacheClass diff --git a/lib/private/Memcache/Memcached.php b/lib/private/Memcache/Memcached.php index 5d80de578af6..1460a279dd19 100644 --- a/lib/private/Memcache/Memcached.php +++ b/lib/private/Memcache/Memcached.php @@ -35,10 +35,7 @@ class Memcached extends Cache implements IMemcache { use CASTrait; - /** - * @var \Memcached $cache - */ - private static $cache = null; + private static ?\Memcached $cache = null; use CADTrait; diff --git a/lib/private/Memcache/Redis.php b/lib/private/Memcache/Redis.php index d92bc5941221..2b21215afccc 100644 --- a/lib/private/Memcache/Redis.php +++ b/lib/private/Memcache/Redis.php @@ -50,15 +50,15 @@ public function get($key) { if ($result === false && !self::$cache->exists($this->getNameSpace() . $key)) { return null; } else { - return \json_decode($result, true); + return \json_decode($result, true, 512, JSON_THROW_ON_ERROR); } } public function set($key, $value, $ttl = 0) { if ($ttl > 0) { - return self::$cache->setex($this->getNameSpace() . $key, $ttl, \json_encode($value)); + return self::$cache->setex($this->getNameSpace() . $key, $ttl, \json_encode($value, JSON_THROW_ON_ERROR)); } else { - return self::$cache->set($this->getNameSpace() . $key, \json_encode($value)); + return self::$cache->set($this->getNameSpace() . $key, \json_encode($value, JSON_THROW_ON_ERROR)); } } @@ -95,7 +95,7 @@ public function clear($prefix = '') { public function add($key, $value, $ttl = 0) { // don't encode ints for inc/dec if (!\is_int($value)) { - $value = \json_encode($value); + $value = \json_encode($value, JSON_THROW_ON_ERROR); } return self::$cache->setnx($this->getPrefix() . $key, $value); } @@ -135,7 +135,7 @@ public function dec($key, $step = 1) { */ public function cas($key, $old, $new) { if (!\is_int($new)) { - $new = \json_encode($new); + $new = \json_encode($new, JSON_THROW_ON_ERROR); } self::$cache->watch($this->getNameSpace() . $key); if ($this->get($key) === $old) { diff --git a/lib/private/Migration/BackgroundRepair.php b/lib/private/Migration/BackgroundRepair.php index e0786cd5f792..f8e437e74278 100644 --- a/lib/private/Migration/BackgroundRepair.php +++ b/lib/private/Migration/BackgroundRepair.php @@ -38,11 +38,9 @@ class BackgroundRepair extends TimedJob { /** @var IJobList */ private $jobList; - /** @var ILogger */ - private $logger; + private ?\OCP\ILogger $logger = null; - /** @var EventDispatcher */ - private $dispatcher; + private ?\Symfony\Component\EventDispatcher\EventDispatcher $dispatcher = null; public function setDispatcher(EventDispatcher $dispatcher) { $this->dispatcher = $dispatcher; diff --git a/lib/private/Migration/ConsoleOutput.php b/lib/private/Migration/ConsoleOutput.php index be7ee89efec6..72bd8ca3b3ee 100644 --- a/lib/private/Migration/ConsoleOutput.php +++ b/lib/private/Migration/ConsoleOutput.php @@ -34,11 +34,9 @@ * @package OC\Migration */ class ConsoleOutput implements IOutput { - /** @var OutputInterface */ - private $output; + private \Symfony\Component\Console\Output\OutputInterface $output; - /** @var ProgressBar */ - private $progressBar; + private ?\Symfony\Component\Console\Helper\ProgressBar $progressBar = null; public function __construct(OutputInterface $output) { $this->output = $output; diff --git a/lib/private/Migration/SimpleOutput.php b/lib/private/Migration/SimpleOutput.php index fadea9b8ee96..8211422aa972 100644 --- a/lib/private/Migration/SimpleOutput.php +++ b/lib/private/Migration/SimpleOutput.php @@ -33,8 +33,7 @@ * @package OC\Migration */ class SimpleOutput implements IOutput { - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; private $appName; public function __construct(ILogger $logger, $appName) { diff --git a/lib/private/NaturalSort.php b/lib/private/NaturalSort.php index 4153a331b0be..be3d6be22fbf 100644 --- a/lib/private/NaturalSort.php +++ b/lib/private/NaturalSort.php @@ -27,9 +27,9 @@ namespace OC; class NaturalSort { - private static $instance; + private static ?\OC\NaturalSort $instance = null; private $collator; - private $cache = []; + private array $cache = []; /** * Instantiate a new \OC\NaturalSort instance. diff --git a/lib/private/NavigationManager.php b/lib/private/NavigationManager.php index ecc1d6a0ed1e..2b26c5914a77 100644 --- a/lib/private/NavigationManager.php +++ b/lib/private/NavigationManager.php @@ -44,16 +44,11 @@ class NavigationManager implements INavigationManager { protected $init = false; /** @var IAppManager */ protected $appManager; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var IFactory */ - private $l10nFac; - /** @var IUserSession */ - private $userSession; - /** @var IGroupManager */ - private $groupManager; - /** @var IConfig */ - private $config; + private ?\OCP\IURLGenerator $urlGenerator = null; + private ?\OCP\L10N\IFactory $l10nFac = null; + private ?\OCP\IUserSession $userSession = null; + private ?\OCP\IGroupManager $groupManager = null; + private ?\OCP\IConfig $config = null; public function __construct( IAppManager $appManager = null, @@ -152,12 +147,12 @@ private function init() { if (!isset($nav['route']) && !isset($nav['static'])) { continue; } - $role = isset($nav['@attributes']['role']) ? $nav['@attributes']['role'] : 'all'; + $role = $nav['@attributes']['role'] ?? 'all'; if ($role === 'admin' && !$this->isAdmin()) { continue; } $l = $this->l10nFac->get($app); - $order = isset($nav['order']) ? $nav['order'] : 100; + $order = $nav['order'] ?? 100; if (isset($nav['route'])) { $route = $this->urlGenerator->linkToRoute($nav['route']); } else { @@ -167,8 +162,8 @@ private function init() { } $route = $this->urlGenerator->linkTo($app, $html); } - $name = isset($nav['name']) ? $nav['name'] : \ucfirst($app); - $icon = isset($nav['icon']) ? $nav['icon'] : 'app.svg'; + $name = $nav['name'] ?? \ucfirst($app); + $icon = $nav['icon'] ?? 'app.svg'; $iconPath = null; foreach ([$icon, "$app.svg"] as $i) { try { diff --git a/lib/private/Notification/Events/RegisterConsumerEventImpl.php b/lib/private/Notification/Events/RegisterConsumerEventImpl.php index f39839a7e202..e428f449c68a 100644 --- a/lib/private/Notification/Events/RegisterConsumerEventImpl.php +++ b/lib/private/Notification/Events/RegisterConsumerEventImpl.php @@ -34,8 +34,7 @@ * while hiding the implementation details. */ class RegisterConsumerEventImpl extends RegisterConsumerEvent { - /** @var Manager */ - private $manager; + private \OC\Notification\Manager $manager; public function __construct(Manager $manager) { $this->manager = $manager; diff --git a/lib/private/Notification/Events/RegisterNotifierEventImpl.php b/lib/private/Notification/Events/RegisterNotifierEventImpl.php index f3fc1915a829..aa46dd04f0a2 100644 --- a/lib/private/Notification/Events/RegisterNotifierEventImpl.php +++ b/lib/private/Notification/Events/RegisterNotifierEventImpl.php @@ -37,8 +37,7 @@ * several instances are used. */ class RegisterNotifierEventImpl extends RegisterNotifierEvent { - /** @var Manager */ - private $manager; + private \OC\Notification\Manager $manager; public function __construct(Manager $manager) { $this->manager = $manager; diff --git a/lib/private/OCS/Exception.php b/lib/private/OCS/Exception.php index 957c795f5fe6..337d95d262cf 100644 --- a/lib/private/OCS/Exception.php +++ b/lib/private/OCS/Exception.php @@ -23,8 +23,7 @@ namespace OC\OCS; class Exception extends \Exception { - /** @var Result */ - private $result; + private \OC\OCS\Result $result; public function __construct(Result $result) { parent::__construct(); diff --git a/lib/private/OCS/Provider.php b/lib/private/OCS/Provider.php index 72ba9b4a4d2b..317287267eda 100644 --- a/lib/private/OCS/Provider.php +++ b/lib/private/OCS/Provider.php @@ -23,8 +23,7 @@ namespace OC\OCS; class Provider extends \OCP\AppFramework\Controller { - /** @var \OCP\App\IAppManager */ - private $appManager; + private \OCP\App\IAppManager $appManager; /** * @param string $appName diff --git a/lib/private/OCS/Result.php b/lib/private/OCS/Result.php index d0aeb506316b..ad8bad04bd72 100644 --- a/lib/private/OCS/Result.php +++ b/lib/private/OCS/Result.php @@ -45,8 +45,7 @@ class Result { /** @var integer */ protected $perPage; - /** @var array */ - private $headers = []; + private array $headers = []; /** * create the OCS_Result object diff --git a/lib/private/Preview.php b/lib/private/Preview.php index e9641e7b6e97..e5ae35a06cb3 100644 --- a/lib/private/Preview.php +++ b/lib/private/Preview.php @@ -58,17 +58,16 @@ class Preview { private $configMaxHeight; //fileview object - private $userView; + private \OC\Files\View $userView; //vars - /** @var Node | null */ - private $file; + private ?\OCP\Files\Node $file = null; private $maxX; private $maxY; private $scalingUp; private $mimeType; - private $keepAspect = false; - private $mode = self::MODE_FILL; + private bool $keepAspect = false; + private string $mode = self::MODE_FILL; //used to calculate the size of the preview to generate /** @var int $maxPreviewWidth max width a preview can have */ @@ -398,7 +397,7 @@ public function isCached() { $previewPath = $this->getPreviewPath(); // We currently can't look for a single file due to bugs related to #16478 $allThumbnails = $this->userView->getDirectoryContent($previewPath); - list($maxPreviewWidth, $maxPreviewHeight) = $this->getMaxPreviewSize($allThumbnails); + [$maxPreviewWidth, $maxPreviewHeight] = $this->getMaxPreviewSize($allThumbnails); // Only use the cache if we have a max preview if ($maxPreviewWidth !== null && $maxPreviewHeight !== null) { @@ -408,7 +407,7 @@ public function isCached() { $this->maxPreviewWidth = $maxPreviewWidth; $this->maxPreviewHeight = $maxPreviewHeight; - list($previewWidth, $previewHeight) = $this->simulatePreviewDimensions(); + [$previewWidth, $previewHeight] = $this->simulatePreviewDimensions(); if (empty($previewWidth) || empty($previewHeight)) { return false; } @@ -461,7 +460,7 @@ private function getMaxPreviewSize($allThumbnails) { foreach ($allThumbnails as $thumbnail) { $name = $thumbnail['name']; if (\strpos($name, 'max')) { - list($maxPreviewX, $maxPreviewY) = $this->getDimensionsFromFilename($name); + [$maxPreviewX, $maxPreviewY] = $this->getDimensionsFromFilename($name); break; } } @@ -496,10 +495,10 @@ private function simulatePreviewDimensions() { $askedHeight = $this->getMaxY(); if ($this->keepAspect) { - list($newPreviewWidth, $newPreviewHeight) = + [$newPreviewWidth, $newPreviewHeight] = $this->applyAspectRatio($askedWidth, $askedHeight); } else { - list($newPreviewWidth, $newPreviewHeight) = $this->fixSize($askedWidth, $askedHeight); + [$newPreviewWidth, $newPreviewHeight] = $this->fixSize($askedWidth, $askedHeight); } return [(int)$newPreviewWidth, (int)$newPreviewHeight]; @@ -627,7 +626,7 @@ private function getPossibleThumbnails($allThumbnails) { $possibleThumbnails = []; foreach ($allThumbnails as $thumbnail) { $name = \rtrim($thumbnail['name'], '.png'); - list($x, $y, $aspectRatio) = $this->getDimensionsFromFilename($name); + [$x, $y, $aspectRatio] = $this->getDimensionsFromFilename($name); if (\abs($aspectRatio - $wantedAspectRatio) >= 0.000001 || $this->unscalable($x, $y) ) { @@ -824,7 +823,7 @@ private function resizeAndStore() { $askedHeight = $this->getMaxY(); if ($this->mode === self::MODE_COVER) { - list($askedWidth, $askedHeight) = + [$askedWidth, $askedHeight] = $this->applyCover($askedWidth, $askedHeight, $previewWidth, $previewHeight); } @@ -832,7 +831,7 @@ private function resizeAndStore() { * Phase 1: If required, adjust boundaries to keep aspect ratio */ if ($this->keepAspect) { - list($askedWidth, $askedHeight) = + [$askedWidth, $askedHeight] = $this->applyAspectRatio($askedWidth, $askedHeight, $previewWidth, $previewHeight); } @@ -840,7 +839,7 @@ private function resizeAndStore() { * Phase 2: Resizes preview to try and match requirements. * Takes the scaling ratio into consideration */ - list($newPreviewWidth, $newPreviewHeight) = $this->scale( + [$newPreviewWidth, $newPreviewHeight] = $this->scale( $image, $askedWidth, $askedHeight, diff --git a/lib/private/Preview/Bitmap.php b/lib/private/Preview/Bitmap.php index 325be7717d42..756c67e51014 100644 --- a/lib/private/Preview/Bitmap.php +++ b/lib/private/Preview/Bitmap.php @@ -105,7 +105,7 @@ private function getResizedPreview($stream, $maxX, $maxY) { * @return \Imagick */ private function resize($bp, $maxX, $maxY) { - list($previewWidth, $previewHeight) = \array_values($bp->getImageGeometry()); + [$previewWidth, $previewHeight] = \array_values($bp->getImageGeometry()); // We only need to resize a preview which doesn't fit in the maximum dimensions if ($previewWidth > $maxX || $previewHeight > $maxY) { diff --git a/lib/private/Preview/MP3.php b/lib/private/Preview/MP3.php index b925ed21389e..64c51ff4d2ed 100644 --- a/lib/private/Preview/MP3.php +++ b/lib/private/Preview/MP3.php @@ -56,7 +56,7 @@ public function getThumbnail(File $file, $maxX, $maxY, $scalingUp) { $getID3 = new ID3Parser(); $tags = $getID3->analyze($absPath); - $picture = isset($tags['id3v2']['APIC'][0]['data']) ? $tags['id3v2']['APIC'][0]['data'] : null; + $picture = $tags['id3v2']['APIC'][0]['data'] ?? null; if ($picture === null && isset($tags['id3v2']['PIC'][0]['data'])) { $picture = $tags['id3v2']['PIC'][0]['data']; } diff --git a/lib/private/Preview/Movie.php b/lib/private/Preview/Movie.php index e2fdca32b8ee..419747e6b691 100644 --- a/lib/private/Preview/Movie.php +++ b/lib/private/Preview/Movie.php @@ -35,10 +35,9 @@ class Movie implements IProvider2 { public static $atomicParsleyBinary; /** - * Keep track of movies without artwork to avoid retries in same request - * @var array - */ - private $noArtworkIndex = []; + * Keep track of movies without artwork to avoid retries in same request + */ + private array $noArtworkIndex = []; /** * {@inheritDoc} @@ -63,7 +62,7 @@ public function getThumbnail(File $file, $maxX, $maxY, $scalingUp) { // we better use 5MB (1024 * 1024 * 5 = 5242880) instead of 1MB. // in some cases 1MB was no enough to generate thumbnail - $firstmb = \stream_get_contents($handle, 5242880); + $firstmb = \stream_get_contents($handle, 5_242_880); \file_put_contents($absPath, $firstmb); \fclose($handle); } diff --git a/lib/private/Preview/TXT.php b/lib/private/Preview/TXT.php index 1764c4dbe3dd..44ae5af82744 100644 --- a/lib/private/Preview/TXT.php +++ b/lib/private/Preview/TXT.php @@ -31,7 +31,7 @@ use OC\Utf8Analyzer; class TXT implements IProvider2 { - private $utf8Analyzer; + private \OC\Utf8Analyzer $utf8Analyzer; public function __construct() { $this->utf8Analyzer = new Utf8Analyzer(); diff --git a/lib/private/PreviewCleanup.php b/lib/private/PreviewCleanup.php index bbf586264cb7..902e2ceb3586 100644 --- a/lib/private/PreviewCleanup.php +++ b/lib/private/PreviewCleanup.php @@ -27,10 +27,7 @@ use OCP\DB\QueryBuilder\IQueryBuilder; class PreviewCleanup { - /** - * @var IDBConnection - */ - private $connection; + private \OCP\IDBConnection $connection; public function __construct(IDBConnection $connection) { $this->connection = $connection; diff --git a/lib/private/PreviewManager.php b/lib/private/PreviewManager.php index a21f1a12d6fe..ce4c59f8223e 100644 --- a/lib/private/PreviewManager.php +++ b/lib/private/PreviewManager.php @@ -54,11 +54,9 @@ class PreviewManager implements IPreview { /** @var array */ protected $defaultProviders; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; - /** @var IUserSession */ - private $userSession; + private \OCP\IUserSession $userSession; /** * Constructor @@ -264,23 +262,19 @@ protected function getEnabledDefaultProvider() { } $imageProviders = [ - 'OC\Preview\PNG', - 'OC\Preview\JPEG', - 'OC\Preview\WEBP', - 'OC\Preview\GIF', - 'OC\Preview\BMP', - 'OC\Preview\Heic', - 'OC\Preview\XBitmap', - 'OC\Preview\SGI', + \OC\Preview\PNG::class, + \OC\Preview\JPEG::class, + \OC\Preview\WEBP::class, + \OC\Preview\GIF::class, + \OC\Preview\BMP::class, + \OC\Preview\Heic::class, + \OC\Preview\XBitmap::class, + \OC\Preview\SGI::class, ]; - $this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', \array_merge([ - 'OC\Preview\MarkDown', - 'OC\Preview\MP3', - 'OC\Preview\TXT', - ], $imageProviders)); + $this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', [\OC\Preview\MarkDown::class, \OC\Preview\MP3::class, \OC\Preview\TXT::class, ...$imageProviders]); - if (\in_array('OC\Preview\Image', $this->defaultProviders)) { + if (\in_array(\OC\Preview\Image::class, $this->defaultProviders)) { $this->defaultProviders = \array_merge($this->defaultProviders, $imageProviders); } $this->defaultProviders = \array_unique($this->defaultProviders); @@ -295,9 +289,7 @@ protected function getEnabledDefaultProvider() { */ protected function registerCoreProvider($class, $mimeType, $options = []) { if (\in_array(\trim($class, '\\'), $this->getEnabledDefaultProvider())) { - $this->registerProvider($mimeType, function () use ($class, $options) { - return new $class($options); - }); + $this->registerProvider($mimeType, fn () => new $class($options)); } } @@ -310,15 +302,15 @@ protected function registerCoreProviders() { } $this->registeredCoreProviders = true; - $this->registerCoreProvider('OC\Preview\TXT', '/text\/plain/'); - $this->registerCoreProvider('OC\Preview\MarkDown', '/text\/(x-)?markdown/'); - $this->registerCoreProvider('OC\Preview\PNG', '/image\/png/'); - $this->registerCoreProvider('OC\Preview\JPEG', '/image\/jpeg/'); - $this->registerCoreProvider('OC\Preview\WEBP', '/image\/webp/'); - $this->registerCoreProvider('OC\Preview\GIF', '/image\/gif/'); - $this->registerCoreProvider('OC\Preview\BMP', '/image\/bmp/'); - $this->registerCoreProvider('OC\Preview\XBitmap', '/image\/x-xbitmap/'); - $this->registerCoreProvider('OC\Preview\MP3', '/audio\/mpeg/'); + $this->registerCoreProvider(\OC\Preview\TXT::class, '/text\/plain/'); + $this->registerCoreProvider(\OC\Preview\MarkDown::class, '/text\/(x-)?markdown/'); + $this->registerCoreProvider(\OC\Preview\PNG::class, '/image\/png/'); + $this->registerCoreProvider(\OC\Preview\JPEG::class, '/image\/jpeg/'); + $this->registerCoreProvider(\OC\Preview\WEBP::class, '/image\/webp/'); + $this->registerCoreProvider(\OC\Preview\GIF::class, '/image\/gif/'); + $this->registerCoreProvider(\OC\Preview\BMP::class, '/image\/bmp/'); + $this->registerCoreProvider(\OC\Preview\XBitmap::class, '/image\/x-xbitmap/'); + $this->registerCoreProvider(\OC\Preview\MP3::class, '/audio\/mpeg/'); // SVG, Office and Bitmap require imagick // Either use the additional library mentioned below when using imagick 6, or use imagick 7 @@ -330,16 +322,16 @@ protected function registerCoreProviders() { $checkImagick = new \Imagick(); $imagickProviders = [ - 'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => '\OC\Preview\SVG'], - 'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => '\OC\Preview\TIFF'], - 'PDF' => ['mimetype' => '/application\/pdf/', 'class' => '\OC\Preview\PDF'], - 'AI' => ['mimetype' => '/application\/illustrator/', 'class' => '\OC\Preview\Illustrator'], - 'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => '\OC\Preview\Photoshop'], - 'EPS' => ['mimetype' => '/application\/postscript/', 'class' => '\OC\Preview\Postscript'], - 'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => '\OC\Preview\Font'], - 'HEIF' => ['mimetype' => '/image\/heif/', 'class' => '\OC\Preview\Heic'], - 'HEIC' => ['mimetype' => '/image\/heic/', 'class' => '\OC\Preview\Heic'], - 'SGI' => ['mimetype' => '/image\/sgi/', 'class' => '\OC\Preview\SGI'], + 'SVG' => ['mimetype' => '/image\/svg\+xml/', 'class' => '\\' . \OC\Preview\SVG::class], + 'TIFF' => ['mimetype' => '/image\/tiff/', 'class' => '\\' . \OC\Preview\TIFF::class], + 'PDF' => ['mimetype' => '/application\/pdf/', 'class' => '\\' . \OC\Preview\PDF::class], + 'AI' => ['mimetype' => '/application\/illustrator/', 'class' => '\\' . \OC\Preview\Illustrator::class], + 'PSD' => ['mimetype' => '/application\/x-photoshop/', 'class' => '\\' . \OC\Preview\Photoshop::class], + 'EPS' => ['mimetype' => '/application\/postscript/', 'class' => '\\' . \OC\Preview\Postscript::class], + 'TTF' => ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => '\\' . \OC\Preview\Font::class], + 'HEIF' => ['mimetype' => '/image\/heif/', 'class' => '\\' . \OC\Preview\Heic::class], + 'HEIC' => ['mimetype' => '/image\/heic/', 'class' => '\\' . \OC\Preview\Heic::class], + 'SGI' => ['mimetype' => '/image\/sgi/', 'class' => '\\' . \OC\Preview\SGI::class], ]; foreach ($imagickProviders as $queryFormat => $provider) { @@ -369,18 +361,18 @@ protected function registerCoreProviders() { } if ($officeFound) { - $this->registerCoreProvider('\OC\Preview\MSOfficeDoc', '/application\/msword/'); - $this->registerCoreProvider('\OC\Preview\MSOffice2003', '/application\/vnd.ms-.*/'); - $this->registerCoreProvider('\OC\Preview\MSOffice2007', '/application\/vnd.openxmlformats-officedocument.*/'); - $this->registerCoreProvider('\OC\Preview\OpenDocument', '/application\/vnd.oasis.opendocument.*/'); - $this->registerCoreProvider('\OC\Preview\StarOffice', '/application\/vnd.sun.xml.*/'); + $this->registerCoreProvider('\\' . \OC\Preview\MSOfficeDoc::class, '/application\/msword/'); + $this->registerCoreProvider('\\' . \OC\Preview\MSOffice2003::class, '/application\/vnd.ms-.*/'); + $this->registerCoreProvider('\\' . \OC\Preview\MSOffice2007::class, '/application\/vnd.openxmlformats-officedocument.*/'); + $this->registerCoreProvider('\\' . \OC\Preview\OpenDocument::class, '/application\/vnd.oasis.opendocument.*/'); + $this->registerCoreProvider('\\' . \OC\Preview\StarOffice::class, '/application\/vnd.sun.xml.*/'); } } } } // Video requires avconv or ffmpeg to be installed on the server - if (\in_array('OC\Preview\Movie', $this->getEnabledDefaultProvider())) { + if (\in_array(\OC\Preview\Movie::class, $this->getEnabledDefaultProvider())) { $avconvBinary = \OC_Helper::findBinaryPath('avconv'); $ffmpegBinary = ($avconvBinary) ? null : \OC_Helper::findBinaryPath('ffmpeg'); $atomicParsleyBinary = \OC_Helper::findBinaryPath('AtomicParsley'); @@ -400,7 +392,7 @@ protected function registerCoreProviders() { $registerProvider = true; } if ($registerProvider === true) { - $this->registerCoreProvider('\OC\Preview\Movie', '/video\/.*/'); + $this->registerCoreProvider('\\' . \OC\Preview\Movie::class, '/video\/.*/'); } } } diff --git a/lib/private/RedisFactory.php b/lib/private/RedisFactory.php index c76b2f0bd49d..6965e64eeefd 100644 --- a/lib/private/RedisFactory.php +++ b/lib/private/RedisFactory.php @@ -29,8 +29,7 @@ class RedisFactory { public const REDIS_MINIMAL_VERSION = '2.2.5'; public const REDIS_EXTRA_PARAMETERS_MINIMAL_VERSION = '5.3.0'; - /** @var SystemConfig */ - private $config; + private \OC\SystemConfig $config; /** * RedisFactory constructor. diff --git a/lib/private/Repair.php b/lib/private/Repair.php index dc5310a740dc..db9577822bb0 100644 --- a/lib/private/Repair.php +++ b/lib/private/Repair.php @@ -58,8 +58,7 @@ class Repair implements IOutput { /* @var IRepairStep[] */ private $repairSteps; - /** @var EventDispatcherInterface */ - private $dispatcher; + private ?\Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher = null; /** @var string */ private $currentStep; @@ -79,13 +78,13 @@ public function __construct($repairSteps = [], EventDispatcherInterface $dispatc */ public function run() { if (\count($this->repairSteps) === 0) { - $this->emit('\OC\Repair', 'info', ['No repair steps available']); + $this->emit('\\' . \OC\Repair::class, 'info', ['No repair steps available']); return; } // run each repair step foreach ($this->repairSteps as $step) { $this->currentStep = $step->getName(); - $this->emit('\OC\Repair', 'step', [$this->currentStep]); + $this->emit('\\' . \OC\Repair::class, 'step', [$this->currentStep]); $step->run($this); } } @@ -230,7 +229,7 @@ public function emit($scope, $method, array $arguments = []) { public function info($string) { // for now just emit as we did in the past - $this->emit('\OC\Repair', 'info', [$string]); + $this->emit('\\' . \OC\Repair::class, 'info', [$string]); } /** @@ -238,7 +237,7 @@ public function info($string) { */ public function warning($message) { // for now just emit as we did in the past - $this->emit('\OC\Repair', 'warning', [$message]); + $this->emit('\\' . \OC\Repair::class, 'warning', [$message]); } /** @@ -246,7 +245,7 @@ public function warning($message) { */ public function startProgress($max = 0) { // for now just emit as we did in the past - $this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]); + $this->emit('\\' . \OC\Repair::class, 'startProgress', [$max, $this->currentStep]); } /** @@ -255,7 +254,7 @@ public function startProgress($max = 0) { */ public function advance($step = 1, $description = '') { // for now just emit as we did in the past - $this->emit('\OC\Repair', 'advance', [$step, $description]); + $this->emit('\\' . \OC\Repair::class, 'advance', [$step, $description]); } /** @@ -263,6 +262,6 @@ public function advance($step = 1, $description = '') { */ public function finishProgress() { // for now just emit as we did in the past - $this->emit('\OC\Repair', 'finishProgress', []); + $this->emit('\\' . \OC\Repair::class, 'finishProgress', []); } } diff --git a/lib/private/Repair/Apps.php b/lib/private/Repair/Apps.php index 7f8ede37e174..897b06c88c16 100644 --- a/lib/private/Repair/Apps.php +++ b/lib/private/Repair/Apps.php @@ -43,17 +43,13 @@ class Apps implements IRepairStep { public const KEY_INCOMPATIBLE = 'incompatible'; public const KEY_MISSING = 'missing'; - /** @var IAppManager */ - private $appManager; + private \OCP\App\IAppManager $appManager; - /** @var EventDispatcherInterface */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var \OC_Defaults */ - private $defaults; + private \OC_Defaults $defaults; /** @var bool */ private $forceMajorUpgrade; @@ -247,16 +243,7 @@ protected function getAppsFromMarket(IOutput $output, $appList, $event) { ), \sprintf('%s::%s', IRepairStep::class, $event) ); - } catch (AppAlreadyInstalledException $e) { - $output->info($e->getMessage()); - $failedApps[] = $app; - } catch (AppNotInstalledException $e) { - $output->info($e->getMessage()); - $failedApps[] = $app; - } catch (AppNotFoundException $e) { - $output->info($e->getMessage()); - $failedApps[] = $app; - } catch (AppUpdateNotFoundException $e) { + } catch (AppAlreadyInstalledException|AppNotInstalledException|AppNotFoundException|AppUpdateNotFoundException $e) { $output->info($e->getMessage()); $failedApps[] = $app; } catch (AppManagerException $e) { @@ -304,9 +291,7 @@ protected function getOccDisableMessage($appList) { return ''; } $appList = \array_map( - function ($appId) { - return "occ app:disable $appId"; - }, + fn ($appId) => "occ app:disable $appId", $appList ); return "\n" . \implode("\n", $appList); diff --git a/lib/private/Repair/DisableExtraThemes.php b/lib/private/Repair/DisableExtraThemes.php index 6d6ca90f1c62..5bf2c78a1518 100644 --- a/lib/private/Repair/DisableExtraThemes.php +++ b/lib/private/Repair/DisableExtraThemes.php @@ -92,9 +92,7 @@ protected function getEnabledAppThemes() { $appTypes = $this->appConfig->getValues(false, 'types'); $allThemes = \array_filter( $appTypes, - function ($appTypes) { - return \in_array('theme', \explode(',', $appTypes)); - } + fn ($appTypes) => \in_array('theme', \explode(',', $appTypes)) ); // calculate an intersection to get enabled themes diff --git a/lib/private/Repair/MoveAvatarIntoSubFolder.php b/lib/private/Repair/MoveAvatarIntoSubFolder.php index 195d7b606f90..1980b39c7a68 100644 --- a/lib/private/Repair/MoveAvatarIntoSubFolder.php +++ b/lib/private/Repair/MoveAvatarIntoSubFolder.php @@ -46,23 +46,17 @@ class MoveAvatarIntoSubFolder implements IRepairStep { /** @var \OCP\IConfig */ protected $config; - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IAvatarManager */ - private $avatarManager; + private \OCP\IAvatarManager $avatarManager; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; - /** @var \OCP\ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var \OCP\IL10N */ - private $l; + private \OCP\IL10N $l; /** * @param IConfig $config config diff --git a/lib/private/Repair/MoveAvatarOutsideHome.php b/lib/private/Repair/MoveAvatarOutsideHome.php index 7f574b491e09..c2ac732ea4cf 100644 --- a/lib/private/Repair/MoveAvatarOutsideHome.php +++ b/lib/private/Repair/MoveAvatarOutsideHome.php @@ -47,23 +47,17 @@ class MoveAvatarOutsideHome implements IRepairStep { /** @var \OCP\IConfig */ protected $config; - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IAvatarManager */ - private $avatarManager; + private \OCP\IAvatarManager $avatarManager; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; - /** @var \OCP\ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var \OCP\IL10N */ - private $l; + private \OCP\IL10N $l; /** * @param IConfig $config config diff --git a/lib/private/Repair/RepairOrphanedSubshare.php b/lib/private/Repair/RepairOrphanedSubshare.php index e45f2368f11c..ed2490a9ae38 100644 --- a/lib/private/Repair/RepairOrphanedSubshare.php +++ b/lib/private/Repair/RepairOrphanedSubshare.php @@ -26,8 +26,7 @@ use OCP\Migration\IRepairStep; class RepairOrphanedSubshare implements IRepairStep { - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; /** * RepairOrphanedSubshare constructor. diff --git a/lib/private/Repair/RepairSubShares.php b/lib/private/Repair/RepairSubShares.php index ed8fdbfe1c1f..437b5dd817c7 100644 --- a/lib/private/Repair/RepairSubShares.php +++ b/lib/private/Repair/RepairSubShares.php @@ -27,8 +27,7 @@ use OCP\Migration\IRepairStep; class RepairSubShares implements IRepairStep { - /** @var IDBConnection */ - private $connection; + private \OCP\IDBConnection $connection; /** @var IQueryBuilder */ private $getDuplicateRows; @@ -101,9 +100,7 @@ public function run(IOutput $output) { $rowIds = []; if (\count($rows) > 0) { $rowIds = \array_map( - function ($value) { - return (int)$value['id']; - }, + fn ($value) => (int)$value['id'], $rows ); } diff --git a/lib/private/Repair/RepairUnmergedShares.php b/lib/private/Repair/RepairUnmergedShares.php index 48fa4a831559..62660ecb1193 100644 --- a/lib/private/Repair/RepairUnmergedShares.php +++ b/lib/private/Repair/RepairUnmergedShares.php @@ -171,9 +171,7 @@ private function isPotentialDuplicateName($name) { private function findBestTargetName($groupShares, $subShares) { $pickedShare = null; // sort by stime, this also properly sorts the direct user share if any - @\usort($subShares, function ($a, $b) { - return ((int)$a['stime'] - (int)$b['stime']); - }); + @\usort($subShares, fn ($a, $b) => (int)$a['stime'] - (int)$b['stime']); foreach ($subShares as $subShare) { // skip entries that have parenthesis with numbers diff --git a/lib/private/Repair/SharePropagation.php b/lib/private/Repair/SharePropagation.php index 62c98ecac97b..df41bfd50fe2 100644 --- a/lib/private/Repair/SharePropagation.php +++ b/lib/private/Repair/SharePropagation.php @@ -26,8 +26,7 @@ use OCP\Migration\IRepairStep; class SharePropagation implements IRepairStep { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** * SharePropagation constructor. diff --git a/lib/private/Route/CachingRouter.php b/lib/private/Route/CachingRouter.php index ad47e762b8df..4cb99fd862c6 100644 --- a/lib/private/Route/CachingRouter.php +++ b/lib/private/Route/CachingRouter.php @@ -52,7 +52,7 @@ public function __construct($cache, ILogger $logger) { */ public function generate($name, $parameters = [], $absolute = false) { \asort($parameters); - $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . \sha1(\json_encode($parameters)) . \intval($absolute); + $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . \sha1(\json_encode($parameters, JSON_THROW_ON_ERROR)) . \intval($absolute); $cachedKey = $this->cache->get($key); if ($cachedKey) { return $cachedKey; diff --git a/lib/private/Route/Router.php b/lib/private/Route/Router.php index cb7db6a4d30f..7ce890018eb6 100644 --- a/lib/private/Route/Router.php +++ b/lib/private/Route/Router.php @@ -258,14 +258,14 @@ public function create( public function match($url) { if (\substr($url, 0, 6) === '/apps/') { // empty string / 'apps' / $app / rest of the route - list(, , $app, ) = \explode('/', $url, 4); + [, , $app, ] = \explode('/', $url, 4); $app = \OC_App::cleanAppId($app); \OC::$REQUESTEDAPP = $app; $this->loadRoutes($app); } elseif (\substr($url, 0, 13) === '/ocsapp/apps/') { // empty string / 'ocsapp' / 'apps' / $app / rest of the route - list(, , , $app, ) = \explode('/', $url, 5); + [, , , $app, ] = \explode('/', $url, 5); $app = \OC_App::cleanAppId($app); \OC::$REQUESTEDAPP = $app; diff --git a/lib/private/Search.php b/lib/private/Search.php index bd87cb9b5b5d..ef6eafcb2713 100644 --- a/lib/private/Search.php +++ b/lib/private/Search.php @@ -95,9 +95,7 @@ public function clearProviders() { public function removeProvider($provider) { $this->registeredProviders = \array_filter( $this->registeredProviders, - function ($element) use ($provider) { - return ($element['class'] != $provider); - } + fn ($element) => $element['class'] != $provider ); // force regeneration of providers on next search $this->providers = []; diff --git a/lib/private/Search/Result/Audio.php b/lib/private/Search/Result/Audio.php index f42a0a963f69..f815726cc58d 100644 --- a/lib/private/Search/Result/Audio.php +++ b/lib/private/Search/Result/Audio.php @@ -32,7 +32,7 @@ class Audio extends File { * @var string */ public $type = 'audio'; - + /** * @TODO add ID3 information */ diff --git a/lib/private/Search/Result/Image.php b/lib/private/Search/Result/Image.php index 4205b7ede499..c5897c7aae31 100644 --- a/lib/private/Search/Result/Image.php +++ b/lib/private/Search/Result/Image.php @@ -32,7 +32,7 @@ class Image extends File { * @var string */ public $type = 'image'; - + /** * @TODO add EXIF information */ diff --git a/lib/private/Security/CSP/ContentSecurityPolicyManager.php b/lib/private/Security/CSP/ContentSecurityPolicyManager.php index 5e4a52fd30dd..485e5a8763ab 100644 --- a/lib/private/Security/CSP/ContentSecurityPolicyManager.php +++ b/lib/private/Security/CSP/ContentSecurityPolicyManager.php @@ -27,7 +27,7 @@ class ContentSecurityPolicyManager implements IContentSecurityPolicyManager { /** @var ContentSecurityPolicy[] */ - private $policies = []; + private array $policies = []; /** {@inheritdoc} */ public function addDefaultPolicy(EmptyContentSecurityPolicy $policy) { diff --git a/lib/private/Security/CSRF/CsrfTokenGenerator.php b/lib/private/Security/CSRF/CsrfTokenGenerator.php index ea279cfb62fb..d4d76959b88d 100644 --- a/lib/private/Security/CSRF/CsrfTokenGenerator.php +++ b/lib/private/Security/CSRF/CsrfTokenGenerator.php @@ -30,8 +30,7 @@ * @package OC\Security\CSRF */ class CsrfTokenGenerator { - /** @var ISecureRandom */ - private $random; + private \OCP\Security\ISecureRandom $random; /** * @param ISecureRandom $random diff --git a/lib/private/Security/CSRF/CsrfTokenManager.php b/lib/private/Security/CSRF/CsrfTokenManager.php index c0ad7d2a2f0a..69bbb82b87aa 100644 --- a/lib/private/Security/CSRF/CsrfTokenManager.php +++ b/lib/private/Security/CSRF/CsrfTokenManager.php @@ -29,10 +29,8 @@ * @package OC\Security\CSRF */ class CsrfTokenManager { - /** @var CsrfTokenGenerator */ - private $tokenGenerator; - /** @var SessionStorage */ - private $sessionStorage; + private \OC\Security\CSRF\CsrfTokenGenerator $tokenGenerator; + private \OC\Security\CSRF\TokenStorage\SessionStorage $sessionStorage; /** * @param CsrfTokenGenerator $tokenGenerator diff --git a/lib/private/Security/CSRF/TokenStorage/SessionStorage.php b/lib/private/Security/CSRF/TokenStorage/SessionStorage.php index 606f33790480..0636235ea5fc 100644 --- a/lib/private/Security/CSRF/TokenStorage/SessionStorage.php +++ b/lib/private/Security/CSRF/TokenStorage/SessionStorage.php @@ -29,8 +29,7 @@ * @package OC\Security\CSRF\TokenStorage */ class SessionStorage { - /** @var ISession */ - private $session; + private ?\OCP\ISession $session = null; /** * @param ISession $session diff --git a/lib/private/Security/Certificate.php b/lib/private/Security/Certificate.php index a2ab33adf789..d8a10d9e3e2f 100644 --- a/lib/private/Security/Certificate.php +++ b/lib/private/Security/Certificate.php @@ -62,12 +62,12 @@ public function __construct($data, $name) { throw new \Exception('Certificate could not get parsed.'); } - $this->commonName = isset($info['subject']['CN']) ? $info['subject']['CN'] : null; - $this->organization = isset($info['subject']['O']) ? $info['subject']['O'] : null; + $this->commonName = $info['subject']['CN'] ?? null; + $this->organization = $info['subject']['O'] ?? null; $this->issueDate = new \DateTime('@' . $info['validFrom_time_t'], $gmt); $this->expireDate = new \DateTime('@' . $info['validTo_time_t'], $gmt); - $this->issuerName = isset($info['issuer']['CN']) ? $info['issuer']['CN'] : null; - $this->issuerOrganization = isset($info['issuer']['O']) ? $info['issuer']['O'] : null; + $this->issuerName = $info['issuer']['CN'] ?? null; + $this->issuerOrganization = $info['issuer']['O'] ?? null; } /** diff --git a/lib/private/Security/CertificateManager.php b/lib/private/Security/CertificateManager.php index c9f7ded32311..623e40a4bab7 100644 --- a/lib/private/Security/CertificateManager.php +++ b/lib/private/Security/CertificateManager.php @@ -244,9 +244,7 @@ private function needsRebundling($uid = '') { $sourceBundles[] = $this->view->filemtime($this->getCertificateBundle(null)); } - $sourceMTime = \array_reduce($sourceMTimes, function ($max, $mtime) { - return \max($max, $mtime); - }, 0); + $sourceMTime = \array_reduce($sourceMTimes, fn ($max, $mtime) => \max($max, $mtime), 0); return $sourceMTime > $this->view->filemtime($targetBundle); } } diff --git a/lib/private/Security/CredentialsManager.php b/lib/private/Security/CredentialsManager.php index 4e77f9a9cb7c..a3c58b56607a 100644 --- a/lib/private/Security/CredentialsManager.php +++ b/lib/private/Security/CredentialsManager.php @@ -56,7 +56,7 @@ public function __construct(ICrypto $crypto, IDBConnection $dbConnection) { * @param mixed $credentials */ public function store($userId, $identifier, $credentials) { - $value = $this->crypto->encrypt(\json_encode($credentials)); + $value = $this->crypto->encrypt(\json_encode($credentials, JSON_THROW_ON_ERROR)); $this->dbConnection->setValues(self::DB_TABLE, [ 'user' => $userId, @@ -87,7 +87,7 @@ public function retrieve($userId, $identifier) { } $value = $result['credentials']; - return \json_decode($this->crypto->decrypt($value), true); + return \json_decode($this->crypto->decrypt($value), true, 512, JSON_THROW_ON_ERROR); } /** diff --git a/lib/private/Security/Crypto.php b/lib/private/Security/Crypto.php index 9e0ac67e7a4d..b50a71a145bc 100644 --- a/lib/private/Security/Crypto.php +++ b/lib/private/Security/Crypto.php @@ -46,14 +46,10 @@ class Crypto implements ICrypto { public const CRYPT_HASH = 'sha1'; public const SALT = 'phpseclib'; - /** @var AES $cipher */ - private $cipher; - /** @var int */ - private $ivLength = 16; - /** @var IConfig */ - private $config; - /** @var ISecureRandom */ - private $random; + private \phpseclib3\Crypt\AES $cipher; + private int $ivLength = 16; + private \OCP\IConfig $config; + private \OCP\Security\ISecureRandom $random; /** * @param IConfig $config @@ -98,7 +94,7 @@ public function encrypt($plaintext, $password = '') { // to harden against related-key attacks // https://github.com/owncloud/encryption/issues/215 $derived = \hash_hkdf('sha512', $password, 0); - list($password, $hmacKey) = \str_split($derived, 32); + [$password, $hmacKey] = \str_split($derived, 32); $this->cipher->setPassword($password, self::CRYPT_METHOD, self::CRYPT_HASH, self::SALT); $iv = \random_bytes($this->ivLength); @@ -127,7 +123,7 @@ public function decrypt($authenticatedCiphertext, $password = '') { // v2 uses stronger binary random iv if (\sizeof($parts) === 4 && $parts[0] === 'v2') { $derived = \hash_hkdf('sha512', $password, 0); - list($password, $hmacKey) = \str_split($derived, 32); + [$password, $hmacKey] = \str_split($derived, 32); $this->cipher->setPassword($password, self::CRYPT_METHOD, self::CRYPT_HASH, self::SALT); $ciphertext = \hex2bin($parts[1]); diff --git a/lib/private/Security/Hasher.php b/lib/private/Security/Hasher.php index 589ff6cf0788..7d82bb23859e 100644 --- a/lib/private/Security/Hasher.php +++ b/lib/private/Security/Hasher.php @@ -46,14 +46,13 @@ * @package OC\Security */ class Hasher implements IHasher { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** @var array Options passed to password_hash and password_needs_rehash */ - private $options = []; + private array $options = []; /** @var string Salt used for legacy passwords */ private $legacySalt = null; /** @var int Current version of the generated hash */ - private $currentVersion = 1; + private int $currentVersion = 1; /** * @param IConfig $config diff --git a/lib/private/Security/SignedUrl/Verifier.php b/lib/private/Security/SignedUrl/Verifier.php index 22d5a3be5c75..0f4f5f3154e7 100644 --- a/lib/private/Security/SignedUrl/Verifier.php +++ b/lib/private/Security/SignedUrl/Verifier.php @@ -25,18 +25,12 @@ use Sabre\HTTP\RequestInterface; class Verifier { - /** - * @var RequestInterface - */ - private $request; - /** - * @var IConfig - */ - private $config; + private \Sabre\HTTP\RequestInterface $request; + private \OCP\IConfig $config; /** * @var \DateTime|null */ - private $now; + private \DateTime $now; public function __construct(RequestInterface $request, IConfig $config, \DateTime $now = null) { $this->request = $request; @@ -52,7 +46,7 @@ public function isSignedRequest(): bool { public function signedRequestIsValid(): bool { $params = $this->getQueryParameters(); if (!isset($params['OC-Signature'], $params['OC-Credential'], $params['OC-Date'], $params['OC-Expires'], $params['OC-Verb'])) { - $q = \json_encode($params); + $q = \json_encode($params, JSON_THROW_ON_ERROR); \OC::$server->getLogger()->debug("Query parameters are missing: $q", ['app' => 'signed-url']); return false; } diff --git a/lib/private/Security/TrustedDomainHelper.php b/lib/private/Security/TrustedDomainHelper.php index 452df0a93993..109e4883e887 100644 --- a/lib/private/Security/TrustedDomainHelper.php +++ b/lib/private/Security/TrustedDomainHelper.php @@ -30,8 +30,7 @@ * @package OC\Security */ class TrustedDomainHelper { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** * @param IConfig $config diff --git a/lib/private/Server.php b/lib/private/Server.php index 46172e9f0d97..821056dfe34e 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -147,36 +147,30 @@ public function __construct($webRoot, \OC\Config $config) { parent::__construct(); $this->webRoot = $webRoot; - $this->registerService('SettingsManager', function (Server $c) { - return new SettingsManager( - $c->getL10N('lib'), - $c->getAppManager(), - $c->getUserSession(), - $c->getLogger(), - $c->getGroupManager(), - $c->getConfig(), - new \OCP\Defaults(), - $c->getURLGenerator(), - new Helper(), - $c->getLockingProvider(), - $c->getDatabaseConnection(), - $c->getLicenseManager(), - $c->getCertificateManager(), - $c->getL10NFactory() - ); - }); - - $this->registerService('ContactsManager', function ($c) { - return new ContactsManager(); - }); - - $this->registerService('PreviewManager', function (Server $c) { - return new PreviewManager( - $c->getConfig(), - $c->getLazyRootFolder(), - $c->getUserSession() - ); - }); + $this->registerService('SettingsManager', fn (Server $c) => new SettingsManager( + $c->getL10N('lib'), + $c->getAppManager(), + $c->getUserSession(), + $c->getLogger(), + $c->getGroupManager(), + $c->getConfig(), + new \OCP\Defaults(), + $c->getURLGenerator(), + new Helper(), + $c->getLockingProvider(), + $c->getDatabaseConnection(), + $c->getLicenseManager(), + $c->getCertificateManager(), + $c->getL10NFactory() + )); + + $this->registerService('ContactsManager', fn ($c) => new ContactsManager()); + + $this->registerService('PreviewManager', fn (Server $c) => new PreviewManager( + $c->getConfig(), + $c->getLazyRootFolder(), + $c->getUserSession() + )); $this->registerService('EncryptionManager', function (Server $c) { $view = new View(); @@ -221,26 +215,20 @@ public function __construct($webRoot, \OC\Config $config) { $c->getUserSession() ); }); - $this->registerService('TagMapper', function (Server $c) { - return new TagMapper($c->getDatabaseConnection()); - }); + $this->registerService('TagMapper', fn (Server $c) => new TagMapper($c->getDatabaseConnection())); $this->registerService('TagManager', function (Server $c) { $tagMapper = $c->query('TagMapper'); return new TagManager($tagMapper, $c->getUserSession()); }); $this->registerService('SystemTagManagerFactory', function (Server $c) { $config = $c->getConfig(); - $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory'); + $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\\' . \OC\SystemTag\ManagerFactory::class); /** @var \OC\SystemTag\ManagerFactory $factory */ $factory = new $factoryClass($this); return $factory; }); - $this->registerService('SystemTagManager', function (Server $c) { - return $c->query('SystemTagManagerFactory')->getManager(); - }); - $this->registerService('SystemTagObjectMapper', function (Server $c) { - return $c->query('SystemTagManagerFactory')->getObjectMapper(); - }); + $this->registerService('SystemTagManager', fn (Server $c) => $c->query('SystemTagManagerFactory')->getManager()); + $this->registerService('SystemTagObjectMapper', fn (Server $c) => $c->query('SystemTagManagerFactory')->getObjectMapper()); $this->registerService('RootFolder', function () { $manager = \OC\Files\Filesystem::getMountManager(null); $view = new View(); @@ -249,29 +237,21 @@ public function __construct($webRoot, \OC\Config $config) { $connector->viewToNode(); return $root; }); - $this->registerService('LazyRootFolder', function (Server $c) { - return new LazyRoot(function () use ($c) { - return $c->getRootFolder(); - }); - }); - $this->registerService('AccountMapper', function (Server $c) { - return new AccountMapper($c->getConfig(), $c->getDatabaseConnection(), new AccountTermMapper($c->getDatabaseConnection())); - }); - $this->registerService('UserManager', function (Server $c) { - return new \OC\User\Manager( + $this->registerService('LazyRootFolder', fn (Server $c) => new LazyRoot(fn () => $c->getRootFolder())); + $this->registerService('AccountMapper', fn (Server $c) => new AccountMapper($c->getConfig(), $c->getDatabaseConnection(), new AccountTermMapper($c->getDatabaseConnection()))); + $this->registerService('UserManager', fn (Server $c) => new \OC\User\Manager( + $c->getConfig(), + $c->getLogger(), + $c->getAccountMapper(), + new SyncService( $c->getConfig(), $c->getLogger(), - $c->getAccountMapper(), - new SyncService( - $c->getConfig(), - $c->getLogger(), - $c->getAccountMapper() - ), - new UserSearch( - $c->getConfig() - ) - ); - }); + $c->getAccountMapper() + ), + new UserSearch( + $c->getConfig() + ) + )); $this->registerService('GroupManager', function (Server $c) { $groupManager = new \OC\Group\Manager( $this->getUserManager(), @@ -303,23 +283,21 @@ public function __construct($webRoot, \OC\Config $config) { }); return $groupManager; }); - $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) { + $this->registerService(\OC\Authentication\Token\DefaultTokenMapper::class, function (Server $c) { $dbConnection = $c->getDatabaseConnection(); return new Authentication\Token\DefaultTokenMapper($dbConnection); }); - $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) { - $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper'); + $this->registerService(\OC\Authentication\Token\DefaultTokenProvider::class, function (Server $c) { + $mapper = $c->query(\OC\Authentication\Token\DefaultTokenMapper::class); $crypto = $c->getCrypto(); $config = $c->getConfig(); $logger = $c->getLogger(); $timeFactory = new TimeFactory(); return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory); }); - $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider'); - $this->registerService('TimeFactory', function () { - return new TimeFactory(); - }); - $this->registerAlias('OCP\AppFramework\Utility\ITimeFactory', 'TimeFactory'); + $this->registerAlias(\OC\Authentication\Token\IProvider::class, \OC\Authentication\Token\DefaultTokenProvider::class); + $this->registerService('TimeFactory', fn () => new TimeFactory()); + $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, 'TimeFactory'); $this->registerService('UserSession', function (Server $c) { $manager = $c->getUserManager(); $session = new Memory(); @@ -327,7 +305,7 @@ public function __construct($webRoot, \OC\Config $config) { // Token providers might require a working database. This code // might however be called when ownCloud is not yet setup. if (\OC::$server->getSystemConfig()->getValue('installed', false)) { - $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider'); + $defaultTokenProvider = $c->query(\OC\Authentication\Token\IProvider::class); } else { $defaultTokenProvider = null; } @@ -362,9 +340,7 @@ public function __construct($webRoot, \OC\Config $config) { $userSession->listen('\OC\User', 'postDelete', function ($user) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]); - $this->emittingCall(function () { - return true; - }, ['before' => [], 'after' => ['uid' => $user->getUID()]], 'user', 'delete'); + $this->emittingCall(fn () => true, ['before' => [], 'after' => ['uid' => $user->getUID()]], 'user', 'delete'); }); $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) { /** @var $user \OC\User\User */ @@ -391,9 +367,7 @@ public function __construct($webRoot, \OC\Config $config) { $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) { /** @var $user \OC\User\User */ \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value]); - $this->emittingCall(function () { - return true; - }, [ + $this->emittingCall(fn () => true, [ 'before' => ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value], 'after' => ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value] ], 'user', 'featurechange'); @@ -401,49 +375,37 @@ public function __construct($webRoot, \OC\Config $config) { return $userSession; }); - $this->registerService('\OC\Authentication\TwoFactorAuth\Manager', function (Server $c) { - return new \OC\Authentication\TwoFactorAuth\Manager( - $c->getAppManager(), - $c->getSession(), - $c->getGroupManager(), - $c->getConfig(), - $c->getRequest(), - $c->getLogger() - ); - }); - - $this->registerService('NavigationManager', function (Server $c) { - return new \OC\NavigationManager( - $c->getAppManager(), - $c->getURLGenerator(), - $c->getL10NFactory(), - $c->getUserSession(), - $c->getGroupManager(), - $c->getConfig() - ); - }); + $this->registerService('\\' . \OC\Authentication\TwoFactorAuth\Manager::class, fn (Server $c) => new \OC\Authentication\TwoFactorAuth\Manager( + $c->getAppManager(), + $c->getSession(), + $c->getGroupManager(), + $c->getConfig(), + $c->getRequest(), + $c->getLogger() + )); + + $this->registerService('NavigationManager', fn (Server $c) => new \OC\NavigationManager( + $c->getAppManager(), + $c->getURLGenerator(), + $c->getL10NFactory(), + $c->getUserSession(), + $c->getGroupManager(), + $c->getConfig() + )); $this->registerAlias(IConfig::class, 'AllConfig'); - $this->registerService('AllConfig', function (Server $c) { - return new \OC\AllConfig( - $c->getSystemConfig(), - $c->getEventDispatcher() - ); - }); - $this->registerService('SystemConfig', function ($c) use ($config) { - return new \OC\SystemConfig($config); - }); - $this->registerService('AppConfig', function (Server $c) { - return new \OC\AppConfig($c->getDatabaseConnection()); - }); - $this->registerService('L10NFactory', function (Server $c) { - return new \OC\L10N\Factory( - $c->getConfig(), - $c->getRequest(), - $c->getThemeService(), - $c->getUserSession(), - \OC::$SERVERROOT - ); - }); + $this->registerService('AllConfig', fn (Server $c) => new \OC\AllConfig( + $c->getSystemConfig(), + $c->getEventDispatcher() + )); + $this->registerService('SystemConfig', fn ($c) => new \OC\SystemConfig($config)); + $this->registerService('AppConfig', fn (Server $c) => new \OC\AppConfig($c->getDatabaseConnection())); + $this->registerService('L10NFactory', fn (Server $c) => new \OC\L10N\Factory( + $c->getConfig(), + $c->getRequest(), + $c->getThemeService(), + $c->getUserSession(), + \OC::$SERVERROOT + )); $this->registerService('URLGenerator', function (Server $c) { $config = $c->getConfig(); $cacheFactory = $c->getMemCacheFactory(); @@ -455,12 +417,8 @@ public function __construct($webRoot, \OC\Config $config) { new \OC\Helper\EnvironmentHelper() ); }); - $this->registerService('AppHelper', function ($c) { - return new \OC\AppHelper(); - }); - $this->registerService('UserCache', function ($c) { - return new Cache\File(); - }); + $this->registerService('AppHelper', fn ($c) => new \OC\AppHelper()); + $this->registerService('UserCache', fn ($c) => new Cache\File()); $this->registerService('MemCacheFactory', function (Server $c) { $config = $c->getConfig(); @@ -481,30 +439,26 @@ public function __construct($webRoot, \OC\Config $config) { return new \OC\Memcache\Factory( '', $c->getLogger(), - '\\OC\\Memcache\\ArrayCache', - '\\OC\\Memcache\\ArrayCache', - '\\OC\\Memcache\\ArrayCache' + '\\' . \OC\Memcache\ArrayCache::class, + '\\' . \OC\Memcache\ArrayCache::class, + '\\' . \OC\Memcache\ArrayCache::class ); }); $this->registerService('RedisFactory', function (Server $c) { $systemConfig = $c->getSystemConfig(); return new RedisFactory($systemConfig); }); - $this->registerService('ActivityManager', function (Server $c) { - return new \OC\Activity\Manager( - $c->getRequest(), - $c->getUserSession(), - $c->getConfig() - ); - }); - $this->registerService('AvatarManager', function (Server $c) { - return new AvatarManager( - $c->getUserManager(), - $c->getLazyRootFolder(), // initialize the root folder lazily - $c->getL10N('lib'), - $c->getLogger() - ); - }); + $this->registerService('ActivityManager', fn (Server $c) => new \OC\Activity\Manager( + $c->getRequest(), + $c->getUserSession(), + $c->getConfig() + )); + $this->registerService('AvatarManager', fn (Server $c) => new AvatarManager( + $c->getUserManager(), + $c->getLazyRootFolder(), // initialize the root folder lazily + $c->getL10N('lib'), + $c->getLogger() + )); $this->registerAlias(ILogger::class, 'Logger'); $this->registerService('Logger', function (Server $c) { $logClass = $c->query('AllConfig')->getSystemValue('log_type', 'owncloud'); @@ -532,22 +486,12 @@ public function __construct($webRoot, \OC\Config $config) { } return $router; }); - $this->registerService('Search', function ($c) { - return new Search(); - }); - $this->registerService('SecureRandom', function ($c) { - return new SecureRandom(); - }); - $this->registerService('Crypto', function (Server $c) { - return new Crypto($c->getConfig(), $c->getSecureRandom()); - }); - $this->registerAlias('OCP\Security\ICrypto', 'Crypto'); - $this->registerService('Hasher', function (Server $c) { - return new Hasher($c->getConfig()); - }); - $this->registerService('CredentialsManager', function (Server $c) { - return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection()); - }); + $this->registerService('Search', fn ($c) => new Search()); + $this->registerService('SecureRandom', fn ($c) => new SecureRandom()); + $this->registerService('Crypto', fn (Server $c) => new Crypto($c->getConfig(), $c->getSecureRandom())); + $this->registerAlias(\OCP\Security\ICrypto::class, 'Crypto'); + $this->registerService('Hasher', fn (Server $c) => new Hasher($c->getConfig())); + $this->registerService('CredentialsManager', fn (Server $c) => new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection())); $this->registerService('DatabaseConnection', function (Server $c) { $systemConfig = $c->getSystemConfig(); $keys = $systemConfig->getKeys(); @@ -566,9 +510,7 @@ public function __construct($webRoot, \OC\Config $config) { return $connection; }); $this->registerAlias(IDBConnection::class, 'DatabaseConnection'); - $this->registerService('Db', function (Server $c) { - return new Db($c->getDatabaseConnection()); - }); + $this->registerService('Db', fn (Server $c) => new Db($c->getDatabaseConnection())); $this->registerService('HTTPHelper', function (Server $c) { $config = $c->getConfig(); return new HTTPHelper( @@ -578,7 +520,7 @@ public function __construct($webRoot, \OC\Config $config) { }); $this->registerService('HttpClientService', function (Server $c) { $user = \OC_User::getUser(); - $uid = $user ? $user : null; + $uid = $user ?: null; return new ClientService( $c->getConfig(), new \OC\Security\CertificateManager($uid, new View(), $c->getConfig()) @@ -586,7 +528,7 @@ public function __construct($webRoot, \OC\Config $config) { }); $this->registerService('WebDavClientService', function (Server $c) { $user = \OC_User::getUser(); - $uid = $user ? $user : null; + $uid = $user ?: null; return new WebDavClientService( $c->getConfig(), new \OC\Security\CertificateManager($uid, new View(), $c->getConfig()) @@ -608,12 +550,10 @@ public function __construct($webRoot, \OC\Config $config) { } return $queryLogger; }); - $this->registerService('TempManager', function (Server $c) { - return new TempManager( - $c->getLogger(), - $c->getConfig() - ); - }); + $this->registerService('TempManager', fn (Server $c) => new TempManager( + $c->getLogger(), + $c->getConfig() + )); $this->registerService('AppManager', function (Server $c) { if (\OC::$server->getSystemConfig()->getValue('installed', false)) { $appConfig = $c->getAppConfig(); @@ -631,12 +571,10 @@ public function __construct($webRoot, \OC\Config $config) { $c->getConfig() ); }); - $this->registerService('DateTimeZone', function (Server $c) { - return new DateTimeZone( - $c->getConfig(), - $c->getSession() - ); - }); + $this->registerService('DateTimeZone', fn (Server $c) => new DateTimeZone( + $c->getConfig(), + $c->getSession() + )); $this->registerService('DateTimeFormatter', function (Server $c) { $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null); @@ -676,16 +614,12 @@ public function __construct($webRoot, \OC\Config $config) { return $manager; }); - $this->registerService('IniWrapper', function ($c) { - return new IniGetWrapper(); - }); + $this->registerService('IniWrapper', fn ($c) => new IniGetWrapper()); $this->registerService('AsyncCommandBus', function (Server $c) { $jobList = $c->getJobList(); return new AsyncBus($jobList); }); - $this->registerService('TrustedDomainHelper', function ($c) { - return new TrustedDomainHelper($this->getConfig()); - }); + $this->registerService('TrustedDomainHelper', fn ($c) => new TrustedDomainHelper($this->getConfig())); $this->registerService('IntegrityCodeChecker', function (Server $c) { // IConfig and IAppManager requires a working database. This code // might however be called when ownCloud is not yet setup. @@ -741,13 +675,11 @@ public function __construct($webRoot, \OC\Config $config) { $stream ); }); - $this->registerService('Mailer', function (Server $c) { - return new Mailer( - $c->getConfig(), - $c->getLogger(), - new \OC_Defaults() - ); - }); + $this->registerService('Mailer', fn (Server $c) => new Mailer( + $c->getConfig(), + $c->getLogger(), + new \OC_Defaults() + )); $this->registerService('LockingProvider', function (Server $c) { $ini = $c->getIniWrapper(); $config = $c->getConfig(); @@ -764,44 +696,32 @@ public function __construct($webRoot, \OC\Config $config) { } return new NoopLockingProvider(); }); - $this->registerAlias('OCP\Lock\ILockingProvider', 'LockingProvider'); - $this->registerService('MountManager', function () { - return new \OC\Files\Mount\Manager(); - }); - $this->registerService('MimeTypeDetector', function (Server $c) { - return new \OC\Files\Type\Detection( - $c->getURLGenerator(), - \OC::$SERVERROOT . '/config/', - \OC::$SERVERROOT . '/resources/config/' - ); - }); - $this->registerService('MimeTypeLoader', function (Server $c) { - return new \OC\Files\Type\Loader( - $c->getDatabaseConnection(), - $c->getMemCacheFactory() - ); - }); - $this->registerAlias('OCP\Files\IMimeTypeLoader', 'MimeTypeLoader'); - $this->registerService('NotificationManager', function (Server $c) { - return new Manager($c->getEventDispatcher()); - }); + $this->registerAlias(\OCP\Lock\ILockingProvider::class, 'LockingProvider'); + $this->registerService('MountManager', fn () => new \OC\Files\Mount\Manager()); + $this->registerService('MimeTypeDetector', fn (Server $c) => new \OC\Files\Type\Detection( + $c->getURLGenerator(), + \OC::$SERVERROOT . '/config/', + \OC::$SERVERROOT . '/resources/config/' + )); + $this->registerService('MimeTypeLoader', fn (Server $c) => new \OC\Files\Type\Loader( + $c->getDatabaseConnection(), + $c->getMemCacheFactory() + )); + $this->registerAlias(\OCP\Files\IMimeTypeLoader::class, 'MimeTypeLoader'); + $this->registerService('NotificationManager', fn (Server $c) => new Manager($c->getEventDispatcher())); $this->registerService('CapabilitiesManager', function (Server $c) { $manager = new \OC\CapabilitiesManager(); - $manager->registerCapability(function () use ($c) { - return new \OC\OCS\CoreCapabilities($c->getConfig(), $c->getURLGenerator()); - }); + $manager->registerCapability(fn () => new \OC\OCS\CoreCapabilities($c->getConfig(), $c->getURLGenerator())); return $manager; }); $this->registerService('CommentsManager', function (Server $c) { $config = $c->getConfig(); - $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory'); + $factoryClass = $config->getSystemValue('comments.managerFactory', '\\' . \OC\Comments\ManagerFactory::class); /** @var \OCP\Comments\ICommentsManagerFactory $factory */ $factory = new $factoryClass($this); return $factory->getManager(); }); - $this->registerService('EventDispatcher', function () { - return new EventDispatcher(); - }); + $this->registerService('EventDispatcher', fn () => new EventDispatcher()); $this->registerService('CryptoWrapper', function (Server $c) { // FIXME: Instantiated here due to cyclic dependency $request = new Request( @@ -836,28 +756,24 @@ public function __construct($webRoot, \OC\Config $config) { $sessionStorage ); }); - $this->registerService('ContentSecurityPolicyManager', function (Server $c) { - return new ContentSecurityPolicyManager(); - }); - $this->registerService('StoragesDBConfigService', function (Server $c) { - return new DBConfigService( - $c->getDatabaseConnection(), - $c->getCrypto() - ); - }); + $this->registerService('ContentSecurityPolicyManager', fn (Server $c) => new ContentSecurityPolicyManager()); + $this->registerService('StoragesDBConfigService', fn (Server $c) => new DBConfigService( + $c->getDatabaseConnection(), + $c->getCrypto() + )); $this->registerService('StoragesBackendService', function (Server $c) { $service = new StoragesBackendService($c->query('AllConfig')); // register auth mechanisms provided by core $provider = new \OC\Files\External\Auth\CoreAuthMechanismProvider($c, [ // AuthMechanism::SCHEME_NULL mechanism - 'OC\Files\External\Auth\NullMechanism', + \OC\Files\External\Auth\NullMechanism::class, // AuthMechanism::SCHEME_BUILTIN mechanism - 'OC\Files\External\Auth\Builtin', + \OC\Files\External\Auth\Builtin::class, // AuthMechanism::SCHEME_PASSWORD mechanisms - 'OC\Files\External\Auth\Password\Password', + \OC\Files\External\Auth\Password\Password::class, ]); $service->registerAuthMechanismProvider($provider); @@ -872,40 +788,34 @@ public function __construct($webRoot, \OC\Config $config) { return $service; }); - $this->registerAlias('OCP\Files\External\IStoragesBackendService', 'StoragesBackendService'); - $this->registerService('GlobalStoragesService', function (Server $c) { - return new GlobalStoragesService( - $c->query('StoragesBackendService'), - $c->query('StoragesDBConfigService'), - $c->query('UserMountCache'), - $c->query('Crypto') - ); - }); - $this->registerAlias('OCP\Files\External\Service\IGlobalStoragesService', 'GlobalStoragesService'); - $this->registerService('UserGlobalStoragesService', function (Server $c) { - return new UserGlobalStoragesService( - $c->query('StoragesBackendService'), - $c->query('StoragesDBConfigService'), - $c->query('UserSession'), - $c->query('GroupManager'), - $c->query('UserMountCache'), - $c->query('Crypto') - ); - }); - $this->registerAlias('OCP\Files\External\Service\IUserGlobalStoragesService', 'UserGlobalStoragesService'); - $this->registerService('UserStoragesService', function (Server $c) { - return new UserStoragesService( - $c->query('StoragesBackendService'), - $c->query('StoragesDBConfigService'), - $c->query('UserSession'), - $c->query('UserMountCache'), - $c->query('Crypto') - ); - }); - $this->registerAlias('OCP\Files\External\Service\IUserStoragesService', 'UserStoragesService'); + $this->registerAlias(\OCP\Files\External\IStoragesBackendService::class, 'StoragesBackendService'); + $this->registerService('GlobalStoragesService', fn (Server $c) => new GlobalStoragesService( + $c->query('StoragesBackendService'), + $c->query('StoragesDBConfigService'), + $c->query('UserMountCache'), + $c->query('Crypto') + )); + $this->registerAlias(\OCP\Files\External\Service\IGlobalStoragesService::class, 'GlobalStoragesService'); + $this->registerService('UserGlobalStoragesService', fn (Server $c) => new UserGlobalStoragesService( + $c->query('StoragesBackendService'), + $c->query('StoragesDBConfigService'), + $c->query('UserSession'), + $c->query('GroupManager'), + $c->query('UserMountCache'), + $c->query('Crypto') + )); + $this->registerAlias(\OCP\Files\External\Service\IUserGlobalStoragesService::class, 'UserGlobalStoragesService'); + $this->registerService('UserStoragesService', fn (Server $c) => new UserStoragesService( + $c->query('StoragesBackendService'), + $c->query('StoragesDBConfigService'), + $c->query('UserSession'), + $c->query('UserMountCache'), + $c->query('Crypto') + )); + $this->registerAlias(\OCP\Files\External\Service\IUserStoragesService::class, 'UserStoragesService'); $this->registerService('ShareManager', function (Server $c) { $config = $c->getConfig(); - $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory'); + $factoryClass = $config->getSystemValue('sharing.managerFactory', '\\' . \OC\Share20\ProviderFactory::class); /** @var \OCP\Share\IProviderFactory $factory */ $factory = new $factoryClass($this); @@ -930,35 +840,29 @@ public function __construct($webRoot, \OC\Config $config) { return $manager; }); - $this->registerService('ThemeService', function ($c) { - return new ThemeService( - $this->getSystemConfig()->getValue('theme'), - $c->getAppManager(), - new \OC\Helper\EnvironmentHelper() - ); - }); - $this->registerAlias('OCP\Theme\IThemeService', 'ThemeService'); - $this->registerAlias('OCP\IUserSession', 'UserSession'); - $this->registerAlias('OCP\Security\ICrypto', 'Crypto'); + $this->registerService('ThemeService', fn ($c) => new ThemeService( + $this->getSystemConfig()->getValue('theme'), + $c->getAppManager(), + new \OC\Helper\EnvironmentHelper() + )); + $this->registerAlias(\OCP\Theme\IThemeService::class, 'ThemeService'); + $this->registerAlias(\OCP\IUserSession::class, 'UserSession'); + $this->registerAlias(\OCP\Security\ICrypto::class, 'Crypto'); - $this->registerService(IServiceLoader::class, function () { - return $this; - }); + $this->registerService(IServiceLoader::class, fn () => $this); - $this->registerService(ILicenseManager::class, function ($c) { - return new LicenseManager( - $c->query(LicenseFetcher::class), - // can't query for MessageService because there is no implementation - // registered for the \OCP\L10N\IFactory interface in the server. - new MessageService( - $c->getL10NFactory() - ), - $c->getAppManager(), - $c->getConfig(), - $c->getTimeFactory(), - $c->getLogger() - ); - }); + $this->registerService(ILicenseManager::class, fn ($c) => new LicenseManager( + $c->query(LicenseFetcher::class), + // can't query for MessageService because there is no implementation + // registered for the \OCP\L10N\IFactory interface in the server. + new MessageService( + $c->getL10NFactory() + ), + $c->getAppManager(), + $c->getConfig(), + $c->getTimeFactory(), + $c->getLogger() + )); $this->registerService(LoginPolicyManager::class, function ($c) { $policyManager = new LoginPolicyManager( @@ -1178,7 +1082,7 @@ public function setSession(ISession $session) { * @return \OC\Authentication\TwoFactorAuth\Manager */ public function getTwoFactorAuthManager() { - return $this->query('\OC\Authentication\TwoFactorAuth\Manager'); + return $this->query('\\' . \OC\Authentication\TwoFactorAuth\Manager::class); } /** @@ -1689,14 +1593,14 @@ public function getShareManager() { * @return IThemeService */ public function getThemeService() { - return $this->query('\OCP\Theme\IThemeService'); + return $this->query('\\' . \OCP\Theme\IThemeService::class); } /** * @return ITimeFactory */ public function getTimeFactory() { - return $this->query('\OCP\AppFramework\Utility\ITimeFactory'); + return $this->query('\\' . \OCP\AppFramework\Utility\ITimeFactory::class); } /** @@ -1720,7 +1624,7 @@ public function load(array $xmlPath, IUser $user = null) { } foreach ($xmlPath as $xml) { - $info = isset($info[$xml]) ? $info[$xml] : []; + $info = $info[$xml] ?? []; } if (!\is_array($info)) { $info = [$info]; diff --git a/lib/private/ServerContainer.php b/lib/private/ServerContainer.php index 33b4ff1e06ba..efd2c1f8ac1e 100644 --- a/lib/private/ServerContainer.php +++ b/lib/private/ServerContainer.php @@ -55,11 +55,7 @@ public function registerAppContainer($appName, DIContainer $container) { * @return DIContainer */ public function getAppContainer($appName) { - if (isset($this->appContainers[$appName])) { - return $this->appContainers[$appName]; - } - - return new DIContainer($appName); + return $this->appContainers[$appName] ?? new DIContainer($appName); } /** diff --git a/lib/private/Session/CryptoSessionData.php b/lib/private/Session/CryptoSessionData.php index 233ba5f025c4..629e59fe0fe1 100644 --- a/lib/private/Session/CryptoSessionData.php +++ b/lib/private/Session/CryptoSessionData.php @@ -78,7 +78,9 @@ protected function initializeSession() { try { $this->sessionValues = \json_decode( $this->crypto->decrypt($encryptedSessionData, $this->passphrase), - true + true, + 512, + JSON_THROW_ON_ERROR ); } catch (\Exception $e) { $this->sessionValues = []; @@ -103,11 +105,7 @@ public function set($key, $value) { * @return string|null Either the value or null */ public function get($key) { - if (isset($this->sessionValues[$key])) { - return $this->sessionValues[$key]; - } - - return null; + return $this->sessionValues[$key] ?? null; } /** @@ -166,7 +164,7 @@ public function getId() { */ public function close() { if ($this->isModified) { - $encryptedValue = $this->crypto->encrypt(\json_encode($this->sessionValues), $this->passphrase); + $encryptedValue = $this->crypto->encrypt(\json_encode($this->sessionValues, JSON_THROW_ON_ERROR), $this->passphrase); $this->session->set(self::encryptedSessionName, $encryptedValue); $this->isModified = false; } diff --git a/lib/private/Session/CryptoWrapper.php b/lib/private/Session/CryptoWrapper.php index 7810f4765e4d..fbc94e97755a 100644 --- a/lib/private/Session/CryptoWrapper.php +++ b/lib/private/Session/CryptoWrapper.php @@ -62,11 +62,9 @@ class CryptoWrapper { /** @var string */ private $passphrase; - /** @var IRequest */ - private $request; + private \OCP\IRequest $request; - /** @var ITimeFactory */ - private $timeFactory; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; /** * @param IConfig $config @@ -179,7 +177,7 @@ private function prepareOptions(IConfig $config) { private function sendCookieToBrowser($value, $options) { if (\version_compare(PHP_VERSION, '7.3.0') === -1) { - \setcookie(self::COOKIE_NAME, $value, $options['expires'], $options['path'], $options['domain'], $options['secure'], $options['httpOnly']); + \setcookie(self::COOKIE_NAME, $value, ['expires' => $options['expires'], 'path' => $options['path'], 'domain' => $options['domain'], 'secure' => $options['secure'], 'httponly' => $options['httpOnly']]); } else { \setcookie(self::COOKIE_NAME, $value, $options); } diff --git a/lib/private/Session/Internal.php b/lib/private/Session/Internal.php index 5ecfa917d8f3..9fe01def98a0 100644 --- a/lib/private/Session/Internal.php +++ b/lib/private/Session/Internal.php @@ -48,7 +48,7 @@ public function __construct($name) { try { $this->start(); } catch (\Exception $e) { - \setcookie(\session_name(), null, -1, \OC::$WEBROOT ? : '/'); + \setcookie(\session_name(), null, ['expires' => -1, 'path' => \OC::$WEBROOT ? : '/']); } \restore_error_handler(); if ($_SESSION === null) { diff --git a/lib/private/Settings/SettingsManager.php b/lib/private/Settings/SettingsManager.php index cdaaacd173b6..cd41b673c9fd 100644 --- a/lib/private/Settings/SettingsManager.php +++ b/lib/private/Settings/SettingsManager.php @@ -480,11 +480,10 @@ protected function loadSection($type, $sectionID) { * @return array */ protected function sortOrder($objects) { - \usort($objects, function ($a, $b) { - /** @var ISection | ISettings $a */ - /** @var ISection | ISettings $b */ - return $b->getPriority() - $a->getPriority(); - }); + \usort($objects, fn ($a, $b) => + /** @var ISection | ISettings $a */ + /** @var ISection | ISettings $b */ + $b->getPriority() - $a->getPriority()); return $objects; } } diff --git a/lib/private/Setup.php b/lib/private/Setup.php index 52d8bd276048..54b20fa056eb 100644 --- a/lib/private/Setup.php +++ b/lib/private/Setup.php @@ -444,7 +444,7 @@ public function install($options) { } public static function installBackgroundJobs() { - \OC::$server->getJobList()->add('\OC\Authentication\Token\DefaultTokenCleanupJob'); + \OC::$server->getJobList()->add('\\' . \OC\Authentication\Token\DefaultTokenCleanupJob::class); } /** diff --git a/lib/private/Setup/AbstractDatabase.php b/lib/private/Setup/AbstractDatabase.php index b216e3837f70..758192457b88 100644 --- a/lib/private/Setup/AbstractDatabase.php +++ b/lib/private/Setup/AbstractDatabase.php @@ -80,7 +80,7 @@ public function initialize($config) { $dbName = $config['dbname']; $dbConnectionString = $config['dbconnectionstring'] ?? ''; $dbHost = !empty($config['dbhost']) ? $config['dbhost'] : 'localhost'; - $dbTablePrefix = isset($config['dbtableprefix']) ? $config['dbtableprefix'] : 'oc_'; + $dbTablePrefix = $config['dbtableprefix'] ?? 'oc_'; $this->config->setSystemValues([ 'dbname' => $dbName, diff --git a/lib/private/Setup/MySQL.php b/lib/private/Setup/MySQL.php index 876fa94ba7d1..8fc14967eea6 100644 --- a/lib/private/Setup/MySQL.php +++ b/lib/private/Setup/MySQL.php @@ -120,7 +120,7 @@ private function connect() { // adding port support if (\strpos($this->dbHost, ':')) { // Host variable may carry a port or socket. - list($host, $portOrSocket) = \explode(':', $this->dbHost, 2); + [$host, $portOrSocket] = \explode(':', $this->dbHost, 2); if (\ctype_digit($portOrSocket)) { $connectionParams['port'] = $portOrSocket; } else { diff --git a/lib/private/Setup/PostgreSQL.php b/lib/private/Setup/PostgreSQL.php index b7a1b6f44935..1a2d320a9ece 100644 --- a/lib/private/Setup/PostgreSQL.php +++ b/lib/private/Setup/PostgreSQL.php @@ -36,7 +36,7 @@ public function setupDatabase($username) { // Fix database with port connection if (\strpos($e_host, ':')) { - list($e_host, $port)=\explode(':', $e_host, 2); + [$e_host, $port]=\explode(':', $e_host, 2); } else { $port=false; } @@ -95,7 +95,7 @@ public function setupDatabase($username) { // Fix database with port connection if (\strpos($e_host, ':')) { - list($e_host, $port)=\explode(':', $e_host, 2); + [$e_host, $port]=\explode(':', $e_host, 2); } else { $port=false; } diff --git a/lib/private/Share/Helper.php b/lib/private/Share/Helper.php index a188d62f13b0..44a8e91f96ac 100644 --- a/lib/private/Share/Helper.php +++ b/lib/private/Share/Helper.php @@ -47,10 +47,7 @@ public static function generateTarget($itemType, $itemSource, $shareType, $share // FIXME: $uidOwner and $groupParent seems to be unused $backend = \OC\Share\Share::getBackend($itemType); if ($shareType === self::SHARE_TYPE_LINK || $shareType === self::SHARE_TYPE_REMOTE) { - if (isset($suggestedTarget)) { - return $suggestedTarget; - } - return $backend->generateTarget($itemSource, false); + return $suggestedTarget ?? $backend->generateTarget($itemSource, false); } else { if ($shareType == self::SHARE_TYPE_USER) { // Share with is a user, so set share type to user and groups diff --git a/lib/private/Share/MailNotifications.php b/lib/private/Share/MailNotifications.php index f62935501f6b..0d0b8aebfe4b 100644 --- a/lib/private/Share/MailNotifications.php +++ b/lib/private/Share/MailNotifications.php @@ -55,26 +55,16 @@ * @package OC\Share */ class MailNotifications { - /** @var IManager */ - private $shareManager; - /** @var IL10N */ - private $l; - /** @var IMailer */ - private $mailer; - /** @var IConfig */ - private $config; - /** @var Defaults */ - private $defaults; - /** @var ILogger */ - private $logger; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var EventDispatcher */ - private $eventDispatcher; - /** @var \OCP\Activity\IManager */ - private $activityManager; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Share\IManager $shareManager; + private \OCP\IL10N $l; + private \OCP\Mail\IMailer $mailer; + private \OCP\IConfig $config; + private \OCP\Defaults $defaults; + private \OCP\ILogger $logger; + private \OCP\IURLGenerator $urlGenerator; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; + private \OCP\Activity\IManager $activityManager; + private \OCP\Files\IRootFolder $rootFolder; /** * @param IManager $shareManager @@ -181,7 +171,7 @@ public function sendInternalShareMail($sender, $node, $shareType, $recipientList $subject = (string)$this->l->t('%s shared »%s« with you', [$filter->getSenderDisplayName(), $unescapedFilename]); } - list($htmlBody, $textBody) = $this->createMailBody( + [$htmlBody, $textBody] = $this->createMailBody( $unescapedFilename, $link, $expiration, @@ -258,7 +248,7 @@ public function sendLinkShareMail($sender, $recipients, $link, $personalNote = n 'senderDisplayName' => $sender->getDisplayName() ]); $subject = (string)$l10n->t('%s shared »%s« with you', [$filter->getSenderDisplayName(), $filter->getFile(true)]); - list($htmlBody, $textBody) = $this->createMailBody( + [$htmlBody, $textBody] = $this->createMailBody( $filter->getFile(), $filter->getLink(), $filter->getExpirationDate(), @@ -355,7 +345,7 @@ protected function createMailBody( $prefix = '', $overrideL10n = null ) { - $l10n = $overrideL10n === null ? $this->l : $overrideL10n; + $l10n = $overrideL10n ?? $this->l; $formattedDate = $expiration ? $l10n->l('date', $expiration) : null; $html = new \OC_Template( diff --git a/lib/private/Share/SearchResultSorter.php b/lib/private/Share/SearchResultSorter.php index c84bc9b4b24c..bc919855f329 100644 --- a/lib/private/Share/SearchResultSorter.php +++ b/lib/private/Share/SearchResultSorter.php @@ -26,10 +26,10 @@ use OCP\ILogger; class SearchResultSorter { - private $search; + private string $search; private $encoding; private $key; - private $log; + private ?\OCP\ILogger $log = null; /** * @param string $search the search term as was given by the user diff --git a/lib/private/Share/Share.php b/lib/private/Share/Share.php index 3340519450c3..9984f2501919 100644 --- a/lib/private/Share/Share.php +++ b/lib/private/Share/Share.php @@ -110,7 +110,7 @@ public static function registerBackend($itemType, $class, $collectionOf = null, return true; } \OCP\Util::writeLog( - 'OCP\Share', + \OCP\Share::class, 'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class'] .' is already registered for '.$itemType, \OCP\Util::WARN @@ -149,7 +149,7 @@ public static function getUsersSharingFile($path, $ownerUser, $includeOwner = fa if ($userObject === null) { $msg = "Backends provided no user object for $ownerUser"; - \OC::$server->getLogger()->error($msg, ['app' => __CLASS__]); + \OC::$server->getLogger()->error($msg, ['app' => self::class]); throw new \OC\User\NoUserException($msg); } @@ -205,7 +205,7 @@ public static function getUsersSharingFile($path, $ownerUser, $includeOwner = fa } if (\OCP\DB::isError($result)) { - \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { while ($row = $result->fetchRow()) { $shares[] = $row['share_with']; @@ -227,7 +227,7 @@ public static function getUsersSharingFile($path, $ownerUser, $includeOwner = fa $result = $query->execute([$source, self::SHARE_TYPE_GROUP]); if (\OCP\DB::isError($result)) { - \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { while ($row = $result->fetchRow()) { $usersInGroup = self::usersInGroup($row['share_with']); @@ -258,7 +258,7 @@ public static function getUsersSharingFile($path, $ownerUser, $includeOwner = fa $result = $query->execute([$source, self::SHARE_TYPE_LINK]); if (\OCP\DB::isError($result)) { - \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { if ($result->fetchRow()) { $publicShare = true; @@ -279,7 +279,7 @@ public static function getUsersSharingFile($path, $ownerUser, $includeOwner = fa $result = $query->execute([$source, self::SHARE_TYPE_REMOTE]); if (\OCP\DB::isError($result)) { - \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { if ($result->fetchRow()) { $remoteShare = true; @@ -315,7 +315,7 @@ public static function getUsersSharingFile($path, $ownerUser, $includeOwner = fa $result = $query->execute(); if (\OCP\DB::isError($result)) { - \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { while ($row = $result->fetchRow()) { foreach ($fileTargets[$row['fileid']] as $uid => $shareData) { @@ -498,7 +498,7 @@ public static function getItemSharedWithUser($itemType, $itemSource, $user, $own } else { \OC::$server->getLogger()->warning( 'Could not resolve mount point for ' . $row['storage_id'], - ['app' => 'OCP\Share'] + ['app' => \OCP\Share::class] ); } } @@ -556,7 +556,7 @@ public static function getItemSharedWithBySource( $includeCollections = false, $shareWith = null ) { - $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith; + $shareWith ??= \OC_User::getUser(); return self::getItems( $itemType, $itemSource, @@ -601,7 +601,7 @@ public static function getShareByToken($token, $checkPasswordProtection = true) $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1); $result = $query->execute([$token]); if ($result === false) { - \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR); } $row = $result->fetchRow(); if ($row === false) { @@ -743,7 +743,7 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, if ($backend->isShareTypeAllowed($shareType) === false) { $message = 'Sharing %s failed, because the backend does not allow shares from type %d'; $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %d', [$itemSourceName, $shareType]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG); throw new \Exception($message_t); } @@ -765,14 +765,14 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, if (!$path) { $message = 'Sharing %s failed, because the file does not exist'; $message_t = $l->t('Sharing %s failed, because the file does not exist', [$itemSourceName]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName), \OCP\Util::DEBUG); throw new \Exception($message_t); } // verify that the user has share permission if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) { $message = 'You are not allowed to share %s'; $message_t = $l->t('You are not allowed to share %s', [$path]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $path), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $path), \OCP\Util::DEBUG); throw new \Exception($message_t); } } @@ -783,9 +783,9 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $mountManager = \OC\Files\Filesystem::getMountManager(); $mounts = $mountManager->findIn($path); foreach ($mounts as $mount) { - if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { + if ($mount->getStorage()->instanceOfStorage('\\' . \OCA\Files_Sharing\ISharedStorage::class)) { $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!'; - \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, $message, \OCP\Util::DEBUG); throw new \Exception($message); } } @@ -816,13 +816,13 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, if ($shareWith == $uidOwner) { $message = 'Sharing %s failed, because you can not share with yourself'; $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName), \OCP\Util::DEBUG); throw new \Exception($message_t); } if (!\OC_User::userExists($shareWith)) { $message = 'Sharing %s failed, because the user %s does not exist'; $message_t = $l->t('Sharing %s failed, because the user %s does not exist', [$itemSourceName, $shareWith]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); throw new \Exception($message_t); } if ($shareWithinGroupOnly) { @@ -831,7 +831,7 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $message = 'Sharing %s failed, because the user ' .'%s is not a member of any groups that %s is a member of'; $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', [$itemName, $shareWith, $uidOwner]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG); throw new \Exception($message_t); } } @@ -854,7 +854,7 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) { $message = 'Sharing %s failed, because this item is already shared with %s'; $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', [$itemSourceName, $shareWith]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); throw new \Exception($message_t); } } @@ -876,7 +876,7 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) { $message = 'Sharing %s failed, because this item is already shared with user %s'; $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', [$itemSourceName, $shareWith]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR); throw new \Exception($message_t); } } @@ -884,14 +884,14 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, if (!\OC::$server->getGroupManager()->groupExists($shareWith)) { $message = 'Sharing %s failed, because the group %s does not exist'; $message_t = $l->t('Sharing %s failed, because the group %s does not exist', [$itemSourceName, $shareWith]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); throw new \Exception($message_t); } if ($shareWithMembershipGroupOnly && !\OC::$server->getGroupManager()->inGroup($uidOwner, $shareWith)) { $message = 'Sharing %s failed, because ' .'%s is not a member of the group %s'; $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', [$itemSourceName, $uidOwner, $shareWith]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG); throw new \Exception($message_t); } // Check if the item source is already shared with the group, either from the same owner or a different user @@ -911,16 +911,14 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) { $message = 'Sharing %s failed, because this item is already shared with %s'; $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', [$itemSourceName, $shareWith]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); throw new \Exception($message_t); } } // Convert share with into an array with the keys group and users $group = $shareWith; $usersInGroup = \OC::$server->getGroupManager()->get($group)->getUsers(); - $usersInGroup = \array_values(\array_map(function (IUser $u) { - return $u->getUID(); - }, $usersInGroup)); + $usersInGroup = \array_values(\array_map(fn (IUser $u) => $u->getUID(), $usersInGroup)); $shareWith = []; $shareWith['group'] = $group; $shareWith['users'] = \array_diff($usersInGroup, [$uidOwner]); @@ -978,7 +976,7 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) { $message = 'You need to provide a password to create a public link, only protected links are allowed'; $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed'); - \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, $message, \OCP\Util::DEBUG); throw new \Exception($message_t); } @@ -1018,7 +1016,7 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, } $message = 'Sharing %s failed, because sharing with links is not allowed'; $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', [$itemSourceName]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName), \OCP\Util::DEBUG); throw new \Exception($message_t); } elseif ($shareType === self::SHARE_TYPE_REMOTE) { /* @@ -1038,18 +1036,18 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, )) { $message = 'Sharing %s failed, because this item is already shared with %s'; $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', [$itemSourceName, $shareWith]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); throw new \Exception($message_t); } // don't allow federated shares if source and target server are the same - list($user, $remote) = Helper::splitUserRemote($shareWith); + [$user, $remote] = Helper::splitUserRemote($shareWith); $currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/')); $currentUser = \OC::$server->getUserSession()->getUser()->getUID(); if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) { $message = 'Not allowed to create a federated share with the same user.'; $message_t = $l->t('Not allowed to create a federated share with the same user'); - \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, $message, \OCP\Util::DEBUG); throw new \Exception($message_t); } @@ -1076,7 +1074,7 @@ public static function shareItem($itemType, $itemSource, $shareType, $shareWith, // Future share types need to include their own conditions $message = 'Share type %s is not valid for %s'; $message_t = $l->t('Share type %s is not valid for %s', [$shareType, $itemSource]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG); throw new \Exception($message_t); } @@ -1103,7 +1101,7 @@ public static function unshare($itemType, $itemSource, $shareType, $shareWith, $ $toDelete = []; $newParent = null; - $currentUser = $owner ? $owner : \OC_User::getUser(); + $currentUser = $owner ?: \OC_User::getUser(); foreach ($items as $item) { // delete the item with the expected share_type and owner if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) { @@ -1147,11 +1145,11 @@ public static function unshareAll($itemType, $itemSource) { 'itemSource' => $itemSource, 'shares' => $shares, ]; - \OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams); + \OC_Hook::emit(\OCP\Share::class, 'pre_unshareAll', $hookParams); foreach ($shares as $share) { self::unshareItem($share); } - \OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams); + \OC_Hook::emit(\OCP\Share::class, 'post_unshareAll', $hookParams); return true; } return false; @@ -1251,7 +1249,7 @@ public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = if ($itemUnshared) { \OC_Hook::emit( - 'OCP\Share', + \OCP\Share::class, 'post_unshareFromSelf', ['unsharedItems' => $listOfUnsharedItems, 'itemType' => $itemType] ); @@ -1279,7 +1277,7 @@ public static function setSendMailStatus($itemType, $itemSource, $shareType, $re $result = $query->execute([$status, $itemType, $itemSource, $shareType, $recipient]); if ($result === false) { - \OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, 'Couldn\'t set send mail status', \OCP\Util::ERROR); } } @@ -1297,11 +1295,7 @@ public static function setPermissions($itemType, $itemSource, $shareType, $share $l = \OC::$server->getL10N('lib'); $connection = \OC::$server->getDatabaseConnection(); - $intArrayToLiteralArray = function ($intArray, $eb) { - return \array_map(function ($int) use ($eb) { - return $eb->literal((int)$int, 'integer'); - }, $intArray); - }; + $intArrayToLiteralArray = fn ($intArray, $eb) => \array_map(fn ($int) => $eb->literal((int)$int, 'integer'), $intArray); $sanitizeItem = function ($item) { $item['id'] = (int)$item['id']; $item['permissions'] = (int)$item['permissions']; @@ -1335,7 +1329,7 @@ public static function setPermissions($itemType, $itemSource, $shareType, $share $message = 'Setting permissions for %s failed,' .' because the permissions exceed permissions granted to %s'; $message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', [$itemSource, \OC_User::getUser()]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSource, \OC_User::getUser()), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSource, \OC_User::getUser()), \OCP\Util::DEBUG); throw new \Exception($message_t); } } @@ -1347,7 +1341,7 @@ public static function setPermissions($itemType, $itemSource, $shareType, $share ->setParameter(':permissions', $permissions); $qb->execute(); if ($itemType === 'file' || $itemType === 'folder') { - \OC_Hook::emit('OCP\Share', 'post_update_permissions', [ + \OC_Hook::emit(\OCP\Share::class, 'post_update_permissions', [ 'itemType' => $itemType, 'itemSource' => $itemSource, 'shareType' => $shareType, @@ -1450,7 +1444,7 @@ public static function setPermissions($itemType, $itemSource, $shareType, $share } foreach ($items as $item) { - \OC_Hook::emit('OCP\Share', 'post_update_permissions', ['share' => $item]); + \OC_Hook::emit(\OCP\Share::class, 'post_update_permissions', ['share' => $item]); } return true; @@ -1458,7 +1452,7 @@ public static function setPermissions($itemType, $itemSource, $shareType, $share $message = 'Setting permissions for %s failed, because the item was not found'; $message_t = $l->t('Setting permissions for %s failed, because the item was not found', [$itemSource]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSource), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSource), \OCP\Util::DEBUG); throw new \Exception($message_t); } @@ -1495,7 +1489,7 @@ private static function validateExpireDate($expireDate, $shareTime, $itemType, $ if ($date > $maxDate) { $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared'; $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', [$maxDays]); - \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN); + \OCP\Util::writeLog(\OCP\Share::class, $warning, \OCP\Util::WARN); throw new \Exception($warning_t); } } @@ -1503,7 +1497,7 @@ private static function validateExpireDate($expireDate, $shareTime, $itemType, $ if ($date < $today) { $message = 'Cannot set expiration date. Expiration date is in the past'; $message_t = $l->t('Cannot set expiration date. Expiration date is in the past'); - \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN); + \OCP\Util::writeLog(\OCP\Share::class, $message, \OCP\Util::WARN); throw new \Exception($message_t); } @@ -1527,7 +1521,7 @@ public static function setExpirationDate($itemType, $itemSource, $date, $shareTi if (\OCP\Util::isDefaultExpireDateEnforced()) { $warning = 'Cannot clear expiration date. Shares are required to have an expiration date.'; $warning_t = $l->t('Cannot clear expiration date. Shares are required to have an expiration date.'); - \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN); + \OCP\Util::writeLog(\OCP\Share::class, $warning, \OCP\Util::WARN); throw new \Exception($warning_t); } else { $date = null; @@ -1544,7 +1538,7 @@ public static function setExpirationDate($itemType, $itemSource, $date, $shareTi $query->execute(); - \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [ + \OC_Hook::emit(\OCP\Share::class, 'post_set_expiration_date', [ 'itemType' => $itemType, 'itemSource' => $itemSource, 'date' => $date, @@ -1692,13 +1686,13 @@ protected static function unshareItem(array $item, $newParent = null) { $hookParams['fileTarget'] = $item['file_target']; } - \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams); + \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams); $deletedShares = Helper::delete($item['id'], false, null, $newParent); $deletedShares[] = $hookParams; $hookParams['deletedShares'] = $deletedShares; - \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams); + \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams); if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) { - list(, $remote) = Helper::splitUserRemote($item['share_with']); + [, $remote] = Helper::splitUserRemote($item['share_with']); self::sendRemoteUnshare($remote, $item['id'], $item['token']); } } @@ -1720,20 +1714,20 @@ public static function getBackend($itemType) { if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) { $message = 'Sharing backend %s must implement the interface OCP\Share_Backend'; $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $class), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $class), \OCP\Util::ERROR); throw new \Exception($message_t); } return self::$backends[$itemType]; } else { $message = 'Sharing backend %s not found'; $message_t = $l->t('Sharing backend %s not found', [$class]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $class), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $class), \OCP\Util::ERROR); throw new \Exception($message_t); } } $message = 'Sharing backend for %s not found'; $message_t = $l->t('Sharing backend for %s not found', [$itemType]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemType), \OCP\Util::ERROR); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemType), \OCP\Util::ERROR); throw new \Exception($message_t); } @@ -2008,7 +2002,7 @@ public static function getItems( $result = $query->execute($queryArgs); if ($result === false) { \OCP\Util::writeLog( - 'OCP\Share', + \OCP\Share::class, \OC_DB::getErrorMessage() . ', select=' . $select . ' where=', \OCP\Util::ERROR ); @@ -2073,7 +2067,7 @@ public static function getItems( $parentResult = $query->execute([$row['parent']]); if ($result === false) { \OCP\Util::writeLog( - 'OCP\Share', + \OCP\Share::class, 'Can\'t select parent: ' . \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where, \OCP\Util::ERROR @@ -2082,7 +2076,7 @@ public static function getItems( $parentRow = $parentResult->fetchRow(); $tmpPath = $parentRow['file_target']; // find the right position where the row path continues from the target path - $pos = \strrpos($row['path'], $parentRow['file_target']); + $pos = \strrpos($row['path'], (string) $parentRow['file_target']); $subPath = \substr($row['path'], $pos); $splitPath = \explode('/', $subPath); foreach (\array_slice($splitPath, 2) as $pathPart) { @@ -2236,9 +2230,7 @@ public static function getItems( // filter out invalid items, these can appear when subshare entries exist // for a group in which the requested user isn't a member any more - $items = \array_filter($items, function ($item) { - return $item['share_type'] !== self::$shareTypeGroupUserUnique; - }); + $items = \array_filter($items, fn ($item) => $item['share_type'] !== self::$shareTypeGroupUserUnique); return self::formatResult($items, $column, $backend, $format, $parameters); } elseif ($includeCollections && $collectionTypes && \in_array('folder', $collectionTypes)) { @@ -2418,7 +2410,7 @@ private static function put( $preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget; $preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith; - \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData); + \OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData); if ($run === false) { throw new \Exception($error); @@ -2562,9 +2554,9 @@ private static function put( $postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget; $postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget; - \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData); + \OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData); - return $id ? $id : false; + return $id ?: false; } /** @@ -2592,7 +2584,7 @@ private static function checkReshare($itemType, $itemSource, $shareType, $shareW $message = 'Sharing %s failed, because the user %s is the original sharer'; $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG); throw new \Exception($message_t); } } @@ -2604,7 +2596,7 @@ private static function checkReshare($itemType, $itemSource, $shareType, $shareW $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s'; $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', [$itemSourceName, $uidOwner]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG); throw new \Exception($message_t); } else { // TODO Don't check if inside folder @@ -2636,7 +2628,7 @@ private static function checkReshare($itemType, $itemSource, $shareType, $shareW $message = 'Sharing %s failed, because resharing is not allowed'; $message_t = $l->t('Sharing %s failed, because resharing is not allowed', [$itemSourceName]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSourceName), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSourceName), \OCP\Util::DEBUG); throw new \Exception($message_t); } } else { @@ -2649,7 +2641,7 @@ private static function checkReshare($itemType, $itemSource, $shareType, $shareW $message = 'Sharing %s failed, because the sharing backend for ' .'%s could not find its source'; $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', [$itemSource, $itemType]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG); throw new \Exception($message_t); } if ($backend instanceof \OCP\Share_Backend_File_Dependent) { @@ -2664,7 +2656,7 @@ private static function checkReshare($itemType, $itemSource, $shareType, $shareW $message = 'Sharing %s failed, because the file could not be found in the file cache'; $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', [$itemSource]); - \OCP\Util::writeLog('OCP\Share', \sprintf($message, $itemSource), \OCP\Util::DEBUG); + \OCP\Util::writeLog(\OCP\Share::class, \sprintf($message, $itemSource), \OCP\Util::DEBUG); throw new \Exception($message_t); } } else { @@ -2936,7 +2928,7 @@ private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, ar * @return bool */ private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) { - list($user, $remote) = Helper::splitUserRemote($shareWith); + [$user, $remote] = Helper::splitUserRemote($shareWith); if ($user && $remote) { $url = $remote; @@ -2954,10 +2946,10 @@ private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $ $url = self::removeProtocolFromUrl($url); $result = self::tryHttpPostToShareEndpoint($url, '', $fields); - $status = \json_decode($result['result'], true); + $status = \json_decode($result['result'], true, 512, JSON_THROW_ON_ERROR); if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) { - \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]); + \OC_Hook::emit(\OCP\Share::class, 'federated_share_added', ['server' => $remote]); return true; } } @@ -2981,7 +2973,7 @@ private static function sendRemoteUnshare($remote, $id, $token) { if (!isset($result['result'])) { return false; } - $status = \json_decode($result['result'], true); + $status = \json_decode($result['result'], true, 512, JSON_THROW_ON_ERROR); return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)); } @@ -3115,9 +3107,7 @@ private static function verifyPassword($password) { */ private static function getGroupsForUser($user) { $groups = \OC::$server->getGroupManager()->getUserIdGroups($user, 'sharing'); - return \array_values(\array_map(function (Group $g) { - return $g->getGID(); - }, $groups)); + return \array_values(\array_map(fn (Group $g) => $g->getGID(), $groups)); } /** @@ -3129,8 +3119,6 @@ private static function usersInGroup($group) { if ($g === null) { return []; } - return \array_values(\array_map(function (IUser $u) { - return $u->getUID(); - }, $g->getUsers())); + return \array_values(\array_map(fn (IUser $u) => $u->getUID(), $g->getUsers())); } } diff --git a/lib/private/Share20/DefaultShareProvider.php b/lib/private/Share20/DefaultShareProvider.php index d30f5ce72b22..1308bad61e0d 100644 --- a/lib/private/Share20/DefaultShareProvider.php +++ b/lib/private/Share20/DefaultShareProvider.php @@ -50,17 +50,13 @@ class DefaultShareProvider implements IShareProvider { // Special share type for user modified group shares public const SHARE_TYPE_USERGROUP = 2; - /** @var IDBConnection */ - private $dbConn; + private \OCP\IDBConnection $dbConn; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IGroupManager */ - private $groupManager; + private \OCP\IGroupManager $groupManager; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; /** * DefaultShareProvider constructor. @@ -717,9 +713,7 @@ private function getSharedWithGroupQuery($groups, $node) { $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId()))); } - $groups = \array_map(function (IGroup $group) { - return $group->getGID(); - }, $groups); + $groups = \array_map(fn (IGroup $group) => $group->getGID(), $groups); $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))) ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter( @@ -756,9 +750,7 @@ private function getSharedWithUserGroupQuery($groups, $userId, $node) { $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId()))); } - $groups = \array_map(function (IGroup $group) { - return $group->getGID(); - }, $groups); + $groups = \array_map(fn (IGroup $group) => $group->getGID(), $groups); $qb->andWhere($qb->expr()->orX( $qb->expr()->andX( @@ -1095,7 +1087,7 @@ private function chunkSharesToMaps($shares) { private function resolveGroupShares($shares, $userId) { $qb = $this->dbConn->getQueryBuilder(); - list($chunkedShareIds, $shareIdToShareMap) = $this->chunkSharesToMaps($shares); + [$chunkedShareIds, $shareIdToShareMap] = $this->chunkSharesToMaps($shares); foreach ($chunkedShareIds as $shareIdsChunk) { $qb->select('*') ->from('share') @@ -1312,7 +1304,7 @@ private function validate($share) { private function updateShareAttributes(IShare $share, $data) { if ($data !== null) { $attributes = new ShareAttributes(); - $compressedAttributes = \json_decode($data, true); + $compressedAttributes = \json_decode($data, true, 512, JSON_THROW_ON_ERROR); foreach ($compressedAttributes as $compressedAttribute) { $attributes->setAttribute( $compressedAttribute[0], @@ -1345,7 +1337,7 @@ private function formatShareAttributes($attributes) { 2 => $attribute['enabled'] ]; } - return \json_encode($compressedAttributes); + return \json_encode($compressedAttributes, JSON_THROW_ON_ERROR); } /** diff --git a/lib/private/Share20/Manager.php b/lib/private/Share20/Manager.php index 22283779bc9b..48a97a2c7694 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -62,38 +62,23 @@ * This class is the communication hub for all sharing related operations. */ class Manager implements IManager { - /** @var IProviderFactory */ - private $factory; - /** @var ILogger */ - private $logger; - /** @var IConfig */ - private $config; - /** @var ISecureRandom */ - private $secureRandom; - /** @var IHasher */ - private $hasher; - /** @var IMountManager */ - private $mountManager; - /** @var IGroupManager */ - private $groupManager; - /** @var IL10N */ - private $l; - /** @var IUserManager */ - private $userManager; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Share\IProviderFactory $factory; + private \OCP\ILogger $logger; + private \OCP\IConfig $config; + private \OCP\Security\ISecureRandom $secureRandom; + private \OCP\Security\IHasher $hasher; + private \OCP\Files\Mount\IMountManager $mountManager; + private \OCP\IGroupManager $groupManager; + private \OCP\IL10N $l; + private \OCP\IUserManager $userManager; + private \OCP\Files\IRootFolder $rootFolder; /** @var CappedMemoryCache */ private $sharingDisabledForUsersCache; - /** @var EventDispatcher */ - private $eventDispatcher; - /** @var View */ - private $view; - /** @var IDBConnection */ - private $connection; - /** @var IUserSession */ - private $userSession; - /** @var ActivityIManager */ - private $activityManager; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; + private \OC\Files\View $view; + private \OCP\IDBConnection $connection; + private ?\OCP\IUserSession $userSession = null; + private \OCP\Activity\IManager $activityManager; /** * Manager constructor. @@ -356,8 +341,7 @@ protected function validatePermissions(IShare $share) { /* By default, there are no required attributes to be set on a file */ $requiredAttributes = $this->newShare()->newAttributes(); - $currentAttributes = $share->getAttributes() !== null ? - $share->getAttributes() : $this->newShare()->newAttributes(); + $currentAttributes = $share->getAttributes() ?? $this->newShare()->newAttributes(); /* * Quick fix for #23536 @@ -387,11 +371,11 @@ protected function validatePermissions(IShare $share) { $requiredAttributes = $this->newShare()->newAttributes(); foreach ($incomingNodes as $incomingNode) { $incomingNodeStorage = $incomingNode->getStorage(); - if ($incomingNodeStorage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { + if ($incomingNodeStorage->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class)) { // if $incomingNode is an incoming federated share use share node permission directly, // fed shares are distinct mounted like normal files/folders $maxPermissions |= $shareNode->getPermissions(); - } elseif ($incomingNodeStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')) { + } elseif ($incomingNodeStorage->instanceOfStorage(\OCA\Files_Sharing\SharedStorage::class)) { // if $incomingNode is user/group share, use supershare permissions /** @var \OCA\Files_Sharing\SharedStorage $incomingNodeStorage */ '@phan-var \OCA\Files_Sharing\SharedStorage $incomingNodeStorage'; @@ -670,7 +654,7 @@ protected function setLinkParent(\OCP\Share\IShare $share) { // No sense in checking if the method is not there. if (\method_exists($share, 'setParent')) { $storage = $share->getNode()->getStorage(); - if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { + if ($storage->instanceOfStorage('\\' . \OCA\Files_Sharing\ISharedStorage::class)) { // ISharedStorage does not mention getShareId // getShareId is in SharedStorage // FixMe: need to be sure that we always have a SharedStorage @@ -691,7 +675,7 @@ protected function pathCreateChecks($path) { if ($path instanceof \OCP\Files\Folder) { $mounts = $this->mountManager->findIn($path->getPath()); foreach ($mounts as $mount) { - if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { + if ($mount->getStorage()->instanceOfStorage('\\' . \OCA\Files_Sharing\ISharedStorage::class)) { throw new \InvalidArgumentException('Path contains files shared with you'); } } @@ -738,9 +722,9 @@ public function createShare(\OCP\Share\IShare $share) { * Except for mounted federated shares. */ $storage = $share->getNode()->getStorage(); - if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { + if ($storage->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class)) { $parent = $share->getNode()->getParent(); - while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { + while ($parent->getStorage()->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class)) { $parent = $parent->getParent(); } $share->setShareOwner($parent->getOwner()->getUID()); @@ -819,7 +803,7 @@ public function createShare(\OCP\Share\IShare $share) { 'run' => &$run, 'error' => &$error, ]; - \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData); + \OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData); $beforeEvent = new GenericEvent(null, ['shareData' => $preHookData, 'shareObject' => $share]); $this->eventDispatcher->dispatch($beforeEvent, 'share.beforeCreate'); @@ -856,7 +840,7 @@ public function createShare(\OCP\Share\IShare $share) { 'passwordEnabled' => ($share->getPassword() !== null and ($share->getPassword() !== '')), ]; - \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData); + \OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData); $afterEvent = new GenericEvent(null, ['shareData' => $postHookData, 'shareObject' => $share]); $this->eventDispatcher->dispatch($afterEvent, 'share.afterCreate'); @@ -1051,7 +1035,7 @@ public function updateShare(\OCP\Share\IShare $share, $skipExpirationValidation $shareAfterUpdateEvent->setArgument('shareobject', $share); $update = false; if ($expirationDateUpdated === true) { - \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [ + \OC_Hook::emit(\OCP\Share::class, 'post_set_expiration_date', [ 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'date' => $share->getExpirationDate(), @@ -1063,7 +1047,7 @@ public function updateShare(\OCP\Share\IShare $share, $skipExpirationValidation } if ($share->getPassword() !== $originalShare->getPassword()) { - \OC_Hook::emit('OCP\Share', 'post_update_password', [ + \OC_Hook::emit(\OCP\Share::class, 'post_update_password', [ 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'uidOwner' => $share->getSharedBy(), @@ -1080,7 +1064,7 @@ public function updateShare(\OCP\Share\IShare $share, $skipExpirationValidation } else { $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); } - \OC_Hook::emit('OCP\Share', 'post_update_permissions', [ + \OC_Hook::emit(\OCP\Share::class, 'post_update_permissions', [ 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), @@ -1184,7 +1168,7 @@ public function deleteShare(\OCP\Share\IShare $share) { $hookParams = self::formatUnshareHookParams($share); // Emit pre-hook - \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams); + \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams); $beforeEvent = new GenericEvent(null, ['shareData' => $hookParams, 'shareObject' => $share]); $this->eventDispatcher->dispatch($beforeEvent, 'share.beforeDelete'); @@ -1204,7 +1188,7 @@ public function deleteShare(\OCP\Share\IShare $share) { $hookParams['deletedShares'] = $formattedDeletedShares; // Emit post hook - \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams); + \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams); $afterEvent = new GenericEvent(null, ['shareData' => $hookParams['deletedShares'], 'shareObject' => $share]); $this->eventDispatcher->dispatch($afterEvent, 'share.afterDelete'); } @@ -1219,7 +1203,7 @@ public function deleteShare(\OCP\Share\IShare $share) { * @param string $recipientId */ public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) { - list($providerId, ) = $this->splitFullId($share->getFullId()); + [$providerId, ] = $this->splitFullId($share->getFullId()); $provider = $this->factory->getProvider($providerId); $provider->deleteFromSelf($share, $recipientId); @@ -1231,7 +1215,7 @@ public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) { $hookParams = self::formatUnshareHookParams($share); $hookParams['itemTarget'] = $hookParams['fileTarget']; $hookParams['unsharedItems'] = [$hookParams]; - \OC_Hook::emit('OCP\Share', 'post_unshareFromSelf', $hookParams); + \OC_Hook::emit(\OCP\Share::class, 'post_unshareFromSelf', $hookParams); $event = new GenericEvent(null, [ 'shareRecipient' => $recipientId, 'shareOwner' => $share->getSharedBy(), @@ -1252,7 +1236,7 @@ public function moveShare(\OCP\Share\IShare $share, $recipientId) { * @inheritdoc */ public function updateShareForRecipient(\OCP\Share\IShare $share, $recipientId) { - list($providerId, ) = $this->splitFullId($share->getFullId()); + [$providerId, ] = $this->splitFullId($share->getFullId()); $provider = $this->factory->getProvider($providerId); return $provider->updateForRecipient($share, $recipientId); @@ -1467,7 +1451,7 @@ public function getShareById($id, $recipient = null) { throw new ShareNotFound(); } - list($providerId, $id) = $this->splitFullId($id); + [$providerId, $id] = $this->splitFullId($id); $provider = $this->factory->getProvider($providerId); $share = $provider->getShareById($id, $recipient); @@ -1536,7 +1520,7 @@ public function getShareByToken($token) { } catch(ShareNotFound $ex) { $this->logger->error( "shared file not found by token: $token for federated user share, try to check federated group share.", - ['app' => __CLASS__] + ['app' => self::class] ); try { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE_GROUP); @@ -1546,13 +1530,13 @@ public function getShareByToken($token) { } catch (ShareNotFound $ex) { $this->logger->error( "shared file not found by token: $token for federated group share", - ['app' => __CLASS__] + ['app' => self::class] ); throw new ShareNotFound(); } catch (ProviderException $ex) { $this->logger->logException( $ex, - ['app' => __CLASS__] + ['app' => self::class] ); throw new ShareNotFound(); } @@ -1945,10 +1929,10 @@ public function sharingDisabledForUser($userId) { if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') { $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); - $excludedGroups = \json_decode($groupsList); + $excludedGroups = \json_decode($groupsList, null, 512, JSON_THROW_ON_ERROR); if ($excludedGroups === null) { $excludedGroups = \explode(',', $groupsList); - $newValue = \json_encode($excludedGroups); + $newValue = \json_encode($excludedGroups, JSON_THROW_ON_ERROR); $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue); } $user = $this->userManager->get($userId); @@ -1981,7 +1965,7 @@ private function hashAttributes($perms) { return ""; } - return \md5(\json_encode($perms->toArray())); + return \md5(\json_encode($perms->toArray(), JSON_THROW_ON_ERROR)); } /** diff --git a/lib/private/Share20/ProviderFactory.php b/lib/private/Share20/ProviderFactory.php index ae9478065bf6..d8414767e1f2 100644 --- a/lib/private/Share20/ProviderFactory.php +++ b/lib/private/Share20/ProviderFactory.php @@ -34,10 +34,8 @@ * @package OC\Share20 */ class ProviderFactory implements IProviderFactory { - /** @var IServerContainer */ - private $serverContainer; - /** @var DefaultShareProvider */ - private $defaultProvider = null; + private \OCP\IServerContainer $serverContainer; + private ?\OC\Share20\DefaultShareProvider $defaultProvider = null; /** @var FederatedShareProvider */ private $federatedProvider = null; diff --git a/lib/private/Share20/Share.php b/lib/private/Share20/Share.php index f91c63db551f..0398d33ee7e7 100644 --- a/lib/private/Share20/Share.php +++ b/lib/private/Share20/Share.php @@ -32,28 +32,21 @@ use OCP\Share\IShare; class Share implements IShare { - /** @var string */ - private $id; - /** @var string */ - private $providerId; + private ?string $id = null; + private ?string $providerId = null; /** @var Node */ private $node; /** @var int */ private $fileId; - /** @var string */ - private $nodeType; + private ?string $nodeType = null; /** @var int */ private $shareType; - /** @var string */ - private $sharedWith; - /** @var string */ - private $sharedBy; - /** @var string */ - private $shareOwner; + private ?string $sharedWith = null; + private ?string $sharedBy = null; + private ?string $shareOwner = null; /** @var int */ private $permissions; - /** @var IAttributes */ - private $attributes; + private ?\OCP\Share\IAttributes $attributes = null; /** @var \DateTime */ private $expireDate; /** @var string */ @@ -64,22 +57,18 @@ class Share implements IShare { private $parent; /** @var string */ private $target; - /** @var \DateTime */ - private $shareTime; + private ?\DateTime $shareTime = null; /** @var bool */ private $mailSend; /** @var string */ private $name; /** @var int */ private $state; - /** @var bool */ - private $shouldHashPassword = true; + private bool $shouldHashPassword = true; - /** @var IRootFolder */ - private $rootFolder; + private \OCP\Files\IRootFolder $rootFolder; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; public function __construct(IRootFolder $rootFolder, IUserManager $userManager) { $this->rootFolder = $rootFolder; diff --git a/lib/private/Shutdown/ShutDownManager.php b/lib/private/Shutdown/ShutDownManager.php index 6fb0256969e4..810770b3013a 100644 --- a/lib/private/Shutdown/ShutDownManager.php +++ b/lib/private/Shutdown/ShutDownManager.php @@ -25,7 +25,7 @@ class ShutDownManager implements IShutdownManager { /** @var array[] */ - private $callbacks = []; + private array $callbacks = []; /** * ShutDownManager constructor. diff --git a/lib/private/Streamer.php b/lib/private/Streamer.php index ddeede9741e4..1b08dcda63ff 100644 --- a/lib/private/Streamer.php +++ b/lib/private/Streamer.php @@ -28,7 +28,7 @@ class Streamer { // array of regexp. Matching user agents will get tar instead of zip - private $preferTarFor = [ '/macintosh|mac os x/i' ]; + private array $preferTarFor = [ '/macintosh|mac os x/i' ]; // streamer instance private $streamerInstance; diff --git a/lib/private/SubAdmin.php b/lib/private/SubAdmin.php index a051ba2c6890..61f455c416c6 100644 --- a/lib/private/SubAdmin.php +++ b/lib/private/SubAdmin.php @@ -36,14 +36,11 @@ class SubAdmin extends PublicEmitter { use EventEmitterTrait; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var IGroupManager */ - private $groupManager; + private \OCP\IGroupManager $groupManager; - /** @var IDBConnection */ - private $dbConn; + private \OCP\IDBConnection $dbConn; /** * @param IUserManager $userManager @@ -86,7 +83,7 @@ public function createSubAdmin(IUser $user, IGroup $group) { ]) ->execute(); - $this->emit('\OC\SubAdmin', 'postCreateSubAdmin', [$user, $group]); + $this->emit('\\' . \OC\SubAdmin::class, 'postCreateSubAdmin', [$user, $group]); \OC_Hook::emit("OC_SubAdmin", "post_createSubAdmin", ["gid" => $group->getGID()]); return true; }, [ @@ -110,7 +107,7 @@ public function deleteSubAdmin(IUser $user, IGroup $group) { ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID()))) ->execute(); - $this->emit('\OC\SubAdmin', 'postDeleteSubAdmin', [$user, $group]); + $this->emit('\\' . \OC\SubAdmin::class, 'postDeleteSubAdmin', [$user, $group]); \OC_Hook::emit("OC_SubAdmin", "post_deleteSubAdmin", ["gid" => $group->getGID()]); return true; }, [ diff --git a/lib/private/SystemConfig.php b/lib/private/SystemConfig.php index d14d06178ac9..cce21ce72298 100644 --- a/lib/private/SystemConfig.php +++ b/lib/private/SystemConfig.php @@ -78,8 +78,7 @@ class SystemConfig { 'client-secret' => true ] ]; - /** @var Config */ - private $config; + private \OC\Config $config; public function __construct(Config $config) { $this->config = $config; diff --git a/lib/private/SystemTag/ManagerFactory.php b/lib/private/SystemTag/ManagerFactory.php index 11e0de026932..5147fd6c09d7 100644 --- a/lib/private/SystemTag/ManagerFactory.php +++ b/lib/private/SystemTag/ManagerFactory.php @@ -34,11 +34,9 @@ */ class ManagerFactory implements ISystemTagManagerFactory { /** - * Server container - * - * @var IServerContainer - */ - private $serverContainer; + * Server container + */ + private \OCP\IServerContainer $serverContainer; /** * Constructor for the system tag manager factory diff --git a/lib/private/SystemTag/SystemTagObjectMapper.php b/lib/private/SystemTag/SystemTagObjectMapper.php index 7dd16dae933e..0dd060d9d30b 100644 --- a/lib/private/SystemTag/SystemTagObjectMapper.php +++ b/lib/private/SystemTag/SystemTagObjectMapper.php @@ -259,9 +259,7 @@ private function assertTagsExist($tagIds) { if (\count($tags) !== \count($tagIds)) { // at least one tag missing, bail out $foundTagIds = \array_map( - function (ISystemTag $tag) { - return $tag->getId(); - }, + fn (ISystemTag $tag) => $tag->getId(), $tags ); $missingTagIds = \array_diff($tagIds, $foundTagIds); diff --git a/lib/private/TagManager.php b/lib/private/TagManager.php index 0b31f43f86a2..1388b146d8a2 100644 --- a/lib/private/TagManager.php +++ b/lib/private/TagManager.php @@ -40,18 +40,14 @@ class TagManager implements \OCP\ITagManager { /** - * User session - * - * @var \OCP\IUserSession - */ - private $userSession; + * User session + */ + private \OCP\IUserSession $userSession; /** - * TagMapper - * - * @var TagMapper - */ - private $mapper; + * TagMapper + */ + private \OC\Tagging\TagMapper $mapper; /** * Constructor. diff --git a/lib/private/Tagging/TagMapper.php b/lib/private/Tagging/TagMapper.php index f9effca8a499..c4db8aa652a2 100644 --- a/lib/private/Tagging/TagMapper.php +++ b/lib/private/Tagging/TagMapper.php @@ -38,7 +38,7 @@ class TagMapper extends Mapper { * @param IDBConnection $db Instance of the Db abstraction layer. */ public function __construct(IDBConnection $db) { - parent::__construct($db, 'vcategory', 'OC\Tagging\Tag'); + parent::__construct($db, 'vcategory', \OC\Tagging\Tag::class); } /** diff --git a/lib/private/Tags.php b/lib/private/Tags.php index 1486b3da7b7f..193bf8d0c859 100644 --- a/lib/private/Tags.php +++ b/lib/private/Tags.php @@ -47,11 +47,9 @@ class Tags implements \OCP\ITags { /** - * Tags - * - * @var array - */ - private $tags = []; + * Tags + */ + private array $tags = []; /** * Used for storing objectid/categoryname pairs while rescanning. @@ -75,11 +73,9 @@ class Tags implements \OCP\ITags { private $user; /** - * Are we including tags for shared items? - * - * @var bool - */ - private $includeShared = false; + * Are we including tags for shared items? + */ + private bool $includeShared = false; /** * The current user, plus any owners of the items shared with the current @@ -90,11 +86,9 @@ class Tags implements \OCP\ITags { private $owners = []; /** - * The Mapper we're using to communicate our Tag objects to the database. - * - * @var TagMapper - */ - private $mapper; + * The Mapper we're using to communicate our Tag objects to the database. + */ + private \OC\Tagging\TagMapper $mapper; /** * The sharing backend for objects of $this->type. Required if @@ -175,9 +169,7 @@ public function getTags() { return []; } - \usort($this->tags, function ($a, $b) { - return \strnatcasecmp($a->getName(), $b->getName()); - }); + \usort($this->tags, fn ($a, $b) => \strnatcasecmp($a->getName(), $b->getName())); $tagMap = []; foreach ($this->tags as $tag) { @@ -198,9 +190,7 @@ public function getTags() { public function getTagsForUser($user) { return \array_filter( $this->tags, - function ($tag) use ($user) { - return $tag->getOwner() === $user; - } + fn ($tag) => $tag->getOwner() === $user ); } @@ -799,9 +789,7 @@ protected function array_searchi($needle, $haystack, $mem='getName') { return \array_search( \strtolower($needle), \array_map( - function ($tag) use ($mem) { - return \strtolower(\call_user_func([$tag, $mem])); - }, + fn ($tag) => \strtolower(\call_user_func([$tag, $mem])), $haystack ) ); diff --git a/lib/private/Template/ResourceLocator.php b/lib/private/Template/ResourceLocator.php index 19e4e8a5e81e..24ebb498d594 100644 --- a/lib/private/Template/ResourceLocator.php +++ b/lib/private/Template/ResourceLocator.php @@ -156,9 +156,7 @@ protected function append($root, $file, $webRoot = null, $throw = true) { */ protected function buildPath($parts) { $trimmedParts = \array_map( - function ($part) { - return \rtrim($part, '/'); - }, + fn ($part) => \rtrim($part, '/'), $parts ); return \join(DIRECTORY_SEPARATOR, $trimmedParts); diff --git a/lib/private/TemplateLayout.php b/lib/private/TemplateLayout.php index eddecf34c9cb..a6bcf3a794d5 100644 --- a/lib/private/TemplateLayout.php +++ b/lib/private/TemplateLayout.php @@ -40,7 +40,7 @@ use OCP\License\ILicenseManager; class TemplateLayout extends \OC_Template { - private static $versionHash = ''; + private static string $versionHash = ''; /** * @var \OCP\IConfig diff --git a/lib/private/Theme/ThemeService.php b/lib/private/Theme/ThemeService.php index dedc80dc7023..aa43bf738159 100644 --- a/lib/private/Theme/ThemeService.php +++ b/lib/private/Theme/ThemeService.php @@ -36,15 +36,9 @@ class ThemeService implements IThemeService { */ private $theme; - /** - * @var IAppManager - */ - private $appManager; + private \OCP\App\IAppManager $appManager; - /** - * @var EnvironmentHelper - */ - private $environmentHelper; + private \OC\Helper\EnvironmentHelper $environmentHelper; /** * ThemeService constructor. diff --git a/lib/private/URLGenerator.php b/lib/private/URLGenerator.php index a6367adea3e0..0cceb1bbf391 100644 --- a/lib/private/URLGenerator.php +++ b/lib/private/URLGenerator.php @@ -44,17 +44,13 @@ * Class to generate URLs */ class URLGenerator implements IURLGenerator { - /** @var IConfig */ - private $config; - /** @var ICacheFactory */ - private $cacheFactory; - /** @var IRouter */ - private $router; + private \OCP\IConfig $config; + private \OCP\ICacheFactory $cacheFactory; + private \OCP\Route\IRouter $router; /** @var ITheme */ private $theme; - /** @var EnvironmentHelper */ - private $environmentHelper; + private \OC\Helper\EnvironmentHelper $environmentHelper; /** * @param IConfig $config diff --git a/lib/private/Updater.php b/lib/private/Updater.php index 21db04031935..b166f1a0fabb 100644 --- a/lib/private/Updater.php +++ b/lib/private/Updater.php @@ -48,19 +48,15 @@ * - failure(string $message) */ class Updater extends BasicEmitter { - /** @var ILogger $log */ - private $log; + private ?\OCP\ILogger $log = null; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var Checker */ - private $checker; + private \OC\IntegrityCheck\Checker $checker; - /** @var bool */ - private $forceMajorUpgrade = false; + private bool $forceMajorUpgrade = false; - private $logLevelNames = [ + private array $logLevelNames = [ 0 => 'Debug', 1 => 'Info', 2 => 'Warning', @@ -93,14 +89,14 @@ public function upgrade() { $this->emitRepairEvents(); $logLevel = $this->config->getSystemValue('loglevel', Util::WARN); - $this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]); + $this->emit('\\' . \OC\Updater::class, 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]); $this->config->setSystemValue('loglevel', Util::DEBUG); $wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false); if (!$wasMaintenanceModeEnabled) { $this->config->setSystemValue('maintenance', true); - $this->emit('\OC\Updater', 'maintenanceEnabled'); + $this->emit('\\' . \OC\Updater::class, 'maintenanceEnabled'); } $installedVersion = $this->config->getSystemValue('version', '0.0.0'); @@ -113,20 +109,20 @@ public function upgrade() { $this->doUpgrade($currentVersion, $installedVersion); } catch (\Exception $exception) { $this->log->logException($exception, ['app' => 'core']); - $this->emit('\OC\Updater', 'failure', [\get_class($exception) . ': ' .$exception->getMessage()]); + $this->emit('\\' . \OC\Updater::class, 'failure', [\get_class($exception) . ': ' .$exception->getMessage()]); $success = false; } - $this->emit('\OC\Updater', 'updateEnd', [$success]); + $this->emit('\\' . \OC\Updater::class, 'updateEnd', [$success]); if (!$wasMaintenanceModeEnabled && $success) { $this->config->setSystemValue('maintenance', false); - $this->emit('\OC\Updater', 'maintenanceDisabled'); + $this->emit('\\' . \OC\Updater::class, 'maintenanceDisabled'); } else { - $this->emit('\OC\Updater', 'maintenanceActive'); + $this->emit('\\' . \OC\Updater::class, 'maintenanceActive'); } - $this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]); + $this->emit('\\' . \OC\Updater::class, 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]); $this->config->setSystemValue('loglevel', $logLevel); $this->config->setSystemValue('installed', true); @@ -277,7 +273,7 @@ private function doUpgrade($currentVersion, $installedVersion) { foreach ($errors as $appId => $exception) { /** @var \Exception $exception */ $this->log->logException($exception, ['app' => $appId]); - $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]); + $this->emit('\\' . \OC\Updater::class, 'failure', [$appId . ': ' . $exception->getMessage()]); } // post-upgrade repairs @@ -289,9 +285,9 @@ private function doUpgrade($currentVersion, $installedVersion) { // Check for code integrity if not disabled if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) { - $this->emit('\OC\Updater', 'startCheckCodeIntegrity'); + $this->emit('\\' . \OC\Updater::class, 'startCheckCodeIntegrity'); $this->checker->runInstanceVerification(); - $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity'); + $this->emit('\\' . \OC\Updater::class, 'finishedCheckCodeIntegrity'); } // only set the final version if everything went well @@ -300,7 +296,7 @@ private function doUpgrade($currentVersion, $installedVersion) { } protected function doCoreUpgrade() { - $this->emit('\OC\Updater', 'dbUpgradeBefore'); + $this->emit('\\' . \OC\Updater::class, 'dbUpgradeBefore'); // execute core migrations if (\is_dir(\OC::$SERVERROOT."/core/Migrations")) { @@ -308,7 +304,7 @@ protected function doCoreUpgrade() { $ms->migrate(); } - $this->emit('\OC\Updater', 'dbUpgrade'); + $this->emit('\\' . \OC\Updater::class, 'dbUpgrade'); } /** @@ -342,9 +338,9 @@ protected function doAppUpgrade() { foreach ($stacks as $type => $stack) { foreach ($stack as $appId) { if (\OC_App::shouldUpgrade($appId)) { - $this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]); + $this->emit('\\' . \OC\Updater::class, 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]); \OC_App::updateApp($appId); - $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]); + $this->emit('\\' . \OC\Updater::class, 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]); } if ($type !== $pseudoOtherType) { // load authentication, filesystem and logging apps after @@ -363,22 +359,22 @@ private function emitRepairEvents() { $dispatcher = \OC::$server->getEventDispatcher(); $dispatcher->addListener('\OC\Repair::warning', function ($event) { if ($event instanceof GenericEvent) { - $this->emit('\OC\Updater', 'repairWarning', $event->getArguments()); + $this->emit('\\' . \OC\Updater::class, 'repairWarning', $event->getArguments()); } }); $dispatcher->addListener('\OC\Repair::error', function ($event) { if ($event instanceof GenericEvent) { - $this->emit('\OC\Updater', 'repairError', $event->getArguments()); + $this->emit('\\' . \OC\Updater::class, 'repairError', $event->getArguments()); } }); $dispatcher->addListener('\OC\Repair::info', function ($event) { if ($event instanceof GenericEvent) { - $this->emit('\OC\Updater', 'repairInfo', $event->getArguments()); + $this->emit('\\' . \OC\Updater::class, 'repairInfo', $event->getArguments()); } }); $dispatcher->addListener('\OC\Repair::step', function ($event) { if ($event instanceof GenericEvent) { - $this->emit('\OC\Updater', 'repairStep', $event->getArguments()); + $this->emit('\\' . \OC\Updater::class, 'repairStep', $event->getArguments()); } }); } diff --git a/lib/private/Updater/VersionCheck.php b/lib/private/Updater/VersionCheck.php index 9269717c6341..f0823f63075e 100644 --- a/lib/private/Updater/VersionCheck.php +++ b/lib/private/Updater/VersionCheck.php @@ -27,11 +27,9 @@ use OCP\Util; class VersionCheck { - /** @var IClientService */ - private $clientService; + private \OCP\Http\Client\IClientService $clientService; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** * @param IClientService $clientService @@ -53,7 +51,7 @@ public function __construct( public function check() { // Look up the cache - it is invalidated all 30 minutes if (((int)$this->config->getAppValue('core', 'lastupdatedat') + 1800) > \time()) { - return \json_decode($this->config->getAppValue('core', 'lastupdateResult'), true); + return \json_decode($this->config->getAppValue('core', 'lastupdateResult'), true, 512, JSON_THROW_ON_ERROR); } $updaterUrl = $this->config->getSystemValue('updater.server.url', 'https://updates.owncloud.com/server/'); @@ -94,7 +92,7 @@ public function check() { } // Cache the result - $this->config->setAppValue('core', 'lastupdateResult', \json_encode($data)); + $this->config->setAppValue('core', 'lastupdateResult', \json_encode($data, JSON_THROW_ON_ERROR)); return $tmp; } diff --git a/lib/private/User/Account.php b/lib/private/User/Account.php index 488d3cad541c..f16a5414b15d 100644 --- a/lib/private/User/Account.php +++ b/lib/private/User/Account.php @@ -63,8 +63,8 @@ class Account extends Entity { protected $state; protected $home; - private $terms = []; - private $_termsChanged = false; + private array $terms = []; + private bool $_termsChanged = false; public function __construct() { $this->addType('state', 'integer'); diff --git a/lib/private/User/Backend.php b/lib/private/User/Backend.php index a4e591a5ae0e..e2b2e591ec8c 100644 --- a/lib/private/User/Backend.php +++ b/lib/private/User/Backend.php @@ -43,9 +43,9 @@ abstract class Backend implements UserInterface { public const CHECK_PASSWORD = 256; // 1 << 8 public const GET_HOME = 4096; // 1 << 12 public const GET_DISPLAYNAME = 65536; // 1 << 16 - public const SET_DISPLAYNAME = 1048576; // 1 << 20 - public const PROVIDE_AVATAR = 16777216; // 1 << 24 - public const COUNT_USERS = 268435456; // 1 << 28 + public const SET_DISPLAYNAME = 1_048_576; // 1 << 20 + public const PROVIDE_AVATAR = 16_777_216; // 1 << 24 + public const COUNT_USERS = 268_435_456; // 1 << 28 protected $possibleActions = [ self::CREATE_USER => 'createUser', diff --git a/lib/private/User/BasicAuthModule.php b/lib/private/User/BasicAuthModule.php index f7c2f24ae530..92e934ac7797 100644 --- a/lib/private/User/BasicAuthModule.php +++ b/lib/private/User/BasicAuthModule.php @@ -32,16 +32,11 @@ use OCP\IUserManager; class BasicAuthModule implements IAuthModule { - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; - /** @var IUserManager */ - private $manager; - /** @var ISession */ - private $session; - /** @var ITimeFactory */ - private $timeFactory; + private \OCP\IConfig $config; + private \OCP\ILogger $logger; + private \OCP\IUserManager $manager; + private \OCP\ISession $session; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; public function __construct(IConfig $config, ILogger $logger, IUserManager $manager, ISession $session, ITimeFactory $timeFactory) { $this->config = $config; @@ -111,9 +106,7 @@ public function auth(IRequest $request) { 'app' => __METHOD__, 'authUser' => $authUser, 'users' => \array_map( - function (IUser $user) { - return $user->getUID(); - }, + fn (IUser $user) => $user->getUID(), $users ) ] diff --git a/lib/private/User/DeletedUser.php b/lib/private/User/DeletedUser.php index 0b6364296cce..39ff742e14be 100644 --- a/lib/private/User/DeletedUser.php +++ b/lib/private/User/DeletedUser.php @@ -34,11 +34,9 @@ */ class DeletedUser implements IUser { /** @var Emitter */ - private $emitter; - /** @var IConfig */ - private $config; - /** @var IURLGenerator */ - private $urlGenerator; + private \OC\User\Manager $emitter; + private \OCP\IConfig $config; + private \OCP\IURLGenerator $urlGenerator; /** @var string */ private $uid; diff --git a/lib/private/User/Manager.php b/lib/private/User/Manager.php index 566a283d933d..d928c4444e8a 100644 --- a/lib/private/User/Manager.php +++ b/lib/private/User/Manager.php @@ -63,27 +63,20 @@ class Manager extends PublicEmitter implements IUserManager { use EventEmitterTrait; /** @var UserInterface[] $backends */ - private $backends = []; + private array $backends = []; - /** @var CappedMemoryCache $cachedUsers */ - private $cachedUsers; + private \OC\Cache\CappedMemoryCache $cachedUsers; - /** @var IConfig $config */ - private $config; + private \OCP\IConfig $config; - /** @var ILogger $logger */ - private $logger; + private \OCP\ILogger $logger; - /** @var AccountMapper */ - private $accountMapper; + private \OC\User\AccountMapper $accountMapper; /** @var SyncService */ private $syncService; - /** - * @var UserSearch - */ - private $userSearch; + private \OCP\Util\UserSearch $userSearch; /** * @param IConfig $config @@ -206,7 +199,7 @@ public function get($uid, $evenMissing = false) { } catch (MultipleObjectsReturnedException $ex) { $this->logger->error( "More than one user found for $uid, treating as nonexistent.", - ['app' => __CLASS__] + ['app' => self::class] ); $this->cachedUsers->set($uid, null); return null; @@ -326,9 +319,7 @@ public function find($pattern, $limit = null, $offset = null) { public function searchDisplayName($pattern, $limit = null, $offset = null) { if ($this->userSearch->isSearchable($pattern)) { $accounts = $this->accountMapper->search('display_name', $pattern, $limit, $offset); - return \array_map(function (Account $account) { - return $this->getUserObject($account); - }, $accounts); + return \array_map(fn (Account $account) => $this->getUserObject($account), $accounts); } return []; } @@ -368,10 +359,7 @@ public function createUser($uid, $password) { throw new \Exception($l->t('The username can not be longer than 64 characters')); } - $invalidUids = \array_merge( - \OCP\User::FILES_THAT_ARE_NOT_USERS, - \OCP\User::DIRECTORIES_THAT_ARE_NOT_USERS - ); + $invalidUids = [...\OCP\User::FILES_THAT_ARE_NOT_USERS, ...\OCP\User::DIRECTORIES_THAT_ARE_NOT_USERS]; if (\in_array(\strtolower($uid), $invalidUids)) { throw new \Exception($l->t("The special username %s is not allowed", $uid)); @@ -402,7 +390,7 @@ public function createUser($uid, $password) { /* @phan-suppress-next-line PhanUndeclaredMethod */ $backend->createUser($uid, $password); $user = $this->createUserFromBackend($uid, $password, $backend); - return $user === null ? false : $user; + return $user ?? false; } } @@ -502,15 +490,10 @@ public function getByEmail($email) { throw new \InvalidArgumentException('$email cannot be empty'); } $accounts = $this->accountMapper->getByEmail($email); - return \array_map(function (Account $account) { - return $this->getUserObject($account); - }, $accounts); + return \array_map(fn (Account $account) => $this->getUserObject($account), $accounts); } public function getBackend($backendClass) { - if (isset($this->backends[$backendClass])) { - return $this->backends[$backendClass]; - } - return null; + return $this->backends[$backendClass] ?? null; } } diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index 951d85b9c01c..1e22a29a9a7b 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -87,28 +87,22 @@ class Session implements IUserSession, Emitter { use EventEmitterTrait; /** @var IUserManager | PublicEmitter $manager */ - private $manager; + private \OCP\IUserManager $manager; - /** @var ISession $session */ - private $session; + private \OCP\ISession $session; - /** @var ITimeFactory */ - private $timeFactory; + private \OCP\AppFramework\Utility\ITimeFactory $timeFactory; - /** @var IProvider */ - private $tokenProvider; + private \OC\Authentication\Token\IProvider $tokenProvider; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; /** @var User $activeUser */ protected $activeUser; - /** @var IServiceLoader */ - private $serviceLoader; + private \OCP\App\IServiceLoader $serviceLoader; /** @var SyncService */ protected $userSyncService; @@ -396,7 +390,7 @@ protected function supportsCookies(IRequest $request) { if ($request->getCookie('cookie_test') !== null) { return true; } - \setcookie('cookie_test', 'test', $this->timeFactory->getTime() + 3600); + \setcookie('cookie_test', 'test', ['expires' => $this->timeFactory->getTime() + 3600]); return false; } @@ -602,7 +596,7 @@ public function loginWithApache(IApacheBackend $apacheBackend) { && $uidAndBackend[0] !== null && $uidAndBackend[1] instanceof UserInterface ) { - list($uid, $backend) = $uidAndBackend; + [$uid, $backend] = $uidAndBackend; } elseif (\is_string($uidAndBackend)) { $uid = $uidAndBackend; if ($apacheBackend instanceof UserInterface) { @@ -664,7 +658,7 @@ public function createSessionToken(IRequest $request, $uid, $loginName, $passwor // User does not exist return false; } - $name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser'; + $name = $request->server['HTTP_USER_AGENT'] ?? 'unknown browser'; try { $sessionId = $this->session->getId(); $pwd = $this->getPassword($password); @@ -1187,9 +1181,7 @@ public function updateSessionTokenPassword($password) { $sessionId = $this->session->getId(); $token = $this->tokenProvider->getToken($sessionId); $this->tokenProvider->setPassword($token, $sessionId, $password); - } catch (SessionNotAvailableException $ex) { - // Nothing to do - } catch (InvalidTokenException $ex) { + } catch (SessionNotAvailableException|InvalidTokenException $ex) { // Nothing to do } } diff --git a/lib/private/User/Sync/BackendUsersIterator.php b/lib/private/User/Sync/BackendUsersIterator.php index 25b5d748e523..5e2c1c5664b8 100644 --- a/lib/private/User/Sync/BackendUsersIterator.php +++ b/lib/private/User/Sync/BackendUsersIterator.php @@ -23,23 +23,20 @@ use OCP\UserInterface; class BackendUsersIterator extends UsersIterator { - /** - * @var UserInterface - */ - private $backend; + private \OCP\UserInterface $backend; /** * @var int the current data position, * we need to track it independently of parent::$position to handle data sets larger thin LIMIT properly */ - private $dataPos = 0; + private int $dataPos = 0; /** * @var int to cache the count($this->data) calculations */ - private $endPos = 0; + private int $endPos = 0; /** @var bool false if the backend returned less than LIMIT results */ - private $hasMoreData = false; + private bool $hasMoreData = false; /** @var string search for the uid string in backend */ private $search; diff --git a/lib/private/User/Sync/SeenUsersIterator.php b/lib/private/User/Sync/SeenUsersIterator.php index f4af918c0a98..fb09a3132921 100644 --- a/lib/private/User/Sync/SeenUsersIterator.php +++ b/lib/private/User/Sync/SeenUsersIterator.php @@ -23,10 +23,7 @@ use OC\User\AccountMapper; class SeenUsersIterator extends UsersIterator { - /** - * @var AccountMapper - */ - private $mapper; + private \OC\User\AccountMapper $mapper; /** * @var string class name */ diff --git a/lib/private/User/SyncService.php b/lib/private/User/SyncService.php index 640c1cce957f..948e35762640 100644 --- a/lib/private/User/SyncService.php +++ b/lib/private/User/SyncService.php @@ -44,12 +44,9 @@ * @package OC\User */ class SyncService { - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $logger; - /** @var AccountMapper */ - private $mapper; + private \OCP\IConfig $config; + private \OCP\ILogger $logger; + private \OC\User\AccountMapper $mapper; /** * SyncService constructor. @@ -150,7 +147,7 @@ public function run(UserInterface $backend, \Traversable $userIds, \Closure $cal */ private function syncState(Account $a) { $uid = $a->getUserId(); - list($hasKey, $value) = $this->readUserConfig($uid, 'core', 'enabled'); + [$hasKey, $value] = $this->readUserConfig($uid, 'core', 'enabled'); if ($hasKey) { if ($value === 'true') { $a->setState(Account::STATE_ENABLED); @@ -178,7 +175,7 @@ private function syncState(Account $a) { */ private function syncLastLogin(Account $a) { $uid = $a->getUserId(); - list($hasKey, $value) = $this->readUserConfig($uid, 'login', 'lastLogin'); + [$hasKey, $value] = $this->readUserConfig($uid, 'login', 'lastLogin'); if ($hasKey) { $a->setLastLogin($value); if (\array_key_exists('lastLogin', $a->getUpdatedFields())) { @@ -201,7 +198,7 @@ private function syncEmail(Account $a, UserInterface $backend) { $email = $backend->getEMailAddress($uid); $a->setEmail($email); } else { - list($hasKey, $email) = $this->readUserConfig($uid, 'settings', 'email'); + [$hasKey, $email] = $this->readUserConfig($uid, 'settings', 'email'); if ($hasKey) { $a->setEmail($email); } @@ -228,7 +225,7 @@ private function syncQuota(Account $a, UserInterface $backend) { } } if ($quota === null) { - list($hasKey, $quota) = $this->readUserConfig($uid, 'files', 'quota'); + [$hasKey, $quota] = $this->readUserConfig($uid, 'files', 'quota'); if ($hasKey) { $a->setQuota($quota); } diff --git a/lib/private/User/TokenAuthModule.php b/lib/private/User/TokenAuthModule.php index 75939d4e73d6..5a9a63bba557 100644 --- a/lib/private/User/TokenAuthModule.php +++ b/lib/private/User/TokenAuthModule.php @@ -32,14 +32,11 @@ use OCP\Session\Exceptions\SessionNotAvailableException; class TokenAuthModule implements IAuthModule { - /** @var ISession */ - private $session; + private \OCP\ISession $session; - /** @var IProvider */ - private $tokenProvider; + private \OC\Authentication\Token\IProvider $tokenProvider; - /** @var IUserManager */ - private $manager; + private \OCP\IUserManager $manager; /** @var string */ private $password = ''; diff --git a/lib/private/User/User.php b/lib/private/User/User.php index a252016b2dd4..d152e9ec6c6b 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -56,8 +56,7 @@ class User implements IUser { use EventEmitterTrait; - /** @var Account */ - private $account; + private \OC\User\Account $account; /** @var Emitter|Manager $emitter */ private $emitter; @@ -74,8 +73,7 @@ class User implements IUser { /** @var EventDispatcher */ private $eventDispatcher; - /** @var AccountMapper */ - private $mapper; + private \OC\User\AccountMapper $mapper; /** @var \OC\Group\Manager */ private $groupManager; @@ -87,13 +85,12 @@ class User implements IUser { private $userExtendedAttributes = null; /** - * This flag is true by default. This flag when set to false - * would not allow the set operations in this class. Or in other - * words the update to the accounts table will be restricted through this flag. - * This flag is only modified inside getExtendedAttributes method. - * @var bool - */ - private $allowUserAccountUpdate = true; + * This flag is true by default. This flag when set to false + * would not allow the set operations in this class. Or in other + * words the update to the accounts table will be restricted through this flag. + * This flag is only modified inside getExtendedAttributes method. + */ + private bool $allowUserAccountUpdate = true; /** * User constructor. @@ -647,9 +644,7 @@ public function setSearchTerms(array $terms) { } // Check length of terms, cut if too long - $terms = \array_map(function ($term) { - return \substr($term, 0, 191); - }, $terms); + $terms = \array_map(fn ($term) => \substr($term, 0, 191), $terms); $this->mapper->setTermsForAccount($this->account->getId(), $terms); } diff --git a/lib/private/Utf8Analyzer.php b/lib/private/Utf8Analyzer.php index bcb16dc77753..9c288ab1dd65 100644 --- a/lib/private/Utf8Analyzer.php +++ b/lib/private/Utf8Analyzer.php @@ -26,7 +26,7 @@ class Utf8Analyzer { * https://en.wikipedia.org/wiki/UTF-8 * Ranges to determine how many bytes we need to read based on the first byte read. */ - private $utf8Ranges = [ + private array $utf8Ranges = [ "1b" => [0x00, 0x7f], "2b" => [0xc0, 0xdf], "3b" => [0xe0, 0xef], @@ -40,7 +40,7 @@ class Utf8Analyzer { * Keep the list sorted to be able to do a binary search * NOTE: The list is incomplete and might be inaccurate with some symbols */ - private $unicodeRanges = [ + private array $unicodeRanges = [ ['range' => [0x0000, 0x0040], 'script' => 'Common'], ['range' => [0x0041, 0x005a], 'script' => 'Latin'], ['range' => [0x005b, 0x0060], 'script' => 'Common'], diff --git a/lib/private/legacy/api.php b/lib/private/legacy/api.php index 1c03a92baf2a..deac70bb1f81 100644 --- a/lib/private/legacy/api.php +++ b/lib/private/legacy/api.php @@ -103,8 +103,8 @@ class OC_API { * api actions */ protected static $actions = []; - private static $logoutRequired = false; - private static $isLoggedIn = false; + private static bool $logoutRequired = false; + private static bool $isLoggedIn = false; /** * registers an api call @@ -502,7 +502,7 @@ public static function requestedFormat() { * @param string $format */ public static function setContentType($format = null) { - $format = $format === null ? self::requestedFormat() : $format; + $format ??= self::requestedFormat(); if ($format === 'xml') { \header('Content-type: text/xml; charset=UTF-8'); return; diff --git a/lib/private/legacy/app.php b/lib/private/legacy/app.php index 8fd96029cb76..eb8f20262f16 100644 --- a/lib/private/legacy/app.php +++ b/lib/private/legacy/app.php @@ -56,12 +56,12 @@ * upgrading and removing apps. */ class OC_App { - private static $adminForms = []; - private static $personalForms = []; + private static array $adminForms = []; + private static array $personalForms = []; private static $appTypes = []; - private static $loadedApps = []; - private static $loadedTypes = []; - private static $altLogin = []; + private static array $loadedApps = []; + private static array $loadedTypes = []; + private static array $altLogin = []; public const officialApp = 200; public const approvedApp = 100; @@ -137,7 +137,7 @@ public static function loadApps($types = null) { $session->validateSession(); } else { /** @var \OC\Authentication\Token\DefaultTokenProvider $tokenProvider */ - $tokenProvider = \OC::$server->query('\OC\Authentication\Token\DefaultTokenProvider'); + $tokenProvider = \OC::$server->query('\\' . \OC\Authentication\Token\DefaultTokenProvider::class); $token = null; try { $token = $tokenProvider->getToken($session->getSession()->getId()); @@ -604,10 +604,7 @@ public static function isAppDirWritable($appId) { */ public static function getAppVersion($appId) { $info = \OC::$server->getAppManager()->getAppInfo($appId); - if (isset($info['version'])) { - return $info['version']; - } - return '0'; + return $info['version'] ?? '0'; } /** @@ -1028,7 +1025,7 @@ public static function executeRepairSteps($appId, array $steps) { try { $r->addStep($step); } catch (Exception $ex) { - $r->emit('\OC\Repair', 'error', [$ex->getMessage()]); + $r->emit('\\' . \OC\Repair::class, 'error', [$ex->getMessage()]); \OC::$server->getLogger()->logException($ex); } } @@ -1051,7 +1048,7 @@ public static function setupBackgroundJobs(array $jobs) { private static function setupLiveMigrations($appId, array $steps) { $queue = \OC::$server->getJobList(); foreach ($steps as $step) { - $queue->add('OC\Migration\BackgroundRepair', [ + $queue->add(\OC\Migration\BackgroundRepair::class, [ 'app' => $appId, 'step' => $step]); } diff --git a/lib/private/legacy/db.php b/lib/private/legacy/db.php index 6e87971de546..bbbbb803a545 100644 --- a/lib/private/legacy/db.php +++ b/lib/private/legacy/db.php @@ -133,7 +133,7 @@ public static function executeAudited($stmt, array $parameters = null) { } self::raiseExceptionOnError($stmt, 'Could not prepare statement'); if ($stmt instanceof OC_DB_StatementWrapper) { - $result = $stmt->execute($parameters === null ? [] : $parameters); + $result = $stmt->execute($parameters ?? []); self::raiseExceptionOnError($result, 'Could not execute statement'); } else { if (\is_object($stmt)) { diff --git a/lib/private/legacy/db/statementwrapper.php b/lib/private/legacy/db/statementwrapper.php index 855104f3df05..f95bb37a49c3 100644 --- a/lib/private/legacy/db/statementwrapper.php +++ b/lib/private/legacy/db/statementwrapper.php @@ -39,8 +39,8 @@ class OC_DB_StatementWrapper { * @var \Doctrine\DBAL\Driver\Statement */ private $statement = null; - private $isManipulation = false; - private $lastArguments = []; + private bool $isManipulation = false; + private array $lastArguments = []; /** * @param boolean $isManipulation diff --git a/lib/private/legacy/defaults.php b/lib/private/legacy/defaults.php index 181fc9b9221e..458accd3d848 100644 --- a/lib/private/legacy/defaults.php +++ b/lib/private/legacy/defaults.php @@ -34,22 +34,23 @@ * */ class OC_Defaults { - private $theme; + /** @var OC_Theme|null */ + private $theme = null; private $l; - private $defaultEntity; - private $defaultName; - private $defaultTitle; - private $defaultBaseUrl; - private $defaultSyncClientUrl; - private $defaultiOSClientUrl; - private $defaultiTunesAppId; - private $defaultAndroidClientUrl; - private $defaultDocBaseUrl; - private $defaultDocVersion; + private string $defaultEntity; + private string $defaultName; + private string $defaultTitle; + private string $defaultBaseUrl; + private string $defaultSyncClientUrl; + private string $defaultiOSClientUrl; + private string $defaultiTunesAppId; + private string $defaultAndroidClientUrl; + private string $defaultDocBaseUrl; + private string $defaultDocVersion; private $defaultSlogan; - private $defaultLogoClaim; - private $defaultMailHeaderColor; + private string $defaultLogoClaim; + private string $defaultMailHeaderColor; /** * @var IConfig */ diff --git a/lib/private/legacy/eventsource.php b/lib/private/legacy/eventsource.php index 2f8e12543194..6c9dd4684d1a 100644 --- a/lib/private/legacy/eventsource.php +++ b/lib/private/legacy/eventsource.php @@ -32,20 +32,11 @@ * use server side events with caution, to many open requests can hang the server */ class OC_EventSource implements \OCP\IEventSource { - /** - * @var bool - */ - private $fallback; + private ?bool $fallback = null; - /** - * @var int - */ - private $fallBackId = 0; + private int $fallBackId = 0; - /** - * @var bool - */ - private $started = false; + private bool $started = false; protected function init() { if ($this->started) { diff --git a/lib/private/legacy/files.php b/lib/private/legacy/files.php index 1e44f2452557..75cea4c3a2fc 100644 --- a/lib/private/legacy/files.php +++ b/lib/private/legacy/files.php @@ -49,16 +49,16 @@ class OC_Files { public const ZIP_FILES = 2; public const ZIP_DIR = 3; - public const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB + public const UPLOAD_MIN_LIMIT_BYTES = 1_048_576; // 1 MiB - private static $multipartBoundary = ''; + private static string $multipartBoundary = ''; /** * @return string */ private static function getBoundary() { if (empty(self::$multipartBoundary)) { - self::$multipartBoundary = \md5(\mt_rand()); + self::$multipartBoundary = \md5(random_int(0, mt_getrandmax())); } return self::$multipartBoundary; } @@ -121,7 +121,7 @@ public static function get($dir, $files, $params = null) { } elseif (\count($listOfFiles) === 1) { $filename = "{$dir}/{$listOfFiles[0]}"; if (!$view->is_dir($filename)) { - self::getSingleFile($view, $dir, $listOfFiles[0], $params === null ? [] : $params); + self::getSingleFile($view, $dir, $listOfFiles[0], $params ?? []); return; } else { $getType = self::ZIP_DIR; @@ -347,10 +347,9 @@ private static function lockFiles($view, $dir, $files) { $view->lockFile($filePath, ILockingProvider::LOCK_SHARED); if ($view->is_dir($filePath)) { $contents = $view->getDirectoryContent($filePath); - $contents = \array_map(function ($fileInfo) use ($file) { - /** @var \OCP\Files\FileInfo $fileInfo */ - return "{$file}/" . $fileInfo->getName(); - }, $contents); + $contents = \array_map(fn ($fileInfo) => + /** @var \OCP\Files\FileInfo $fileInfo */ + "{$file}/" . $fileInfo->getName(), $contents); self::lockFiles($view, $dir, $contents); // $dir is expected to remain constant while $files can // evolve to ["d1/d2/d3/file001", "d1/d2/d3/file002", ...] @@ -369,10 +368,9 @@ private static function unlockFiles($view, $dir, $files) { $view->unlockFile($filePath, ILockingProvider::LOCK_SHARED); if ($view->is_dir($filePath)) { $contents = $view->getDirectoryContent($filePath); - $contents = \array_map(function ($fileInfo) use ($file) { - /** @var \OCP\Files\FileInfo $fileInfo */ - return "{$file}/" . $fileInfo->getName(); - }, $contents); + $contents = \array_map(fn ($fileInfo) => + /** @var \OCP\Files\FileInfo $fileInfo */ + "{$file}/" . $fileInfo->getName(), $contents); self::unlockFiles($view, $dir, $contents); // $dir is expected to remain constant while $files can // evolve to ["d1/d2/d3/file001", "d1/d2/d3/file002", ...] diff --git a/lib/private/legacy/helper.php b/lib/private/legacy/helper.php index 25d4f5701d5f..6b71131bc6be 100644 --- a/lib/private/legacy/helper.php +++ b/lib/private/legacy/helper.php @@ -49,7 +49,7 @@ * Collection of useful functions */ class OC_Helper { - private static $templateManager; + private static ?\OC\Files\Type\TemplateManager $templateManager = null; /** * Creates an absolute url for public use @@ -591,7 +591,7 @@ public static function getStorageInfo($path, $rootInfo = null) { $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED; $storage = $rootInfo->getStorage(); $sourceStorage = $storage; - if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) { + if ($storage->instanceOfStorage('\\' . \OCA\Files_Sharing\SharedStorage::class)) { $includeExtStorage = false; '@phan-var \OCA\Files_Sharing\SharedStorage $storage'; $sourceStorage = $storage->getSourceStorage(); @@ -605,7 +605,7 @@ public static function getStorageInfo($path, $rootInfo = null) { } // TODO: need a better way to get total space from storage - if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) { + if ($sourceStorage->instanceOfStorage('\\' . \OC\Files\Storage\Wrapper\Quota::class)) { /** @var \OC\Files\Storage\Wrapper\Quota $sourceStorage */ '@phan-var \OC\Files\Storage\Wrapper\Quota $sourceStorage'; $quota = $sourceStorage->getQuota(); diff --git a/lib/private/legacy/image.php b/lib/private/legacy/image.php index 8844710a3f56..87235a2fe277 100644 --- a/lib/private/legacy/image.php +++ b/lib/private/legacy/image.php @@ -52,8 +52,7 @@ class OC_Image implements \OCP\IImage { protected $bitDepth = 24; /** @var null|string */ protected $filePath = null; - /** @var finfo */ - private $fileInfo; + private ?\finfo $fileInfo = null; /** @var \OCP\ILogger */ private $logger; /** @var \OCP\IConfig */ @@ -1027,7 +1026,7 @@ function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) { } elseif ($bit == 32) { $bit = 24; } - $bits = \pow(2, $bit); + $bits = 2 ** $bit; \imagetruecolortopalette($im, true, $bits); $width = \imagesx($im); $height = \imagesy($im); diff --git a/lib/private/legacy/response.php b/lib/private/legacy/response.php index 52f8b5be8e55..ee84e73987b2 100644 --- a/lib/private/legacy/response.php +++ b/lib/private/legacy/response.php @@ -294,7 +294,7 @@ public static function setCorsHeaders($userId, $domain, \OCP\IConfig $config = n $isCorsRequest = (\is_array($globalAllowedDomains) && \in_array($domain, $globalAllowedDomains, true)); if (!$isCorsRequest && $userId !== null) { // check if any of the user specific CORS domains matches - $allowedDomains = \json_decode($config->getUserValue($userId, 'core', 'domains'), true); + $allowedDomains = \json_decode($config->getUserValue($userId, 'core', 'domains'), true, 512, JSON_THROW_ON_ERROR); $isCorsRequest = (\is_array($allowedDomains) && \in_array($domain, $allowedDomains, true)); } if ($isCorsRequest) { diff --git a/lib/private/legacy/template.php b/lib/private/legacy/template.php index 3bf323eca716..d1b2bc4a8b59 100644 --- a/lib/private/legacy/template.php +++ b/lib/private/legacy/template.php @@ -51,10 +51,7 @@ class OC_Template extends \OC\Template\Base { */ private $renderAs; - /** - * @var array - */ - private $headers = []; + private array $headers = []; /** * @var string @@ -159,7 +156,7 @@ public static function initTemplateEngine($renderAs) { // specified in core/js/core.json $fileContent = \file_get_contents(OC::$SERVERROOT . '/core/js/core.json'); if ($fileContent !== false) { - $coreDependencies = \json_decode($fileContent, true); + $coreDependencies = \json_decode($fileContent, true, 512, JSON_THROW_ON_ERROR); foreach (\array_reverse($coreDependencies['vendor']) as $vendorLibrary) { // remove trailing ".js" as addVendorScript will append it OC_Util::addVendorScript( @@ -275,7 +272,7 @@ public function fetchPage($additionalParams = null) { * to include template from a different app. */ public function inc($file, $additionalParams = null) { - $app = (isset($additionalParams['app'])) ? $additionalParams['app'] : $this->app; + $app = $additionalParams['app'] ?? $this->app; $template = $this->findTemplate($this->theme, $app, $file); return $this->load($template, $additionalParams); } diff --git a/lib/private/legacy/user.php b/lib/private/legacy/user.php index 40398b3addf9..b2297085560f 100644 --- a/lib/private/legacy/user.php +++ b/lib/private/legacy/user.php @@ -65,10 +65,10 @@ public static function getUserSession() { private static $_usedBackends = []; - private static $_configuredBackends = []; + private static array $_configuredBackends = []; // bool, stores if a user want to access a resource anonymously, e.g if they open a public link - private static $incognitoMode = false; + private static bool $incognitoMode = false; /** * Adds the backend to the list of used backends diff --git a/lib/private/legacy/util.php b/lib/private/legacy/util.php index 6fde07d85891..e85e46000564 100644 --- a/lib/private/legacy/util.php +++ b/lib/private/legacy/util.php @@ -67,8 +67,8 @@ class OC_Util { public static $scripts = []; public static $styles = []; public static $headers = []; - private static $rootMounted = false; - private static $fsSetup = false; + private static bool $rootMounted = false; + private static bool $fsSetup = false; private static $version; public const EDITION_COMMUNITY = 'Community'; public const EDITION_ENTERPRISE = 'Enterprise'; @@ -83,7 +83,7 @@ private static function initLocalStorageRootFS() { //first set up the local "root" storage \OC\Files\Filesystem::initMountManager(); if (!self::$rootMounted) { - \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', ['datadir' => $configDataDirectory], '/'); + \OC\Files\Filesystem::mount('\\' . \OC\Files\Storage\Local::class, ['datadir' => $configDataDirectory], '/'); self::$rootMounted = true; } } @@ -112,7 +112,7 @@ private static function initObjectStoreRootFS($config) { } $config['arguments']['objectstore'] = new $config['class']($config['arguments']); // mount with plain / root object store implementation - $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage'; + $config['class'] = '\\' . \OC\Files\ObjectStore\ObjectStoreStorage::class; // mount object storage as root \OC\Files\Filesystem::initMountManager(); @@ -158,7 +158,7 @@ public static function setupFS($user = '', $fullInit = true) { \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false); \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) { - if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) { + if ($storage->instanceOfStorage('\\' . \OC\Files\Storage\Common::class)) { /** @var \OC\Files\Storage\Common $storage */ '@phan-var \OC\Files\Storage\Common $storage'; $storage->setMountOptions($mount->getOptions()); @@ -188,7 +188,7 @@ public static function setupFS($user = '', $fullInit = true) { // install storage availability wrapper, before most other wrappers \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, $storage) { - if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) { + if (!$storage->instanceOfStorage('\\' . \OCA\Files_Sharing\SharedStorage::class) && !$storage->isLocal()) { return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]); } return $storage; @@ -196,7 +196,7 @@ public static function setupFS($user = '', $fullInit = true) { // install storage checksum wrapper \OC\Files\Filesystem::addStorageWrapper('oc_checksum', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) { - if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) { + if (!$storage->instanceOfStorage('\\' . \OCA\Files_Sharing\SharedStorage::class)) { return new \OC\Files\Storage\Wrapper\Checksum(['storage' => $storage]); } @@ -204,7 +204,7 @@ public static function setupFS($user = '', $fullInit = true) { }, 1); \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) { - if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) { + if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\\' . \OCA\Files_Sharing\SharedStorage::class) && !$storage->isLocal()) { return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]); } return $storage; @@ -217,8 +217,8 @@ public static function setupFS($user = '', $fullInit = true) { /** * @var \OC\Files\Storage\Storage $storage */ - if ($storage->instanceOfStorage('\OC\Files\Storage\Home') - || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage') + if ($storage->instanceOfStorage('\\' . \OC\Files\Storage\Home::class) + || $storage->instanceOfStorage('\\' . \OC\Files\ObjectStore\HomeObjectStoreStorage::class) ) { /** @var \OC\Files\Storage\Home $storage */ if (\is_object($storage->getUser())) { @@ -255,7 +255,7 @@ public static function setupFS($user = '', $fullInit = true) { 'core', 'read_only_groups', '[]' - ), true); + ), true, 512, JSON_THROW_ON_ERROR); if (!\is_array($readOnlyGroups)) { $readOnlyGroups = []; @@ -1245,9 +1245,7 @@ public static function getInstanceId() { */ public static function sanitizeHTML($value) { if (\is_array($value)) { - $value = \array_map(function ($value) { - return self::sanitizeHTML($value); - }, $value); + $value = \array_map(fn ($value) => self::sanitizeHTML($value), $value); } else { // Specify encoding for PHP<5.4 $value = \htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); diff --git a/lib/public/App/ManagerEvent.php b/lib/public/App/ManagerEvent.php index 034365b7bb06..e95c1d8be3fa 100644 --- a/lib/public/App/ManagerEvent.php +++ b/lib/public/App/ManagerEvent.php @@ -77,9 +77,8 @@ public function getAppID() { * @since 9.0.0 */ public function getGroups() { - return \array_map(function ($group) { - /** @var \OCP\IGroup $group */ - return $group->getGID(); - }, $this->groups); + return \array_map(fn ($group) => + /** @var \OCP\IGroup $group */ + $group->getGID(), $this->groups); } } diff --git a/lib/public/AppFramework/ApiController.php b/lib/public/AppFramework/ApiController.php index 01a973a33328..b1871e55eaef 100644 --- a/lib/public/AppFramework/ApiController.php +++ b/lib/public/AppFramework/ApiController.php @@ -59,7 +59,7 @@ public function __construct( IRequest $request, $corsMethods='PUT, POST, GET, DELETE, PATCH', $corsAllowedHeaders='Authorization, Content-Type, Accept', - $corsMaxAge=1728000 + $corsMaxAge=1_728_000 ) { parent::__construct($appName, $request); $this->corsMethods = $corsMethods; diff --git a/lib/public/AppFramework/App.php b/lib/public/AppFramework/App.php index 70a7a9232b53..5e4f80ed1283 100644 --- a/lib/public/AppFramework/App.php +++ b/lib/public/AppFramework/App.php @@ -63,7 +63,7 @@ public function __construct($appName, $urlParams = []) { $this->container = new \OC\AppFramework\DependencyInjection\DIContainer($appName, $urlParams); } - private $container; + private \OC\AppFramework\DependencyInjection\DIContainer $container; /** * @return IAppContainer diff --git a/lib/public/AppFramework/Http/Response.php b/lib/public/AppFramework/Http/Response.php index 082671614beb..0825aeaf8821 100644 --- a/lib/public/AppFramework/Http/Response.php +++ b/lib/public/AppFramework/Http/Response.php @@ -41,10 +41,9 @@ */ class Response { /** - * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate'] - * @var array - */ - private $headers = [ + * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate'] + */ + private array $headers = [ 'Cache-Control' => 'no-cache, no-store, must-revalidate' ]; @@ -55,10 +54,9 @@ class Response { private $cookies = []; /** - * HTTP status code - defaults to STATUS OK - * @var int - */ - private $status = Http::STATUS_OK; + * HTTP status code - defaults to STATUS OK + */ + private int $status = Http::STATUS_OK; /** * Last modified date @@ -73,7 +71,7 @@ class Response { private $ETag; /** @var ContentSecurityPolicy|null Used Content-Security-Policy */ - private $contentSecurityPolicy = null; + private ?\OCP\AppFramework\Http\ContentSecurityPolicy $contentSecurityPolicy = null; /** * Caches the response diff --git a/lib/public/AppFramework/OCSController.php b/lib/public/AppFramework/OCSController.php index afa47f24f01d..dd6194421b00 100644 --- a/lib/public/AppFramework/OCSController.php +++ b/lib/public/AppFramework/OCSController.php @@ -63,7 +63,7 @@ public function __construct( IRequest $request, $corsMethods='PUT, POST, GET, DELETE, PATCH', $corsAllowedHeaders='Authorization, Content-Type, Accept', - $corsMaxAge=1728000 + $corsMaxAge=1_728_000 ) { parent::__construct( $appName, @@ -72,12 +72,8 @@ public function __construct( $corsAllowedHeaders, $corsMaxAge ); - $this->registerResponder('json', function ($data) { - return $this->buildOCSResponse('json', $data); - }); - $this->registerResponder('xml', function ($data) { - return $this->buildOCSResponse('xml', $data); - }); + $this->registerResponder('json', fn ($data) => $this->buildOCSResponse('json', $data)); + $this->registerResponder('xml', fn ($data) => $this->buildOCSResponse('xml', $data)); } /** diff --git a/lib/public/Authentication/Exceptions/AccountCheckException.php b/lib/public/Authentication/Exceptions/AccountCheckException.php index 8537cf33880a..6c25bc2dbe5c 100644 --- a/lib/public/Authentication/Exceptions/AccountCheckException.php +++ b/lib/public/Authentication/Exceptions/AccountCheckException.php @@ -31,10 +31,7 @@ * @since 10.0.9 */ class AccountCheckException extends Exception { - /** - * @var RedirectResponse - */ - private $redirectResponse; + private \OCP\AppFramework\Http\RedirectResponse $redirectResponse; /** * AccountCheckException constructor. diff --git a/lib/public/BackgroundJob.php b/lib/public/BackgroundJob.php index 5e3b46047264..6b205c20aed7 100644 --- a/lib/public/BackgroundJob.php +++ b/lib/public/BackgroundJob.php @@ -100,7 +100,7 @@ public static function registerJob($job, $argument = null) { */ public static function addRegularTask($klass, $method) { if (!\OCP\Util::needUpgrade()) { - self::registerJob('OC\BackgroundJob\Legacy\RegularJob', [$klass, $method]); + self::registerJob(\OC\BackgroundJob\Legacy\RegularJob::class, [$klass, $method]); return true; } } @@ -161,7 +161,7 @@ public static function queuedTaskWhereAppIs($app) { * @since 4.5.0 */ public static function addQueuedTask($app, $class, $method, $parameters) { - self::registerJob('OC\BackgroundJob\Legacy\QueuedJob', ['app' => $app, 'klass' => $class, 'method' => $method, 'parameters' => $parameters]); + self::registerJob(\OC\BackgroundJob\Legacy\QueuedJob::class, ['app' => $app, 'klass' => $class, 'method' => $method, 'parameters' => $parameters]); return true; } diff --git a/lib/public/Defaults.php b/lib/public/Defaults.php index 63f20056d9b1..a2d9385c8a79 100644 --- a/lib/public/Defaults.php +++ b/lib/public/Defaults.php @@ -42,7 +42,7 @@ class Defaults { * @return string * @since 6.0.0 */ - private $defaults; + private \OC_Defaults $defaults; /** * creates a \OC_Defaults instance which is used in all methods to retrieve the diff --git a/lib/public/Files.php b/lib/public/Files.php index 725e541be818..b88cdf90a4bf 100644 --- a/lib/public/Files.php +++ b/lib/public/Files.php @@ -82,7 +82,7 @@ public static function searchByMime($mimetype) { * @since 5.0.0 */ public static function streamCopy($source, $target) { - list($count, ) = \OC_Helper::streamCopy($source, $target); + [$count, ] = \OC_Helper::streamCopy($source, $target); return $count; } diff --git a/lib/public/Files/External/Backend/Backend.php b/lib/public/Files/External/Backend/Backend.php index e11856d65cc6..27b68ce86504 100644 --- a/lib/public/Files/External/Backend/Backend.php +++ b/lib/public/Files/External/Backend/Backend.php @@ -68,7 +68,7 @@ abstract class Backend implements \JsonSerializable { private $storageClass; /** @var array 'scheme' => true, supported authentication schemes */ - private $authSchemes = []; + private array $authSchemes = []; /** @var AuthMechanism|callable authentication mechanism fallback */ private $legacyAuthMechanism; diff --git a/lib/public/Files/External/Backend/InvalidBackend.php b/lib/public/Files/External/Backend/InvalidBackend.php index 8a6488afdf4b..3f4557b778f8 100644 --- a/lib/public/Files/External/Backend/InvalidBackend.php +++ b/lib/public/Files/External/Backend/InvalidBackend.php @@ -42,7 +42,7 @@ class InvalidBackend extends Backend { public function __construct($invalidId) { $this->invalidId = $invalidId; $this->setIdentifier($invalidId) - ->setStorageClass('\OC\Files\External\InvalidStorage') + ->setStorageClass('\\' . \OC\Files\External\InvalidStorage::class) ->setText('Unknown storage backend ' . $invalidId) ; } diff --git a/lib/public/Files/External/DefinitionParameter.php b/lib/public/Files/External/DefinitionParameter.php index ed00e2c1d9c9..318084e2ae38 100644 --- a/lib/public/Files/External/DefinitionParameter.php +++ b/lib/public/Files/External/DefinitionParameter.php @@ -47,10 +47,10 @@ class DefinitionParameter implements \JsonSerializable { private $text; /** @var int value type, see self::VALUE_* constants */ - private $type = self::VALUE_TEXT; + private int $type = self::VALUE_TEXT; /** @var int flags, see self::FLAG_* constants */ - private $flags = self::FLAG_NONE; + private int $flags = self::FLAG_NONE; /** * @param string $name diff --git a/lib/public/Files/LockNotAcquiredException.php b/lib/public/Files/LockNotAcquiredException.php index 4e8ac4de8ff3..56367de96836 100644 --- a/lib/public/Files/LockNotAcquiredException.php +++ b/lib/public/Files/LockNotAcquiredException.php @@ -59,6 +59,6 @@ public function __construct($path, $lockType, $code = 0, \Exception $previous = * @since 7.0.0 */ public function __toString() { - return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; + return self::class . ": [{$this->code}]: {$this->message}\n"; } } diff --git a/lib/public/ITags.php b/lib/public/ITags.php index a674831fc0fd..7773e6235702 100644 --- a/lib/public/ITags.php +++ b/lib/public/ITags.php @@ -33,7 +33,7 @@ namespace OCP; // FIXME: Where should I put this? Or should it be implemented as a Listener? -\OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Tags', 'post_deleteUser'); +\OC_Hook::connect('OC_User', 'post_deleteUser', \OC\Tags::class, 'post_deleteUser'); /** * Class for easily tagging objects by their id diff --git a/lib/public/Roles/AddRolesEvent.php b/lib/public/Roles/AddRolesEvent.php index d6c3536fdab3..e6db99197c7d 100644 --- a/lib/public/Roles/AddRolesEvent.php +++ b/lib/public/Roles/AddRolesEvent.php @@ -29,7 +29,7 @@ * @package OCP\Roles */ class AddRolesEvent extends Event { - private $roles; + private ?array $roles = null; /** * @param array $role diff --git a/lib/public/User/UserExtendedAttributesEvent.php b/lib/public/User/UserExtendedAttributesEvent.php index 675f91d537c2..cbc943ada6e9 100644 --- a/lib/public/User/UserExtendedAttributesEvent.php +++ b/lib/public/User/UserExtendedAttributesEvent.php @@ -35,11 +35,9 @@ class UserExtendedAttributesEvent extends Event { public const USER_EXTENDED_ATTRIBUTES = 'UserExtendedAttributesEvent'; - /** @var array */ - private $attributes = []; + private array $attributes = []; - /** @var IUser */ - private $user; + private \OCP\IUser $user; /** * UserExtendedAttributesEvent constructor. diff --git a/lib/public/Util.php b/lib/public/Util.php index ae61cf8500f7..34c89d0bff27 100644 --- a/lib/public/Util.php +++ b/lib/public/Util.php @@ -816,7 +816,7 @@ public static function getFullDomain($url) { throw new \InvalidArgumentException('Only http based URLs supported'); } - if (isset($parts['port']) && $port !== '') { + if (isset($parts['port']) && $port !== 0) { $port = $parts['port']; } diff --git a/rector.php b/rector.php index 43c6d093ea3b..29ec4f6ffb9f 100644 --- a/rector.php +++ b/rector.php @@ -21,5 +21,7 @@ $rectorConfig->skip([ __DIR__ . '/*/templates/*', __DIR__ . '/lib/composer/*', + __DIR__ . '/lib/private/Repair/DropOldJobs.php', + __DIR__ . '/lib/private/legacy/defaults.php' ]); }; diff --git a/settings/Application.php b/settings/Application.php index 8569c6b21347..6e86e8da7916 100644 --- a/settings/Application.php +++ b/settings/Application.php @@ -65,174 +65,134 @@ public function __construct(array $urlParams=[]) { /** * Controllers */ - $container->registerService('SettingsPageController', function (IContainer $c) { - return new SettingsPageController( - $c->query('AppName'), - $c->query('Request'), - $c->query('SettingsManager'), - $c->query('ServerContainer')->getURLGenerator(), - $c->query('GroupManager'), - $c->query('UserSession') - ); - }); - $container->registerService('MailSettingsController', function (IContainer $c) { - return new MailSettingsController( - $c->query('AppName'), - $c->query('Request'), - $c->query('L10N'), - $c->query('Config'), - $c->query('UserSession'), - $c->query('Defaults'), - $c->query('Mailer'), - $c->query('DefaultMailAddress') - ); - }); - $container->registerService('AppSettingsController', function (IContainer $c) { - return new AppSettingsController( - $c->query('AppName'), - $c->query('Request'), - $c->query('L10N'), - $c->query('Config'), - $c->query('IAppManager') - ); - }); - $container->registerService('AuthSettingsController', function (IContainer $c) { - return new AuthSettingsController( - $c->query('AppName'), - $c->query('Request'), - $c->query('ServerContainer')->query('OC\Authentication\Token\IProvider'), - $c->query('UserManager'), - $c->query('ServerContainer')->getSession(), - $c->query('ServerContainer')->getSecureRandom(), - $c->query('UserId') - ); - }); - $container->registerService('CertificateController', function (IContainer $c) { - return new CertificateController( - $c->query('AppName'), - $c->query('Request'), - $c->query('CertificateManager'), - $c->query('SystemCertificateManager'), - $c->query('L10N'), - $c->query('IAppManager') - ); - }); - $container->registerService('GroupsController', function (IContainer $c) { - return new GroupsController( - $c->query('AppName'), - $c->query('Request'), - $c->query('GroupManager'), - $c->query('UserSession'), - $c->query('IsAdmin'), - $c->query('L10N') - ); - }); - $container->registerService('UsersController', function (IContainer $c) { - return new UsersController( - $c->query('AppName'), - $c->query('Request'), - $c->query('UserManager'), - $c->query('GroupManager'), - $c->query('UserSession'), - $c->query('Config'), - $c->query('SecureRandom'), - $c->query('IsAdmin'), - $c->query('L10N'), - $c->query('Logger'), - $c->query('Defaults'), - $c->query('Mailer'), - $c->query('TimeFactory'), - $c->query('DefaultMailAddress'), - $c->query('URLGenerator'), - $c->query('OCP\\App\\IAppManager'), - $c->query('OCP\\IAvatarManager'), - $c->query('ServerContainer')->getEventDispatcher() - ); - }); - $container->registerService('LogSettingsController', function (IContainer $c) { - return new LogSettingsController( - $c->query('AppName'), - $c->query('Request'), - $c->query('Config'), - $c->query('L10N') - ); - }); - $container->registerService('LegalSettingsController', function (IContainer $c) { - return new LegalSettingsController( - $c->query('AppName'), - $c->query('Request'), - $c->query('L10N'), - $c->query('Config') - ); - }); - $container->registerService('CheckSetupController', function (IContainer $c) { - return new CheckSetupController( - $c->query('AppName'), - $c->query('Request'), - $c->query('Config'), - $c->query('ClientService'), - $c->query('URLGenerator'), - $c->query('Util'), - $c->query('L10N'), - $c->query('Checker') - ); - }); - $container->registerService('CorsController', function (IContainer $c) { - return new CorsController( - $c->query('AppName'), - $c->query('Request'), - $c->query('UserSession'), - $c->query('Logger'), - $c->query('URLGenerator'), - $c->query('Config'), - $c->query('L10N') - ); - }); - $container->registerService('AppConfigController', function (IContainer $c) { - return new AppConfigController( - $c->query('AppName'), - $c->query('Request'), - $c->query('ServerContainer')->getAppConfig() - ); - }); + $container->registerService('SettingsPageController', fn (IContainer $c) => new SettingsPageController( + $c->query('AppName'), + $c->query('Request'), + $c->query('SettingsManager'), + $c->query('ServerContainer')->getURLGenerator(), + $c->query('GroupManager'), + $c->query('UserSession') + )); + $container->registerService('MailSettingsController', fn (IContainer $c) => new MailSettingsController( + $c->query('AppName'), + $c->query('Request'), + $c->query('L10N'), + $c->query('Config'), + $c->query('UserSession'), + $c->query('Defaults'), + $c->query('Mailer'), + $c->query('DefaultMailAddress') + )); + $container->registerService('AppSettingsController', fn (IContainer $c) => new AppSettingsController( + $c->query('AppName'), + $c->query('Request'), + $c->query('L10N'), + $c->query('Config'), + $c->query('IAppManager') + )); + $container->registerService('AuthSettingsController', fn (IContainer $c) => new AuthSettingsController( + $c->query('AppName'), + $c->query('Request'), + $c->query('ServerContainer')->query(\OC\Authentication\Token\IProvider::class), + $c->query('UserManager'), + $c->query('ServerContainer')->getSession(), + $c->query('ServerContainer')->getSecureRandom(), + $c->query('UserId') + )); + $container->registerService('CertificateController', fn (IContainer $c) => new CertificateController( + $c->query('AppName'), + $c->query('Request'), + $c->query('CertificateManager'), + $c->query('SystemCertificateManager'), + $c->query('L10N'), + $c->query('IAppManager') + )); + $container->registerService('GroupsController', fn (IContainer $c) => new GroupsController( + $c->query('AppName'), + $c->query('Request'), + $c->query('GroupManager'), + $c->query('UserSession'), + $c->query('IsAdmin'), + $c->query('L10N') + )); + $container->registerService('UsersController', fn (IContainer $c) => new UsersController( + $c->query('AppName'), + $c->query('Request'), + $c->query('UserManager'), + $c->query('GroupManager'), + $c->query('UserSession'), + $c->query('Config'), + $c->query('SecureRandom'), + $c->query('IsAdmin'), + $c->query('L10N'), + $c->query('Logger'), + $c->query('Defaults'), + $c->query('Mailer'), + $c->query('TimeFactory'), + $c->query('DefaultMailAddress'), + $c->query('URLGenerator'), + $c->query(\OCP\App\IAppManager::class), + $c->query(\OCP\IAvatarManager::class), + $c->query('ServerContainer')->getEventDispatcher() + )); + $container->registerService('LogSettingsController', fn (IContainer $c) => new LogSettingsController( + $c->query('AppName'), + $c->query('Request'), + $c->query('Config'), + $c->query('L10N') + )); + $container->registerService('LegalSettingsController', fn (IContainer $c) => new LegalSettingsController( + $c->query('AppName'), + $c->query('Request'), + $c->query('L10N'), + $c->query('Config') + )); + $container->registerService('CheckSetupController', fn (IContainer $c) => new CheckSetupController( + $c->query('AppName'), + $c->query('Request'), + $c->query('Config'), + $c->query('ClientService'), + $c->query('URLGenerator'), + $c->query('Util'), + $c->query('L10N'), + $c->query('Checker') + )); + $container->registerService('CorsController', fn (IContainer $c) => new CorsController( + $c->query('AppName'), + $c->query('Request'), + $c->query('UserSession'), + $c->query('Logger'), + $c->query('URLGenerator'), + $c->query('Config'), + $c->query('L10N') + )); + $container->registerService('AppConfigController', fn (IContainer $c) => new AppConfigController( + $c->query('AppName'), + $c->query('Request'), + $c->query('ServerContainer')->getAppConfig() + )); /** * Middleware */ - $container->registerService('SubadminMiddleware', function (IContainer $c) { - return new SubadminMiddleware( - $c->query('ControllerMethodReflector'), - $c->query('IsSubAdmin') - ); - }); + $container->registerService('SubadminMiddleware', fn (IContainer $c) => new SubadminMiddleware( + $c->query('ControllerMethodReflector'), + $c->query('IsSubAdmin') + )); // Execute middlewares $container->registerMiddleware('SubadminMiddleware'); /** * Core class wrappers */ - $container->registerService('Config', function (IContainer $c) { - return $c->query('ServerContainer')->getConfig(); - }); - $container->registerService('ICacheFactory', function (IContainer $c) { - return $c->query('ServerContainer')->getMemCacheFactory(); - }); - $container->registerService('L10N', function (IContainer $c) { - return $c->query('ServerContainer')->getL10N('settings'); - }); - $container->registerService('GroupManager', function (IContainer $c) { - return $c->query('ServerContainer')->getGroupManager(); - }); - $container->registerService('UserManager', function (IContainer $c) { - return $c->query('ServerContainer')->getUserManager(); - }); - $container->registerService('UserSession', function (IContainer $c) { - return $c->query('ServerContainer')->getUserSession(); - }); + $container->registerService('Config', fn (IContainer $c) => $c->query('ServerContainer')->getConfig()); + $container->registerService('ICacheFactory', fn (IContainer $c) => $c->query('ServerContainer')->getMemCacheFactory()); + $container->registerService('L10N', fn (IContainer $c) => $c->query('ServerContainer')->getL10N('settings')); + $container->registerService('GroupManager', fn (IContainer $c) => $c->query('ServerContainer')->getGroupManager()); + $container->registerService('UserManager', fn (IContainer $c) => $c->query('ServerContainer')->getUserManager()); + $container->registerService('UserSession', fn (IContainer $c) => $c->query('ServerContainer')->getUserSession()); /** FIXME: Remove once OC_User is non-static and mockable */ - $container->registerService('IsAdmin', function (IContainer $c) { - return \OC_User::isAdminUser(\OC_User::getUser()); - }); + $container->registerService('IsAdmin', fn (IContainer $c) => \OC_User::isAdminUser(\OC_User::getUser())); /** FIXME: Remove once OC_SubAdmin is non-static and mockable */ $container->registerService('IsSubAdmin', function (IContainer $c) { $userObject = \OC::$server->getUserSession()->getUser(); @@ -242,58 +202,26 @@ public function __construct(array $urlParams=[]) { } return $isSubAdmin; }); - $container->registerService('Mailer', function (IContainer $c) { - return $c->query('ServerContainer')->getMailer(); - }); - $container->registerService('Defaults', function (IContainer $c) { - return new \OC_Defaults; - }); - $container->registerService('DefaultMailAddress', function (IContainer $c) { - return Util::getDefaultEmailAddress('no-reply'); - }); - $container->registerService('Logger', function (IContainer $c) { - return $c->query('ServerContainer')->getLogger(); - }); - $container->registerService('URLGenerator', function (IContainer $c) { - return $c->query('ServerContainer')->getURLGenerator(); - }); - $container->registerService('ClientService', function (IContainer $c) { - return $c->query('ServerContainer')->getHTTPClientService(); - }); - $container->registerService('INavigationManager', function (IContainer $c) { - return $c->query('ServerContainer')->getNavigationManager(); - }); - $container->registerService('IAppManager', function (IContainer $c) { - return $c->query('ServerContainer')->getAppManager(); - }); - $container->registerService('OcsClient', function (IContainer $c) { - return $c->query('ServerContainer')->getOcsClient(); - }); - $container->registerService('Util', function (IContainer $c) { - return new \OC_Util(); - }); - $container->registerService('DatabaseConnection', function (IContainer $c) { - return $c->query('ServerContainer')->getDatabaseConnection(); - }); - $container->registerService('CertificateManager', function (IContainer $c) { - return $c->query('ServerContainer')->getCertificateManager(); - }); - $container->registerService('SystemCertificateManager', function (IContainer $c) { - return $c->query('ServerContainer')->getCertificateManager(null); - }); + $container->registerService('Mailer', fn (IContainer $c) => $c->query('ServerContainer')->getMailer()); + $container->registerService('Defaults', fn (IContainer $c) => new \OC_Defaults); + $container->registerService('DefaultMailAddress', fn (IContainer $c) => Util::getDefaultEmailAddress('no-reply')); + $container->registerService('Logger', fn (IContainer $c) => $c->query('ServerContainer')->getLogger()); + $container->registerService('URLGenerator', fn (IContainer $c) => $c->query('ServerContainer')->getURLGenerator()); + $container->registerService('ClientService', fn (IContainer $c) => $c->query('ServerContainer')->getHTTPClientService()); + $container->registerService('INavigationManager', fn (IContainer $c) => $c->query('ServerContainer')->getNavigationManager()); + $container->registerService('IAppManager', fn (IContainer $c) => $c->query('ServerContainer')->getAppManager()); + $container->registerService('OcsClient', fn (IContainer $c) => $c->query('ServerContainer')->getOcsClient()); + $container->registerService('Util', fn (IContainer $c) => new \OC_Util()); + $container->registerService('DatabaseConnection', fn (IContainer $c) => $c->query('ServerContainer')->getDatabaseConnection()); + $container->registerService('CertificateManager', fn (IContainer $c) => $c->query('ServerContainer')->getCertificateManager()); + $container->registerService('SystemCertificateManager', fn (IContainer $c) => $c->query('ServerContainer')->getCertificateManager(null)); $container->registerService('Checker', function (IContainer $c) { /** @var Server $server */ $server = $c->query('ServerContainer'); return $server->getIntegrityCodeChecker(); }); - $container->registerService('TimeFactory', function (IContainer $c) { - return new TimeFactory(); - }); - $container->registerService('SecureRandom', function (IContainer $c) { - return $c->query('ServerContainer')->getSecureRandom(); - }); - $container->registerService('SettingsManager', function (IContainer $c) { - return $c->query('ServerContainer')->getSettingsManager(); - }); + $container->registerService('TimeFactory', fn (IContainer $c) => new TimeFactory()); + $container->registerService('SecureRandom', fn (IContainer $c) => $c->query('ServerContainer')->getSecureRandom()); + $container->registerService('SettingsManager', fn (IContainer $c) => $c->query('ServerContainer')->getSettingsManager()); } } diff --git a/settings/ChangePassword/Controller.php b/settings/ChangePassword/Controller.php index 487777b718c3..c914dacf1a28 100644 --- a/settings/ChangePassword/Controller.php +++ b/settings/ChangePassword/Controller.php @@ -39,8 +39,8 @@ public static function changePersonalPassword($args) { \OC_JSON::checkLoggedIn(); $username = \OC_User::getUser(); - $password = isset($_POST['personal-password']) ? $_POST['personal-password'] : null; - $oldPassword = isset($_POST['oldpassword']) ? $_POST['oldpassword'] : ''; + $password = $_POST['personal-password'] ?? null; + $oldPassword = $_POST['oldpassword'] ?? ''; if (!\OC_User::checkPassword($username, $oldPassword)) { $l = \OC::$server->getL10NFactory()->get('settings'); @@ -80,8 +80,8 @@ public static function changeUserPassword($args) { exit(); } - $password = isset($_POST['password']) ? $_POST['password'] : null; - $recoveryPassword = isset($_POST['recoveryPassword']) ? $_POST['recoveryPassword'] : null; + $password = $_POST['password'] ?? null; + $recoveryPassword = $_POST['recoveryPassword'] ?? null; $isUserAccessible = false; $currentUserObject = \OC::$server->getUserSession()->getUser(); diff --git a/settings/Controller/AppConfigController.php b/settings/Controller/AppConfigController.php index 92f2b6ed227d..5d6cbce2aab0 100644 --- a/settings/Controller/AppConfigController.php +++ b/settings/Controller/AppConfigController.php @@ -36,8 +36,7 @@ * @package OC\Settings\Controller */ class AppConfigController extends Controller { - /** @var IAppConfig */ - private $appConfig; + private \OCP\IAppConfig $appConfig; /** * @param string $appName diff --git a/settings/Controller/AppSettingsController.php b/settings/Controller/AppSettingsController.php index 45f9b18a2ccf..38471545bf73 100644 --- a/settings/Controller/AppSettingsController.php +++ b/settings/Controller/AppSettingsController.php @@ -40,12 +40,9 @@ class AppSettingsController extends Controller { public const CAT_ENABLED = 0; public const CAT_DISABLED = 1; - /** @var \OCP\IL10N */ - private $l10n; - /** @var IConfig */ - private $config; - /** @var IAppManager */ - private $appManager; + private \OCP\IL10N $l10n; + private \OCP\IConfig $config; + private \OCP\App\IAppManager $appManager; /** * @param string $appName @@ -84,25 +81,17 @@ public function listApps($category = '') { \usort($apps, function ($a, $b) { $a = (string)$a['name']; $b = (string)$b['name']; - if ($a === $b) { - return 0; - } - return ($a < $b) ? -1 : 1; + return $a <=> $b; }); break; // not-installed apps case 'disabled': $apps = \OC_App::listAllApps(); - $apps = \array_filter($apps, function ($app) { - return !$app['active']; - }); + $apps = \array_filter($apps, fn ($app) => !$app['active']); \usort($apps, function ($a, $b) { $a = (string)$a['name']; $b = (string)$b['name']; - if ($a === $b) { - return 0; - } - return ($a < $b) ? -1 : 1; + return $a <=> $b; }); break; default: @@ -117,7 +106,7 @@ public function listApps($category = '') { // fix groups $groups = []; if (\is_string($app['groups'])) { - $groups = \json_decode($app['groups']); + $groups = \json_decode($app['groups'], null, 512, JSON_THROW_ON_ERROR); } elseif (\is_array($app['groups'])) { $groups = $app['groups']; } @@ -148,9 +137,7 @@ public function listApps($category = '') { */ private function getInstalledApps() { $apps = \OC_App::listAllApps(); - $apps = \array_filter($apps, function ($app) { - return $app['active']; - }); + $apps = \array_filter($apps, fn ($app) => $app['active']); return $apps; } } diff --git a/settings/Controller/AuthSettingsController.php b/settings/Controller/AuthSettingsController.php index 9339834e9950..4dffa433aae4 100644 --- a/settings/Controller/AuthSettingsController.php +++ b/settings/Controller/AuthSettingsController.php @@ -35,20 +35,16 @@ use OCP\Session\Exceptions\SessionNotAvailableException; class AuthSettingsController extends Controller { - /** @var IProvider */ - private $tokenProvider; + private \OC\Authentication\Token\IProvider $tokenProvider; - /** @var IUserManager */ - private $userManager; + private \OCP\IUserManager $userManager; - /** @var ISession */ - private $session; + private \OCP\ISession $session; /** @var string */ private $uid; - /** @var ISecureRandom */ - private $random; + private \OCP\Security\ISecureRandom $random; /** * @param string $appName @@ -141,9 +137,7 @@ public function create($name) { 'loginName' => $loginName, 'deviceToken' => $deviceToken ]; - } catch (\InvalidArgumentException $ex) { - return $this->getServiceNotAvailableResponse(); - } catch (InvalidTokenException $ex) { + } catch (\InvalidArgumentException|InvalidTokenException $ex) { return $this->getServiceNotAvailableResponse(); } } diff --git a/settings/Controller/CertificateController.php b/settings/Controller/CertificateController.php index 1aadb215fa33..43c58867e61f 100644 --- a/settings/Controller/CertificateController.php +++ b/settings/Controller/CertificateController.php @@ -36,14 +36,10 @@ * @package OC\Settings\Controller */ class CertificateController extends Controller { - /** @var ICertificateManager */ - private $userCertificateManager; - /** @var ICertificateManager */ - private $systemCertificateManager; - /** @var IL10N */ - private $l10n; - /** @var IAppManager */ - private $appManager; + private \OCP\ICertificateManager $userCertificateManager; + private \OCP\ICertificateManager $systemCertificateManager; + private \OCP\IL10N $l10n; + private \OCP\App\IAppManager $appManager; /** * @param string $appName diff --git a/settings/Controller/CheckSetupController.php b/settings/Controller/CheckSetupController.php index 828d9350bf83..12a59f8c74d6 100644 --- a/settings/Controller/CheckSetupController.php +++ b/settings/Controller/CheckSetupController.php @@ -43,18 +43,12 @@ * @package OC\Settings\Controller */ class CheckSetupController extends Controller { - /** @var IConfig */ - private $config; - /** @var IClientService */ - private $clientService; - /** @var \OC_Util */ - private $util; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var IL10N */ - private $l10n; - /** @var Checker */ - private $checker; + private \OCP\IConfig $config; + private \OCP\Http\Client\IClientService $clientService; + private \OC_Util $util; + private \OCP\IURLGenerator $urlGenerator; + private \OCP\IL10N $l10n; + private \OC\IntegrityCheck\Checker $checker; /** * @param string $AppName @@ -232,7 +226,7 @@ private function forwardedForHeadersWorking() { * @return bool */ private function isCorrectMemcachedPHPModuleInstalled() { - if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') { + if ($this->config->getSystemValue('memcache.distributed', null) !== '\\' . \OC\Memcache\Memcached::class) { return true; } diff --git a/settings/Controller/CorsController.php b/settings/Controller/CorsController.php index 53f6bb98a0f7..38fd3575ceaa 100644 --- a/settings/Controller/CorsController.php +++ b/settings/Controller/CorsController.php @@ -33,23 +33,19 @@ * @package OC\Settings\Controller */ class CorsController extends Controller { - /** @var ILogger */ - private $logger; + private \OCP\ILogger $logger; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; /** @var string */ private $userId; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; /** @var string */ private $AppName; - /** @var IL10N */ - private $l10n; + private \OCP\IL10N $l10n; /** * CorsController constructor. @@ -90,7 +86,7 @@ public function __construct( */ public function getDomains() { $userId = $this->userId; - $domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true); + $domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true, 512, JSON_THROW_ON_ERROR); return new JSONResponse($domains); } @@ -106,7 +102,7 @@ public function getDomains() { public function addDomain($domain) { if ($this->isValidUrl($domain)) { $userId = $this->userId; - $domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true); + $domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true, 512, JSON_THROW_ON_ERROR); $domains = \array_filter($domains); \array_push($domains, $domain); @@ -114,7 +110,7 @@ public function addDomain($domain) { $domains = \array_unique($domains); // Store as comma separated string - $domainsString = \json_encode($domains); + $domainsString = \json_encode($domains, JSON_THROW_ON_ERROR); $this->config->setUserValue($userId, 'core', 'domains', $domainsString); $this->logger->debug("The domain {$domain} has been white-listed.", ['app' => $this->appName]); @@ -137,11 +133,11 @@ public function addDomain($domain) { public function removeDomain($domain) { $userId = $this->userId; $decodedDomain = \urldecode($domain); - $domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true); + $domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true, 512, JSON_THROW_ON_ERROR); if (($key = \array_search($decodedDomain, $domains)) !== false) { unset($domains[$key]); if (\count($domains)) { - $this->config->setUserValue($userId, 'core', 'domains', \json_encode($domains)); + $this->config->setUserValue($userId, 'core', 'domains', \json_encode($domains, JSON_THROW_ON_ERROR)); } else { $this->config->deleteUserValue($userId, 'core', 'domains'); } diff --git a/settings/Controller/GroupsController.php b/settings/Controller/GroupsController.php index 222d2612e6a7..504aefe364f8 100644 --- a/settings/Controller/GroupsController.php +++ b/settings/Controller/GroupsController.php @@ -37,12 +37,9 @@ * @package OC\Settings\Controller */ class GroupsController extends Controller { - /** @var IGroupManager */ - private $groupManager; - /** @var IL10N */ - private $l10n; - /** @var IUserSession */ - private $userSession; + private \OCP\IGroupManager $groupManager; + private \OCP\IL10N $l10n; + private \OCP\IUserSession $userSession; /** @var bool */ private $isAdmin; @@ -87,7 +84,7 @@ public function index($pattern = '', $filterGroups = false, $sortGroups = MetaDa $this->userSession ); $groupsInfo->setSorting($sortGroups); - list($adminGroups, $groups) = $groupsInfo->get($groupPattern, $pattern); + [$adminGroups, $groups] = $groupsInfo->get($groupPattern, $pattern); return new DataResponse( [ diff --git a/settings/Controller/LegalSettingsController.php b/settings/Controller/LegalSettingsController.php index af0eede18077..cba40ad04d59 100644 --- a/settings/Controller/LegalSettingsController.php +++ b/settings/Controller/LegalSettingsController.php @@ -30,15 +30,9 @@ * @package OC\Settings\Controller */ class LegalSettingsController extends Controller { - /** - * @var \OCP\IL10N - */ - private $l10n; + private \OCP\IL10N $l10n; - /** - * @var \OCP\IConfig - */ - private $config; + private \OCP\IConfig $config; /** * @param string $appName diff --git a/settings/Controller/LogSettingsController.php b/settings/Controller/LogSettingsController.php index 50209f317d16..e7267e80b883 100644 --- a/settings/Controller/LogSettingsController.php +++ b/settings/Controller/LogSettingsController.php @@ -39,15 +39,9 @@ * @package OC\Settings\Controller */ class LogSettingsController extends Controller { - /** - * @var \OCP\IConfig - */ - private $config; + private \OCP\IConfig $config; - /** - * @var \OCP\IL10N - */ - private $l10n; + private \OCP\IL10N $l10n; /** * @param string $appName diff --git a/settings/Controller/MailSettingsController.php b/settings/Controller/MailSettingsController.php index 9e6e3287e1d4..4936b4c8889e 100644 --- a/settings/Controller/MailSettingsController.php +++ b/settings/Controller/MailSettingsController.php @@ -36,16 +36,11 @@ * @package OC\Settings\Controller */ class MailSettingsController extends Controller { - /** @var \OCP\IL10N */ - private $l10n; - /** @var \OCP\IConfig */ - private $config; - /** @var Session */ - private $userSession; - /** @var \OC_Defaults */ - private $defaults; - /** @var IMailer */ - private $mailer; + private \OCP\IL10N $l10n; + private \OCP\IConfig $config; + private \OC\User\Session $userSession; + private \OC_Defaults $defaults; + private \OCP\Mail\IMailer $mailer; /** @var string */ private $defaultMailAddress; diff --git a/settings/Controller/UsersController.php b/settings/Controller/UsersController.php index aadc712e335e..b0d6a3ebfa7b 100644 --- a/settings/Controller/UsersController.php +++ b/settings/Controller/UsersController.php @@ -64,40 +64,28 @@ * @package OC\Settings\Controller */ class UsersController extends Controller { - /** @var IL10N */ - private $l10n; - /** @var Session */ - private $userSession; + private \OCP\IL10N $l10n; + private \OC\User\Session $userSession; /** @var bool */ private $isAdmin; - /** @var IUserManager */ - private $userManager; - /** @var IGroupManager */ - private $groupManager; - /** @var IConfig */ - private $config; - /** @var ILogger */ - private $log; - /** @var \OC_Defaults */ - private $defaults; - /** @var IMailer */ - private $mailer; + private \OCP\IUserManager $userManager; + private \OCP\IGroupManager $groupManager; + private \OCP\IConfig $config; + private \OCP\ILogger $log; + private \OC_Defaults $defaults; + private \OCP\Mail\IMailer $mailer; /** @var string */ private $fromMailAddress; - /** @var IURLGenerator */ - private $urlGenerator; + private \OCP\IURLGenerator $urlGenerator; /** @var bool contains the state of the admin recovery setting */ - private $isRestoreEnabled = false; - /** @var IAvatarManager */ - private $avatarManager; + private bool $isRestoreEnabled = false; + private \OCP\IAvatarManager $avatarManager; /** @var ISecureRandom */ protected $secureRandom; /** @var ITimeFactory */ protected $timeFactory; - /** @var EventDispatcherInterface */ - private $eventDispatcher; - /** @var UserTypeHelper */ - private $userTypeHelper; + private \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher; + private \OC\Helper\UserTypeHelper $userTypeHelper; /** * @param string $appName @@ -217,7 +205,7 @@ private function formatUserForIndex(IUser $user, array $userGroups = null) { } } - $groups = ($userGroups === null) ? $this->groupManager->getUserGroups($user, 'management') : $userGroups; + $groups = $userGroups ?? $this->groupManager->getUserGroups($user, 'management'); $groupsKV = []; foreach ($groups as $group) { $groupsKV[$group->getGID()] = [ diff --git a/settings/Panels/Admin/Enforce2fa.php b/settings/Panels/Admin/Enforce2fa.php index 832a9523f5d9..0a9713464c63 100644 --- a/settings/Panels/Admin/Enforce2fa.php +++ b/settings/Panels/Admin/Enforce2fa.php @@ -36,7 +36,7 @@ public function getPriority() { } public function getPanel() { - $enforce2faExcludedGroups = \json_decode($this->config->getAppValue('core', 'enforce_2fa_excluded_groups', '[]'), true); + $enforce2faExcludedGroups = \json_decode($this->config->getAppValue('core', 'enforce_2fa_excluded_groups', '[]'), true, 512, JSON_THROW_ON_ERROR); $tmpl = new Template('settings', 'panels/admin/enforce2fa'); $tmpl->assign('enforce2fa', $this->config->getAppValue('core', 'enforce_2fa', 'no') === 'yes'); $tmpl->assign('enforce2faExcludedGroups', \implode('|', $enforce2faExcludedGroups)); diff --git a/settings/Panels/Admin/FileSharing.php b/settings/Panels/Admin/FileSharing.php index 43c1d424bd0f..e7c14bd0066a 100644 --- a/settings/Panels/Admin/FileSharing.php +++ b/settings/Panels/Admin/FileSharing.php @@ -33,10 +33,8 @@ class FileSharing implements ISettings { protected $config; /** @var Helper */ protected $helper; - /** @var IFactory */ - private $lfactory; - /** @var LocaleHelper */ - private $localeHelper; + private \OCP\L10N\IFactory $lfactory; + private ?\OC\Helper\LocaleHelper $localeHelper = null; public function __construct(IConfig $config, Helper $helper, IFactory $lfactory) { $this->config = $config; @@ -56,7 +54,7 @@ public function getPanel() { 'owner' ); $this->localeHelper = new LocaleHelper(); - list($userLang, $commonLanguages, $languages) = $this->localeHelper->getNormalizedLanguages( + [$userLang, $commonLanguages, $languages] = $this->localeHelper->getNormalizedLanguages( $this->lfactory, $activeLangCode ); @@ -103,7 +101,7 @@ public function getPanel() { $excludeGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes' ? true : false; $template->assign('shareExcludeGroups', $excludeGroups); $excludedGroupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); - $excludedGroupsList = \json_decode($excludedGroupsList); + $excludedGroupsList = \json_decode($excludedGroupsList, null, 512, JSON_THROW_ON_ERROR); $template->assign('shareExcludedGroupsList', $excludedGroupsList !== null ? \implode('|', $excludedGroupsList) : ''); $template->assign('shareExpireAfterNDays', $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7')); $template->assign('shareEnforceExpireDate', $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no')); diff --git a/settings/Panels/Admin/License.php b/settings/Panels/Admin/License.php index 436531b4bc45..2b06068fc2c4 100644 --- a/settings/Panels/Admin/License.php +++ b/settings/Panels/Admin/License.php @@ -26,8 +26,7 @@ use OCP\Template; class License implements ISettings { - /** @var ILicenseManager */ - private $licenseManager; + private \OCP\License\ILicenseManager $licenseManager; public function __construct(ILicenseManager $licenseManager) { $this->licenseManager = $licenseManager; diff --git a/settings/Panels/Admin/PersistentLocking.php b/settings/Panels/Admin/PersistentLocking.php index 94cfeeee90b7..42e9c861ba46 100644 --- a/settings/Panels/Admin/PersistentLocking.php +++ b/settings/Panels/Admin/PersistentLocking.php @@ -27,8 +27,7 @@ use OCP\IConfig; class PersistentLocking implements ISettings { - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; public function __construct(IConfig $config) { $this->config = $config; @@ -43,7 +42,7 @@ public function getSectionID() { } public function getPanel() { - $lockBreakerGroups = \json_decode($this->config->getAppValue('core', 'lock-breaker-groups', '[]'), true); + $lockBreakerGroups = \json_decode($this->config->getAppValue('core', 'lock-breaker-groups', '[]'), true, 512, JSON_THROW_ON_ERROR); // we must use the same container $tmpl = new Template('settings', 'panels/admin/persistentlocking'); diff --git a/settings/Panels/Personal/Cors.php b/settings/Panels/Personal/Cors.php index 54a1cb3ad7cc..39e062801b73 100644 --- a/settings/Panels/Personal/Cors.php +++ b/settings/Panels/Personal/Cors.php @@ -35,8 +35,7 @@ class Cors implements ISettings { */ protected $urlGenerator; - /** @var IConfig */ - private $config; + private \OCP\IConfig $config; public function __construct( IUserSession $userSession, @@ -57,7 +56,7 @@ public function getSectionID() { */ public function getPanel() { $userId = $this->userSession->getUser()->getUID(); - $domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true); + $domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true, 512, JSON_THROW_ON_ERROR); $t = new Template('settings', 'panels/personal/cors'); $t->assign('user_id', $userId); diff --git a/settings/Panels/Personal/Legacy.php b/settings/Panels/Personal/Legacy.php index 5d4576e579b3..697d3ae5f01f 100644 --- a/settings/Panels/Personal/Legacy.php +++ b/settings/Panels/Personal/Legacy.php @@ -28,8 +28,7 @@ use OC\Settings\Panels\Helper; class Legacy implements ISettings { - /** @var Helper */ - private $helper; + private \OC\Settings\Panels\Helper $helper; public function __construct(Helper $helper) { $this->helper = $helper; diff --git a/settings/Panels/Personal/Profile.php b/settings/Panels/Personal/Profile.php index bd7caeb062fb..58891a82ec61 100644 --- a/settings/Panels/Personal/Profile.php +++ b/settings/Panels/Personal/Profile.php @@ -42,10 +42,7 @@ class Profile implements ISettings { /** @var IFactory */ protected $lfactory; - /** - * @var LocaleHelper - */ - private $localeHelper; + private \OC\Helper\LocaleHelper $localeHelper; /** * Profile constructor. @@ -82,7 +79,7 @@ public function getPanel() { $this->lfactory->findLanguage() ); - list($userLang, $commonLanguages, $languages) = $this->localeHelper->getNormalizedLanguages( + [$userLang, $commonLanguages, $languages] = $this->localeHelper->getNormalizedLanguages( $this->lfactory, $activeLangCode ); diff --git a/settings/ajax/togglegroups.php b/settings/ajax/togglegroups.php index 5b60bb740fdf..b5251e4851fa 100644 --- a/settings/ajax/togglegroups.php +++ b/settings/ajax/togglegroups.php @@ -73,9 +73,7 @@ $action = "remove"; $targetGroupObject->removeUser($targetUserObject); $usersInGroup = $targetGroupObject->getUsers(); - $usersInGroup = \array_values(\array_map(function (\OCP\IUser $g) { - return $g->getUID(); - }, $usersInGroup)); + $usersInGroup = \array_values(\array_map(fn (\OCP\IUser $g) => $g->getUID(), $usersInGroup)); } else { $targetGroupObject->addUser($targetUserObject); } diff --git a/settings/routes.php b/settings/routes.php index 21868b4f339f..9e311fa5a8b3 100644 --- a/settings/routes.php +++ b/settings/routes.php @@ -97,13 +97,13 @@ ->actionInclude('settings/ajax/togglesubadmins.php'); $this->create('settings_users_changepassword', '/settings/users/changepassword') ->post() - ->action('OC\Settings\ChangePassword\Controller', 'changeUserPassword'); + ->action(\OC\Settings\ChangePassword\Controller::class, 'changeUserPassword'); $this->create('settings_ajax_changegroupname', '/settings/ajax/changegroupname.php') ->actionInclude('settings/ajax/changegroupname.php'); // personal $this->create('settings_personal_changepassword', '/settings/personal/changepassword') ->post() - ->action('OC\Settings\ChangePassword\Controller', 'changePersonalPassword'); + ->action(\OC\Settings\ChangePassword\Controller::class, 'changePersonalPassword'); $this->create('settings_ajax_setlanguage', '/settings/ajax/setlanguage.php') ->actionInclude('settings/ajax/setlanguage.php'); // apps diff --git a/settings/users.php b/settings/users.php index 0b3c3a681bc9..51f947386021 100644 --- a/settings/users.php +++ b/settings/users.php @@ -67,7 +67,7 @@ \OC::$server->getUserSession() ); $groupsInfo->setSorting($sortGroupsBy); -list($adminGroup, $groups) = $groupsInfo->get(); +[$adminGroup, $groups] = $groupsInfo->get(); $recoveryAdminEnabled = OC_App::isEnabled('encryption') && $config->getAppValue('encryption', 'recoveryAdminEnabled', null); diff --git a/tests/Core/Command/Apps/AppsDisableTest.php b/tests/Core/Command/Apps/AppsDisableTest.php index 00f956fa065b..30ca1bec20ef 100644 --- a/tests/Core/Command/Apps/AppsDisableTest.php +++ b/tests/Core/Command/Apps/AppsDisableTest.php @@ -31,8 +31,7 @@ * @group DB */ class AppsDisableTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; public function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Apps/AppsEnableTest.php b/tests/Core/Command/Apps/AppsEnableTest.php index 38ac05e2494a..2eac82288a7d 100644 --- a/tests/Core/Command/Apps/AppsEnableTest.php +++ b/tests/Core/Command/Apps/AppsEnableTest.php @@ -31,8 +31,7 @@ * @group DB */ class AppsEnableTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; public function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Apps/AppsGetPathTest.php b/tests/Core/Command/Apps/AppsGetPathTest.php index 333dd4422859..788fb9d15ebf 100644 --- a/tests/Core/Command/Apps/AppsGetPathTest.php +++ b/tests/Core/Command/Apps/AppsGetPathTest.php @@ -31,8 +31,7 @@ * @group DB */ class AppsGetPathTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; public function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Apps/AppsListTest.php b/tests/Core/Command/Apps/AppsListTest.php index 78f4b56f8a9d..3ac5de151adb 100644 --- a/tests/Core/Command/Apps/AppsListTest.php +++ b/tests/Core/Command/Apps/AppsListTest.php @@ -31,8 +31,7 @@ * @group DB */ class AppsListTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; public function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Apps/CheckCodeTest.php b/tests/Core/Command/Apps/CheckCodeTest.php index 90edb4322e60..36d10a6cfd38 100644 --- a/tests/Core/Command/Apps/CheckCodeTest.php +++ b/tests/Core/Command/Apps/CheckCodeTest.php @@ -32,8 +32,7 @@ * @group DB */ class CheckCodeTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private ?\Symfony\Component\Console\Tester\CommandTester $commandTester = null; /** */ diff --git a/tests/Core/Command/Background/Queue/DeleteTest.php b/tests/Core/Command/Background/Queue/DeleteTest.php index 9e616db64c0d..520b89092b9c 100644 --- a/tests/Core/Command/Background/Queue/DeleteTest.php +++ b/tests/Core/Command/Background/Queue/DeleteTest.php @@ -32,19 +32,16 @@ * @group DB */ class DeleteTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; /** @var IJobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; public function setUp(): void { parent::setUp(); $this->jobList = $this->createMock(IJobList::class); $this->jobList->expects($this->any())->method('jobIdExists') - ->willReturnCallback(function ($id) { - return ($id !== '666') ? true : false; - }); + ->willReturnCallback(fn ($id) => ($id !== '666') ? true : false); $command = new Delete($this->jobList); $this->commandTester = new CommandTester($command); diff --git a/tests/Core/Command/Background/Queue/ExecuteTest.php b/tests/Core/Command/Background/Queue/ExecuteTest.php index 9745825c7aa7..3d2bb57e68e7 100644 --- a/tests/Core/Command/Background/Queue/ExecuteTest.php +++ b/tests/Core/Command/Background/Queue/ExecuteTest.php @@ -35,12 +35,11 @@ * @group DB */ class ExecuteTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; /** @var IJobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var ITimeFactory */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** @var IJob[] */ private $jobById = []; diff --git a/tests/Core/Command/Background/Queue/StatusTest.php b/tests/Core/Command/Background/Queue/StatusTest.php index 90c22b41b32f..54d410f0ec68 100644 --- a/tests/Core/Command/Background/Queue/StatusTest.php +++ b/tests/Core/Command/Background/Queue/StatusTest.php @@ -34,10 +34,9 @@ * @group DB */ class StatusTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; /** @var IJobList */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; public function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Config/App/DeleteConfigTest.php b/tests/Core/Command/Config/App/DeleteConfigTest.php index 5b877a75ce12..be296373b3c4 100644 --- a/tests/Core/Command/Config/App/DeleteConfigTest.php +++ b/tests/Core/Command/Config/App/DeleteConfigTest.php @@ -39,11 +39,11 @@ class DeleteConfigTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = $this->config = $this->getMockBuilder('OCP\IConfig') + $config = $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\IConfig $config */ $this->command = new DeleteConfig($config); diff --git a/tests/Core/Command/Config/App/GetConfigTest.php b/tests/Core/Command/Config/App/GetConfigTest.php index 64c5fd8b668f..d7e5afbf1a5a 100644 --- a/tests/Core/Command/Config/App/GetConfigTest.php +++ b/tests/Core/Command/Config/App/GetConfigTest.php @@ -63,17 +63,17 @@ public function getData() { ['name', null, false, null, false, 'json', 1, null], // Int "0" output as json/plain - ['name', 0, true, null, false, 'json', 0, \json_encode(0)], + ['name', 0, true, null, false, 'json', 0, \json_encode(0, JSON_THROW_ON_ERROR)], ['name', 0, true, null, false, 'plain', 0, '0'], // Int "1" output as json/plain - ['name', 1, true, null, false, 'json', 0, \json_encode(1)], + ['name', 1, true, null, false, 'json', 0, \json_encode(1, JSON_THROW_ON_ERROR)], ['name', 1, true, null, false, 'plain', 0, '1'], // Bool "true" output as json/plain - ['name', true, true, null, false, 'json', 0, \json_encode(true)], + ['name', true, true, null, false, 'json', 0, \json_encode(true, JSON_THROW_ON_ERROR)], ['name', true, true, null, false, 'plain', 0, 'true'], // Bool "false" output as json/plain - ['name', false, true, null, false, 'json', 0, \json_encode(false)], + ['name', false, true, null, false, 'json', 0, \json_encode(false, JSON_THROW_ON_ERROR)], ['name', false, true, null, false, 'plain', 0, 'false'], // Null output as json/plain diff --git a/tests/Core/Command/Config/App/SetConfigTest.php b/tests/Core/Command/Config/App/SetConfigTest.php index db87c11d1fcb..c53720993e2a 100644 --- a/tests/Core/Command/Config/App/SetConfigTest.php +++ b/tests/Core/Command/Config/App/SetConfigTest.php @@ -39,11 +39,11 @@ class SetConfigTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = $this->config = $this->getMockBuilder('OCP\IConfig') + $config = $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\IConfig $config */ $this->command = new SetConfig($config); diff --git a/tests/Core/Command/Config/ImportTest.php b/tests/Core/Command/Config/ImportTest.php index 0c622af10389..ca5478772860 100644 --- a/tests/Core/Command/Config/ImportTest.php +++ b/tests/Core/Command/Config/ImportTest.php @@ -39,11 +39,11 @@ class ImportTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = $this->config = $this->getMockBuilder('OCP\IConfig') + $config = $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\IConfig $config */ $this->command = new Import($config); diff --git a/tests/Core/Command/Config/ListConfigsTest.php b/tests/Core/Command/Config/ListConfigsTest.php index 7e7803fb6838..5bb9ddfaed95 100644 --- a/tests/Core/Command/Config/ListConfigsTest.php +++ b/tests/Core/Command/Config/ListConfigsTest.php @@ -42,14 +42,14 @@ class ListConfigsTest extends TestCase { protected function setUp(): void { parent::setUp(); - $systemConfig = $this->systemConfig = $this->getMockBuilder('OC\SystemConfig') + $systemConfig = $this->systemConfig = $this->getMockBuilder(\OC\SystemConfig::class) ->disableOriginalConstructor() ->getMock(); - $appConfig = $this->appConfig = $this->getMockBuilder('OCP\IAppConfig') + $appConfig = $this->appConfig = $this->getMockBuilder(\OCP\IAppConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OC\SystemConfig $systemConfig */ /** @var \OCP\IAppConfig $appConfig */ diff --git a/tests/Core/Command/Config/System/DeleteConfigTest.php b/tests/Core/Command/Config/System/DeleteConfigTest.php index f66875387015..2a17fbed23de 100644 --- a/tests/Core/Command/Config/System/DeleteConfigTest.php +++ b/tests/Core/Command/Config/System/DeleteConfigTest.php @@ -39,11 +39,11 @@ class DeleteConfigTest extends TestCase { protected function setUp(): void { parent::setUp(); - $systemConfig = $this->systemConfig = $this->getMockBuilder('OC\SystemConfig') + $systemConfig = $this->systemConfig = $this->getMockBuilder(\OC\SystemConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OC\SystemConfig $systemConfig */ $this->command = new DeleteConfig($systemConfig); diff --git a/tests/Core/Command/Config/System/GetConfigTest.php b/tests/Core/Command/Config/System/GetConfigTest.php index 4bffddf3d683..8137daa465f6 100644 --- a/tests/Core/Command/Config/System/GetConfigTest.php +++ b/tests/Core/Command/Config/System/GetConfigTest.php @@ -62,17 +62,17 @@ public function getData() { ['name', null, false, null, false, 'json', 1, null], // Int "0" output as json/plain - ['name', 0, true, null, false, 'json', 0, \json_encode(0)], + ['name', 0, true, null, false, 'json', 0, \json_encode(0, JSON_THROW_ON_ERROR)], ['name', 0, true, null, false, 'plain', 0, '0'], // Int "1" output as json/plain - ['name', 1, true, null, false, 'json', 0, \json_encode(1)], + ['name', 1, true, null, false, 'json', 0, \json_encode(1, JSON_THROW_ON_ERROR)], ['name', 1, true, null, false, 'plain', 0, '1'], // Bool "true" output as json/plain - ['name', true, true, null, false, 'json', 0, \json_encode(true)], + ['name', true, true, null, false, 'json', 0, \json_encode(true, JSON_THROW_ON_ERROR)], ['name', true, true, null, false, 'plain', 0, 'true'], // Bool "false" output as json/plain - ['name', false, true, null, false, 'json', 0, \json_encode(false)], + ['name', false, true, null, false, 'json', 0, \json_encode(false, JSON_THROW_ON_ERROR)], ['name', false, true, null, false, 'plain', 0, 'false'], // Null output as json/plain @@ -90,9 +90,9 @@ public function getData() { ['name', ['a' => 1, 'b' => 2], true, null, false, 'plain', 0, "a: 1\nb: 2"], // Nested depth - [['name', 'a'], ['a' => 1, 'b' => 2], true, null, false, 'json', 0, \json_encode(1)], + [['name', 'a'], ['a' => 1, 'b' => 2], true, null, false, 'json', 0, \json_encode(1, JSON_THROW_ON_ERROR)], [['name', 'a'], ['a' => 1, 'b' => 2], true, null, false, 'plain', 0, '1'], - [['name', 'c'], ['a' => 1, 'b' => 2], true, true, true, 'json', 0, \json_encode(true)], + [['name', 'c'], ['a' => 1, 'b' => 2], true, true, true, 'json', 0, \json_encode(true, JSON_THROW_ON_ERROR)], [['name', 'c'], ['a' => 1, 'b' => 2], true, true, false, 'json', 1, null], ]; diff --git a/tests/Core/Command/Config/System/SetConfigTest.php b/tests/Core/Command/Config/System/SetConfigTest.php index 5c53b4ca202e..7a7309089afb 100644 --- a/tests/Core/Command/Config/System/SetConfigTest.php +++ b/tests/Core/Command/Config/System/SetConfigTest.php @@ -39,11 +39,11 @@ class SetConfigTest extends TestCase { protected function setUp(): void { parent::setUp(); - $systemConfig = $this->systemConfig = $this->getMockBuilder('OC\SystemConfig') + $systemConfig = $this->systemConfig = $this->getMockBuilder(\OC\SystemConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OC\SystemConfig $systemConfig */ $this->command = new SetConfig($systemConfig); diff --git a/tests/Core/Command/Db/ConvertTypeTest.php b/tests/Core/Command/Db/ConvertTypeTest.php index dad4d979e0aa..c494adc91888 100644 --- a/tests/Core/Command/Db/ConvertTypeTest.php +++ b/tests/Core/Command/Db/ConvertTypeTest.php @@ -35,15 +35,14 @@ */ class ConvertTypeTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ConnectionFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $connectionFactory; + private \PHPUnit\Framework\MockObject\MockObject $connectionFactory; /** @var AppManager | \PHPUnit\Framework\MockObject\MockObject */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; - /** @var CommandTester */ - private $commandTester; + private ?\Symfony\Component\Console\Tester\CommandTester $commandTester = null; /** @var \Doctrine\DBAL\Connection */ private $connection; diff --git a/tests/Core/Command/Db/RestoreDefaultRowFormatTest.php b/tests/Core/Command/Db/RestoreDefaultRowFormatTest.php index 9af2c7c35c74..784526355a63 100644 --- a/tests/Core/Command/Db/RestoreDefaultRowFormatTest.php +++ b/tests/Core/Command/Db/RestoreDefaultRowFormatTest.php @@ -37,13 +37,12 @@ */ class RestoreDefaultRowFormatTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ConnectionFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $connectionFactory; - /** @var CommandTester */ - private $commandTester; + private \PHPUnit\Framework\MockObject\MockObject $connectionFactory; + private ?\Symfony\Component\Console\Tester\CommandTester $commandTester = null; /** @var \Doctrine\DBAL\Connection | \PHPUnit\Framework\MockObject\MockObject */ - private $connection; + private \PHPUnit\Framework\MockObject\MockObject $connection; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php b/tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php index b47ea01968b8..577e58cb2fcd 100644 --- a/tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php +++ b/tests/Core/Command/Encryption/ChangeKeyStorageRootTest.php @@ -63,14 +63,14 @@ class ChangeKeyStorageRootTest extends TestCase { public function setUp(): void { parent::setUp(); - $this->view = $this->createMock('\OC\Files\View'); - $this->userManager = $this->createMock('\OCP\IUserManager'); - $this->config = $this->createMock('\OCP\IConfig'); - $this->util = $this->getMockBuilder('OC\Encryption\Util')->disableOriginalConstructor()->getMock(); - $this->questionHelper = $this->createMock('Symfony\Component\Console\Helper\QuestionHelper'); - $this->inputInterface = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->outputInterface = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); - $this->userInterface = $this->createMock('\OCP\UserInterface'); + $this->view = $this->createMock('\\' . \OC\Files\View::class); + $this->userManager = $this->createMock('\\' . \OCP\IUserManager::class); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->util = $this->getMockBuilder(\OC\Encryption\Util::class)->disableOriginalConstructor()->getMock(); + $this->questionHelper = $this->createMock(\Symfony\Component\Console\Helper\QuestionHelper::class); + $this->inputInterface = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->outputInterface = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); + $this->userInterface = $this->createMock('\\' . \OCP\UserInterface::class); $outputFormatterInterface = $this->createMock(OutputFormatterInterface::class); $outputFormatterInterface->expects($this->any())->method('isDecorated') @@ -91,7 +91,7 @@ public function setUp(): void { * @dataProvider dataTestExecute */ public function testExecute($newRoot, $answer, $successMoveKey) { - $changeKeyStorageRoot = $this->getMockBuilder('OC\Core\Command\Encryption\ChangeKeyStorageRoot') + $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class) ->setConstructorArgs( [ $this->view, @@ -145,7 +145,7 @@ public function dataTestExecute() { public function testMoveAllKeys() { /** @var \OC\Core\Command\Encryption\ChangeKeyStorageRoot $changeKeyStorageRoot */ - $changeKeyStorageRoot = $this->getMockBuilder('OC\Core\Command\Encryption\ChangeKeyStorageRoot') + $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class) ->setConstructorArgs( [ $this->view, @@ -226,7 +226,7 @@ public function testPrepareNewRootExceptionForNullDir($dirExists) { * @param bool $executeRename */ public function testMoveSystemKeys($dirExists, $targetExists, $executeRename) { - $changeKeyStorageRoot = $this->getMockBuilder('OC\Core\Command\Encryption\ChangeKeyStorageRoot') + $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class) ->setConstructorArgs( [ $this->view, @@ -262,7 +262,7 @@ public function dataTestMoveSystemKeys() { } public function testMoveUserKeys() { - $changeKeyStorageRoot = $this->getMockBuilder('OC\Core\Command\Encryption\ChangeKeyStorageRoot') + $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class) ->setConstructorArgs( [ $this->view, @@ -292,7 +292,7 @@ public function testMoveUserKeys() { * @param bool $shouldRename */ public function testMoveUserEncryptionFolder($userExists, $isDir, $targetExists, $shouldRename) { - $changeKeyStorageRoot = $this->getMockBuilder('OC\Core\Command\Encryption\ChangeKeyStorageRoot') + $changeKeyStorageRoot = $this->getMockBuilder(\OC\Core\Command\Encryption\ChangeKeyStorageRoot::class) ->setConstructorArgs( [ $this->view, diff --git a/tests/Core/Command/Encryption/DecryptAllTest.php b/tests/Core/Command/Encryption/DecryptAllTest.php index 8ec9098ff3fb..df4749f0e609 100644 --- a/tests/Core/Command/Encryption/DecryptAllTest.php +++ b/tests/Core/Command/Encryption/DecryptAllTest.php @@ -49,22 +49,22 @@ class DecryptAllTest extends TestCase { public function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder('OCP\IConfig') + $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->encryptionManager = $this->getMockBuilder('OCP\Encryption\IManager') + $this->encryptionManager = $this->getMockBuilder(\OCP\Encryption\IManager::class) ->disableOriginalConstructor() ->getMock(); - $this->appManager = $this->getMockBuilder('OCP\App\IAppManager') + $this->appManager = $this->getMockBuilder(\OCP\App\IAppManager::class) ->disableOriginalConstructor() ->getMock(); - $this->questionHelper = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') + $this->questionHelper = $this->getMockBuilder(\Symfony\Component\Console\Helper\QuestionHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->decryptAll = $this->getMockBuilder('OC\Encryption\DecryptAll') + $this->decryptAll = $this->getMockBuilder(\OC\Encryption\DecryptAll::class) ->disableOriginalConstructor()->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); $this->config->expects($this->any()) ->method('getSystemValue') diff --git a/tests/Core/Command/Encryption/EnableTest.php b/tests/Core/Command/Encryption/EnableTest.php index 4adfe0cb14fd..098feeb6407c 100644 --- a/tests/Core/Command/Encryption/EnableTest.php +++ b/tests/Core/Command/Encryption/EnableTest.php @@ -40,14 +40,14 @@ class EnableTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = $this->config = $this->getMockBuilder('OCP\IConfig') + $config = $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $manager = $this->manager = $this->getMockBuilder('OCP\Encryption\IManager') + $manager = $this->manager = $this->getMockBuilder(\OCP\Encryption\IManager::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\IConfig $config */ /** @var \OCP\Encryption\IManager $manager */ @@ -75,7 +75,7 @@ public function dataEnable() { * @param string $expectedDefaultModuleString */ public function testEnable($oldStatus, $defaultModule, $availableModules, $isUpdating, $expectedString, $expectedDefaultModuleString) { - $defaultModule = ($defaultModule === null) ? '' : $defaultModule; + $defaultModule ??= ''; $invokeCount = 0; $this->manager->method('isEnabled') ->willReturn(\filter_var($oldStatus, FILTER_VALIDATE_BOOLEAN)); diff --git a/tests/Core/Command/Encryption/EncryptAllTest.php b/tests/Core/Command/Encryption/EncryptAllTest.php index 4ca0bb82ac93..f90b6bda4a12 100644 --- a/tests/Core/Command/Encryption/EncryptAllTest.php +++ b/tests/Core/Command/Encryption/EncryptAllTest.php @@ -52,23 +52,23 @@ class EncryptAllTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder('OCP\IConfig') + $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->encryptionManager = $this->getMockBuilder('OCP\Encryption\IManager') + $this->encryptionManager = $this->getMockBuilder(\OCP\Encryption\IManager::class) ->disableOriginalConstructor() ->getMock(); - $this->appManager = $this->getMockBuilder('OCP\App\IAppManager') + $this->appManager = $this->getMockBuilder(\OCP\App\IAppManager::class) ->disableOriginalConstructor() ->getMock(); - $this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') + $this->encryptionModule = $this->getMockBuilder('\\' . \OCP\Encryption\IEncryptionModule::class) ->disableOriginalConstructor() ->getMock(); - $this->questionHelper = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') + $this->questionHelper = $this->getMockBuilder(\Symfony\Component\Console\Helper\QuestionHelper::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); } public function testSingleUserAndTrashbin() { diff --git a/tests/Core/Command/Encryption/SetDefaultModuleTest.php b/tests/Core/Command/Encryption/SetDefaultModuleTest.php index 68cb47f6b449..08199341a822 100644 --- a/tests/Core/Command/Encryption/SetDefaultModuleTest.php +++ b/tests/Core/Command/Encryption/SetDefaultModuleTest.php @@ -38,11 +38,11 @@ class SetDefaultModuleTest extends TestCase { protected function setUp(): void { parent::setUp(); - $manager = $this->manager = $this->getMockBuilder('OCP\Encryption\IManager') + $manager = $this->manager = $this->getMockBuilder(\OCP\Encryption\IManager::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\Encryption\IManager $manager */ $this->command = new SetDefaultModule($manager); diff --git a/tests/Core/Command/Group/AddMemberTest.php b/tests/Core/Command/Group/AddMemberTest.php index 275fbae84ea6..6c5391b1053d 100644 --- a/tests/Core/Command/Group/AddMemberTest.php +++ b/tests/Core/Command/Group/AddMemberTest.php @@ -34,8 +34,7 @@ class AddMemberTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Group/AddTest.php b/tests/Core/Command/Group/AddTest.php index 2cb42046a308..e5b12b121c17 100644 --- a/tests/Core/Command/Group/AddTest.php +++ b/tests/Core/Command/Group/AddTest.php @@ -31,8 +31,7 @@ * @group DB */ class AddTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Group/DeleteTest.php b/tests/Core/Command/Group/DeleteTest.php index e22cfc0455b9..0df2cda86bf9 100644 --- a/tests/Core/Command/Group/DeleteTest.php +++ b/tests/Core/Command/Group/DeleteTest.php @@ -38,11 +38,11 @@ class DeleteTest extends TestCase { protected function setUp(): void { parent::setUp(); - $groupManager = $this->groupManager = $this->getMockBuilder('OCP\IGroupManager') + $groupManager = $this->groupManager = $this->getMockBuilder(\OCP\IGroupManager::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\IGroupManager $groupManager */ $this->command = new Delete($groupManager); @@ -62,7 +62,7 @@ public function validGroupLastSeen() { * @param string $expectedString */ public function testValidGroup($deleteSuccess, $expectedString) { - $group = $this->createMock('OCP\IGroup'); + $group = $this->createMock(\OCP\IGroup::class); $group->expects($this->once()) ->method('delete') ->willReturn($deleteSuccess); diff --git a/tests/Core/Command/Group/ListGroupMembersTest.php b/tests/Core/Command/Group/ListGroupMembersTest.php index bd666f7bd9cf..342e477e5d58 100644 --- a/tests/Core/Command/Group/ListGroupMembersTest.php +++ b/tests/Core/Command/Group/ListGroupMembersTest.php @@ -34,8 +34,7 @@ class ListGroupMembersTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Group/ListGroupsTest.php b/tests/Core/Command/Group/ListGroupsTest.php index 87285396c494..9f0b7828c440 100644 --- a/tests/Core/Command/Group/ListGroupsTest.php +++ b/tests/Core/Command/Group/ListGroupsTest.php @@ -31,8 +31,7 @@ * @group DB */ class ListGroupsTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Group/RemoveMemberTest.php b/tests/Core/Command/Group/RemoveMemberTest.php index 2eb71b8abe43..3ec801f9668f 100644 --- a/tests/Core/Command/Group/RemoveMemberTest.php +++ b/tests/Core/Command/Group/RemoveMemberTest.php @@ -34,8 +34,7 @@ class RemoveMemberTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/Log/ManageTest.php b/tests/Core/Command/Log/ManageTest.php index 74723adde009..ef78a3f97b36 100644 --- a/tests/Core/Command/Log/ManageTest.php +++ b/tests/Core/Command/Log/ManageTest.php @@ -38,11 +38,11 @@ class ManageTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = $this->config = $this->getMockBuilder('OCP\IConfig') + $config = $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); $this->command = new Manage($config); } diff --git a/tests/Core/Command/Log/OwnCloudTest.php b/tests/Core/Command/Log/OwnCloudTest.php index 91d988a7b05d..fc425ed10809 100644 --- a/tests/Core/Command/Log/OwnCloudTest.php +++ b/tests/Core/Command/Log/OwnCloudTest.php @@ -38,11 +38,11 @@ class OwnCloudTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = $this->config = $this->getMockBuilder('OCP\IConfig') + $config = $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); $this->command = new OwnCloud($config); } diff --git a/tests/Core/Command/Maintenance/DataFingerprintTest.php b/tests/Core/Command/Maintenance/DataFingerprintTest.php index e0a828837bc9..19dfa188d46f 100644 --- a/tests/Core/Command/Maintenance/DataFingerprintTest.php +++ b/tests/Core/Command/Maintenance/DataFingerprintTest.php @@ -31,15 +31,14 @@ class DataFingerprintTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var \Symfony\Component\Console\Command\Command */ - private $command; - /** @var CommandTester */ - private $commandTester; + private \OC\Core\Command\Maintenance\DataFingerprint $command; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; public function providesAnswers() { return [ diff --git a/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php b/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php index bcf262776854..cae03bfd79e9 100644 --- a/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php +++ b/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php @@ -43,15 +43,15 @@ class UpdateDBTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->detector = $this->getMockBuilder('OC\Files\Type\Detection') + $this->detector = $this->getMockBuilder(\OC\Files\Type\Detection::class) ->disableOriginalConstructor() ->getMock(); - $this->loader = $this->getMockBuilder('OC\Files\Type\Loader') + $this->loader = $this->getMockBuilder(\OC\Files\Type\Loader::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); $this->command = new UpdateDB($this->detector, $this->loader); } diff --git a/tests/Core/Command/Maintenance/RepairTest.php b/tests/Core/Command/Maintenance/RepairTest.php index 741576a41df5..bf271f0e4385 100644 --- a/tests/Core/Command/Maintenance/RepairTest.php +++ b/tests/Core/Command/Maintenance/RepairTest.php @@ -32,8 +32,7 @@ * @group DB */ class RepairTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); @@ -73,7 +72,7 @@ public function inputProvider() { [['--list' => true], true, 0, 'Found'], [[], false, 0, 'Turn on maintenance mode to use this command'], [['--single' => '\OC\UnexistingClass'], true, 1, 'Repair step not found'], - [['--single' => 'OC\Repair\RepairMimeTypes'], true, 0, 'Repair mime types'], + [['--single' => \OC\Repair\RepairMimeTypes::class], true, 0, 'Repair mime types'], [[], true, 0, 'Step:'], [['--include-expensive' => true], true, 0, 'Remove shares of old group memberships'] ]; diff --git a/tests/Core/Command/Maintenance/SingleUserTest.php b/tests/Core/Command/Maintenance/SingleUserTest.php index d9ee58827257..b74dac8bd097 100644 --- a/tests/Core/Command/Maintenance/SingleUserTest.php +++ b/tests/Core/Command/Maintenance/SingleUserTest.php @@ -38,11 +38,11 @@ class SingleUserTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = $this->config = $this->getMockBuilder('OCP\IConfig') + $config = $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\IConfig $config */ $this->command = new SingleUser($config); diff --git a/tests/Core/Command/Security/ImportCertificateTest.php b/tests/Core/Command/Security/ImportCertificateTest.php index f4879cbcdb79..f0873411cbaa 100644 --- a/tests/Core/Command/Security/ImportCertificateTest.php +++ b/tests/Core/Command/Security/ImportCertificateTest.php @@ -34,11 +34,9 @@ * @group DB */ class ImportCertificateTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; - /** @var CertificateManager */ - private $certificateManager; + private \OC\Security\CertificateManager $certificateManager; protected function setUp(): void { parent::setUp(); @@ -46,7 +44,7 @@ protected function setUp(): void { $this->certificateManager = new CertificateManager( self::getUniqueID('', 20), new View(), - $this->createMock('OCP\IConfig') + $this->createMock(\OCP\IConfig::class) ); $command = new ImportCertificate( $this->certificateManager diff --git a/tests/Core/Command/Security/RemoveCertificateTest.php b/tests/Core/Command/Security/RemoveCertificateTest.php index 78930f9382b0..89c1e53a2732 100644 --- a/tests/Core/Command/Security/RemoveCertificateTest.php +++ b/tests/Core/Command/Security/RemoveCertificateTest.php @@ -34,11 +34,9 @@ * @group DB */ class RemoveCertificateTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; - /** @var CertificateManager */ - private $certificateManager; + private \OC\Security\CertificateManager $certificateManager; protected function setUp(): void { parent::setUp(); @@ -46,7 +44,7 @@ protected function setUp(): void { $this->certificateManager = new CertificateManager( self::getUniqueID('', 20), new View(), - $this->createMock('OCP\IConfig') + $this->createMock(\OCP\IConfig::class) ); $command = new RemoveCertificate( $this->certificateManager diff --git a/tests/Core/Command/System/CronTest.php b/tests/Core/Command/System/CronTest.php index 61353f48dcc3..6df4f9e23e39 100644 --- a/tests/Core/Command/System/CronTest.php +++ b/tests/Core/Command/System/CronTest.php @@ -40,16 +40,15 @@ class CronTest extends TestCase { use UserTrait; /** @var IConfig | \PHPUnit_Framework_MockObject_MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger | \PHPUnit_Framework_MockObject_MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IJobList | \PHPUnit_Framework_MockObject_MockObject */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var ITempManager | \PHPUnit_Framework_MockObject_MockObject */ - private $tempManager; + private \PHPUnit\Framework\MockObject\MockObject $tempManager; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/TwoFactorAuth/DisableTest.php b/tests/Core/Command/TwoFactorAuth/DisableTest.php index ef9bce00d7c8..6264ec7cedae 100644 --- a/tests/Core/Command/TwoFactorAuth/DisableTest.php +++ b/tests/Core/Command/TwoFactorAuth/DisableTest.php @@ -34,8 +34,7 @@ class DisableTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/TwoFactorAuth/EnableTest.php b/tests/Core/Command/TwoFactorAuth/EnableTest.php index ecec04b26999..6c61b08512ba 100644 --- a/tests/Core/Command/TwoFactorAuth/EnableTest.php +++ b/tests/Core/Command/TwoFactorAuth/EnableTest.php @@ -34,8 +34,7 @@ class EnableTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/User/AddTest.php b/tests/Core/Command/User/AddTest.php index 0787ce9f8bfa..8dc018eed1c0 100644 --- a/tests/Core/Command/User/AddTest.php +++ b/tests/Core/Command/User/AddTest.php @@ -36,8 +36,7 @@ class AddTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/User/DeleteTest.php b/tests/Core/Command/User/DeleteTest.php index 917230296faf..f26cf5f4999c 100644 --- a/tests/Core/Command/User/DeleteTest.php +++ b/tests/Core/Command/User/DeleteTest.php @@ -31,14 +31,13 @@ class DeleteTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject|IUserManager */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); - $this->userManager = $this->getMockBuilder('OCP\IUserManager') + $this->userManager = $this->getMockBuilder(\OCP\IUserManager::class) ->disableOriginalConstructor() ->getMock(); @@ -61,7 +60,7 @@ public function validUserLastSeen() { * @param string $expectedOutput */ public function testValidUser($deleteSuccess, $expectedOutput) { - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->once()) ->method('delete') ->willReturn($deleteSuccess); diff --git a/tests/Core/Command/User/DisableTest.php b/tests/Core/Command/User/DisableTest.php index c0a77df60cd3..d93e88566615 100644 --- a/tests/Core/Command/User/DisableTest.php +++ b/tests/Core/Command/User/DisableTest.php @@ -34,8 +34,7 @@ class DisableTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/User/EnableTest.php b/tests/Core/Command/User/EnableTest.php index b96a47c79471..20d3e96eb549 100644 --- a/tests/Core/Command/User/EnableTest.php +++ b/tests/Core/Command/User/EnableTest.php @@ -34,8 +34,7 @@ class EnableTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/User/HomeListDirsTest.php b/tests/Core/Command/User/HomeListDirsTest.php index acda00e1a449..d719bb37410d 100644 --- a/tests/Core/Command/User/HomeListDirsTest.php +++ b/tests/Core/Command/User/HomeListDirsTest.php @@ -31,11 +31,10 @@ * Class HomeListDirsTest */ class HomeListDirsTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; protected function setUp(): void { parent::setUp(); @@ -87,7 +86,7 @@ protected function tearDown(): void { } private function overwriteConfigWithObjectStorage() { - $config = $this->createMock('\OCP\IConfig'); + $config = $this->createMock('\\' . \OCP\IConfig::class); $config->expects($this->any()) ->method('getSystemValue') ->willReturn(['objectstore' => true]); @@ -96,7 +95,7 @@ private function overwriteConfigWithObjectStorage() { } private function overwriteAppManagerWithObjectStorage() { - $config = $this->createMock('\OCP\App\IAppManager'); + $config = $this->createMock('\\' . \OCP\App\IAppManager::class); $config->expects($this->any()) ->method('isEnabledForUser') ->willReturn(true); diff --git a/tests/Core/Command/User/HomeListUsersTest.php b/tests/Core/Command/User/HomeListUsersTest.php index 0aa77c29998a..fb0b2373fa50 100644 --- a/tests/Core/Command/User/HomeListUsersTest.php +++ b/tests/Core/Command/User/HomeListUsersTest.php @@ -35,11 +35,10 @@ * @group DB */ class HomeListUsersTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; /** @var IDBConnection | \PHPUnit\Framework\MockObject\MockObject */ - private $connection; + private \PHPUnit\Framework\MockObject\MockObject $connection; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ protected $userManager; @@ -84,7 +83,7 @@ public function testCommandInputForHomePath($objectStorageUsed) { $resultMock = $this->createMock(DriverStatement::class); $resultMock->method('fetch')->willReturnOnConsecutiveCalls(['user_id' => $uid], false); - $queryMock = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder') + $queryMock = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\QueryBuilder::class) ->setConstructorArgs([$this->connection]) ->setMethods(['execute']) ->getMock(); @@ -109,7 +108,7 @@ protected function tearDown(): void { public function testCommandInputAll() { $uid = 'testhomeuser'; $path = '/some/path'; - $userObject = $this->getMockBuilder('\OC\User\User') + $userObject = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor() ->getMock(); $userObject->method('getHome')->willReturn($path . '/' . $uid); @@ -134,7 +133,7 @@ public function testCommandInputNone() { } private function overwriteConfigWithObjectStorage() { - $config = $this->createMock('\OCP\IConfig'); + $config = $this->createMock('\\' . \OCP\IConfig::class); $config->expects($this->any()) ->method('getSystemValue') ->willReturn(['objectstore' => true]); @@ -143,7 +142,7 @@ private function overwriteConfigWithObjectStorage() { } private function overwriteAppManagerWithObjectStorage() { - $config = $this->createMock('\OCP\App\IAppManager'); + $config = $this->createMock('\\' . \OCP\App\IAppManager::class); $config->expects($this->any()) ->method('isEnabledForUser') ->willReturn(true); diff --git a/tests/Core/Command/User/InactiveTest.php b/tests/Core/Command/User/InactiveTest.php index 1d354d199bfd..7b9a45352498 100644 --- a/tests/Core/Command/User/InactiveTest.php +++ b/tests/Core/Command/User/InactiveTest.php @@ -41,11 +41,11 @@ class InactiveTest extends TestCase { protected function setUp(): void { parent::setUp(); - $userManager = $this->userManager = $this->getMockBuilder('OCP\IUserManager') + $userManager = $this->userManager = $this->getMockBuilder(\OCP\IUserManager::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\IUserManager $userManager */ $this->command = new Inactive($userManager); @@ -124,9 +124,7 @@ public function testWithValidDays($users, $days, $expectedCount) { $this->consoleOutput->expects($this->once()) ->method('writeLn') - ->with($this->callback(function ($output) use ($expectedCount) { - return self::isJson($output) && \count(\json_decode($output)) === $expectedCount; - })); + ->with($this->callback(fn ($output) => self::isJson() && \count(\json_decode($output, null, 512, JSON_THROW_ON_ERROR)) === $expectedCount)); self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]); } diff --git a/tests/Core/Command/User/LastSeenTest.php b/tests/Core/Command/User/LastSeenTest.php index af147435423d..67b4d6c33579 100644 --- a/tests/Core/Command/User/LastSeenTest.php +++ b/tests/Core/Command/User/LastSeenTest.php @@ -38,11 +38,11 @@ class LastSeenTest extends TestCase { protected function setUp(): void { parent::setUp(); - $userManager = $this->userManager = $this->getMockBuilder('OCP\IUserManager') + $userManager = $this->userManager = $this->getMockBuilder(\OCP\IUserManager::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->createMock('Symfony\Component\Console\Input\InputInterface'); - $this->consoleOutput = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); + $this->consoleInput = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); + $this->consoleOutput = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); /** @var \OCP\IUserManager $userManager */ $this->command = new LastSeen($userManager); @@ -62,7 +62,7 @@ public function validUserLastSeen() { * @param string $expectedString */ public function testValidUser($lastSeen, $expectedString) { - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->expects($this->once()) ->method('getLastLogin') ->willReturn($lastSeen); diff --git a/tests/Core/Command/User/ListUserGroupsTest.php b/tests/Core/Command/User/ListUserGroupsTest.php index 7bc41218b4d8..bc2fde6cc4cd 100644 --- a/tests/Core/Command/User/ListUserGroupsTest.php +++ b/tests/Core/Command/User/ListUserGroupsTest.php @@ -34,8 +34,7 @@ class ListUserGroupsTest extends TestCase { use UserTrait; - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/User/ListUsersTest.php b/tests/Core/Command/User/ListUsersTest.php index c37f37137985..37becd3220ea 100644 --- a/tests/Core/Command/User/ListUsersTest.php +++ b/tests/Core/Command/User/ListUsersTest.php @@ -31,8 +31,7 @@ * @group DB */ class ListUsersTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/User/MoveHomeTest.php b/tests/Core/Command/User/MoveHomeTest.php index 0c471efbbe00..5f04acc82e7b 100644 --- a/tests/Core/Command/User/MoveHomeTest.php +++ b/tests/Core/Command/User/MoveHomeTest.php @@ -34,14 +34,8 @@ * @package Tests\Core\Command\User */ class MoveHomeTest extends TestCase { - /** - * @var CommandTester - */ - private $commandTester; - /** - * @var string - */ - private $newLocation; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; + private string $newLocation; /** * @var bool|IUser */ diff --git a/tests/Core/Command/User/ReportTest.php b/tests/Core/Command/User/ReportTest.php index 184ea1f68be1..5307929437d3 100644 --- a/tests/Core/Command/User/ReportTest.php +++ b/tests/Core/Command/User/ReportTest.php @@ -35,16 +35,15 @@ * @group DB */ class ReportTest extends TestCase { - /** @var CommandTester */ - private $commandTester; + private \Symfony\Component\Console\Tester\CommandTester $commandTester; /** @var IUserManager */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var UserTypeHelper */ - private $userTypeHelper; + private \PHPUnit\Framework\MockObject\MockObject $userTypeHelper; - private $isObjectStorage = false; + private bool $isObjectStorage = false; protected function setUp(): void { parent::setUp(); @@ -104,7 +103,7 @@ public function testCommandInputObjectStorage() { ])); $this->userManager->method('countUsers')->willReturn([ - 'OC\User\Database' => 2, + \OC\User\Database::class => 2, 'Custom\Class' => 4, ]); $this->userManager->method('callForSeenUsers') @@ -156,7 +155,7 @@ public function testCommandInput() { ])); $this->userManager->method('countUsers')->willReturn([ - 'OC\User\Database' => 2, + \OC\User\Database::class => 2, 'Custom\Class' => 4, ]); $this->userManager->method('callForSeenUsers') @@ -196,7 +195,7 @@ public function testCommandInput() { } private function overwriteConfigWithObjectStorage() { - $config = $this->createMock('\OCP\IConfig'); + $config = $this->createMock('\\' . \OCP\IConfig::class); $config->expects($this->any()) ->method('getSystemValue') ->willReturn(['objectstore' => true]); @@ -205,7 +204,7 @@ private function overwriteConfigWithObjectStorage() { } private function overwriteAppManagerWithObjectStorage() { - $config = $this->createMock('\OCP\App\IAppManager'); + $config = $this->createMock('\\' . \OCP\App\IAppManager::class); $config->expects($this->any()) ->method('isEnabledForUser') ->willReturn(true); diff --git a/tests/Core/Command/User/ResetPasswordTest.php b/tests/Core/Command/User/ResetPasswordTest.php index e878b2ab9337..45954407160f 100644 --- a/tests/Core/Command/User/ResetPasswordTest.php +++ b/tests/Core/Command/User/ResetPasswordTest.php @@ -40,17 +40,16 @@ */ class ResetPasswordTest extends TestCase { /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** @var EnvironmentHelper | \PHPUnit\Framework\MockObject\MockObject */ - private $environmentHelper; + private \PHPUnit\Framework\MockObject\MockObject $environmentHelper; /** @var LostController | \PHPUnit\Framework\MockObject\MockObject */ - private $lostController; - /** @var ResetPassword */ - private $resetPassword; + private \PHPUnit\Framework\MockObject\MockObject $lostController; + private \OC\Core\Command\User\ResetPassword $resetPassword; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Command/User/SettingTest.php b/tests/Core/Command/User/SettingTest.php index 1bf2b7063250..03fcd9521be9 100644 --- a/tests/Core/Command/User/SettingTest.php +++ b/tests/Core/Command/User/SettingTest.php @@ -39,19 +39,19 @@ class SettingTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->userManager = $this->getMockBuilder('OCP\IUserManager') + $this->userManager = $this->getMockBuilder(\OCP\IUserManager::class) ->disableOriginalConstructor() ->getMock(); - $this->config = $this->getMockBuilder('OCP\IConfig') + $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $this->connection = $this->getMockBuilder('OCP\IDBConnection') + $this->connection = $this->getMockBuilder(\OCP\IDBConnection::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleInput = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface') + $this->consoleInput = $this->getMockBuilder(\Symfony\Component\Console\Input\InputInterface::class) ->disableOriginalConstructor() ->getMock(); - $this->consoleOutput = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface') + $this->consoleOutput = $this->getMockBuilder(\Symfony\Component\Console\Output\OutputInterface::class) ->disableOriginalConstructor() ->getMock(); } @@ -60,7 +60,7 @@ public function getCommand(array $methods = []) { if (empty($methods)) { return new Setting($this->userManager, $this->config, $this->connection); } else { - $mock = $this->getMockBuilder('OC\Core\Command\User\Setting') + $mock = $this->getMockBuilder(\OC\Core\Command\User\Setting::class) ->setConstructorArgs([ $this->userManager, $this->config, diff --git a/tests/Core/Controller/AppRegistryControllerTest.php b/tests/Core/Controller/AppRegistryControllerTest.php index f6b9d5c9ef43..b404ccee75c5 100644 --- a/tests/Core/Controller/AppRegistryControllerTest.php +++ b/tests/Core/Controller/AppRegistryControllerTest.php @@ -93,9 +93,7 @@ public function testOpenWithWeb(): void { }); $generator->method('linkToRouteAbsolute')->willReturn('https://example.cloud/index.php/apps/drawio/editor/123'); $request->method('getHeader')->willReturn('ownCloudApp/12.0.2'); - $config->method('getSystemValue')->willReturnCallback(function ($key, $default) { - return $default; - }); + $config->method('getSystemValue')->willReturnCallback(fn ($key, $default) => $default); $controller = new AppRegistryController('core', $request, $appManager, $rootFolder, $generator, $config, $logger); @@ -116,7 +114,7 @@ public function testNew(): void { $parent_folder = $this->createMock(Folder::class); $newFile = $this->createMock(File::class); $parent_folder->method('newFile')->willReturn($newFile); - $newFile->method('getId')->willReturn(9999999); + $newFile->method('getId')->willReturn(9_999_999); $appManager->method('isEnabledForUser')->willReturn(true); $rootFolder->method('getById')->willReturnCallback(function ($file_id) use ($parent_folder) { @@ -128,9 +126,7 @@ public function testNew(): void { }); $generator->method('linkToRouteAbsolute')->willReturn('https://example.cloud/index.php/apps/drawio/editor/123'); $request->method('getHeader')->willReturn('ownCloud iOS'); - $config->method('getSystemValue')->willReturnCallback(function ($key, $default) { - return $default; - }); + $config->method('getSystemValue')->willReturnCallback(fn ($key, $default) => $default); $controller = new AppRegistryController('core', $request, $appManager, $rootFolder, $generator, $config, $logger); diff --git a/tests/Core/Controller/AvatarControllerTest.php b/tests/Core/Controller/AvatarControllerTest.php index 4fe9274eb8df..bcd9191f8ed9 100644 --- a/tests/Core/Controller/AvatarControllerTest.php +++ b/tests/Core/Controller/AvatarControllerTest.php @@ -50,29 +50,29 @@ class AvatarControllerTest extends TestCase { use UserTrait; /** @var \OC\Core\Controller\AvatarController */ - private $avatarController; + private \PHPUnit\Framework\MockObject\MockObject $avatarController; /** @var IAvatar | \PHPUnit\Framework\MockObject\MockObject */ - private $avatarMock; + private \PHPUnit\Framework\MockObject\MockObject $avatarMock; /** @var IUser | \PHPUnit\Framework\MockObject\MockObject */ - private $userMock; + private \PHPUnit\Framework\MockObject\MockObject $userMock; /** @var File | \PHPUnit\Framework\MockObject\MockObject*/ - private $avatarFile; + private \PHPUnit\Framework\MockObject\MockObject $avatarFile; /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $l10N; + private \PHPUnit\Framework\MockObject\MockObject $l10N; /** @var IAvatarManager | \PHPUnit\Framework\MockObject\MockObject */ - private $avatarManager; + private \PHPUnit\Framework\MockObject\MockObject $avatarManager; /** @var \OC\Cache\File | \PHPUnit\Framework\MockObject\MockObject */ - private $cache; + private \PHPUnit\Framework\MockObject\MockObject $cache; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var Folder | \PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; protected function setUp(): void { parent::setUp(); @@ -108,9 +108,7 @@ protected function setUp(): void { $this->avatarController ->expects($this->any()) ->method('isUploadFile') - ->willReturnCallback(function ($file) { - return \file_exists($file); - }); + ->willReturnCallback(fn ($file) => \file_exists($file)); // Configure userMock $this->userMock->expects($this->any())->method('getDisplayName')->willReturn('displayName'); @@ -119,7 +117,7 @@ protected function setUp(): void { ->willReturnMap([['userId', false, $this->userMock]]); $this->userSession->expects($this->any())->method('getUser')->willReturn($this->userMock); - $this->avatarFile = $this->createMock('OCP\Files\File'); + $this->avatarFile = $this->createMock(\OCP\Files\File::class); $this->avatarFile->expects($this->any())->method('getContent')->willReturn('image data'); $this->avatarFile->expects($this->any())->method('getMimeType')->willReturn('image type'); $this->avatarFile->expects($this->any())->method('getEtag')->willReturn('my etag'); @@ -333,7 +331,7 @@ public function testPostAvatarFileGif() { public function testPostAvatarFromFile() { //Mock node API call $userFolder = $this->createMock(Folder::class); - $file = $this->getMockBuilder('OCP\Files\File') + $file = $this->getMockBuilder(\OCP\Files\File::class) ->disableOriginalConstructor()->getMock(); $filePath = \OC::$SERVERROOT.'/tests/data/testimage.jpg'; $handle = \fopen($filePath, 'r'); @@ -354,7 +352,7 @@ public function testPostAvatarFromFile() { */ public function testPostAvatarFromNoFile() { $userFolder = $this->createMock(Folder::class); - $file = $this->createMock('OCP\Files\Node'); + $file = $this->createMock(\OCP\Files\Node::class); $userFolder ->expects($this->once()) ->method('get') @@ -377,7 +375,7 @@ public function testPostAvatarException() { ->method('set') ->will($this->throwException(new \Exception("foo"))); $userFolder = $this->createMock(Folder::class); - $file = $this->getMockBuilder('OCP\Files\File') + $file = $this->getMockBuilder(\OCP\Files\File::class) ->disableOriginalConstructor()->getMock(); $filePath = \OC::$SERVERROOT.'/tests/data/testimage.jpg'; $handle = \fopen($filePath, 'r'); diff --git a/tests/Core/Controller/CronControllerTest.php b/tests/Core/Controller/CronControllerTest.php index adcf517d442d..1ac2fd2a3cdb 100644 --- a/tests/Core/Controller/CronControllerTest.php +++ b/tests/Core/Controller/CronControllerTest.php @@ -36,16 +36,15 @@ * @package OC\Core\Controller */ class CronControllerTest extends TestCase { - /** @var CronController */ - private $controller; + private \OC\Core\Controller\CronController $controller; /** @var IConfig | \PHPUnit_Framework_MockObject_MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger | \PHPUnit_Framework_MockObject_MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IJobList | \PHPUnit_Framework_MockObject_MockObject */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var IRequest | \PHPUnit_Framework_MockObject_MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; protected function setUp(): void { $this->request = $this->createMock(IRequest::class); diff --git a/tests/Core/Controller/LicenseControllerTest.php b/tests/Core/Controller/LicenseControllerTest.php index 815efd56b71c..895612c51bae 100644 --- a/tests/Core/Controller/LicenseControllerTest.php +++ b/tests/Core/Controller/LicenseControllerTest.php @@ -27,11 +27,10 @@ class LicenseControllerTest extends TestCase { /** @var IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var ILicenseManager */ - private $licenseManager; - /** @var LicenseController */ - private $licenseController; + private \PHPUnit\Framework\MockObject\MockObject $licenseManager; + private \OC\Core\Controller\LicenseController $licenseController; protected function setUp(): void { parent::setUp(); @@ -44,13 +43,13 @@ protected function setUp(): void { public function testGetGracePeriod() { $this->licenseManager->method('getGracePeriod') ->willReturn([ - 'start' => 100200300, - 'end' => 100300500, + 'start' => 100_200_300, + 'end' => 100_300_500, ]); $expected = [ - 'start' => 100200300, - 'end' => 100300500, + 'start' => 100_200_300, + 'end' => 100_300_500, ]; $this->assertSame($expected, $this->licenseController->getGracePeriod()->getData()); } @@ -71,14 +70,14 @@ public function testGetGracePeriodWithApps($appList, $expectedCount) { $this->licenseManager->method('getGracePeriod') ->willReturn([ 'apps' => $appList, - 'start' => 100200300, - 'end' => 100300500, + 'start' => 100_200_300, + 'end' => 100_300_500, ]); $expected = [ 'apps' => $expectedCount, - 'start' => 100200300, - 'end' => 100300500, + 'start' => 100_200_300, + 'end' => 100_300_500, ]; $this->assertSame($expected, $this->licenseController->getGracePeriod()->getData()); } diff --git a/tests/Core/Controller/LoginControllerTest.php b/tests/Core/Controller/LoginControllerTest.php index 617554120035..eb110e335f48 100644 --- a/tests/Core/Controller/LoginControllerTest.php +++ b/tests/Core/Controller/LoginControllerTest.php @@ -40,21 +40,21 @@ class LoginControllerTest extends TestCase { /** @var LoginController */ private $loginController; /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ISession | \PHPUnit\Framework\MockObject\MockObject */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; /** @var Session | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var Manager | \PHPUnit\Framework\MockObject\MockObject */ - private $twoFactorManager; + private \PHPUnit\Framework\MockObject\MockObject $twoFactorManager; /** @var ILicenseManager */ - private $licenseManager; + private \PHPUnit\Framework\MockObject\MockObject $licenseManager; public function setUp(): void { parent::setUp(); diff --git a/tests/Core/Controller/LostControllerTest.php b/tests/Core/Controller/LostControllerTest.php index f4711ca8d692..f8c974521d55 100644 --- a/tests/Core/Controller/LostControllerTest.php +++ b/tests/Core/Controller/LostControllerTest.php @@ -42,35 +42,34 @@ * @package OC\Core\Controller */ class LostControllerTest extends TestCase { - /** @var LostController */ - private $lostController; + private \OC\Core\Controller\LostController $lostController; /** @var IUser */ - private $existingUser; + private \PHPUnit\Framework\MockObject\MockObject $existingUser; /** @var IURLGenerator | PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var IUserManager | PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var \OC_Defaults */ - private $defaults; + private \PHPUnit\Framework\MockObject\MockObject $defaults; /** @var IConfig | PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IMailer | PHPUnit\Framework\MockObject\MockObject */ - private $mailer; + private \PHPUnit\Framework\MockObject\MockObject $mailer; /** @var ISecureRandom | PHPUnit\Framework\MockObject\MockObject */ - private $secureRandom; + private \PHPUnit\Framework\MockObject\MockObject $secureRandom; /** @var ITimeFactory | PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** @var IRequest | PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var ILogger | PHPUnit\Framework\MockObject\MockObject*/ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var Session */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; protected function setUp(): void { - $this->existingUser = $this->getMockBuilder('OCP\IUser') + $this->existingUser = $this->getMockBuilder(\OCP\IUser::class) ->disableOriginalConstructor()->getMock(); $this->existingUser @@ -88,33 +87,31 @@ protected function setUp(): void { ->method('getUID') ->willReturn('ExistingUser'); - $this->config = $this->getMockBuilder('\OCP\IConfig') + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor()->getMock(); - $this->l10n = $this->getMockBuilder('\OCP\IL10N') + $this->l10n = $this->getMockBuilder('\\' . \OCP\IL10N::class) ->disableOriginalConstructor()->getMock(); $this->l10n ->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $this->defaults = $this->getMockBuilder('\OC_Defaults') ->disableOriginalConstructor()->getMock(); - $this->userManager = $this->getMockBuilder('\OCP\IUserManager') + $this->userManager = $this->getMockBuilder('\\' . \OCP\IUserManager::class) ->disableOriginalConstructor()->getMock(); - $this->urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $this->urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor()->getMock(); - $this->mailer = $this->getMockBuilder('\OCP\Mail\IMailer') + $this->mailer = $this->getMockBuilder('\\' . \OCP\Mail\IMailer::class) ->disableOriginalConstructor()->getMock(); - $this->secureRandom = $this->getMockBuilder('\OCP\Security\ISecureRandom') + $this->secureRandom = $this->getMockBuilder('\\' . \OCP\Security\ISecureRandom::class) ->disableOriginalConstructor()->getMock(); - $this->timeFactory = $this->getMockBuilder('\OCP\AppFramework\Utility\ITimeFactory') + $this->timeFactory = $this->getMockBuilder('\\' . \OCP\AppFramework\Utility\ITimeFactory::class) ->disableOriginalConstructor()->getMock(); - $this->request = $this->getMockBuilder('OCP\IRequest') + $this->request = $this->getMockBuilder(\OCP\IRequest::class) ->disableOriginalConstructor()->getMock(); - $this->logger = $this->getMockBuilder('OCP\ILogger') + $this->logger = $this->getMockBuilder(\OCP\ILogger::class) ->disableOriginalConstructor()->getMock(); - $this->userSession = $this->getMockBuilder('OC\User\Session') + $this->userSession = $this->getMockBuilder(\OC\User\Session::class) ->disableOriginalConstructor()->getMock(); $this->lostController = new LostController( 'Core', @@ -157,7 +154,7 @@ public function testResetFormInvalidTokenMatch() { ->method('getUserValue') ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor()->getMock(); $user ->expects($this->once()) @@ -185,7 +182,7 @@ public function testResetFormInvalidTokenMatch() { } public function testResetFormExpiredToken() { - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor()->getMock(); $this->userManager ->expects($this->once()) @@ -218,7 +215,7 @@ public function testResetFormExpiredToken() { } public function testResetFormValidToken() { - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor()->getMock(); $user ->expects($this->once()) @@ -389,7 +386,7 @@ public function testEmailUsedForLoginSuccessful() { ->method('linkToRouteAbsolute') ->with('core.lost.resetform', ['userId' => 'ExistingUser', 'token' => 'ThisIsMaybeANotSoSecretToken!']) ->will($this->returnValue('https://ownCloud.com/index.php/lostpassword/')); - $message = $this->getMockBuilder('\OC\Mail\Message') + $message = $this->getMockBuilder('\\' . \OC\Mail\Message::class) ->disableOriginalConstructor()->getMock(); $message ->expects($this->once()) @@ -490,7 +487,7 @@ public function testEmailSuccessful() { ->method('linkToRouteAbsolute') ->with('core.lost.resetform', ['userId' => 'ExistingUser', 'token' => 'ThisIsMaybeANotSoSecretToken!']) ->will($this->returnValue('https://ownCloud.com/index.php/lostpassword/')); - $message = $this->getMockBuilder('\OC\Mail\Message') + $message = $this->getMockBuilder('\\' . \OC\Mail\Message::class) ->disableOriginalConstructor()->getMock(); $message ->expects($this->once()) @@ -555,7 +552,7 @@ public function testEmailCantSendException() { ->method('linkToRouteAbsolute') ->with('core.lost.resetform', ['userId' => 'ExistingUser', 'token' => 'ThisIsMaybeANotSoSecretToken!']) ->will($this->returnValue('https://ownCloud.com/index.php/lostpassword/')); - $message = $this->getMockBuilder('\OC\Mail\Message') + $message = $this->getMockBuilder('\\' . \OC\Mail\Message::class) ->disableOriginalConstructor()->getMock(); $message ->expects($this->once()) @@ -620,7 +617,7 @@ public function testSetPasswordSuccessful() { ->method('getUserValue') ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor()->getMock(); $user ->expects($this->once()) @@ -647,7 +644,7 @@ public function testSetPasswordSuccessful() { ->method('getDisplayName') ->will($this->returnValue('ValidTokenUser')); - $message = $this->getMockBuilder('\OC\Mail\Message') + $message = $this->getMockBuilder('\\' . \OC\Mail\Message::class) ->disableOriginalConstructor()->getMock(); $message ->expects($this->once()) @@ -689,7 +686,7 @@ public function testSetPasswordExpiredToken() { ->method('getUserValue') ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor()->getMock(); $this->userManager ->expects($this->once()) @@ -715,7 +712,7 @@ public function testSetPasswordInvalidDataInDb() { ->method('getUserValue') ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) ->will($this->returnValue('TheOnlyAndOnlyOneTokenToResetThePassword')); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor()->getMock(); $this->userManager ->expects($this->once()) @@ -737,7 +734,7 @@ public function testSetPasswordExpiredTokenDueToLogin() { ->method('getUserValue') ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor()->getMock(); $user ->expects($this->once()) diff --git a/tests/Core/Controller/OccControllerTest.php b/tests/Core/Controller/OccControllerTest.php index c71ec344d812..5e0c43c2f6f6 100644 --- a/tests/Core/Controller/OccControllerTest.php +++ b/tests/Core/Controller/OccControllerTest.php @@ -36,13 +36,13 @@ class OccControllerTest extends TestCase { public const TEMP_SECRET = 'test'; /** @var \OC\AppFramework\Http\Request | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private ?\PHPUnit\Framework\MockObject\MockObject $request = null; /** @var \OC\Core\Controller\OccController | \PHPUnit\Framework\MockObject\MockObject */ - private $controller; + private ?\OC\Core\Controller\OccController $controller = null; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private ?\PHPUnit\Framework\MockObject\MockObject $config = null; /** @var Application | \PHPUnit\Framework\MockObject\MockObject */ - private $console; + private ?\PHPUnit\Framework\MockObject\MockObject $console = null; public function testFromInvalidLocation() { $fakeHost = 'example.org'; @@ -102,14 +102,14 @@ function ($input, $output) { $this->assertEquals(0, $responseData['exitCode']); $this->assertArrayHasKey('response', $responseData); - $decoded = \json_decode($responseData['response'], true); + $decoded = \json_decode($responseData['response'], true, 512, JSON_THROW_ON_ERROR); $this->assertArrayHasKey('installed', $decoded); $this->assertTrue($decoded['installed']); } private function getControllerMock($host) { - $this->request = $this->getMockBuilder('OC\AppFramework\Http\Request') + $this->request = $this->getMockBuilder(\OC\AppFramework\Http\Request::class) ->setConstructorArgs([ ['server' => []], \OC::$server->getSecureRandom(), @@ -121,14 +121,14 @@ private function getControllerMock($host) { $this->request->expects($this->any())->method('getRemoteAddress') ->will($this->returnValue($host)); - $this->config = $this->getMockBuilder('\OCP\IConfig') + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); $this->config->expects($this->any())->method('getSystemValue') ->with('updater.secret') ->willReturn(\password_hash(self::TEMP_SECRET, PASSWORD_DEFAULT)); - $this->console = $this->getMockBuilder('\OC\Console\Application') + $this->console = $this->getMockBuilder('\\' . \OC\Console\Application::class) ->disableOriginalConstructor() ->getMock(); @@ -137,7 +137,7 @@ private function getControllerMock($host) { $this->request, $this->config, $this->console, - $this->getMockBuilder('\OCP\ILogger') + $this->getMockBuilder('\\' . \OCP\ILogger::class) ->disableOriginalConstructor() ->getMock() ); diff --git a/tests/Core/Controller/OcsControllerTest.php b/tests/Core/Controller/OcsControllerTest.php index a8e3b7ab6903..9f4c7776f35f 100644 --- a/tests/Core/Controller/OcsControllerTest.php +++ b/tests/Core/Controller/OcsControllerTest.php @@ -39,19 +39,19 @@ */ class OcsControllerTest extends TestCase { /** @var Request | MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IDBConnection | MockObject */ - private $dbConn; + private \PHPUnit\Framework\MockObject\MockObject $dbConn; /** @var IUserSession | MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IUserManager | MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var OcsController | MockObject */ - private $controller; + private \OC\Core\Controller\OcsController $controller; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Controller/TokenControllerTest.php b/tests/Core/Controller/TokenControllerTest.php index b36d96358d2e..37d5dadf5ff3 100644 --- a/tests/Core/Controller/TokenControllerTest.php +++ b/tests/Core/Controller/TokenControllerTest.php @@ -30,25 +30,25 @@ class TokenControllerTest extends TestCase { /** \OC\Core\Controller\TokenController */ - private $tokenController; - private $request; - private $userManager; - private $tokenProvider; - private $twoFactorAuthManager; - private $secureRandom; + private \OC\Core\Controller\TokenController $tokenController; + private \PHPUnit\Framework\MockObject\MockObject $request; + private \PHPUnit\Framework\MockObject\MockObject $userManager; + private \PHPUnit\Framework\MockObject\MockObject $tokenProvider; + private \PHPUnit\Framework\MockObject\MockObject $twoFactorAuthManager; + private \PHPUnit\Framework\MockObject\MockObject $secureRandom; protected function setUp(): void { parent::setUp(); - $this->request = $this->createMock('\OCP\IRequest'); - $this->userManager = $this->getMockBuilder('\OC\User\Manager') + $this->request = $this->createMock('\\' . \OCP\IRequest::class); + $this->userManager = $this->getMockBuilder('\\' . \OC\User\Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->tokenProvider = $this->createMock('\OC\Authentication\Token\IProvider'); - $this->twoFactorAuthManager = $this->getMockBuilder('\OC\Authentication\TwoFactorAuth\Manager') + $this->tokenProvider = $this->createMock('\\' . \OC\Authentication\Token\IProvider::class); + $this->twoFactorAuthManager = $this->getMockBuilder('\\' . \OC\Authentication\TwoFactorAuth\Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->secureRandom = $this->createMock('\OCP\Security\ISecureRandom'); + $this->secureRandom = $this->createMock('\\' . \OCP\Security\ISecureRandom::class); $this->tokenController = new TokenController('core', $this->request, $this->userManager, $this->tokenProvider, $this->twoFactorAuthManager, $this->secureRandom); } @@ -76,7 +76,7 @@ public function testWithInvalidCredentials() { } public function testWithValidCredentials() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->userManager->expects($this->once()) ->method('checkPassword') ->with('john', '123456') @@ -105,7 +105,7 @@ public function testWithValidCredentials() { } public function testWithValidCredentialsBut2faEnabled() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->userManager->expects($this->once()) ->method('checkPassword') ->with('john', '123456') diff --git a/tests/Core/Controller/TwoFactorChallengeControllerTest.php b/tests/Core/Controller/TwoFactorChallengeControllerTest.php index 7e45659c3292..2dc11ed668b5 100644 --- a/tests/Core/Controller/TwoFactorChallengeControllerTest.php +++ b/tests/Core/Controller/TwoFactorChallengeControllerTest.php @@ -38,18 +38,18 @@ class TwoFactorChallengeControllerTest extends TestCase { /** @var IRequest | MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var Manager | MockObject */ - private $twoFactorManager; + private \PHPUnit\Framework\MockObject\MockObject $twoFactorManager; /** @var IUserSession | MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var ISession | MockObject */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; /** @var IURLGenerator | MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var TwoFactorChallengeController|MockObject */ - private $controller; + private \PHPUnit\Framework\MockObject\MockObject $controller; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Controller/UserSyncControllerTest.php b/tests/Core/Controller/UserSyncControllerTest.php index 8163f3ade1d2..d65b301eddae 100644 --- a/tests/Core/Controller/UserSyncControllerTest.php +++ b/tests/Core/Controller/UserSyncControllerTest.php @@ -37,18 +37,15 @@ * @package OC\Core\Controller */ class UserSyncControllerTest extends TestCase { - /** - * @var UserSyncController - */ - private $controller; + private \OC\Core\Controller\UserSyncController $controller; /** * @var MockObject | IUserManager */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** * @var MockObject | SyncService */ - private $syncService; + private \PHPUnit\Framework\MockObject\MockObject $syncService; protected function setUp(): void { /** @var IRequest $request */ diff --git a/tests/Core/Middleware/AccountModuleMiddlewareTest.php b/tests/Core/Middleware/AccountModuleMiddlewareTest.php index 4b02cd0138d3..0d3357334c96 100644 --- a/tests/Core/Middleware/AccountModuleMiddlewareTest.php +++ b/tests/Core/Middleware/AccountModuleMiddlewareTest.php @@ -35,19 +35,18 @@ class AccountModuleMiddlewareTest extends TestCase { /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var Manager|\PHPUnit\Framework\MockObject\MockObject */ - private $manager; + private \PHPUnit\Framework\MockObject\MockObject $manager; /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IControllerMethodReflector|\PHPUnit\Framework\MockObject\MockObject */ - private $reflector; + private \PHPUnit\Framework\MockObject\MockObject $reflector; - /** @var AccountModuleMiddleware */ - private $middleware; + private \OC\Core\Middleware\AccountModuleMiddleware $middleware; protected function setUp(): void { parent::setUp(); diff --git a/tests/Core/Middleware/TwoFactorMiddlewareTest.php b/tests/Core/Middleware/TwoFactorMiddlewareTest.php index 00a0a0681b26..6070005ff701 100644 --- a/tests/Core/Middleware/TwoFactorMiddlewareTest.php +++ b/tests/Core/Middleware/TwoFactorMiddlewareTest.php @@ -35,22 +35,20 @@ class TwoFactorMiddlewareTest extends TestCase { /** @var Manager|\PHPUnit\Framework\MockObject\MockObject */ - private $twoFactorManager; + private \PHPUnit\Framework\MockObject\MockObject $twoFactorManager; /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IControllerMethodReflector|\PHPUnit\Framework\MockObject\MockObject */ - private $reflector; + private \PHPUnit\Framework\MockObject\MockObject $reflector; - /** @var Request */ - private $request; + private \OC\AppFramework\Http\Request $request; - /** @var TwoFactorMiddleware */ - private $middleware; + private \OC\Core\Middleware\TwoFactorMiddleware $middleware; protected function setUp(): void { parent::setUp(); @@ -101,7 +99,7 @@ public function testBeforeControllerPublicPage() { } public function testBeforeControllerNoTwoFactorCheckNeeded() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->reflector->expects($this->once()) ->method('hasAnnotation') @@ -126,7 +124,7 @@ public function testBeforeControllerNoTwoFactorCheckNeeded() { public function testBeforeControllerTwoFactorAuthRequired() { $this->expectException(\OC\Authentication\Exceptions\TwoFactorAuthRequiredException::class); - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->reflector->expects($this->once()) ->method('hasAnnotation') @@ -154,7 +152,7 @@ public function testBeforeControllerTwoFactorAuthRequired() { public function testBeforeControllerUserAlreadyLoggedIn() { $this->expectException(\OC\Authentication\Exceptions\UserAlreadyLoggedInException::class); - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->reflector->expects($this->once()) ->method('hasAnnotation') @@ -174,7 +172,7 @@ public function testBeforeControllerUserAlreadyLoggedIn() { ->method('needsSecondFactor') ->will($this->returnValue(false)); - $twoFactorChallengeController = $this->getMockBuilder('\OC\Core\Controller\TwoFactorChallengeController') + $twoFactorChallengeController = $this->getMockBuilder('\\' . \OC\Core\Controller\TwoFactorChallengeController::class) ->disableOriginalConstructor() ->getMock(); $this->middleware->beforeController($twoFactorChallengeController, 'index'); diff --git a/tests/Settings/Controller/AppConfigControllerTest.php b/tests/Settings/Controller/AppConfigControllerTest.php index 111a0f2bb753..fc1b49cca2b4 100644 --- a/tests/Settings/Controller/AppConfigControllerTest.php +++ b/tests/Settings/Controller/AppConfigControllerTest.php @@ -36,9 +36,8 @@ class AppConfigControllerTest extends TestCase { /** @var (IRequest & MockObject) */ public $request; /** @var IAppConfig */ - private $appConfig; - /** @var AppConfigController */ - private $appConfigController; + private \PHPUnit\Framework\MockObject\MockObject $appConfig; + private \OC\Settings\Controller\AppConfigController $appConfigController; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Controller/AppSettingsControllerTest.php b/tests/Settings/Controller/AppSettingsControllerTest.php index 9beffa9f753f..0b003c74ba91 100644 --- a/tests/Settings/Controller/AppSettingsControllerTest.php +++ b/tests/Settings/Controller/AppSettingsControllerTest.php @@ -34,16 +34,15 @@ * @package Tests\Settings\Controller */ class AppSettingsControllerTest extends TestCase { - /** @var AppSettingsController */ - private $appSettingsController; + private \OC\Settings\Controller\AppSettingsController $appSettingsController; /** @var IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IAppManager */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Controller/AuthSettingsControllerTest.php b/tests/Settings/Controller/AuthSettingsControllerTest.php index 437d3ec7105c..83f6f0f523b7 100644 --- a/tests/Settings/Controller/AuthSettingsControllerTest.php +++ b/tests/Settings/Controller/AuthSettingsControllerTest.php @@ -33,25 +33,24 @@ class AuthSettingsControllerTest extends TestCase { public $user; - /** @var AuthSettingsController */ - private $controller; - private $request; - private $tokenProvider; - private $userManager; - private $session; - private $secureRandom; - private $uid; + private \OC\Settings\Controller\AuthSettingsController $controller; + private \PHPUnit\Framework\MockObject\MockObject $request; + private \PHPUnit\Framework\MockObject\MockObject $tokenProvider; + private \PHPUnit\Framework\MockObject\MockObject $userManager; + private \PHPUnit\Framework\MockObject\MockObject $session; + private \PHPUnit\Framework\MockObject\MockObject $secureRandom; + private string $uid; protected function setUp(): void { parent::setUp(); - $this->request = $this->createMock('\OCP\IRequest'); - $this->tokenProvider = $this->createMock('\OC\Authentication\Token\IProvider'); - $this->userManager = $this->createMock('\OCP\IUserManager'); - $this->session = $this->createMock('\OCP\ISession'); - $this->secureRandom = $this->createMock('\OCP\Security\ISecureRandom'); + $this->request = $this->createMock('\\' . \OCP\IRequest::class); + $this->tokenProvider = $this->createMock('\\' . \OC\Authentication\Token\IProvider::class); + $this->userManager = $this->createMock('\\' . \OCP\IUserManager::class); + $this->session = $this->createMock('\\' . \OCP\ISession::class); + $this->secureRandom = $this->createMock('\\' . \OCP\Security\ISecureRandom::class); $this->uid = 'jane'; - $this->user = $this->createMock('\OCP\IUser'); + $this->user = $this->createMock('\\' . \OCP\IUser::class); $this->controller = new AuthSettingsController('core', $this->request, $this->tokenProvider, $this->userManager, $this->session, $this->secureRandom, $this->uid); } @@ -104,8 +103,8 @@ public function testIndex() { public function testCreate() { $name = 'Nexus 4'; - $sessionToken = $this->createMock('\OC\Authentication\Token\IToken'); - $deviceToken = $this->createMock('\OC\Authentication\Token\IToken'); + $sessionToken = $this->createMock('\\' . \OC\Authentication\Token\IToken::class); + $deviceToken = $this->createMock('\\' . \OC\Authentication\Token\IToken::class); $password = '123456'; $this->session->expects($this->once()) @@ -174,7 +173,7 @@ public function testCreateInvalidToken() { public function testDestroy() { $id = 123; - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->userManager->expects($this->once()) ->method('get') diff --git a/tests/Settings/Controller/CertificateControllerTest.php b/tests/Settings/Controller/CertificateControllerTest.php index 035d9e457e67..1fd63c4d2733 100644 --- a/tests/Settings/Controller/CertificateControllerTest.php +++ b/tests/Settings/Controller/CertificateControllerTest.php @@ -36,28 +36,28 @@ */ class CertificateControllerTest extends \Test\TestCase { /** @var CertificateController */ - private $certificateController; + private \PHPUnit\Framework\MockObject\MockObject $certificateController; /** @var IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var ICertificateManager */ - private $certificateManager; + private \PHPUnit\Framework\MockObject\MockObject $certificateManager; /** @var IL10N */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var IAppManager */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; /** @var ICertificateManager */ - private $systemCertificateManager; + private \PHPUnit\Framework\MockObject\MockObject $systemCertificateManager; public function setUp(): void { parent::setUp(); - $this->request = $this->createMock('\OCP\IRequest'); - $this->certificateManager = $this->createMock('\OCP\ICertificateManager'); - $this->systemCertificateManager = $this->createMock('\OCP\ICertificateManager'); - $this->l10n = $this->createMock('\OCP\IL10N'); - $this->appManager = $this->createMock('OCP\App\IAppManager'); + $this->request = $this->createMock('\\' . \OCP\IRequest::class); + $this->certificateManager = $this->createMock('\\' . \OCP\ICertificateManager::class); + $this->systemCertificateManager = $this->createMock('\\' . \OCP\ICertificateManager::class); + $this->l10n = $this->createMock('\\' . \OCP\IL10N::class); + $this->appManager = $this->createMock(\OCP\App\IAppManager::class); - $this->certificateController = $this->getMockBuilder('OC\Settings\Controller\CertificateController') + $this->certificateController = $this->getMockBuilder(\OC\Settings\Controller\CertificateController::class) ->setConstructorArgs( [ 'settings', @@ -90,7 +90,7 @@ public function testAddPersonalRootCertificateValidCertificate() { 'name' => 'goodCertificate.crt', ]; - $certificate = $this->createMock('\OCP\ICertificate'); + $certificate = $this->createMock('\\' . \OCP\ICertificate::class); $certificate ->expects($this->once()) ->method('getName') @@ -147,8 +147,8 @@ public function testAddPersonalRootCertificateValidCertificate() { 'name' => 'Name', 'commonName' => 'CommonName', 'organization' => 'Organization', - 'validFrom' => 1429099555, - 'validTill' => 1529099555, + 'validFrom' => 1_429_099_555, + 'validTill' => 1_529_099_555, 'validFromString' => 'Valid From as String', 'validTillString' => 'Valid Till as String', 'issuer' => 'Issuer', diff --git a/tests/Settings/Controller/CheckSetupControllerTest.php b/tests/Settings/Controller/CheckSetupControllerTest.php index 24d3b92cec33..2f8f876d4bf3 100644 --- a/tests/Settings/Controller/CheckSetupControllerTest.php +++ b/tests/Settings/Controller/CheckSetupControllerTest.php @@ -43,47 +43,45 @@ */ class CheckSetupControllerTest extends TestCase { /** @var CheckSetupController | \PHPUnit\Framework\MockObject\MockObject */ - private $checkSetupController; + private \PHPUnit\Framework\MockObject\MockObject $checkSetupController; /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IClientService | \PHPUnit\Framework\MockObject\MockObject*/ - private $clientService; + private \PHPUnit\Framework\MockObject\MockObject $clientService; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var OC_Util */ - private $util; + private \PHPUnit\Framework\MockObject\MockObject $util; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var Checker | \PHPUnit\Framework\MockObject\MockObject */ - private $checker; + private \PHPUnit\Framework\MockObject\MockObject $checker; public function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder('\OCP\IRequest') + $this->request = $this->getMockBuilder('\\' . \OCP\IRequest::class) ->disableOriginalConstructor()->getMock(); - $this->config = $this->getMockBuilder('\OCP\IConfig') + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor()->getMock(); - $this->config = $this->getMockBuilder('\OCP\IConfig') + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor()->getMock(); - $this->clientService = $this->getMockBuilder('\OCP\Http\Client\IClientService') + $this->clientService = $this->getMockBuilder('\\' . \OCP\Http\Client\IClientService::class) ->disableOriginalConstructor()->getMock(); $this->util = $this->getMockBuilder('\OC_Util') ->disableOriginalConstructor()->getMock(); - $this->urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $this->urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor()->getMock(); - $this->l10n = $this->getMockBuilder('\OCP\IL10N') + $this->l10n = $this->getMockBuilder('\\' . \OCP\IL10N::class) ->disableOriginalConstructor()->getMock(); $this->l10n->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($message, array $replace) { - return \vsprintf($message, $replace); - })); - $this->checker = $this->getMockBuilder('\OC\IntegrityCheck\Checker') + ->will($this->returnCallback(fn ($message, array $replace) => \vsprintf($message, $replace))); + $this->checker = $this->getMockBuilder('\\' . \OC\IntegrityCheck\Checker::class) ->disableOriginalConstructor()->getMock(); - $this->checkSetupController = $this->getMockBuilder('\OC\Settings\Controller\CheckSetupController') + $this->checkSetupController = $this->getMockBuilder('\\' . \OC\Settings\Controller\CheckSetupController::class) ->setConstructorArgs([ 'settings', $this->request, @@ -117,7 +115,7 @@ public function testIsInternetConnectionWorkingCorrectly() { ->with('has_internet_connection', true) ->will($this->returnValue(true)); - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); $client ->expects($this->exactly(2)) @@ -145,7 +143,7 @@ public function testIsInternetConnectionHttpsFail() { ->with('has_internet_connection', true) ->will($this->returnValue(true)); - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); $client ->expects($this->once()) @@ -171,7 +169,7 @@ public function testIsInternetConnectionHttpFail() { ->with('has_internet_connection', true) ->will($this->returnValue(true)); - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); $client ->expects($this->exactly(2)) @@ -309,7 +307,7 @@ public function testCheck() { ->method('getRemoteAddress') ->willReturn('4.3.2.1'); - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); $client ->expects($this->exactly(2)) @@ -369,7 +367,7 @@ public function testCheck() { } public function testGetCurlVersion() { - $checkSetupController = $this->getMockBuilder('\OC\Settings\Controller\CheckSetupController') + $checkSetupController = $this->getMockBuilder('\\' . \OC\Settings\Controller\CheckSetupController::class) ->setConstructorArgs([ 'settings', $this->request, @@ -459,12 +457,12 @@ public function testIsBuggyNss400() { ->expects($this->once()) ->method('getCurlVersion') ->will($this->returnValue(['ssl_version' => 'NSS/1.0.2b'])); - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); /** @var ClientException | \PHPUnit\Framework\MockObject\MockObject $exception */ - $exception = $this->getMockBuilder('\GuzzleHttp\Exception\ClientException') + $exception = $this->getMockBuilder('\\' . \GuzzleHttp\Exception\ClientException::class) ->disableOriginalConstructor()->getMock(); - $response = $this->getMockBuilder('\Psr\Http\Message\ResponseInterface') + $response = $this->getMockBuilder('\\' . \Psr\Http\Message\ResponseInterface::class) ->disableOriginalConstructor()->getMock(); $response->expects($this->once()) ->method('getStatusCode') @@ -494,12 +492,12 @@ public function testIsBuggyNss200() { ->expects($this->once()) ->method('getCurlVersion') ->will($this->returnValue(['ssl_version' => 'NSS/1.0.2b'])); - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); /** @var ClientException | \PHPUnit\Framework\MockObject\MockObject $exception */ - $exception = $this->getMockBuilder('\GuzzleHttp\Exception\ClientException') + $exception = $this->getMockBuilder('\\' . \GuzzleHttp\Exception\ClientException::class) ->disableOriginalConstructor()->getMock(); - $response = $this->getMockBuilder('\Psr\Http\Message\ResponseInterface') + $response = $this->getMockBuilder('\\' . \Psr\Http\Message\ResponseInterface::class) ->disableOriginalConstructor()->getMock(); $response->expects($this->once()) ->method('getStatusCode') @@ -625,7 +623,7 @@ public function testGetFailedIntegrityCheckFilesWithSomeErrorsFound() { $this->checker ->expects($this->once()) ->method('getResults') - ->will($this->returnValue(['core' => ['EXTRA_FILE' => ['/testfile' => []], 'INVALID_HASH' => ['/.idea/workspace.xml' => ['expected' => 'f1c5e2630d784bc9cb02d5a28f55d6f24d06dae2a0fee685f3c2521b050955d9d452769f61454c9ddfa9c308146ade10546cfa829794448eaffbc9a04a29d216', 'current' => 'ce08bf30bcbb879a18b49239a9bec6b8702f52452f88a9d32142cad8d2494d5735e6bfa0d8642b2762c62ca5be49f9bf4ec231d4a230559d4f3e2c471d3ea094',], '/lib/private/integritycheck/checker.php' => ['expected' => 'c5a03bacae8dedf8b239997901ba1fffd2fe51271d13a00cc4b34b09cca5176397a89fc27381cbb1f72855fa18b69b6f87d7d5685c3b45aee373b09be54742ea', 'current' => '88a3a92c11db91dec1ac3be0e1c87f862c95ba6ffaaaa3f2c3b8f682187c66f07af3a3b557a868342ef4a271218fe1c1e300c478e6c156c5955ed53c40d06585',], '/settings/controller/checksetupcontroller.php' => ['expected' => '3e1de26ce93c7bfe0ede7c19cb6c93cadc010340225b375607a7178812e9de163179b0dc33809f451e01f491d93f6f5aaca7929685d21594cccf8bda732327c4', 'current' => '09563164f9904a837f9ca0b5f626db56c838e5098e0ccc1d8b935f68fa03a25c5ec6f6b2d9e44a868e8b85764dafd1605522b4af8db0ae269d73432e9a01e63a',],],], 'bookmarks' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'dav' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'encryption' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'external' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'federation' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files_antivirus' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files_drop' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files_external' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files_pdfviewer' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files_sharing' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files_trashbin' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files_versions' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'files_videoviewer' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'firstrunwizard' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'gitsmart' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'logreader' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature could not get verified.',],], 'password_policy' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'provisioning_api' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'sketch' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'threatblock' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'two_factor_auth' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'user_ldap' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],], 'user_shibboleth' => ['EXCEPTION' => ['class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', 'message' => 'Signature data not found.',],],])); + ->will($this->returnValue(['core' => ['EXTRA_FILE' => ['/testfile' => []], 'INVALID_HASH' => ['/.idea/workspace.xml' => ['expected' => 'f1c5e2630d784bc9cb02d5a28f55d6f24d06dae2a0fee685f3c2521b050955d9d452769f61454c9ddfa9c308146ade10546cfa829794448eaffbc9a04a29d216', 'current' => 'ce08bf30bcbb879a18b49239a9bec6b8702f52452f88a9d32142cad8d2494d5735e6bfa0d8642b2762c62ca5be49f9bf4ec231d4a230559d4f3e2c471d3ea094',], '/lib/private/integritycheck/checker.php' => ['expected' => 'c5a03bacae8dedf8b239997901ba1fffd2fe51271d13a00cc4b34b09cca5176397a89fc27381cbb1f72855fa18b69b6f87d7d5685c3b45aee373b09be54742ea', 'current' => '88a3a92c11db91dec1ac3be0e1c87f862c95ba6ffaaaa3f2c3b8f682187c66f07af3a3b557a868342ef4a271218fe1c1e300c478e6c156c5955ed53c40d06585',], '/settings/controller/checksetupcontroller.php' => ['expected' => '3e1de26ce93c7bfe0ede7c19cb6c93cadc010340225b375607a7178812e9de163179b0dc33809f451e01f491d93f6f5aaca7929685d21594cccf8bda732327c4', 'current' => '09563164f9904a837f9ca0b5f626db56c838e5098e0ccc1d8b935f68fa03a25c5ec6f6b2d9e44a868e8b85764dafd1605522b4af8db0ae269d73432e9a01e63a',],],], 'bookmarks' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'dav' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'encryption' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'external' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'federation' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files_antivirus' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files_drop' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files_external' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files_pdfviewer' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files_sharing' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files_trashbin' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files_versions' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'files_videoviewer' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'firstrunwizard' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'gitsmart' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'logreader' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature could not get verified.',],], 'password_policy' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'provisioning_api' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'sketch' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'threatblock' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'two_factor_auth' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'user_ldap' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],], 'user_shibboleth' => ['EXCEPTION' => ['class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature data not found.',],],])); $expected = new DataDisplayResponse( 'Technical information diff --git a/tests/Settings/Controller/CorsControllerTest.php b/tests/Settings/Controller/CorsControllerTest.php index f3176c9550a6..c918cfca866e 100644 --- a/tests/Settings/Controller/CorsControllerTest.php +++ b/tests/Settings/Controller/CorsControllerTest.php @@ -39,26 +39,25 @@ * @package Tests\Settings\Controller */ class CorsControllerTest extends TestCase { - /** @var CorsController */ - private $corsController; + private \OC\Settings\Controller\CorsController $corsController; /** @var IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IURLGenerator */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IL10N | MockObject */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var IUser */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; public function setUp(): void { parent::setUp(); @@ -103,9 +102,7 @@ public function testAddDomainWithNoProto() { ->method("setUserValue"); $this->l10n->method('t') - ->willReturnCallback(function ($a) { - return $a; - }); + ->willReturnCallback(fn ($a) => $a); $response = $this->corsController->addDomain("non-valid domain"); @@ -127,9 +124,7 @@ public function testAddInvalidDomain() { ->method("setUserValue"); $this->l10n->method('t') - ->willReturnCallback(function ($a) { - return $a; - }); + ->willReturnCallback(fn ($a) => $a); $response = $this->corsController->addDomain("http://non-valid domain"); @@ -168,9 +163,7 @@ public function testAddInvalidDomainWithPaths() { ->method("setUserValue"); $this->l10n->method('t') - ->willReturnCallback(function ($a) { - return $a; - }); + ->willReturnCallback(fn ($a) => $a); $response = $this->corsController->addDomain("http://test.com/path1/path2"); @@ -192,9 +185,7 @@ public function testAddInvalidDomainWithQueryParams() { ->method("setUserValue"); $this->l10n->method('t') - ->willReturnCallback(function ($a) { - return $a; - }); + ->willReturnCallback(fn ($a) => $a); $response = $this->corsController->addDomain("http://test.com?query=existent"); @@ -216,9 +207,7 @@ public function testAddInvalidProtocol() { ->method("setUserValue"); $this->l10n->method('t') - ->willReturnCallback(function ($a) { - return $a; - }); + ->willReturnCallback(fn ($a) => $a); $response = $this->corsController->addDomain("ftp://test.com"); diff --git a/tests/Settings/Controller/GroupsControllerTest.php b/tests/Settings/Controller/GroupsControllerTest.php index 40288cd9725b..fbe74c418cb7 100644 --- a/tests/Settings/Controller/GroupsControllerTest.php +++ b/tests/Settings/Controller/GroupsControllerTest.php @@ -33,19 +33,17 @@ protected function setUp(): void { $app = new Application(); $this->container = $app->getContainer(); $this->container['AppName'] = 'settings'; - $this->container['GroupManager'] = $this->getMockBuilder('\OC\Group\Manager') + $this->container['GroupManager'] = $this->getMockBuilder('\\' . \OC\Group\Manager::class) ->disableOriginalConstructor()->getMock(); - $this->container['UserSession'] = $this->getMockBuilder('\OC\User\Session') + $this->container['UserSession'] = $this->getMockBuilder('\\' . \OC\User\Session::class) ->disableOriginalConstructor()->getMock(); - $this->container['L10N'] = $this->getMockBuilder('\OCP\IL10N') + $this->container['L10N'] = $this->getMockBuilder('\\' . \OCP\IL10N::class) ->disableOriginalConstructor()->getMock(); $this->container['IsAdmin'] = true; $this->container['L10N'] ->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $this->groupsController = $this->container['GroupsController']; } @@ -54,7 +52,7 @@ protected function setUp(): void { * to test for subadmins. Thus the test always assumes you have admin permissions... */ public function testIndexSortByName() { - $firstGroup = $this->getMockBuilder('\OC\Group\Group') + $firstGroup = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $firstGroup ->method('getGID') @@ -63,7 +61,7 @@ public function testIndexSortByName() { $firstGroup ->method('count') ->will($this->returnValue(12)); - $secondGroup = $this->getMockBuilder('\OC\Group\Group') + $secondGroup = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $secondGroup ->method('getGID') @@ -72,7 +70,7 @@ public function testIndexSortByName() { $secondGroup ->method('count') ->will($this->returnValue(25)); - $thirdGroup = $this->getMockBuilder('\OC\Group\Group') + $thirdGroup = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $thirdGroup ->method('getGID') @@ -81,7 +79,7 @@ public function testIndexSortByName() { $thirdGroup ->method('count') ->will($this->returnValue(14)); - $fourthGroup = $this->getMockBuilder('\OC\Group\Group') + $fourthGroup = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $fourthGroup ->method('getGID') @@ -97,7 +95,7 @@ public function testIndexSortByName() { $groups[] = $thirdGroup; $groups[] = $fourthGroup; - $user = $this->getMockBuilder('\OC\User\User') + $user = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); $this->container['UserSession'] ->expects($this->once()) @@ -151,7 +149,7 @@ public function testIndexSortByName() { * to test for subadmins. Thus the test always assumes you have admin permissions... */ public function testIndexSortbyCount() { - $firstGroup = $this->getMockBuilder('\OC\Group\Group') + $firstGroup = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $firstGroup ->method('getGID') @@ -160,7 +158,7 @@ public function testIndexSortbyCount() { $firstGroup ->method('count') ->will($this->returnValue(12)); - $secondGroup = $this->getMockBuilder('\OC\Group\Group') + $secondGroup = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $secondGroup ->method('getGID') @@ -169,7 +167,7 @@ public function testIndexSortbyCount() { $secondGroup ->method('count') ->will($this->returnValue(25)); - $thirdGroup = $this->getMockBuilder('\OC\Group\Group') + $thirdGroup = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $thirdGroup ->method('getGID') @@ -178,7 +176,7 @@ public function testIndexSortbyCount() { $thirdGroup ->method('count') ->will($this->returnValue(14)); - $fourthGroup = $this->getMockBuilder('\OC\Group\Group') + $fourthGroup = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $fourthGroup ->method('getGID') @@ -194,7 +192,7 @@ public function testIndexSortbyCount() { $groups[] = $thirdGroup; $groups[] = $fourthGroup; - $user = $this->getMockBuilder('\OC\User\User') + $user = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor()->getMock(); $this->container['UserSession'] ->expects($this->once()) @@ -325,7 +323,7 @@ public function destroyData() { * @dataProvider destroyData */ public function testDestroySuccessful($groupName) { - $group = $this->getMockBuilder('\OC\Group\Group') + $group = $this->getMockBuilder('\\' . \OC\Group\Group::class) ->disableOriginalConstructor()->getMock(); $this->container['GroupManager'] ->expects($this->once()) @@ -400,7 +398,7 @@ public function testGetAssignableAndRemovableGroups() { ->with('assignableGroup') ->willReturn($aGroup); $assignableGroups = ['assignableGroup']; - $backend = $this->createMock('\OCP\GroupInterface'); + $backend = $this->createMock('\\' . \OCP\GroupInterface::class); $backend ->expects($this->once()) ->method('getGroups') @@ -462,7 +460,7 @@ public function testGetAssignableAndRemovableGroups2() { ->with('assignableGroup') ->willReturn($aGroup); $assignableGroups = ['assignableGroup']; - $backend = $this->createMock('\OCP\GroupInterface'); + $backend = $this->createMock('\\' . \OCP\GroupInterface::class); $backend ->expects($this->once()) ->method('getGroups') @@ -520,7 +518,7 @@ public function testGetAssignableAndRemovableGroupsBackendNoActions() { ->method('isAdmin') ->with($userid) ->willReturn(true); - $backend = $this->createMock('\OCP\GroupInterface'); + $backend = $this->createMock('\\' . \OCP\GroupInterface::class); $backend->method('implementsActions') ->willReturn(false); $this->container['GroupManager'] @@ -556,7 +554,7 @@ public function testGetAssignableAndRemovableGroupsSubadmin() { ->method('isAdmin') ->with($userid) ->willReturn(false); - $backend = $this->createMock('\OCP\GroupInterface'); + $backend = $this->createMock('\\' . \OCP\GroupInterface::class); $backend->method('implementsActions') ->willReturn(true); diff --git a/tests/Settings/Controller/LogSettingsControllerTest.php b/tests/Settings/Controller/LogSettingsControllerTest.php index b6f762eff096..7ca172be3422 100644 --- a/tests/Settings/Controller/LogSettingsControllerTest.php +++ b/tests/Settings/Controller/LogSettingsControllerTest.php @@ -26,7 +26,7 @@ class LogSettingsControllerTest extends \Test\TestCase { protected function setUp(): void { $app = new Application(); $this->container = $app->getContainer(); - $this->container['Config'] = $this->getMockBuilder('\OCP\IConfig') + $this->container['Config'] = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor()->getMock(); $this->container['AppName'] = 'settings'; $this->logSettingsController = $this->container['LogSettingsController']; @@ -69,7 +69,7 @@ public function logLevelData() { public function testDownload() { $response = $this->logSettingsController->download(); - $this->assertInstanceOf('\OCP\AppFramework\Http\StreamResponse', $response); + $this->assertInstanceOf('\\' . \OCP\AppFramework\Http\StreamResponse::class, $response); $headers = $response->getHeaders(); $this->assertEquals('application/octet-stream', $headers['Content-Type']); $this->assertEquals('attachment; filename="owncloud.log"', $headers['Content-Disposition']); diff --git a/tests/Settings/Controller/MailSettingsControllerTest.php b/tests/Settings/Controller/MailSettingsControllerTest.php index c37206aa97fd..8c3c56926133 100644 --- a/tests/Settings/Controller/MailSettingsControllerTest.php +++ b/tests/Settings/Controller/MailSettingsControllerTest.php @@ -23,16 +23,16 @@ protected function setUp(): void { $app = new Application(); $this->container = $app->getContainer(); - $this->container['Config'] = $this->getMockBuilder('\OCP\IConfig') + $this->container['Config'] = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor()->getMock(); - $this->container['L10N'] = $this->getMockBuilder('\OCP\IL10N') + $this->container['L10N'] = $this->getMockBuilder('\\' . \OCP\IL10N::class) ->disableOriginalConstructor()->getMock(); $this->container['AppName'] = 'settings'; - $this->container['UserSession'] = $this->getMockBuilder('\OC\User\Session') + $this->container['UserSession'] = $this->getMockBuilder('\\' . \OC\User\Session::class) ->disableOriginalConstructor()->getMock(); $this->container['MailMessage'] = $this->getMockBuilder('\OCP\Mail\IMessage') ->disableOriginalConstructor()->getMock(); - $this->container['Mailer'] = $this->getMockBuilder('\OC\Mail\Mailer') + $this->container['Mailer'] = $this->getMockBuilder('\\' . \OC\Mail\Mailer::class) ->setMethods(['send', 'validateMailAddress']) ->disableOriginalConstructor()->getMock(); $this->container['Defaults'] = $this->getMockBuilder('\OC_Defaults') @@ -201,7 +201,7 @@ public function testStoreCredentials() { } public function testSendTestMail() { - $user = $this->getMockBuilder('\OC\User\User') + $user = $this->getMockBuilder('\\' . \OC\User\User::class) ->disableOriginalConstructor() ->getMock(); $user->expects($this->any()) diff --git a/tests/Settings/Controller/UsersControllerTest.php b/tests/Settings/Controller/UsersControllerTest.php index ebe2b64b1462..b7e9a16ca022 100644 --- a/tests/Settings/Controller/UsersControllerTest.php +++ b/tests/Settings/Controller/UsersControllerTest.php @@ -77,9 +77,7 @@ protected function setUp(): void { ->disableOriginalConstructor()->getMock(); $this->container['L10N'] ->method('t') - ->willReturnCallback(function ($text, $parameters = []) { - return vsprintf($text, $parameters); - }); + ->willReturnCallback(fn ($text, $parameters = []) => vsprintf($text, $parameters)); $this->container['Defaults'] = $this->getMockBuilder(OC_Defaults::class) ->disableOriginalConstructor()->getMock(); $this->container['Mailer'] = $this->getMockBuilder(IMailer::class) @@ -89,7 +87,7 @@ protected function setUp(): void { ->disableOriginalConstructor()->getMock(); $this->container['URLGenerator'] = $this->getMockBuilder(IURLGenerator::class) ->disableOriginalConstructor()->getMock(); - $this->container['OCP\\App\\IAppManager'] = $this->getMockBuilder(IAppManager::class) + $this->container[\OCP\App\IAppManager::class] = $this->getMockBuilder(IAppManager::class) ->disableOriginalConstructor()->getMock(); $this->container['SecureRandom'] = $this->getMockBuilder(ISecureRandom::class) ->disableOriginalConstructor()->getMock(); @@ -104,13 +102,13 @@ protected function setUp(): void { /* * Set default avtar behaviour for whole testsuite */ - $this->container['OCP\\IAvatarManager'] = $this->createMock(IAvatarManager::class); + $this->container[\OCP\IAvatarManager::class] = $this->createMock(IAvatarManager::class); $avatarExists = $this->createMock(IAvatar::class); $avatarExists->method('exists')->willReturn(true); $avatarNotExists = $this->createMock(IAvatar::class); $avatarNotExists->method('exists')->willReturn(false); - $this->container['OCP\\IAvatarManager'] + $this->container[\OCP\IAvatarManager::class] ->method('getAvatar') ->willReturnMap([ ['foo', $avatarExists], @@ -191,7 +189,7 @@ public function testIndexAdmin(): void { $admin ->expects($this->once()) ->method('getBackendClassName') - ->willReturn('\Test\Util\User\Dummy'); + ->willReturn('\\' . \Test\Util\User\Dummy::class); $bar = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $bar @@ -222,7 +220,7 @@ public function testIndexAdmin(): void { $bar ->expects($this->once()) ->method('getBackendClassName') - ->willReturn('\Test\Util\User\Dummy'); + ->willReturn('\\' . \Test\Util\User\Dummy::class); $group1 = $this->createMock(IGroup::class); $group1->method('getGID')->willReturn('abc-cde-123-456'); @@ -324,7 +322,7 @@ public function testIndexAdmin(): void { 'quota' => 404, 'storageLocation' => '/home/admin', 'lastLogin' => 12000, - 'backend' => '\Test\Util\User\Dummy', + 'backend' => '\\' . \Test\Util\User\Dummy::class, 'email' => 'admin@bar.com', 'isRestoreDisabled' => false, 'isAvatarAvailable' => false, @@ -344,8 +342,8 @@ public function testIndexAdmin(): void { 'isEnabled' => false, 'quota' => 2323, 'storageLocation' => '/home/bar', - 'lastLogin' => 3999000, - 'backend' => '\Test\Util\User\Dummy', + 'lastLogin' => 3_999_000, + 'backend' => '\\' . \Test\Util\User\Dummy::class, 'email' => 'bar@dummy.com', 'isRestoreDisabled' => false, 'isAvatarAvailable' => true, @@ -431,7 +429,7 @@ public function testIndexSubAdmin(): void { $admin ->expects($this->once()) ->method('getBackendClassName') - ->willReturn('\Test\Util\User\Dummy'); + ->willReturn('\\' . \Test\Util\User\Dummy::class); $bar = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $bar @@ -462,7 +460,7 @@ public function testIndexSubAdmin(): void { $bar ->expects($this->once()) ->method('getBackendClassName') - ->willReturn('\Test\Util\User\Dummy'); + ->willReturn('\\' . \Test\Util\User\Dummy::class); $this->container['GroupManager'] ->expects($this->exactly(2)) @@ -543,8 +541,8 @@ public function testIndexSubAdmin(): void { 'isEnabled' => false, 'quota' => 2323, 'storageLocation' => '/home/bar', - 'lastLogin' => 3999000, - 'backend' => '\Test\Util\User\Dummy', + 'lastLogin' => 3_999_000, + 'backend' => '\\' . \Test\Util\User\Dummy::class, 'email' => 'bar@dummy.com', 'isRestoreDisabled' => false, 'isAvatarAvailable' => true, @@ -590,7 +588,7 @@ public function testIndexSubAdmin(): void { 'quota' => 404, 'storageLocation' => '/home/admin', 'lastLogin' => 12000, - 'backend' => '\Test\Util\User\Dummy', + 'backend' => '\\' . \Test\Util\User\Dummy::class, 'email' => 'admin@bar.com', 'isRestoreDisabled' => false, 'isAvatarAvailable' => false, @@ -675,7 +673,7 @@ public function testIndexWithSearch(): void { $admin ->expects($this->once()) ->method('getBackendClassName') - ->willReturn('\Test\Util\User\Dummy'); + ->willReturn('\\' . \Test\Util\User\Dummy::class); $bar = $this->getMockBuilder(User::class) ->disableOriginalConstructor()->getMock(); $bar @@ -706,7 +704,7 @@ public function testIndexWithSearch(): void { $bar ->expects($this->once()) ->method('getBackendClassName') - ->willReturn('\Test\Util\User\Dummy'); + ->willReturn('\\' . \Test\Util\User\Dummy::class); $this->container['UserManager'] ->expects($this->once()) @@ -787,7 +785,7 @@ public function testIndexWithSearch(): void { 'quota' => 404, 'storageLocation' => '/home/admin', 'lastLogin' => 12000, - 'backend' => '\Test\Util\User\Dummy', + 'backend' => '\\' . \Test\Util\User\Dummy::class, 'email' => 'admin@bar.com', 'isRestoreDisabled' => false, 'isAvatarAvailable' => false, @@ -807,8 +805,8 @@ public function testIndexWithSearch(): void { 'isEnabled' => false, 'quota' => 2323, 'storageLocation' => '/home/bar', - 'lastLogin' => 3999000, - 'backend' => '\Test\Util\User\Dummy', + 'lastLogin' => 3_999_000, + 'backend' => '\\' . \Test\Util\User\Dummy::class, 'email' => 'bar@dummy.com', 'isRestoreDisabled' => false, 'isAvatarAvailable' => true, @@ -902,7 +900,7 @@ public function testIndexWithBackend(): void { ] ] ); - $response = $this->container['UsersController']->index(0, 10, '', '', '\Test\Util\User\Dummy'); + $response = $this->container['UsersController']->index(0, 10, '', '', '\\' . \Test\Util\User\Dummy::class); $this->assertEquals($expectedResponse, $response); } @@ -920,7 +918,7 @@ public function testIndexWithBackendNoUser(): void { ->willReturn([]); $expectedResponse = new DataResponse([]); - $response = $this->container['UsersController']->index(0, 10, '', '', '\Test\Util\User\Dummy'); + $response = $this->container['UsersController']->index(0, 10, '', '', '\\' . \Test\Util\User\Dummy::class); $this->assertEquals($expectedResponse, $response); } @@ -1788,7 +1786,7 @@ private function mockUser( public function testRestorePossibleWithoutEncryption(): void { $this->container['IsAdmin'] = true; - list($user, $expectedResult) = $this->mockUser(); + [$user, $expectedResult] = $this->mockUser(); $expectedResult['isGuest'] = false; $subadmin = $this->getMockBuilder(SubAdmin::class) @@ -1810,10 +1808,10 @@ public function testRestorePossibleWithoutEncryption(): void { public function testRestorePossibleWithAdminAndUserRestore(): void { $this->container['IsAdmin'] = true; - list($user, $expectedResult) = $this->mockUser(); + [$user, $expectedResult] = $this->mockUser(); $expectedResult['isGuest'] = false; - $this->container['OCP\\App\\IAppManager'] + $this->container[\OCP\App\IAppManager::class] ->expects($this->once()) ->method('isEnabledForUser') ->with( @@ -1867,10 +1865,10 @@ public function testRestorePossibleWithAdminAndUserRestore(): void { public function testRestoreNotPossibleWithoutAdminRestore(): void { $this->container['IsAdmin'] = true; - list($user, $expectedResult) = $this->mockUser(); + [$user, $expectedResult] = $this->mockUser(); $expectedResult['isGuest'] = false; - $this->container['OCP\\App\\IAppManager'] + $this->container[\OCP\App\IAppManager::class] ->method('isEnabledForUser') ->with( $this->equalTo('encryption') @@ -1898,10 +1896,10 @@ public function testRestoreNotPossibleWithoutAdminRestore(): void { public function testRestoreNotPossibleWithoutUserRestore(): void { $this->container['IsAdmin'] = true; - list($user, $expectedResult) = $this->mockUser(); + [$user, $expectedResult] = $this->mockUser(); $expectedResult['isGuest'] = false; - $this->container['OCP\\App\\IAppManager'] + $this->container[\OCP\App\IAppManager::class] ->expects($this->once()) ->method('isEnabledForUser') ->with( @@ -1957,7 +1955,7 @@ public function testRestoreNotPossibleWithoutUserRestore(): void { public function testNoAvatar(): void { $this->container['IsAdmin'] = true; - list($user, $expectedResult) = $this->mockUser(); + [$user, $expectedResult] = $this->mockUser(); $expectedResult['isGuest'] = false; $subadmin = $this->getMockBuilder(SubAdmin::class) @@ -1972,7 +1970,7 @@ public function testNoAvatar(): void { ->willReturn($subadmin); $this->container['GroupManager']->method('getUserGroups')->willReturn([]); - $this->container['OCP\\IAvatarManager'] + $this->container[\OCP\IAvatarManager::class] ->method('getAvatar') ->will($this->throwException(new NotFoundException())); $expectedResult['isAvatarAvailable'] = false; diff --git a/tests/Settings/Middleware/SubadminMiddlewareTest.php b/tests/Settings/Middleware/SubadminMiddlewareTest.php index 8bc5e1943845..fa6d36d8486c 100644 --- a/tests/Settings/Middleware/SubadminMiddlewareTest.php +++ b/tests/Settings/Middleware/SubadminMiddlewareTest.php @@ -23,19 +23,17 @@ * @package Tests\Settings\Middleware */ class SubadminMiddlewareTest extends \Test\TestCase { - /** @var SubadminMiddleware */ - private $subadminMiddlewareAsSubAdmin; - /** @var SubadminMiddleware */ - private $subadminMiddleware; + private \OC\Settings\Middleware\SubadminMiddleware $subadminMiddlewareAsSubAdmin; + private \OC\Settings\Middleware\SubadminMiddleware $subadminMiddleware; /** @var ControllerMethodReflector */ - private $reflector; + private \PHPUnit\Framework\MockObject\MockObject $reflector; /** @var Controller */ - private $controller; + private \PHPUnit\Framework\MockObject\MockObject $controller; protected function setUp(): void { - $this->reflector = $this->getMockBuilder('\OC\AppFramework\Utility\ControllerMethodReflector') + $this->reflector = $this->getMockBuilder('\\' . \OC\AppFramework\Utility\ControllerMethodReflector::class) ->disableOriginalConstructor()->getMock(); - $this->controller = $this->getMockBuilder('\OCP\AppFramework\Controller') + $this->controller = $this->getMockBuilder('\\' . \OCP\AppFramework\Controller::class) ->disableOriginalConstructor()->getMock(); $this->subadminMiddlewareAsSubAdmin = new SubadminMiddleware($this->reflector, true); diff --git a/tests/Settings/Panels/Admin/AppsTest.php b/tests/Settings/Panels/Admin/AppsTest.php index 6625e860457b..d8d33bebe147 100644 --- a/tests/Settings/Panels/Admin/AppsTest.php +++ b/tests/Settings/Panels/Admin/AppsTest.php @@ -17,10 +17,9 @@ * @package Tests\Settings\Panels\Admin */ class AppsTest extends \Test\TestCase { - /** @var Apps */ - private $panel; + private \OC\Settings\Panels\Admin\Apps $panel; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/BackgroundJobsTest.php b/tests/Settings/Panels/Admin/BackgroundJobsTest.php index 66f391f62f04..0a3deb7c3ff9 100644 --- a/tests/Settings/Panels/Admin/BackgroundJobsTest.php +++ b/tests/Settings/Panels/Admin/BackgroundJobsTest.php @@ -18,10 +18,9 @@ * @group DB */ class BackgroundJobsTest extends \Test\TestCase { - /** @var BackgroundJobs */ - private $panel; + private \OC\Settings\Panels\Admin\BackgroundJobs $panel; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/CertificatesTest.php b/tests/Settings/Panels/Admin/CertificatesTest.php index 5923959c72ed..e349150bd08a 100644 --- a/tests/Settings/Panels/Admin/CertificatesTest.php +++ b/tests/Settings/Panels/Admin/CertificatesTest.php @@ -20,14 +20,13 @@ * @package Tests\Settings\Panels\Admin */ class CertificatesTest extends \Test\TestCase { - /** @var Certificates */ - private $panel; + private \OC\Settings\Panels\Admin\Certificates $panel; /** @var IURLGenerator */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ICertificateManager */ - private $certManager; + private \PHPUnit\Framework\MockObject\MockObject $certManager; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/EncryptionTest.php b/tests/Settings/Panels/Admin/EncryptionTest.php index 74ce3fa95ef0..3834b8abd000 100644 --- a/tests/Settings/Panels/Admin/EncryptionTest.php +++ b/tests/Settings/Panels/Admin/EncryptionTest.php @@ -16,8 +16,7 @@ * @package Tests\Settings\Panels\Admin */ class EncryptionTest extends \Test\TestCase { - /** @var Encryption */ - private $panel; + private \OC\Settings\Panels\Admin\Encryption $panel; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/Enforce2faTest.php b/tests/Settings/Panels/Admin/Enforce2faTest.php index a469c22369ef..96ac5ebafebf 100644 --- a/tests/Settings/Panels/Admin/Enforce2faTest.php +++ b/tests/Settings/Panels/Admin/Enforce2faTest.php @@ -28,9 +28,8 @@ */ class Enforce2faTest extends \Test\TestCase { /** @var IConfig */ - private $config; - /** @var Enforce2fa */ - private $panel; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OC\Settings\Panels\Admin\Enforce2fa $panel; protected function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/FileSharingTest.php b/tests/Settings/Panels/Admin/FileSharingTest.php index e08644c8860f..0c85532e99ec 100644 --- a/tests/Settings/Panels/Admin/FileSharingTest.php +++ b/tests/Settings/Panels/Admin/FileSharingTest.php @@ -20,12 +20,11 @@ * @package Tests\Settings\Panels\Admin */ class FileSharingTest extends \Test\TestCase { - /** @var FileSharing */ - private $panel; + private \OC\Settings\Panels\Admin\FileSharing $panel; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var Helper */ - private $helper; + private \PHPUnit\Framework\MockObject\MockObject $helper; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/LegacyTest.php b/tests/Settings/Panels/Admin/LegacyTest.php index 7600ef789ba6..4c619235e4c9 100644 --- a/tests/Settings/Panels/Admin/LegacyTest.php +++ b/tests/Settings/Panels/Admin/LegacyTest.php @@ -17,10 +17,9 @@ * @package Tests\Settings\Panels\Admin */ class LegacyTest extends \Test\TestCase { - /** @var Legacy */ - private $panel; + private \OC\Settings\Panels\Admin\Legacy $panel; /** @var Helper */ - private $helper; + private \PHPUnit\Framework\MockObject\MockObject $helper; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/LegalTest.php b/tests/Settings/Panels/Admin/LegalTest.php index 9c8e171d1f70..80db1968cb25 100644 --- a/tests/Settings/Panels/Admin/LegalTest.php +++ b/tests/Settings/Panels/Admin/LegalTest.php @@ -28,10 +28,9 @@ * @package Tests\Settings\Panels\Admin */ class LegalTest extends \Test\TestCase { - /** @var Legal */ - private $panel; + private \OC\Settings\Panels\Admin\Legal $panel; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/LicenseTest.php b/tests/Settings/Panels/Admin/LicenseTest.php index 30406bfd1a9b..e28666ac3fd3 100644 --- a/tests/Settings/Panels/Admin/LicenseTest.php +++ b/tests/Settings/Panels/Admin/LicenseTest.php @@ -28,10 +28,9 @@ * @package Tests\Settings\Panels\Admin */ class LicenseTest extends \Test\TestCase { - /** @var License */ - private $panel; + private \OC\Settings\Panels\Admin\License $panel; /** @var ILicenseManager */ - private $licenseManager; + private \PHPUnit\Framework\MockObject\MockObject $licenseManager; protected function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/LoggingTest.php b/tests/Settings/Panels/Admin/LoggingTest.php index 85c46368b7c6..4bb2e3a3a105 100644 --- a/tests/Settings/Panels/Admin/LoggingTest.php +++ b/tests/Settings/Panels/Admin/LoggingTest.php @@ -19,14 +19,13 @@ * @package Tests\Settings\Panels\Admin */ class LoggingTest extends \Test\TestCase { - /** @var Logging */ - private $panel; + private \OC\Settings\Panels\Admin\Logging $panel; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IURLGenerator */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var Helper */ - private $helper; + private \PHPUnit\Framework\MockObject\MockObject $helper; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/MailTest.php b/tests/Settings/Panels/Admin/MailTest.php index 8eab7ce9a5e2..1353c6bde653 100644 --- a/tests/Settings/Panels/Admin/MailTest.php +++ b/tests/Settings/Panels/Admin/MailTest.php @@ -20,16 +20,15 @@ * @package Tests\Settings\Panels\Admin */ class MailTest extends \Test\TestCase { - /** @var Mail */ - private $panel; + private \OC\Settings\Panels\Admin\Mail $panel; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var Helper */ - private $helper; + private \PHPUnit\Framework\MockObject\MockObject $helper; /** @var IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; /** @var IUser */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/PersistentLockingTest.php b/tests/Settings/Panels/Admin/PersistentLockingTest.php index 5ab0fe4678ff..ee4c32412889 100644 --- a/tests/Settings/Panels/Admin/PersistentLockingTest.php +++ b/tests/Settings/Panels/Admin/PersistentLockingTest.php @@ -30,11 +30,8 @@ */ class PersistentLockingTest extends TestCase { /** @var IConfig */ - private $config; - /** - * @var PersistentLocking - */ - private $panel; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OC\Settings\Panels\Admin\PersistentLocking $panel; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/SecurityWarningTest.php b/tests/Settings/Panels/Admin/SecurityWarningTest.php index ed250f7d5c61..f560101139e7 100644 --- a/tests/Settings/Panels/Admin/SecurityWarningTest.php +++ b/tests/Settings/Panels/Admin/SecurityWarningTest.php @@ -21,18 +21,17 @@ * @package Tests\Settings\Panels\Admin */ class SecurityWarningTest extends \Test\TestCase { - /** @var SecurityWarning */ - private $panel; + private \OC\Settings\Panels\Admin\SecurityWarning $panel; /** @var IL10N */ - private $l; + private \PHPUnit\Framework\MockObject\MockObject $l; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IDBConnection */ - private $dbconnection; + private \PHPUnit\Framework\MockObject\MockObject $dbconnection; /** @var ILockingProvider */ - private $lockingProvider; + private \PHPUnit\Framework\MockObject\MockObject $lockingProvider; /** @var Helper */ - private $helper; + private \PHPUnit\Framework\MockObject\MockObject $helper; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Admin/TipsTest.php b/tests/Settings/Panels/Admin/TipsTest.php index 7030c3c71527..17e2c23cbf1d 100644 --- a/tests/Settings/Panels/Admin/TipsTest.php +++ b/tests/Settings/Panels/Admin/TipsTest.php @@ -16,8 +16,7 @@ * @package Tests\Settings\Panels\Admin */ class TipsTest extends \Test\TestCase { - /** @var Tips */ - private $panel; + private \OC\Settings\Panels\Admin\Tips $panel; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Personal/ClientsTest.php b/tests/Settings/Panels/Personal/ClientsTest.php index 3c10d0cde34a..495452b11529 100644 --- a/tests/Settings/Panels/Personal/ClientsTest.php +++ b/tests/Settings/Panels/Personal/ClientsTest.php @@ -18,12 +18,11 @@ * @package Tests\Settings\Panels\Personal */ class ClientsTest extends \Test\TestCase { - /** @var Clients */ - private $panel; + private \OC\Settings\Panels\Personal\Clients $panel; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var Defaults */ - private $defaults; + private \PHPUnit\Framework\MockObject\MockObject $defaults; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Personal/LegacyTest.php b/tests/Settings/Panels/Personal/LegacyTest.php index c21c628dc332..f158422381bd 100644 --- a/tests/Settings/Panels/Personal/LegacyTest.php +++ b/tests/Settings/Panels/Personal/LegacyTest.php @@ -17,10 +17,9 @@ * @package Tests\Settings\Panels\Personal */ class LegacyTest extends \Test\TestCase { - /** @var Legacy */ - private $panel; + private \OC\Settings\Panels\Personal\Legacy $panel; /** @var Helper */ - private $helper; + private \PHPUnit\Framework\MockObject\MockObject $helper; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Personal/ProfileTest.php b/tests/Settings/Panels/Personal/ProfileTest.php index 8a7bd286a6c3..5bc697c47f3c 100644 --- a/tests/Settings/Panels/Personal/ProfileTest.php +++ b/tests/Settings/Panels/Personal/ProfileTest.php @@ -23,16 +23,15 @@ * @package Tests\Settings\Panels\Personal */ class ProfileTest extends \Test\TestCase { - /** @var Profile */ - private $panel; + private \OC\Settings\Panels\Personal\Profile $panel; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IGroupManager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var IFactory */ - private $lfactory; + private \PHPUnit\Framework\MockObject\MockObject $lfactory; /** @var IUserSession */ - private $userSession; + private \PHPUnit\Framework\MockObject\MockObject $userSession; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Personal/QuotaTest.php b/tests/Settings/Panels/Personal/QuotaTest.php index 66b48d61b721..a381d298ee21 100644 --- a/tests/Settings/Panels/Personal/QuotaTest.php +++ b/tests/Settings/Panels/Personal/QuotaTest.php @@ -17,10 +17,9 @@ * @package Tests\Settings\Panels */ class QuotaTest extends \Test\TestCase { - /** @var Quota */ - private $panel; + private \OC\Settings\Panels\Personal\Quota $panel; /** @var Helper */ - private $helper; + private \PHPUnit\Framework\MockObject\MockObject $helper; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Personal/TokensTest.php b/tests/Settings/Panels/Personal/TokensTest.php index 6ad679468ced..190463d5cc3f 100644 --- a/tests/Settings/Panels/Personal/TokensTest.php +++ b/tests/Settings/Panels/Personal/TokensTest.php @@ -16,8 +16,7 @@ * @package Tests\Settings\Panels\Personal */ class TokensTest extends \Test\TestCase { - /** @var Tokens */ - private $panel; + private \OC\Settings\Panels\Personal\Tokens $panel; public function setUp(): void { parent::setUp(); diff --git a/tests/Settings/Panels/Personal/VersionTest.php b/tests/Settings/Panels/Personal/VersionTest.php index a5baef090065..e042355d39df 100644 --- a/tests/Settings/Panels/Personal/VersionTest.php +++ b/tests/Settings/Panels/Personal/VersionTest.php @@ -16,8 +16,7 @@ * @package Tests\Settings\Panels\Personal */ class VersionTest extends \Test\TestCase { - /** @var Version */ - private $panel; + private \OC\Settings\Panels\Personal\Version $panel; public function setUp(): void { parent::setUp(); diff --git a/tests/TestHelpers/AppConfigHelper.php b/tests/TestHelpers/AppConfigHelper.php index cd69fa5874a9..d59b948ad136 100644 --- a/tests/TestHelpers/AppConfigHelper.php +++ b/tests/TestHelpers/AppConfigHelper.php @@ -513,7 +513,7 @@ public static function getAppConfigs( } $responseXml = HttpRequestHelper::getResponseXml($response, __METHOD__)->data[0]; - return \json_decode(\json_encode($responseXml), true)['element']; + return \json_decode(\json_encode($responseXml, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR)['element']; } /** @@ -567,6 +567,6 @@ public static function getAppConfig( } $responseXml = HttpRequestHelper::getResponseXml($response, __METHOD__)->data[0]; - return \json_decode(\json_encode($responseXml), true)['element']; + return \json_decode(\json_encode($responseXml, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR)['element']; } } diff --git a/tests/TestHelpers/EmailHelper.php b/tests/TestHelpers/EmailHelper.php index 7bff21c27008..ffe01648938e 100644 --- a/tests/TestHelpers/EmailHelper.php +++ b/tests/TestHelpers/EmailHelper.php @@ -61,7 +61,7 @@ public static function getMailboxInformation(string $mailBox, ?string $xRequestI null, ['Content-Type' => 'application/json'] ); - return \json_decode($response->getBody()->getContents()); + return \json_decode($response->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR); } /** @@ -144,7 +144,7 @@ public static function getBodyOfAnEmailById(string $mailBox, string $mailboxId, ['Content-Type' => 'application/json'] ); - return \json_decode($response->getBody()->getContents()); + return \json_decode($response->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR); } /** diff --git a/tests/TestHelpers/SetupHelper.php b/tests/TestHelpers/SetupHelper.php index 89a811b1c078..edf4103d8e63 100644 --- a/tests/TestHelpers/SetupHelper.php +++ b/tests/TestHelpers/SetupHelper.php @@ -62,7 +62,7 @@ public static function createUser( ):array { $occCommand = ['user:add', '--password-from-env']; if ($displayName !== null) { - $occCommand = \array_merge($occCommand, ["--display-name", $displayName]); + $occCommand = [...$occCommand, "--display-name", $displayName]; } if ($email !== null) { $occCommand = \array_merge($occCommand, ["--email", $email]); @@ -211,7 +211,10 @@ public static function getGroups( self::runOcc( ['group:list', '--output=json'], $xRequestId - )['stdOut'] + )['stdOut'], + null, + 512, + JSON_THROW_ON_ERROR ); } /** @@ -812,7 +815,7 @@ public static function runBulkOcc( "POST", "/apps/testing/api/v1/occ/bulk?format=json", $xRequestId, - \json_encode($bodies) + \json_encode($bodies, JSON_THROW_ON_ERROR) ); } catch (ServerException $e) { throw new Exception( @@ -821,7 +824,7 @@ public static function runBulkOcc( $e->getResponse()->getBody() ); } - $result = \json_decode($result->getBody()->getContents()); + $result = \json_decode($result->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR); return $result->ocs->data; } @@ -1204,7 +1207,7 @@ public static function getSystemConfigValue( public static function findLines(?string $input, ?string $text):array { $results = []; foreach (\explode("\n", $input) as $line) { - if (\strpos($line, $text) !== false) { + if (\strpos($line, (string) $text) !== false) { $results[] = $line; } } diff --git a/tests/TestHelpers/TagsHelper.php b/tests/TestHelpers/TagsHelper.php index 6ce59146e412..c710cccfdded 100644 --- a/tests/TestHelpers/TagsHelper.php +++ b/tests/TestHelpers/TagsHelper.php @@ -267,7 +267,7 @@ public static function createTag( $tagsPath, ['Content-Type' => 'application/json',], $xRequestId, - \json_encode($body), + \json_encode($body, JSON_THROW_ON_ERROR), $davPathVersionToUse, "systemtags" ); diff --git a/tests/TestHelpers/Unit/DeleteHelperTest.php b/tests/TestHelpers/Unit/DeleteHelperTest.php index e08e6e8d0c77..0c247ca08378 100644 --- a/tests/TestHelpers/Unit/DeleteHelperTest.php +++ b/tests/TestHelpers/Unit/DeleteHelperTest.php @@ -33,7 +33,7 @@ */ class DeleteHelperTest extends PHPUnit\Framework\TestCase { public Client $client; - private $container = []; + private array $container = []; /** * Setup http client, mock requests, and attach history diff --git a/tests/TestHelpers/UploadHelper.php b/tests/TestHelpers/UploadHelper.php index 7cb3d4534156..1a20b00e8cf5 100644 --- a/tests/TestHelpers/UploadHelper.php +++ b/tests/TestHelpers/UploadHelper.php @@ -82,7 +82,7 @@ public static function upload( } else { //prepare chunking $chunks = self::chunkFile($source, $noOfChunks); - $chunkingId = 'chunking-' . \rand(1000, 9999); + $chunkingId = 'chunking-' . random_int(1000, 9999); $v2ChunksDestination = '/uploads/' . $user . '/' . $chunkingId; } diff --git a/tests/TestHelpers/WebDavHelper.php b/tests/TestHelpers/WebDavHelper.php index 577519240264..4eb4b900a6c7 100644 --- a/tests/TestHelpers/WebDavHelper.php +++ b/tests/TestHelpers/WebDavHelper.php @@ -462,7 +462,7 @@ public static function getPersonalSpaceIdForUser(string $baseUrl, string $user, $password ); $bodyContents = $response->getBody()->getContents(); - $json = \json_decode($bodyContents); + $json = \json_decode($bodyContents, null, 512, JSON_THROW_ON_ERROR); $personalSpaceId = ''; if ($json === null) { // the graph endpoint did not give a useful answer @@ -876,7 +876,7 @@ public static function getMtimeOfResource( Assert::assertArrayHasKey( 0, $xmlpart, - __METHOD__ . " XML part does not have key 0. Expected a value at index 0 of 'xmlPart' but, found: " . json_encode($xmlpart) + __METHOD__ . " XML part does not have key 0. Expected a value at index 0 of 'xmlPart' but, found: " . json_encode($xmlpart, JSON_THROW_ON_ERROR) ); $mtime = new DateTime($xmlpart[0]->__toString()); return $mtime->format('U'); diff --git a/tests/acceptance/features/bootstrap/AppManagementContext.php b/tests/acceptance/features/bootstrap/AppManagementContext.php index 33615a55fddd..e3875fefaaf8 100644 --- a/tests/acceptance/features/bootstrap/AppManagementContext.php +++ b/tests/acceptance/features/bootstrap/AppManagementContext.php @@ -50,7 +50,7 @@ class AppManagementContext implements Context { public function setAppsPaths(array $appsPaths):array { return SetupHelper::setSystemConfig( 'apps_paths', - \json_encode($appsPaths), + \json_encode($appsPaths, JSON_THROW_ON_ERROR), $this->featureContext->getStepLineRef(), 'json' ); @@ -71,7 +71,9 @@ public function setAppDirectories(TableNode $table):void { $this->featureContext->getStepLineRef(), "json" )['stdOut'], - true + true, + 512, + JSON_THROW_ON_ERROR ); $this->featureContext->verifyTableNodeColumns($table, ['dir'], ['is_writable']); foreach ($table as $appsPathToAdd) { @@ -159,7 +161,7 @@ public function appHasBeenPutInDir(string $appId, string $version, string $dir): ['app:list', '--output json'], $this->featureContext->getStepLineRef() ); - $appsDisabled = \json_decode($check['stdOut'], true)['disabled']; + $appsDisabled = \json_decode($check['stdOut'], true, 512, JSON_THROW_ON_ERROR)['disabled']; if (!\array_key_exists($appId, $appsDisabled)) { throw new \Exception( __METHOD__ @@ -483,7 +485,7 @@ public function prepareParameters(BeforeScenarioScope $scope):void { if ($value === '') { $this->oldAppsPaths = null; } else { - $this->oldAppsPaths = \json_decode($value, true); + $this->oldAppsPaths = \json_decode($value, true, 512, JSON_THROW_ON_ERROR); } } @@ -519,7 +521,7 @@ public function deleteCreatedApps():void { ['config:list'], $this->featureContext->getStepLineRef() )['stdOut']; - $configList = \json_decode($configJson, true); + $configList = \json_decode($configJson, true, 512, JSON_THROW_ON_ERROR); foreach ($this->createdApps as $app => $paths) { //disable the app $this->featureContext->appHasBeenDisabled($app, 'disables'); diff --git a/tests/acceptance/features/bootstrap/AuthContext.php b/tests/acceptance/features/bootstrap/AuthContext.php index 0f58b5043586..4633a9e1dc79 100644 --- a/tests/acceptance/features/bootstrap/AuthContext.php +++ b/tests/acceptance/features/bootstrap/AuthContext.php @@ -662,7 +662,7 @@ public function userGeneratesNewAppPasswordNamed(string $name):void { $this->featureContext->getCookieJar() ) ); - $token = \json_decode($this->featureContext->getResponse()->getBody()->getContents()); + $token = \json_decode($this->featureContext->getResponse()->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR); $this->appToken = $token->token; $this->appTokens[$token->deviceToken->name] = ["id" => $token->deviceToken->id, "token" => $token->token]; @@ -735,7 +735,8 @@ public function aNewClientTokenHasBeenGenerated(string $user):void { [ 'user' => $this->featureContext->getActualUsername($user), 'password' => $this->featureContext->getPasswordForUser($user), - ] + ], + JSON_THROW_ON_ERROR ); $headers = ['Content-Type' => 'application/json']; $url = $this->featureContext->getBaseUrl() . '/token/generate'; @@ -751,7 +752,7 @@ public function aNewClientTokenHasBeenGenerated(string $user):void { ); $this->featureContext->theHTTPStatusCodeShouldBe("200"); $this->clientToken - = \json_decode($this->featureContext->getResponse()->getBody()->getContents())->token; + = \json_decode($this->featureContext->getResponse()->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR)->token; } /** diff --git a/tests/acceptance/features/bootstrap/CorsContext.php b/tests/acceptance/features/bootstrap/CorsContext.php index 0f394744f623..06bd89ab4a72 100644 --- a/tests/acceptance/features/bootstrap/CorsContext.php +++ b/tests/acceptance/features/bootstrap/CorsContext.php @@ -55,7 +55,7 @@ public function addDomainToPrivateCORSLists(string $user, string $domain):void { ); if ($occStatus === 0) { $domainsJson = $this->featureContext->getStdOutOfOccCommand(); - $domains = \json_decode($domainsJson); + $domains = \json_decode($domainsJson, null, 512, JSON_THROW_ON_ERROR); } else { $domainsJson = ""; $domains = []; @@ -67,7 +67,7 @@ public function addDomainToPrivateCORSLists(string $user, string $domain):void { } $domains[] = $domain; - $valueString = \json_encode($domains); + $valueString = \json_encode($domains, JSON_THROW_ON_ERROR); $occStatus = $this->featureContext->runOcc( [ 'user:setting', @@ -92,7 +92,7 @@ public function addDomainToPrivateCORSLists(string $user, string $domain):void { 'domains' ] ); - $domains = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $domains = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); Assert::assertIsArray( $domains, diff --git a/tests/acceptance/features/bootstrap/FeatureContext.php b/tests/acceptance/features/bootstrap/FeatureContext.php index f43dfc75176d..f219ab514908 100644 --- a/tests/acceptance/features/bootstrap/FeatureContext.php +++ b/tests/acceptance/features/bootstrap/FeatureContext.php @@ -486,7 +486,9 @@ public function usersToBeReplaced():?array { if (($this->userReplacements === null) && $this->isTestingReplacingUsernames()) { $this->userReplacements = \json_decode( \file_get_contents("./tests/acceptance/usernames.json"), - true + true, + 512, + JSON_THROW_ON_ERROR ); // Loop through the user replacements, and make entries for the lower // and upper case forms. This allows for steps that specifically @@ -570,61 +572,61 @@ public function __construct( } // get the admin username from the environment (if defined) - $adminUsernameFromEnvironment = $this->getAdminUsernameFromEnvironment(); + $adminUsernameFromEnvironment = self::getAdminUsernameFromEnvironment(); if ($adminUsernameFromEnvironment !== false) { $this->adminUsername = $adminUsernameFromEnvironment; } // get the admin password from the environment (if defined) - $adminPasswordFromEnvironment = $this->getAdminPasswordFromEnvironment(); + $adminPasswordFromEnvironment = self::getAdminPasswordFromEnvironment(); if ($adminPasswordFromEnvironment !== false) { $this->adminPassword = $adminPasswordFromEnvironment; } // get the regular user password from the environment (if defined) - $regularUserPasswordFromEnvironment = $this->getRegularUserPasswordFromEnvironment(); + $regularUserPasswordFromEnvironment = self::getRegularUserPasswordFromEnvironment(); if ($regularUserPasswordFromEnvironment !== false) { $this->regularUserPassword = $regularUserPasswordFromEnvironment; } // get the alternate(1) user password from the environment (if defined) - $alt1UserPasswordFromEnvironment = $this->getAlt1UserPasswordFromEnvironment(); + $alt1UserPasswordFromEnvironment = self::getAlt1UserPasswordFromEnvironment(); if ($alt1UserPasswordFromEnvironment !== false) { $this->alt1UserPassword = $alt1UserPasswordFromEnvironment; } // get the alternate(2) user password from the environment (if defined) - $alt2UserPasswordFromEnvironment = $this->getAlt2UserPasswordFromEnvironment(); + $alt2UserPasswordFromEnvironment = self::getAlt2UserPasswordFromEnvironment(); if ($alt2UserPasswordFromEnvironment !== false) { $this->alt2UserPassword = $alt2UserPasswordFromEnvironment; } // get the alternate(3) user password from the environment (if defined) - $alt3UserPasswordFromEnvironment = $this->getAlt3UserPasswordFromEnvironment(); + $alt3UserPasswordFromEnvironment = self::getAlt3UserPasswordFromEnvironment(); if ($alt3UserPasswordFromEnvironment !== false) { $this->alt3UserPassword = $alt3UserPasswordFromEnvironment; } // get the alternate(4) user password from the environment (if defined) - $alt4UserPasswordFromEnvironment = $this->getAlt4UserPasswordFromEnvironment(); + $alt4UserPasswordFromEnvironment = self::getAlt4UserPasswordFromEnvironment(); if ($alt4UserPasswordFromEnvironment !== false) { $this->alt4UserPassword = $alt4UserPasswordFromEnvironment; } // get the sub-admin password from the environment (if defined) - $subAdminPasswordFromEnvironment = $this->getSubAdminPasswordFromEnvironment(); + $subAdminPasswordFromEnvironment = self::getSubAdminPasswordFromEnvironment(); if ($subAdminPasswordFromEnvironment !== false) { $this->subAdminPassword = $subAdminPasswordFromEnvironment; } // get the alternate admin password from the environment (if defined) - $alternateAdminPasswordFromEnvironment = $this->getAlternateAdminPasswordFromEnvironment(); + $alternateAdminPasswordFromEnvironment = self::getAlternateAdminPasswordFromEnvironment(); if ($alternateAdminPasswordFromEnvironment !== false) { $this->alternateAdminPassword = $alternateAdminPasswordFromEnvironment; } // get the public link share password from the environment (if defined) - $publicLinkSharePasswordFromEnvironment = $this->getPublicLinkSharePasswordFromEnvironment(); + $publicLinkSharePasswordFromEnvironment = self::getPublicLinkSharePasswordFromEnvironment(); if ($publicLinkSharePasswordFromEnvironment !== false) { $this->publicLinkSharePassword = $publicLinkSharePasswordFromEnvironment; } @@ -1300,9 +1302,7 @@ public function getXMLKey1Key2Key3AttributeValue( */ public function simplifyArray(array $arrayOfArrays):array { $a = \array_map( - function ($subArray) { - return $subArray[0]; - }, + fn ($subArray) => $subArray[0], $arrayOfArrays ); return $a; @@ -1486,7 +1486,7 @@ private function getJSONSchema(PyStringNode $schemaString) { $schemaRawString = $schemaString->getRaw(); // substitute the inline codes or values $schemaRawString = $this->substituteInLineCodes($schemaRawString); - $schema = json_decode($schemaRawString); + $schema = json_decode($schemaRawString, null, 512, JSON_THROW_ON_ERROR); Assert::assertNotNull($schema, 'schema is not valid JSON'); return $schema; } @@ -1499,10 +1499,10 @@ private function getJSONSchema(PyStringNode $schemaString) { * @return object */ public function getJsonDecodedResponseBodyContent(ResponseInterface $response = null):?object { - $response = $response ?? $this->response; + $response ??= $this->response; if ($response !== null) { $response->getBody()->rewind(); - return json_decode($response->getBody()->getContents()); + return json_decode($response->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR); } return null; } @@ -2553,8 +2553,8 @@ public function getStatusPhp():ResponseInterface { * @return void */ public function jsonRespondedShouldMatch(PyStringNode $jsonExpected):void { - $jsonExpectedEncoded = \json_encode($jsonExpected->getRaw()); - $jsonRespondedEncoded = \json_encode((string) $this->response->getBody()); + $jsonExpectedEncoded = \json_encode($jsonExpected->getRaw(), JSON_THROW_ON_ERROR); + $jsonRespondedEncoded = \json_encode((string) $this->response->getBody(), JSON_THROW_ON_ERROR); Assert::assertEquals( $jsonExpectedEncoded, $jsonRespondedEncoded, @@ -2571,7 +2571,7 @@ public function jsonRespondedShouldMatch(PyStringNode $jsonExpected):void { * @throws Exception */ public function statusPhpRespondedShouldMatch(PyStringNode $jsonExpected):void { - $jsonExpectedDecoded = \json_decode($jsonExpected->getRaw(), true); + $jsonExpectedDecoded = \json_decode($jsonExpected->getRaw(), true, 512, JSON_THROW_ON_ERROR); $jsonRespondedDecoded = $this->getJsonDecodedResponse(); $this->appConfigurationContext->theAdministratorGetsCapabilitiesCheckResponse(); @@ -2836,7 +2836,9 @@ public function getJsonDecodedResponse(?ResponseInterface $response = null):arra } return \json_decode( (string) $response->getBody(), - true + true, + 512, + JSON_THROW_ON_ERROR ); } @@ -2855,10 +2857,7 @@ public function getJsonDecodedStatusPhp():array { */ public function getEditionFromStatus():string { $decodedResponse = $this->getJsonDecodedStatusPhp(); - if (isset($decodedResponse['edition'])) { - return $decodedResponse['edition']; - } - return ''; + return $decodedResponse['edition'] ?? ''; } /** @@ -2866,10 +2865,7 @@ public function getEditionFromStatus():string { */ public function getProductNameFromStatus():?string { $decodedResponse = $this->getJsonDecodedStatusPhp(); - if (isset($decodedResponse['productname'])) { - return $decodedResponse['productname']; - } - return ''; + return $decodedResponse['productname'] ?? ''; } /** @@ -2877,10 +2873,7 @@ public function getProductNameFromStatus():?string { */ public function getVersionFromStatus():?string { $decodedResponse = $this->getJsonDecodedStatusPhp(); - if (isset($decodedResponse['version'])) { - return $decodedResponse['version']; - } - return ''; + return $decodedResponse['version'] ?? ''; } /** @@ -2888,10 +2881,7 @@ public function getVersionFromStatus():?string { */ public function getVersionStringFromStatus():?string { $decodedResponse = $this->getJsonDecodedStatusPhp(); - if (isset($decodedResponse['versionstring'])) { - return $decodedResponse['versionstring']; - } - return ''; + return $decodedResponse['versionstring'] ?? ''; } /** @@ -3129,7 +3119,7 @@ public function substituteInLineCodes( } foreach ($substitutions as $substitution) { - if (strpos($value, $substitution['code']) === false) { + if (strpos($value, (string) $substitution['code']) === false) { continue; } @@ -3186,7 +3176,7 @@ public function temporaryStorageSubfolderName():string { * @return string */ public function acceptanceTestsDirLocation():string { - return \dirname(__FILE__) . "/../../"; + return __DIR__ . "/../../"; } /** @@ -3251,7 +3241,7 @@ public function theConfigKeyOfAppShouldHaveValue(string $key, string $appID, str * @return array */ public function parseConfigListFromResponseXml(SimpleXMLElement $responseXml):array { - $configkeyData = \json_decode(\json_encode($responseXml->data), true); + $configkeyData = \json_decode(\json_encode($responseXml->data, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); if (isset($configkeyData['element'])) { $configkeyData = $configkeyData['element']; } else { @@ -3380,8 +3370,8 @@ public function followingConfigKeysShouldExist(string $shouldOrNot, TableNode $t */ public function sendUserSyncRequest(string $user, ?string $asUser = null, ?string $password = null):void { $user = $this->getActualUsername($user); - $asUser = $asUser ?? $this->getAdminUsername(); - $password = $password ?? $this->getPasswordForUser($asUser); + $asUser ??= $this->getAdminUsername(); + $password ??= $this->getPasswordForUser($asUser); $response = OcsApiHelper::sendRequest( $this->getBaseUrl(), $asUser, @@ -3705,9 +3695,9 @@ public static function useBigFileIDs(BeforeSuiteScope $scope):void { $adminUsername = null; $adminPassword = null; foreach ($suiteSettingsContexts as $context) { - if (isset($context[__CLASS__])) { - $adminUsername = $context[__CLASS__]['adminUsername']; - $adminPassword = $context[__CLASS__]['adminPassword']; + if (isset($context[self::class])) { + $adminUsername = $context[self::class]['adminUsername']; + $adminPassword = $context[self::class]['adminPassword']; break; } } @@ -4055,9 +4045,7 @@ public function findLastTransferFolderForUser(string $sourceUser, string $target \usort( $foundPaths, - function ($a, $b) { - return $a['date'] - $b['date']; - } + fn ($a, $b) => $a['date'] - $b['date'] ); $davPath = \rtrim($this->getFullDavFilesPath($targetUser), '/'); @@ -4136,9 +4124,12 @@ public function getTrustedServers(string $server = 'LOCAL'):array { ); $serverData = \json_decode( \json_encode( - $responseXml->data + $responseXml->data, + JSON_THROW_ON_ERROR ), - true + true, + 512, + JSON_THROW_ON_ERROR ); if (!\array_key_exists('element', $serverData)) { return []; @@ -4196,7 +4187,7 @@ public function prepareParametersBeforeScenario():void { $this->getBaseUrl(), $this->getOcPath() ); - $this->savedConfigList[$server] = \json_decode($result['stdOut'], true); + $this->savedConfigList[$server] = \json_decode($result['stdOut'], true, 512, JSON_THROW_ON_ERROR); } } $this->usingServer($previousServer); @@ -4241,7 +4232,7 @@ private function restoreParameters(string $server):void { $this->getBaseUrl(), $this->getOcPath() ); - $currentConfigList = \json_decode($result['stdOut'], true); + $currentConfigList = \json_decode($result['stdOut'], true, 512, JSON_THROW_ON_ERROR); foreach ($currentConfigList['system'] as $configKey => $configValue) { if (!\array_key_exists( $configKey, @@ -4255,7 +4246,7 @@ private function restoreParameters(string $server):void { if (!\array_key_exists($configKey, $currentConfigList["system"]) || $currentConfigList["system"][$configKey] !== $this->savedConfigList[$server]['system'][$configKey] ) { - \array_push($commands, ["command" => ['config:system:set', "--type=json", "--value=" . \json_encode($configValue), $configKey]]); + \array_push($commands, ["command" => ['config:system:set', "--type=json", "--value=" . \json_encode($configValue, JSON_THROW_ON_ERROR), $configKey]]); } } foreach ($currentConfigList['apps'] as $appName => $appSettings) { diff --git a/tests/acceptance/features/bootstrap/LoggingContext.php b/tests/acceptance/features/bootstrap/LoggingContext.php index 994403efa69c..869feeaad552 100644 --- a/tests/acceptance/features/bootstrap/LoggingContext.php +++ b/tests/acceptance/features/bootstrap/LoggingContext.php @@ -77,7 +77,7 @@ public function theLastLinesOfTheLogFileShouldContainEntriesWithTheseAttributes( ); $lineNo = 0; foreach ($expectedLogEntries as $expectedLogEntry) { - $logEntry = \json_decode($logLines[$lineNo], true); + $logEntry = \json_decode($logLines[$lineNo], true, 512, JSON_THROW_ON_ERROR); if ($logEntry === null) { throw new Exception("the log line :\n$logLines[$lineNo] is not valid JSON"); } @@ -282,7 +282,7 @@ private function assertLogFileContainsAtLeastOneEntryMatchingTable( ); $expectedLogEntries = $expectedLogEntries->getHash(); foreach ($logLines as $logLine) { - $logEntry = \json_decode($logLine, true); + $logEntry = \json_decode($logLine, true, 512, JSON_THROW_ON_ERROR); if ($logEntry === null) { throw new Exception("the log line :\n$logLine is not valid JSON"); } @@ -384,7 +384,7 @@ public function theLogFileShouldNotContainAnyLogEntriesWithTheseAttributes( $this->featureContext->getStepLineRef() ); foreach ($logLines as $logLine) { - $logEntry = \json_decode($logLine, true); + $logEntry = \json_decode($logLine, true, 512, JSON_THROW_ON_ERROR); if ($logEntry === null) { throw new Exception("the log line :\n$logLine is not valid JSON"); } @@ -400,7 +400,7 @@ public function theLogFileShouldNotContainAnyLogEntriesWithTheseAttributes( if ($withOrContaining === 'with') { $match = ($logEntryExpectedNotToExist[$attribute] === $logEntry[$attribute]); } else { - $match = (\strpos($logEntry[$attribute], $logEntryExpectedNotToExist[$attribute]) !== false); + $match = (\strpos($logEntry[$attribute], (string) $logEntryExpectedNotToExist[$attribute]) !== false); } } if (!isset($logEntry[$attribute])) { diff --git a/tests/acceptance/features/bootstrap/NotificationsCoreContext.php b/tests/acceptance/features/bootstrap/NotificationsCoreContext.php index 9d8d9c1d653a..89247b93cb27 100644 --- a/tests/acceptance/features/bootstrap/NotificationsCoreContext.php +++ b/tests/acceptance/features/bootstrap/NotificationsCoreContext.php @@ -237,7 +237,9 @@ public function matchNotification( ); $response = \json_decode( $this->featureContext->getResponse()->getBody()->getContents(), - true + true, + 512, + JSON_THROW_ON_ERROR ); $this->featureContext->verifyTableNodeColumns($formData, ['key', 'regex']); @@ -276,7 +278,7 @@ public function matchNotification( * @return array */ public function getArrayOfNotificationsResponded(ResponseInterface $resp):array { - $jsonResponse = \json_decode($resp->getBody()->getContents(), true); + $jsonResponse = \json_decode($resp->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR); return $jsonResponse['ocs']['data']; } diff --git a/tests/acceptance/features/bootstrap/OCSContext.php b/tests/acceptance/features/bootstrap/OCSContext.php index 050b00114b94..c6b02aa2b6bc 100644 --- a/tests/acceptance/features/bootstrap/OCSContext.php +++ b/tests/acceptance/features/bootstrap/OCSContext.php @@ -964,7 +964,9 @@ public function getActualStatusMessage(string $statusMessage, ?string $language if ($language !== null) { $multiLingualMessage = \json_decode( \file_get_contents(__DIR__ . "/../../fixtures/multiLanguageErrors.json"), - true + true, + 512, + JSON_THROW_ON_ERROR ); if (isset($multiLingualMessage[$statusMessage][$language])) { diff --git a/tests/acceptance/features/bootstrap/OccAppManagementContext.php b/tests/acceptance/features/bootstrap/OccAppManagementContext.php index 7258482cb0a9..ff0ca969eb56 100644 --- a/tests/acceptance/features/bootstrap/OccAppManagementContext.php +++ b/tests/acceptance/features/bootstrap/OccAppManagementContext.php @@ -111,7 +111,7 @@ public function theAdministratorChecksTheLocationOfTheAppUsingTheOccCommand(stri */ public function theAppNameReturnedByTheOccCommandShouldBe(string $appName):void { $lastOutput = $this->featureContext->getStdOutOfOccCommand(); - $lastOutputArray = \json_decode($lastOutput, true); + $lastOutputArray = \json_decode($lastOutput, true, 512, JSON_THROW_ON_ERROR); Assert::assertEquals( $appName, \key($lastOutputArray['apps']), @@ -133,7 +133,7 @@ public function thePathReturnedByTheOccCommandShouldBeInsideOneOfTheAppsPathInTh $this->occContext->invokingTheCommand("config:list"); $lastOutput = $this->featureContext->getStdOutOfOccCommand(); - $configOutputArray = \json_decode($lastOutput, true); + $configOutputArray = \json_decode($lastOutput, true, 512, JSON_THROW_ON_ERROR); // Default apps location is '${INSTALLED_LOCATION}/apps/${appName} if (\substr_compare($appPath, "/apps/$appName", 0)) { @@ -165,7 +165,7 @@ public function thePathReturnedByTheOccCommandShouldBeInsideOneOfTheAppsPathInTh */ public function theAppEnabledStatusShouldBe(string $appName, string $appStatus):void { $lastOutput = $this->featureContext->getStdOutOfOccCommand(); - $lastOutputArray = \json_decode($lastOutput, true); + $lastOutputArray = \json_decode($lastOutput, true, 512, JSON_THROW_ON_ERROR); $actualAppEnabledStatus = $lastOutputArray['apps'][$appName]['enabled']; Assert::assertEquals( $appStatus, @@ -185,7 +185,7 @@ public function theAppEnabledStatusShouldBe(string $appName, string $appStatus): public function theAppsReturnedByTheOccCommandShouldInclude(TableNode $appListTable):void { $this->featureContext->verifyTableNodeColumnsCount($appListTable, 1); $lastOutput = $this->featureContext->getStdOutOfOccCommand(); - $lastOutputApps = \array_keys(\json_decode($lastOutput, true)['apps']); + $lastOutputApps = \array_keys(\json_decode($lastOutput, true, 512, JSON_THROW_ON_ERROR)['apps']); $apps = $appListTable->getRows(); $appsSimplified = $this->featureContext->simplifyArray($apps); diff --git a/tests/acceptance/features/bootstrap/OccContext.php b/tests/acceptance/features/bootstrap/OccContext.php index 4b486834a7fe..f001e044396c 100644 --- a/tests/acceptance/features/bootstrap/OccContext.php +++ b/tests/acceptance/features/bootstrap/OccContext.php @@ -1524,7 +1524,7 @@ public function getListOfApplicableUserOrGroupForMount(string $mount, string $us '--output=json' ] ); - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); return ($userOrGroup === "users") ? $commandOutput->users : $commandOutput->groups; } @@ -1908,7 +1908,7 @@ public function adminListsLocalStorageShowPasswordUsingTheOccCommand():void { public function theFollowingLocalStoragesShouldExist(TableNode $mountPoints):void { $createdLocalStorage = []; $expectedLocalStorages = $mountPoints->getColumnsHash(); - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); foreach ($commandOutput as $storageEntry) { $createdLocalStorage[$storageEntry->mount_id] = \ltrim($storageEntry->mount_point, '/'); } @@ -1936,7 +1936,7 @@ public function theFollowingLocalStoragesShouldNotExist(TableNode $mountPoints): $createdLocalStorage = []; $this->listLocalStorageMount(); $expectedLocalStorages = $mountPoints->getColumnsHash(); - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); foreach ($commandOutput as $i) { $createdLocalStorage[$i->mount_id] = \ltrim($i->mount_point, '/'); } @@ -1969,7 +1969,7 @@ public function theFollowingBackendTypesShouldBeListed(TableNode $table):void { . "' do not have key 'backend-type'" ); } - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); $keys = \array_keys((array) $commandOutput); foreach ($expectedBackendTypes as $backendTypesEntry) { Assert::assertContains( @@ -2003,7 +2003,7 @@ public function theFollowingBackendsShouldBeListed(TableNode $table):void { . "' do not have key 'backends'" ); } - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); $keys = \array_keys((array) $commandOutput); foreach ($expectedBackends as $backendsEntry) { Assert::assertContains( @@ -2037,7 +2037,7 @@ public function theFollowingBackendKeysOfTypeShouldBeListed(TableNode $table):vo . "' do not have key 'backend-keys'" ); } - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); $keys = \array_keys((array) $commandOutput); foreach ($expectedBackendKeys as $backendKeysEntry) { Assert::assertContains( @@ -2066,7 +2066,7 @@ public function theFollowingLocalStorageShouldBeListed(TableNode $table):void { ['Storage', 'AuthenticationType', 'Configuration', 'Options', 'Auth', 'Type'] ); $expectedLocalStorages = $table->getColumnsHash(); - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); foreach ($expectedLocalStorages as $expectedStorageEntry) { $isStorageEntryListed = false; foreach ($commandOutput as $listedStorageEntry) { @@ -2246,7 +2246,7 @@ public function theFollowingShouldBeIncludedInTheConfigurationOfLocalStorage(str . "' do not have key 'configuration'" ); } - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); $isStorageEntryListed = false; foreach ($commandOutput as $listedStorageEntry) { if ($listedStorageEntry->mount_point === $localStorage) { @@ -2315,7 +2315,7 @@ public function theFollowingShouldBeIncludedInTheOptionsOfLocalStorage(string $l . "' do not have key 'option'" ); } - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); $isStorageEntryListed = false; foreach ($commandOutput as $listedStorageEntry) { if ($listedStorageEntry->mount_point === $localStorage) { @@ -2361,7 +2361,7 @@ public function theFollowingShouldNotBeIncludedInTheOptionsOfLocalStorage(string . "' do not have key 'options'" ); } - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); $isStorageEntryListed = false; foreach ($commandOutput as $listedStorageEntry) { if ($listedStorageEntry->mount_point === $localStorage) { @@ -2422,7 +2422,7 @@ public function getMountIdForLocalStorage(string $folder): ?int { $createdLocalStorage = []; $mount_id = null; $this->listLocalStorageMount(); - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); foreach ($commandOutput as $i) { $createdLocalStorage[$i->mount_id] = \ltrim($i->mount_point, '/'); } @@ -2501,7 +2501,7 @@ public function theAdministratorHasExportedTheMountsUsingTheOccCommand():void { public function theOutputShouldContainConfigurationForMount(string $mount):void { $actualConfig = null; - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); foreach ($commandOutput as $i) { if ($mount === \ltrim($i->mount_point, '/')) { $actualConfig = $i; @@ -2522,7 +2522,7 @@ public function theOutputShouldContainConfigurationForMount(string $mount):void */ public function theAdministratorVerifiesTheMountConfigurationForLocalStorageUsingTheOccCommand(string $localStorage):void { $this->listLocalStorageMount(); - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); foreach ($commandOutput as $entry) { if (\ltrim($entry->mount_point, '/') == $localStorage) { $mountId = $entry->mount_id; @@ -3034,7 +3034,7 @@ public function theAdministratorListsTheConfigKeys():void { * @return void */ public function theCommandOutputShouldContainTheAppsConfigs():void { - $config_list = \json_decode($this->featureContext->getStdOutOfOccCommand(), true); + $config_list = \json_decode($this->featureContext->getStdOutOfOccCommand(), true, 512, JSON_THROW_ON_ERROR); Assert::assertArrayHasKey( 'apps', $config_list, @@ -3052,7 +3052,7 @@ public function theCommandOutputShouldContainTheAppsConfigs():void { * @return void */ public function theCommandOutputShouldContainTheSystemConfigs():void { - $config_list = \json_decode($this->featureContext->getStdOutOfOccCommand(), true); + $config_list = \json_decode($this->featureContext->getStdOutOfOccCommand(), true, 512, JSON_THROW_ON_ERROR); Assert::assertArrayHasKey( 'system', $config_list, @@ -3139,7 +3139,9 @@ public function theSystemConfigKeyFromLastCommandOutputShouldContainValue( ):void { $configList = \json_decode( $this->featureContext->getStdOutOfOccCommand(), - true + true, + 512, + JSON_THROW_ON_ERROR ); $systemConfig = $configList['system']; @@ -3472,7 +3474,7 @@ public function adminDeletesExternalMountPoint(string $mountPoint):void { * @return void */ public function mountPointShouldNotBeListedAsAnExternalStorage(string $mountPoint):void { - $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand()); + $commandOutput = \json_decode($this->featureContext->getStdOutOfOccCommand(), null, 512, JSON_THROW_ON_ERROR); foreach ($commandOutput as $entry) { Assert::assertNotEquals($mountPoint, $entry->mount_point); } diff --git a/tests/acceptance/features/bootstrap/OccUsersGroupsContext.php b/tests/acceptance/features/bootstrap/OccUsersGroupsContext.php index b08ec9339725..2525144716f7 100644 --- a/tests/acceptance/features/bootstrap/OccUsersGroupsContext.php +++ b/tests/acceptance/features/bootstrap/OccUsersGroupsContext.php @@ -587,7 +587,7 @@ public function theLanguageOfUserReturnedByTheOccCommandShouldBe(string $usernam public function theUsersReturnedByTheOccCommandShouldBe(TableNode $useridTable):void { $this->featureContext->verifyTableNodeColumns($useridTable, ['uid']); $lastOutput = $this->featureContext->getStdOutOfOccCommand(); - $lastOutputUsers = \json_decode($lastOutput, true); + $lastOutputUsers = \json_decode($lastOutput, true, 512, JSON_THROW_ON_ERROR); $result = []; // check if an array is a multi-dimensional array with inner array key 'displayName' if (\array_column($lastOutputUsers, 'displayName')) { @@ -626,7 +626,7 @@ public function theUsersReturnedByTheOccCommandShouldBe(TableNode $useridTable): public function theInactiveUsersReturnedByTheOccCommandShouldBe(TableNode $userTable):void { $this->featureContext->verifyTableNodeColumns($userTable, ['uid', 'display name', 'inactive days']); $lastOutput = $this->featureContext->getStdOutOfOccCommand(); - $lastOutputUsers = \json_decode($lastOutput, true); + $lastOutputUsers = \json_decode($lastOutput, true, 512, JSON_THROW_ON_ERROR); Assert::assertEquals( \count($userTable->getColumnsHash()), @@ -675,7 +675,7 @@ public function theInactiveUsersReturnedByTheOccCommandShouldBe(TableNode $userT public function theGroupsReturnedByTheOccCommandShouldBe(TableNode $groupTableNode):void { $this->featureContext->verifyTableNodeColumns($groupTableNode, ['group']); $lastOutput = $this->featureContext->getStdOutOfOccCommand(); - $lastOutputGroups = \json_decode($lastOutput, true); + $lastOutputGroups = \json_decode($lastOutput, true, 512, JSON_THROW_ON_ERROR); foreach ($groupTableNode as $row) { Assert::assertContains( @@ -718,7 +718,7 @@ public function theDisplayNameReturnedByTheOccCommandShouldBe(string $place, str $index = 0; } $lastOutput = $this->featureContext->getStdOutOfOccCommand(); - $lastOutputUser = \json_decode($lastOutput, true); + $lastOutputUser = \json_decode($lastOutput, true, 512, JSON_THROW_ON_ERROR); $lastOutputDisplayName = \array_column($lastOutputUser, 'displayName')[$index]; Assert::assertEquals( $displayName, diff --git a/tests/acceptance/features/bootstrap/Provisioning.php b/tests/acceptance/features/bootstrap/Provisioning.php index 511c5adaa63a..776ada9f5e65 100644 --- a/tests/acceptance/features/bootstrap/Provisioning.php +++ b/tests/acceptance/features/bootstrap/Provisioning.php @@ -593,7 +593,9 @@ public function connectToLdap(array $suiteParameters):void { $ldapConfig = \json_decode( $occResult['stdOut'], - true + true, + 512, + JSON_THROW_ON_ERROR ); Assert::assertNotNull( $ldapConfig, @@ -3513,7 +3515,7 @@ public function adminSendsGroupCreationRequestUsingTheProvisioningApi( ?string $user = null ):void { $bodyTable = new TableNode([['groupid', $group]]); - $user = $user === null ? $this->getAdminUsername() : $user; + $user ??= $this->getAdminUsername(); $this->emptyLastHTTPStatusCodesArray(); $this->emptyLastOCSStatusCodesArray(); $this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody( @@ -4441,9 +4443,7 @@ public function theUsersShouldBe(TableNode $usersList):void { $this->verifyTableNodeColumnsCount($usersList, 1); $users = $usersList->getRows(); $usersSimplified = \array_map( - function ($user) { - return $this->getActualUsername($user); - }, + fn ($user) => $this->getActualUsername($user), $this->simplifyArray($users) ); $respondedArray = $this->getArrayOfUsersResponded($this->response); @@ -4467,9 +4467,7 @@ public function theUsersShouldInclude(TableNode $usersList):void { $this->verifyTableNodeColumnsCount($usersList, 1); $users = $usersList->getRows(); $usersSimplified = \array_map( - function ($user) { - return $this->getActualUsername($user); - }, + fn ($user) => $this->getActualUsername($user), $this->simplifyArray($users) ); $respondedArray = $this->getArrayOfUsersResponded($this->response); @@ -4921,7 +4919,7 @@ public function theCreationTimeReturnedByTheApiShouldBe():void { public function getArrayOfUsersResponded(ResponseInterface $resp):array { $listCheckedElements = $this->getResponseXml($resp, __METHOD__)->data[0]->users[0]->element; - return \json_decode(\json_encode($listCheckedElements), true); + return \json_decode(\json_encode($listCheckedElements, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); } /** @@ -4935,7 +4933,7 @@ public function getArrayOfUsersResponded(ResponseInterface $resp):array { public function getArrayOfGroupsResponded(ResponseInterface $resp):array { $listCheckedElements = $this->getResponseXml($resp, __METHOD__)->data[0]->groups[0]->element; - return \json_decode(\json_encode($listCheckedElements), true); + return \json_decode(\json_encode($listCheckedElements, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); } /** @@ -4949,7 +4947,7 @@ public function getArrayOfGroupsResponded(ResponseInterface $resp):array { public function getArrayOfAppsResponded(ResponseInterface $resp):array { $listCheckedElements = $this->getResponseXml($resp, __METHOD__)->data[0]->apps[0]->element; - return \json_decode(\json_encode($listCheckedElements), true); + return \json_decode(\json_encode($listCheckedElements, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); } /** @@ -4963,7 +4961,7 @@ public function getArrayOfAppsResponded(ResponseInterface $resp):array { public function getArrayOfSubadminsResponded(ResponseInterface $resp):array { $listCheckedElements = $this->getResponseXml($resp, __METHOD__)->data[0]->element; - return \json_decode(\json_encode($listCheckedElements), true); + return \json_decode(\json_encode($listCheckedElements, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); } /** @@ -4977,7 +4975,7 @@ public function getArrayOfSubadminsResponded(ResponseInterface $resp):array { public function getArrayOfAppInfoResponded(ResponseInterface $resp):array { $listCheckedElements = $this->getResponseXml($resp, __METHOD__)->data[0]; - return \json_decode(\json_encode($listCheckedElements), true); + return \json_decode(\json_encode($listCheckedElements, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); } /** @@ -5404,7 +5402,7 @@ public function rememberAppEnabledDisabledState():void { $this->getOcPath() ); $this->runOcc(['app:list', '--output json']); - $apps = \json_decode($this->getStdOutOfOccCommand(), true); + $apps = \json_decode($this->getStdOutOfOccCommand(), true, 512, JSON_THROW_ON_ERROR); $this->enabledApps = \array_keys($apps["enabled"]); $this->disabledApps = \array_keys($apps["disabled"]); } @@ -5429,7 +5427,7 @@ public function restoreAppEnabledDisabledState():void { if (!$this->isRunningForDbConversion()) { $this->runOcc(['app:list', '--output json']); - $apps = \json_decode($this->getStdOutOfOccCommand(), true); + $apps = \json_decode($this->getStdOutOfOccCommand(), true, 512, JSON_THROW_ON_ERROR); $currentlyEnabledApps = \array_keys($apps["enabled"]); $currentlyDisabledApps = \array_keys($apps["disabled"]); diff --git a/tests/acceptance/features/bootstrap/PublicWebDavContext.php b/tests/acceptance/features/bootstrap/PublicWebDavContext.php index 37d02153d420..20ddf36c0680 100644 --- a/tests/acceptance/features/bootstrap/PublicWebDavContext.php +++ b/tests/acceptance/features/bootstrap/PublicWebDavContext.php @@ -1058,8 +1058,7 @@ public function shouldBeAbleToDownloadRangeOfFileInsidePublicSharedFolder( $range, $path, $publicWebDAVAPIVersion, - "", - $content + "" ); } diff --git a/tests/acceptance/features/bootstrap/ShareesContext.php b/tests/acceptance/features/bootstrap/ShareesContext.php index 2fc8cbf146af..2c1efb7a9106 100644 --- a/tests/acceptance/features/bootstrap/ShareesContext.php +++ b/tests/acceptance/features/bootstrap/ShareesContext.php @@ -164,7 +164,7 @@ public function getArrayOfShareesResponded( string $shareeType ):array { $elements = $this->featureContext->getResponseXml($response, __METHOD__)->data; - $elements = \json_decode(\json_encode($elements), true); + $elements = \json_decode(\json_encode($elements, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR); if (\strpos($shareeType, 'exact ') === 0) { $elements = $elements['exact']; $shareeType = \substr($shareeType, 6); diff --git a/tests/acceptance/features/bootstrap/Sharing.php b/tests/acceptance/features/bootstrap/Sharing.php index f1bd50755761..59b46bcab074 100644 --- a/tests/acceptance/features/bootstrap/Sharing.php +++ b/tests/acceptance/features/bootstrap/Sharing.php @@ -174,15 +174,12 @@ private function splitPermissionsString(string $str):array { if (\in_array('uploadwriteonly', $permissions, true)) { // remove 'uploadwriteonly' from $permissions $permissions = \array_diff($permissions, ['uploadwriteonly']); - $permissions = \array_merge($permissions, ['create']); + $permissions = [...$permissions, 'create']; } if (\in_array('change', $permissions, true)) { // remove 'change' from $permissions $permissions = \array_diff($permissions, ['change']); - $permissions = \array_merge( - $permissions, - ['create', 'delete', 'read', 'update'] - ); + $permissions = [...$permissions, 'create', 'delete', 'read', 'update']; } return \array_unique($permissions); @@ -1109,7 +1106,7 @@ public function isFieldInResponse(string $field, ?string $contentExpected, bool $dateFieldsArrayToConvert = ['expiration', 'original_date', 'new_date']; //do not try to convert empty date - if ((string) \in_array($field, \array_merge($dateFieldsArrayToConvert)) && !empty($contentExpected)) { + if ((string) \in_array($field, [...$dateFieldsArrayToConvert]) && !empty($contentExpected)) { $timestamp = \strtotime($contentExpected, $this->getServerShareTimeFromLastResponse()); // strtotime returns false if it failed to parse, just leave it as it is in that condition if ($timestamp !== false) { @@ -2792,7 +2789,7 @@ public function removeAllSharesFromResource(string $user, string $fileName):void $this->setResponse($res); $this->theHTTPStatusCodeShouldBeSuccess(); - $json = \json_decode($res->getBody()->getContents(), true); + $json = \json_decode($res->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR); $deleted = false; foreach ($json['ocs']['data'] as $data) { if (\stripslashes($data['path']) === $fileName) { @@ -3364,7 +3361,7 @@ public function administratorAddsGroupToExcludeFromReceivingSharesList(string $g $occStdOut = "[]"; } - $currentGroups = \json_decode($occStdOut, true); + $currentGroups = \json_decode($occStdOut, true, 512, JSON_THROW_ON_ERROR); Assert::assertNotNull( $currentGroups, "could not json decode app setting 'blacklisted_receiver_groups' of 'files_sharing'\n" . @@ -3377,7 +3374,7 @@ public function administratorAddsGroupToExcludeFromReceivingSharesList(string $g [ 'config:app:set', 'files_sharing blacklisted_receiver_groups', - '--value=' . \json_encode($currentGroups) + '--value=' . \json_encode($currentGroups, JSON_THROW_ON_ERROR) ] ); } @@ -3465,7 +3462,7 @@ private function getAllSharesSharedWithUser(string $user, ?string $state = "all" ); } $result = $this->response->getBody()->getContents(); - $usersShares = \json_decode($result, true); + $usersShares = \json_decode($result, true, 512, JSON_THROW_ON_ERROR); if (!\is_array($usersShares)) { throw new Exception( __METHOD__ . " API result about shares is not valid JSON" @@ -3592,7 +3589,7 @@ public function saveLastSharedPublicLinkShare( public function userHasAddedPublicShareCreatedByUser(string $user, string $shareServer):void { $this->saveLastSharedPublicLinkShare($user, $shareServer); - $resBody = json_decode($this->response->getBody()->getContents()); + $resBody = json_decode($this->response->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR); $status = ''; $message = ''; if ($resBody) { diff --git a/tests/acceptance/features/bootstrap/TUSContext.php b/tests/acceptance/features/bootstrap/TUSContext.php index ed53c0e4572f..3684e1934e8b 100644 --- a/tests/acceptance/features/bootstrap/TUSContext.php +++ b/tests/acceptance/features/bootstrap/TUSContext.php @@ -193,7 +193,7 @@ public function userUploadsUsingTusAFileTo( ); $client->setMetadata($uploadMetadata); $sourceFile = $this->featureContext->acceptanceTestsDirLocation() . $source; - $client->setKey((string)rand())->file($sourceFile, $destination); + $client->setKey((string)random_int(0, mt_getrandmax()))->file($sourceFile, $destination); $this->featureContext->pauseUploadDelete(); if ($bytes !== null) { diff --git a/tests/acceptance/features/bootstrap/TagsContext.php b/tests/acceptance/features/bootstrap/TagsContext.php index 19c645969175..fdbb07c98449 100644 --- a/tests/acceptance/features/bootstrap/TagsContext.php +++ b/tests/acceptance/features/bootstrap/TagsContext.php @@ -580,11 +580,8 @@ public function requestTagByDisplayName( $tagData = $tagList->xpath( "//d:prop//oc:display-name[text() = '$tagDisplayName']/.." ); - if (isset($tagData[0])) { - return $tagData[0]; - } - return null; + return $tagData[0] ?? null; } /** diff --git a/tests/acceptance/features/bootstrap/TransferOwnershipContext.php b/tests/acceptance/features/bootstrap/TransferOwnershipContext.php index 8a8b466a6a76..5ac5872ece7f 100644 --- a/tests/acceptance/features/bootstrap/TransferOwnershipContext.php +++ b/tests/acceptance/features/bootstrap/TransferOwnershipContext.php @@ -32,7 +32,7 @@ class TransferOwnershipContext implements Context { private FeatureContext $featureContext; private OccContext $occContext; - private ?string $lastTransferPath; + private ?string $lastTransferPath = null; /** * @return string diff --git a/tests/acceptance/features/bootstrap/TrashbinContext.php b/tests/acceptance/features/bootstrap/TrashbinContext.php index 3c06eae5ff65..de656c0bcac1 100644 --- a/tests/acceptance/features/bootstrap/TrashbinContext.php +++ b/tests/acceptance/features/bootstrap/TrashbinContext.php @@ -124,7 +124,7 @@ static function (SimpleXMLElement $propStat) { 'href' => (string) $href, 'name' => isset($name[0]) ? (string) $name[0] : null, 'mtime' => isset($mtime[0]) ? (string) $mtime[0] : null, - 'collection' => isset($collection[0]) ? $collection[0] : false, + 'collection' => $collection[0] ?? false, 'original-location' => isset($originalLocation[0]) ? (string) $originalLocation[0] : null ]; }, @@ -173,9 +173,7 @@ public function listTopOfTrashbinFolder(?string $user, string $depth = "infinity // filter root element $files = \array_filter( $files, - static function ($element) use ($user) { - return ($element['href'] !== "/remote.php/dav/trash-bin/$user/"); - } + static fn ($element) => $element['href'] !== "/remote.php/dav/trash-bin/$user/" ); return $files; } @@ -279,9 +277,7 @@ static function ($element) use ($user, $collectionPath) { // filter the collection element. We only want the members. $nextFiles = \array_filter( $nextFiles, - static function ($element) use ($user, $trashbinRef) { - return ($element['href'] !== $trashbinRef); - } + static fn ($element) => $element['href'] !== $trashbinRef ); \array_push($files, ...$nextFiles); } @@ -369,8 +365,8 @@ public function theTrashbinDavResponseShouldContainTheseNodes(TableNode $table): * @throws Exception */ public function sendTrashbinListRequest(string $user, ?string $asUser = null, ?string $password = null):void { - $asUser = $asUser ?? $user; - $password = $password ?? $this->featureContext->getPasswordForUser($asUser); + $asUser ??= $user; + $password ??= $this->featureContext->getPasswordForUser($asUser); $davPathVersion = $this->featureContext->getDavPathVersion(); $response = WebDavHelper::propfind( $this->featureContext->getBaseUrl(), @@ -580,7 +576,7 @@ private function convertTrashbinHref(string $href):string { */ public function tryToDeleteFileFromTrashbin(?string $user, ?string $originalPath, ?string $asUser = null, ?string $password = null):int { $user = $this->featureContext->getActualUsername($user); - $asUser = $asUser ?? $user; + $asUser ??= $user; $listing = $this->listTrashbinFolder($user); $originalPath = \trim($originalPath, '/'); $numItemsDeleted = 0; @@ -750,7 +746,7 @@ private function isInTrash(?string $user, ?string $originalPath):bool { * @return ResponseInterface */ private function sendUndeleteRequest(string $user, string $trashItemHRef, string $destinationPath, ?string $asUser = null, ?string $password = null):ResponseInterface { - $asUser = $asUser ?? $user; + $asUser ??= $user; $destinationPath = \trim($destinationPath, '/'); $destinationValue = $this->featureContext->getBaseUrl() . "/remote.php/dav/files/$user/$destinationPath"; @@ -785,7 +781,7 @@ private function sendUndeleteRequest(string $user, string $trashItemHRef, string * @throws Exception */ private function restoreElement(string $user, string $originalPath, ?string $destinationPath = null, bool $throwExceptionIfNotFound = true, ?string $asUser = null, ?string $password = null):void { - $asUser = $asUser ?? $user; + $asUser ??= $user; $listing = $this->listTrashbinFolder($user); $originalPath = \trim($originalPath, '/'); if ($destinationPath === null) { @@ -824,7 +820,7 @@ private function restoreElement(string $user, string $originalPath, ?string $des * @throws Exception */ public function restoreFileWithoutDestination(string $user, string $originalPath):ResponseInterface { - $asUser = $asUser ?? $user; + $asUser ??= $user; $listing = $this->listTrashbinFolder($user); $originalPath = \trim($originalPath, '/'); diff --git a/tests/acceptance/features/bootstrap/WebDav.php b/tests/acceptance/features/bootstrap/WebDav.php index f2fa4da5da23..96c23f1a250c 100644 --- a/tests/acceptance/features/bootstrap/WebDav.php +++ b/tests/acceptance/features/bootstrap/WebDav.php @@ -1707,7 +1707,7 @@ public function jobStatusValuesShouldMatchRegEx(string $user, TableNode $table): $this->getPasswordForUser($user) ); $contents = $response->getBody()->getContents(); - $result = \json_decode($contents, true); + $result = \json_decode($contents, true, 512, JSON_THROW_ON_ERROR); PHPUnit\Framework\Assert::assertNotNull($result, "'$contents' is not valid JSON"); foreach ($table->getTable() as $row) { $expectedKey = $row[0]; @@ -5037,9 +5037,7 @@ public function theSearchResultOfUserShouldContainAnyOfTheseEntries( // into the step. findEntryFromPropfindResponse returns entries without // any leading (or trailing) slash $expectedEntries = \array_map( - function ($value) { - return \trim($value, "/"); - }, + fn ($value) => \trim($value, "/"), $elementRows ); $resultEntries = $this->findEntryFromPropfindResponse(null, $user, "REPORT"); diff --git a/tests/acceptance/features/bootstrap/WebDavLockingContext.php b/tests/acceptance/features/bootstrap/WebDavLockingContext.php index 22ccfa92804d..7f7730242a6f 100644 --- a/tests/acceptance/features/bootstrap/WebDavLockingContext.php +++ b/tests/acceptance/features/bootstrap/WebDavLockingContext.php @@ -649,7 +649,7 @@ public function groupShouldExistAsLockBreakerGroups(string $expectedGroup) { ); $responseXml = HttpRequestHelper::getResponseXml($response, __METHOD__)->data->element; - $lockbreakergroup = trim(\json_decode(\json_encode($responseXml), true)['value'], '\'[]"'); + $lockbreakergroup = trim(\json_decode(\json_encode($responseXml, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR)['value'], '\'[]"'); $actualgroup = explode("\",\"", $lockbreakergroup); if (!\in_array($expectedGroup, $actualgroup)) { Assert::fail("could not find group '$expectedGroup' in lock breakers group"); diff --git a/tests/acceptance/features/bootstrap/WebUIAdminStorageSettingsContext.php b/tests/acceptance/features/bootstrap/WebUIAdminStorageSettingsContext.php index 68553e55aa73..e86b832908d4 100644 --- a/tests/acceptance/features/bootstrap/WebUIAdminStorageSettingsContext.php +++ b/tests/acceptance/features/bootstrap/WebUIAdminStorageSettingsContext.php @@ -110,8 +110,7 @@ public function createLocalStorageMountUsingTheWebui(string $mount):void { $dirLocation ); $storageIds = $this->featureContext->getStorageIds(); - \end($storageIds); - $lastMountId = \key($storageIds); + $lastMountId = array_key_last($storageIds); $this->featureContext->addStorageId($mount, $lastMountId + 1); } diff --git a/tests/acceptance/features/bootstrap/WebUIPersonalSecuritySettingsContext.php b/tests/acceptance/features/bootstrap/WebUIPersonalSecuritySettingsContext.php index 6fb66e552d6d..b452e1a6eebd 100644 --- a/tests/acceptance/features/bootstrap/WebUIPersonalSecuritySettingsContext.php +++ b/tests/acceptance/features/bootstrap/WebUIPersonalSecuritySettingsContext.php @@ -34,7 +34,7 @@ */ class WebUIPersonalSecuritySettingsContext extends RawMinkContext implements Context { private PersonalSecuritySettingsPage $personalSecuritySettingsPage; - private $appName; + private string $appName; private string $strForAppName = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; private WebUILoginContext $webUILoginContext; private WebUIGeneralContext $webUIGeneralContext; diff --git a/tests/acceptance/features/bootstrap/bootstrap.php b/tests/acceptance/features/bootstrap/bootstrap.php index 338cb0d67587..897ddce3864f 100644 --- a/tests/acceptance/features/bootstrap/bootstrap.php +++ b/tests/acceptance/features/bootstrap/bootstrap.php @@ -38,7 +38,7 @@ const MINIMUM_UI_WAIT_TIMEOUT_MICROSEC = MINIMUM_UI_WAIT_TIMEOUT_MILLISEC * 1000; // Minimum mtime difference for new version to generate -const VERSION_MTIME_WAIT_TIMEOUT_MICROSEC = 1000000; +const VERSION_MTIME_WAIT_TIMEOUT_MICROSEC = 1_000_000; // Minimum timeout for emails const EMAIL_WAIT_TIMEOUT_SEC = 10; diff --git a/tests/acceptance/features/lib/AdminEncryptionSettingsPage.php b/tests/acceptance/features/lib/AdminEncryptionSettingsPage.php index 063790bd9642..65ca7d37f7bc 100644 --- a/tests/acceptance/features/lib/AdminEncryptionSettingsPage.php +++ b/tests/acceptance/features/lib/AdminEncryptionSettingsPage.php @@ -36,10 +36,10 @@ class AdminEncryptionSettingsPage extends OwncloudPage { */ protected $path = '/index.php/settings/admin?sectionid=encryption'; - private $encryptionRecoveryPasswordFieldId = 'encryptionRecoveryPassword'; - private $repeatEncryptionRecoveryPasswordFieldId = 'repeatEncryptionRecoveryPassword'; - private $enableRecoveryBtnId = 'enableRecoveryKey'; - private $enableEncryptionCheckboxId = 'enableEncryption'; + private string $encryptionRecoveryPasswordFieldId = 'encryptionRecoveryPassword'; + private string $repeatEncryptionRecoveryPasswordFieldId = 'repeatEncryptionRecoveryPassword'; + private string $enableRecoveryBtnId = 'enableRecoveryKey'; + private string $enableEncryptionCheckboxId = 'enableEncryption'; /** * Enable recovery key and set recovery key diff --git a/tests/acceptance/features/lib/FilesPage.php b/tests/acceptance/features/lib/FilesPage.php index 0e2e1c61664c..f7bdf8420e4b 100644 --- a/tests/acceptance/features/lib/FilesPage.php +++ b/tests/acceptance/features/lib/FilesPage.php @@ -353,7 +353,7 @@ public function open(array $urlParameters = []): Page { try { if (\strpos( $this->getDriver()->getCurrentUrl(), - $this->getUrl($urlParameters) + (string) $this->getUrl($urlParameters) ) === false ) { throw new UnexpectedPageException( diff --git a/tests/acceptance/features/lib/FilesPageElement/ConflictDialog.php b/tests/acceptance/features/lib/FilesPageElement/ConflictDialog.php index c794264d3bee..3864b65db006 100644 --- a/tests/acceptance/features/lib/FilesPageElement/ConflictDialog.php +++ b/tests/acceptance/features/lib/FilesPageElement/ConflictDialog.php @@ -31,8 +31,8 @@ * already exists. */ class ConflictDialog extends OCDialog { - private $keepNewFilesCheckXpath = "//label[@for='checkbox-allnewfiles']"; - private $keepExistingFilesCheckXpath = "//label[@for='checkbox-allexistingfiles']"; + private string $keepNewFilesCheckXpath = "//label[@for='checkbox-allnewfiles']"; + private string $keepExistingFilesCheckXpath = "//label[@for='checkbox-allexistingfiles']"; /** * takes the xpath and selects the option with that xpath diff --git a/tests/acceptance/features/lib/FilesPageElement/DetailsDialog.php b/tests/acceptance/features/lib/FilesPageElement/DetailsDialog.php index c09b04a166b7..a7614a243458 100644 --- a/tests/acceptance/features/lib/FilesPageElement/DetailsDialog.php +++ b/tests/acceptance/features/lib/FilesPageElement/DetailsDialog.php @@ -43,45 +43,45 @@ class DetailsDialog extends OwncloudPage { * @var string $path */ protected $path = '/index.php/apps/files/'; - private $detailsDialogCloseXpath = "//*[@class='close icon-close']"; - private $thumbnailContainerXpath = ".//*[contains(@class,'thumbnailContainer')]"; - private $thumbnailFromContainerXpath = "/a"; - private $detailsTabId = [ + private string $detailsDialogCloseXpath = "//*[@class='close icon-close']"; + private string $thumbnailContainerXpath = ".//*[contains(@class,'thumbnailContainer')]"; + private string $thumbnailFromContainerXpath = "/a"; + private array $detailsTabId = [ 'comments' => "commentsTabView", 'sharing' => "shareTabView", 'versions' => "versionsTabView", 'tags' => "systemTagsTabView", ]; - private $tabSwitchBtnXpath = "//li[@data-tabid='%s']"; - private $tagsContainer = "//div[@class='systemTagsInputFieldContainer']"; - private $tagList = "//span[@class='system-tag-list-item']"; - private $tagSearchChoiceXpath = "//li[@class='select2-search-choice']" . "//span[@class='label']"; + private string $tabSwitchBtnXpath = "//li[@data-tabid='%s']"; + private string $tagsContainer = "//div[@class='systemTagsInputFieldContainer']"; + private string $tagList = "//span[@class='system-tag-list-item']"; + private string $tagSearchChoiceXpath = "//li[@class='select2-search-choice']" . "//span[@class='label']"; - private $tagsInputXpath = "//li[@class='select2-search-field']//input"; + private string $tagsInputXpath = "//li[@class='select2-search-field']//input"; - private $tagsSuggestDropDownXpath = "//div[contains(@class, 'systemtags-select2-dropdown') and contains(@id, 'select2-drop')]"; + private string $tagsSuggestDropDownXpath = "//div[contains(@class, 'systemtags-select2-dropdown') and contains(@id, 'select2-drop')]"; - private $tagsResultFromDropdownXpath = "//li[contains(@class, 'select2-result')]"; - private $tagEditButtonInTagXpath = "//div[@class='systemtags-actions']//a[contains(@class, 'rename')]"; - private $tagDeleteButtonInTagXpath = "//div[@class='systemtags-actions']//a[contains(@class, 'delete')]"; - private $tagsDropDownResultXpath = "//div[contains(@class, 'systemtags-select2-dropdown')]" . + private string $tagsResultFromDropdownXpath = "//li[contains(@class, 'select2-result')]"; + private string $tagEditButtonInTagXpath = "//div[@class='systemtags-actions']//a[contains(@class, 'rename')]"; + private string $tagDeleteButtonInTagXpath = "//div[@class='systemtags-actions']//a[contains(@class, 'delete')]"; + private string $tagsDropDownResultXpath = "//div[contains(@class, 'systemtags-select2-dropdown')]" . "//ul[@class='select2-results']" . "//span[@class='label']"; - private $tagEditInputXpath = "//input[contains(@id, 'rename-input') and contains(@value, %s)]"; + private string $tagEditInputXpath = "//input[contains(@id, 'rename-input') and contains(@value, %s)]"; protected $tagDeleteConfirmButtonXpath = ".//div[contains(@class, 'oc-dialog-buttonrow twobuttons') and not(ancestor::div[contains(@style, 'display: none')])]//button[text()='Yes']"; - private $commentXpath = "//ul[@class='comments']//div[@class='message' and contains(., '%s')]"; - private $commentInputXpath = "//form[@class='newCommentForm']//textarea[@class='message']"; - private $commentPostXpath = "//form[@class='newCommentForm']//input[@class='submit']"; - private $commentEditFormXpath = "//ul[@class='comments']//div[@class='newCommentRow comment']"; - private $commentEditButtonXpath = "//a[@data-original-title='Edit comment']"; - private $commentDeleteButtonXpath = "//a[@data-original-title='Delete comment']"; - private $commentListXpath = "//ul[@class='comments']//div[@class='message']"; - - private $versionsListXpath = "//div[@id='versionsTabView']//ul[@class='versions']"; - private $versionDetailsXpath = "//div[@id='versionsTabView']//ul[@class='versions']/li//div[@class='version-details']"; - private $lastVersionRevertButton = "//div[@id='versionsTabView']//ul[@class='versions']//li[2]/div/div[@class='action-container']/a"; + private string $commentXpath = "//ul[@class='comments']//div[@class='message' and contains(., '%s')]"; + private string $commentInputXpath = "//form[@class='newCommentForm']//textarea[@class='message']"; + private string $commentPostXpath = "//form[@class='newCommentForm']//input[@class='submit']"; + private string $commentEditFormXpath = "//ul[@class='comments']//div[@class='newCommentRow comment']"; + private string $commentEditButtonXpath = "//a[@data-original-title='Edit comment']"; + private string $commentDeleteButtonXpath = "//a[@data-original-title='Delete comment']"; + private string $commentListXpath = "//ul[@class='comments']//div[@class='message']"; + + private string $versionsListXpath = "//div[@id='versionsTabView']//ul[@class='versions']"; + private string $versionDetailsXpath = "//div[@id='versionsTabView']//ul[@class='versions']/li//div[@class='version-details']"; + private string $lastVersionRevertButton = "//div[@id='versionsTabView']//ul[@class='versions']//li[2]/div/div[@class='action-container']/a"; /** * diff --git a/tests/acceptance/features/lib/FilesPageElement/SharingDialog.php b/tests/acceptance/features/lib/FilesPageElement/SharingDialog.php index 2489b40e8e77..da6741d1d307 100644 --- a/tests/acceptance/features/lib/FilesPageElement/SharingDialog.php +++ b/tests/acceptance/features/lib/FilesPageElement/SharingDialog.php @@ -43,43 +43,40 @@ class SharingDialog extends OwncloudPage { * @var string $path */ protected $path = '/index.php/apps/files/'; - private $shareWithFieldXpath = ".//*[contains(@class,'shareWithField')]"; - private $shareWithTooltipXpath = "/..//*[@class='tooltip-inner']"; - private $shareWithAutocompleteListXpath = ".//ul[contains(@class,'ui-autocomplete')]"; - private $autocompleteItemsTextXpath = "//*[@class='autocomplete-item-text']"; - private $suffixToIdentifyGroups = " Group"; - private $suffixToIdentifyUsers = " User"; - private $suffixToIdentifyMultipleUsers = " Add multiple users"; - private $suffixToIdentifyRemoteUsers = " Federated"; - private $sharerInformationXpath = ".//*[@class='reshare']"; - private $sharedWithAndByRegEx = "Shared with you(?: and the group (.*))? by (.*)$"; - private $permissionsFieldByUserNameWithExtraInfo = "//*[@id='shareWithList']//span[contains(text(), '%s')]/parent::li[@data-share-with='%s']"; - private $permissionsFieldByUserName = "//*[@id='shareWithList']//span[contains(text(), '%s')]/parent::li"; - private $permissionsFieldByGroupName = "//*[@id='shareWithList']//span[contains(text(), '%s (group)')]/parent::li"; - private $permissionLabelXpath = ".//label[@for='%s']"; - private $showCrudsXpath = ".//span[@class='icon icon-settings-dark']"; - private $shareOptionsXpath = "//div[@class='shareOption']"; - private $publicLinksShareTabXpath = ".//li[contains(@class,'subtab-publicshare')]"; - private $publicLinksTabContentXpath = "//div[@id='shareDialogLinkList']"; - private $noSharingMessageXpath = "//div[@class='noSharingPlaceholder']"; - private $publicLinkRemoveBtnXpath = "//div[contains(@class, 'removeLink')]"; - private $publicLinkTitleXpath = "//span[@class='link-entry--title']"; - private $notifyByEmailBtnXpath = "//input[@name='mailNotification']"; - private $shareWithExpirationFieldXpath = "//*[@id='shareWithList']//span[@class='has-tooltip username' and .='%s']/..//input[contains(@class, 'expiration')]"; - private $shareWithClearExpirationFieldXpath = "/following-sibling::button[@class='removeExpiration']"; // in relation to $shareWithExpirationFieldXpath - private $shareWithListXpath = "//ul[@id='shareWithList']/li"; - private $shareWithListDetailsXpath = "//div[@class='shareWithList__details']"; - private $userOrGroupNameSpanXpath = "//span[contains(@class,'username')]"; - private $unShareTabXpath = "//a[contains(@class,'unshare')]"; - private $sharedWithGroupAndSharerName = null; - private $publicLinkRemoveDeclineMsg = "No"; - private $shareTreeItemByNameAndPathXpath = "//li[@class='shareTree-item' and strong/text()='%s' and span/text()='via %s']"; - private $userAndGroupsShareTabXpath = "//div[@class='dialogContainer']//li[contains(text(), 'User and Groups')]"; + private string $shareWithFieldXpath = ".//*[contains(@class,'shareWithField')]"; + private string $shareWithTooltipXpath = "/..//*[@class='tooltip-inner']"; + private string $shareWithAutocompleteListXpath = ".//ul[contains(@class,'ui-autocomplete')]"; + private string $autocompleteItemsTextXpath = "//*[@class='autocomplete-item-text']"; + private string $suffixToIdentifyGroups = " Group"; + private string $suffixToIdentifyUsers = " User"; + private string $suffixToIdentifyMultipleUsers = " Add multiple users"; + private string $suffixToIdentifyRemoteUsers = " Federated"; + private string $sharerInformationXpath = ".//*[@class='reshare']"; + private string $sharedWithAndByRegEx = "Shared with you(?: and the group (.*))? by (.*)$"; + private string $permissionsFieldByUserNameWithExtraInfo = "//*[@id='shareWithList']//span[contains(text(), '%s')]/parent::li[@data-share-with='%s']"; + private string $permissionsFieldByUserName = "//*[@id='shareWithList']//span[contains(text(), '%s')]/parent::li"; + private string $permissionsFieldByGroupName = "//*[@id='shareWithList']//span[contains(text(), '%s (group)')]/parent::li"; + private string $permissionLabelXpath = ".//label[@for='%s']"; + private string $showCrudsXpath = ".//span[@class='icon icon-settings-dark']"; + private string $shareOptionsXpath = "//div[@class='shareOption']"; + private string $publicLinksShareTabXpath = ".//li[contains(@class,'subtab-publicshare')]"; + private string $publicLinksTabContentXpath = "//div[@id='shareDialogLinkList']"; + private string $noSharingMessageXpath = "//div[@class='noSharingPlaceholder']"; + private string $publicLinkRemoveBtnXpath = "//div[contains(@class, 'removeLink')]"; + private string $publicLinkTitleXpath = "//span[@class='link-entry--title']"; + private string $notifyByEmailBtnXpath = "//input[@name='mailNotification']"; + private string $shareWithExpirationFieldXpath = "//*[@id='shareWithList']//span[@class='has-tooltip username' and .='%s']/..//input[contains(@class, 'expiration')]"; + private string $shareWithClearExpirationFieldXpath = "/following-sibling::button[@class='removeExpiration']"; // in relation to $shareWithExpirationFieldXpath + private string $shareWithListXpath = "//ul[@id='shareWithList']/li"; + private string $shareWithListDetailsXpath = "//div[@class='shareWithList__details']"; + private string $userOrGroupNameSpanXpath = "//span[contains(@class,'username')]"; + private string $unShareTabXpath = "//a[contains(@class,'unshare')]"; + private ?array $sharedWithGroupAndSharerName = null; + private string $publicLinkRemoveDeclineMsg = "No"; + private string $shareTreeItemByNameAndPathXpath = "//li[@class='shareTree-item' and strong/text()='%s' and span/text()='via %s']"; + private string $userAndGroupsShareTabXpath = "//div[@class='dialogContainer']//li[contains(text(), 'User and Groups')]"; - /** - * @var string - */ - private $groupFramework = "%s (group)"; + private string $groupFramework = "%s (group)"; /** * diff --git a/tests/acceptance/features/lib/FilesPageElement/SharingDialogElement/EditPublicLinkPopup.php b/tests/acceptance/features/lib/FilesPageElement/SharingDialogElement/EditPublicLinkPopup.php index 2755b1d8c229..6970507dd8e9 100644 --- a/tests/acceptance/features/lib/FilesPageElement/SharingDialogElement/EditPublicLinkPopup.php +++ b/tests/acceptance/features/lib/FilesPageElement/SharingDialogElement/EditPublicLinkPopup.php @@ -38,25 +38,25 @@ class EditPublicLinkPopup extends OwncloudPage { * @var NodeElement of this popup */ private $popupElement; - private $nameInputXpath = ".//input[@name='linkName']"; - private $passwordInputXpath = ".//input[@type='password']"; - private $expirationDateLabelXpath = ".//label[contains(text(), 'Expiration')]"; - private $expirationDateInputXpath = ".//input[contains(@class,'expirationDate')]"; - private $emailInputXpath = "//form[@id='emailPrivateLink']//input[@class='select2-input']"; - private $emailToSelfCheckboxXpath = "//form[@id='emailPrivateLink']" . "//input[@class='emailPrivateLinkForm--emailToSelf']"; - private $emailInputCloseXpath = "//a[@class='select2-search-choice-close']"; - private $personalMessageInputXpath = "//*[@class='public-link-modal--input emailPrivateLinkForm--emailBodyField']"; - private $shareButtonXpath = ".//button[contains(text(), 'Share') or contains(text(), 'Save')]"; - private $cancelButtonXpath = ".//button[contains(text(), 'Cancel')]"; - private $permissionLabelXpath = [ + private string $nameInputXpath = ".//input[@name='linkName']"; + private string $passwordInputXpath = ".//input[@type='password']"; + private string $expirationDateLabelXpath = ".//label[contains(text(), 'Expiration')]"; + private string $expirationDateInputXpath = ".//input[contains(@class,'expirationDate')]"; + private string $emailInputXpath = "//form[@id='emailPrivateLink']//input[@class='select2-input']"; + private string $emailToSelfCheckboxXpath = "//form[@id='emailPrivateLink']" . "//input[@class='emailPrivateLinkForm--emailToSelf']"; + private string $emailInputCloseXpath = "//a[@class='select2-search-choice-close']"; + private string $personalMessageInputXpath = "//*[@class='public-link-modal--input emailPrivateLinkForm--emailBodyField']"; + private string $shareButtonXpath = ".//button[contains(text(), 'Share') or contains(text(), 'Save')]"; + private string $cancelButtonXpath = ".//button[contains(text(), 'Cancel')]"; + private array $permissionLabelXpath = [ 'read' => ".//label[contains(@for, 'sharingDialogAllowPublicRead')]", 'read-write-folder' => ".//label[contains(@for, 'sharingDialogAllowPublicFolderReadWrite')]", 'read-write-file' => ".//label[contains(@for, 'sharingDialogAllowPublicFileReadWrite')]", 'upload-write-without-modify' => ".//label[contains(@for, 'sharingDialogAllowpublicUploadWrite')]", 'upload' => ".//label[contains(@for, 'sharingDialogAllowPublicUpload')]" ]; - private $popupCloseButton = "//a[@class='oc-dialog-close']"; - private $expirationDateRequiredErrorMessageXpath = './/*[@id="shareDialogLinkExpirationView"]//span[@class="error-message"]'; + private string $popupCloseButton = "//a[@class='oc-dialog-close']"; + private string $expirationDateRequiredErrorMessageXpath = './/*[@id="shareDialogLinkExpirationView"]//span[@class="error-message"]'; /** * sets the NodeElement for the current popup diff --git a/tests/acceptance/features/lib/FilesPageElement/SharingDialogElement/PublicLinkTab.php b/tests/acceptance/features/lib/FilesPageElement/SharingDialogElement/PublicLinkTab.php index eb797a1f7e3c..87a7432a0add 100644 --- a/tests/acceptance/features/lib/FilesPageElement/SharingDialogElement/PublicLinkTab.php +++ b/tests/acceptance/features/lib/FilesPageElement/SharingDialogElement/PublicLinkTab.php @@ -39,13 +39,13 @@ class PublicLinkTab extends OwncloudPage { * @var NodeElement of this tab */ private $publicLinkTabElement; - private $createLinkBtnXpath = ".//button[@class='addLink']"; - private $popupXpath = ".//div[@class='oc-dialog' and not(contains(@style,'display: none'))]"; - private $linkEntryByNameXpath = ".//*[@class='link-entry--title' and .=%s]/.."; - private $linkEntriesNamesXpath = "//div[@id='shareDialogLinkList']//span[@class='link-entry--title']"; - private $linkUrlInputXpath = ".//input"; - private $publicLinkWarningMessageXpath = ".//*[@class='error-message-global'][last()]"; - private $linkEditBtnXpath = "//div[@class='link-entry--icon-button editLink']"; + private string $createLinkBtnXpath = ".//button[@class='addLink']"; + private string $popupXpath = ".//div[@class='oc-dialog' and not(contains(@style,'display: none'))]"; + private string $linkEntryByNameXpath = ".//*[@class='link-entry--title' and .=%s]/.."; + private string $linkEntriesNamesXpath = "//div[@id='shareDialogLinkList']//span[@class='link-entry--title']"; + private string $linkUrlInputXpath = ".//input"; + private string $publicLinkWarningMessageXpath = ".//*[@class='error-message-global'][last()]"; + private string $linkEditBtnXpath = "//div[@class='link-entry--icon-button editLink']"; /** * diff --git a/tests/acceptance/features/lib/Notification.php b/tests/acceptance/features/lib/Notification.php index ac1d08cd7c78..3abae7e1f42d 100644 --- a/tests/acceptance/features/lib/Notification.php +++ b/tests/acceptance/features/lib/Notification.php @@ -36,8 +36,8 @@ class Notification extends OwncloudPage { */ private $notificationElement; - private $buttonByTextXpath = "//button[text()='%s']"; - private $notificationLinkXpath = "//a[@class='notification-link']"; + private string $buttonByTextXpath = "//button[text()='%s']"; + private string $notificationLinkXpath = "//a[@class='notification-link']"; /** * sets the NodeElement for the current notification diff --git a/tests/acceptance/features/lib/NotificationsAppDialog.php b/tests/acceptance/features/lib/NotificationsAppDialog.php index 659f824f906e..d47da6c91fe5 100644 --- a/tests/acceptance/features/lib/NotificationsAppDialog.php +++ b/tests/acceptance/features/lib/NotificationsAppDialog.php @@ -29,10 +29,10 @@ * PageObject for the Notifications area */ class NotificationsAppDialog extends OwncloudPage { - private $notificationContainerXpath = "//div[@class='notification']"; - private $notificationTitleXpath = "//h3[@class='notification-title']"; - private $notificationLinkXpath = "//a[@class='notification-link']"; - private $notificationMessageXpath = "//p[@class='notification-message']"; + private string $notificationContainerXpath = "//div[@class='notification']"; + private string $notificationTitleXpath = "//h3[@class='notification-title']"; + private string $notificationLinkXpath = "//a[@class='notification-link']"; + private string $notificationMessageXpath = "//p[@class='notification-message']"; /** * diff --git a/tests/acceptance/features/lib/NotificationsEnabledOwncloudPage.php b/tests/acceptance/features/lib/NotificationsEnabledOwncloudPage.php index 79eed8fcaabc..17f1dac83add 100644 --- a/tests/acceptance/features/lib/NotificationsEnabledOwncloudPage.php +++ b/tests/acceptance/features/lib/NotificationsEnabledOwncloudPage.php @@ -32,7 +32,7 @@ * plus what the notifications App adds to it */ class NotificationsEnabledOwncloudPage extends OwncloudPage { - private $notificationsButtonXpath = "//div[contains(@class,'notifications-button')]"; + private string $notificationsButtonXpath = "//div[contains(@class,'notifications-button')]"; /** * diff --git a/tests/acceptance/features/lib/OwncloudPage.php b/tests/acceptance/features/lib/OwncloudPage.php index 24b2fe4b406a..5ff50921fb61 100644 --- a/tests/acceptance/features/lib/OwncloudPage.php +++ b/tests/acceptance/features/lib/OwncloudPage.php @@ -48,7 +48,7 @@ class OwncloudPage extends Page { protected $titleXpath = ".//title"; protected $searchBoxId = "searchbox"; protected $sidebarNavXpath = "//li[@data-id='%s']"; - private $sidebarItemId = [ + private array $sidebarItemId = [ 'All files' => "files", 'Favorites' => "favorites", 'Shared with you' => "sharingin", diff --git a/tests/acceptance/features/lib/OwncloudPageElement/SettingsMenu.php b/tests/acceptance/features/lib/OwncloudPageElement/SettingsMenu.php index 360acf9122af..5b9ff21434e7 100644 --- a/tests/acceptance/features/lib/OwncloudPageElement/SettingsMenu.php +++ b/tests/acceptance/features/lib/OwncloudPageElement/SettingsMenu.php @@ -32,7 +32,7 @@ * */ class SettingsMenu extends OwncloudPage { - private $logoutButtonXpath = "//*[@id='logout']"; + private string $logoutButtonXpath = "//*[@id='logout']"; /** * Logout with the logout button diff --git a/tests/acceptance/features/lib/PersonalEncryptionSettingsPage.php b/tests/acceptance/features/lib/PersonalEncryptionSettingsPage.php index 5e3acf0f6120..564fe6ac25d4 100644 --- a/tests/acceptance/features/lib/PersonalEncryptionSettingsPage.php +++ b/tests/acceptance/features/lib/PersonalEncryptionSettingsPage.php @@ -37,8 +37,8 @@ class PersonalEncryptionSettingsPage extends OwncloudPage { */ protected $path = '/index.php/settings/personal?sectionid=encryption'; - private $userEnableRecoveryCheckboxId = 'userEnableRecoveryCheckbox'; - private $userEnableRecoveryCheckboxXpath = '//label[@for="userEnableRecoveryCheckbox"]'; + private string $userEnableRecoveryCheckboxId = 'userEnableRecoveryCheckbox'; + private string $userEnableRecoveryCheckboxXpath = '//label[@for="userEnableRecoveryCheckbox"]'; /** * Enable password recovery diff --git a/tests/acceptance/features/lib/PersonalSecuritySettingsPage.php b/tests/acceptance/features/lib/PersonalSecuritySettingsPage.php index a4f8a3a80c0c..c48b36c300c2 100644 --- a/tests/acceptance/features/lib/PersonalSecuritySettingsPage.php +++ b/tests/acceptance/features/lib/PersonalSecuritySettingsPage.php @@ -85,7 +85,7 @@ public function createNewAppPassword(string $appName): void { while (\strpos( $createNewAppPasswordButton->getAttribute("class"), - $this->createNewAppPasswordLoadingIndicatorClass + (string) $this->createNewAppPasswordLoadingIndicatorClass ) !== false ) { \usleep(STANDARD_SLEEP_TIME_MICROSEC); diff --git a/tests/acceptance/features/lib/TagsPage.php b/tests/acceptance/features/lib/TagsPage.php index 29b6f2967b93..88bfa1c4de31 100644 --- a/tests/acceptance/features/lib/TagsPage.php +++ b/tests/acceptance/features/lib/TagsPage.php @@ -45,8 +45,8 @@ class TagsPage extends FilesPageBasic { */ protected $filesPageCRUDFunctions; - private $tagsInputXpath = "//div[@id='app-content-systemtagsfilter']//li[@class='select2-search-field']//input"; - private $tagsSuggestDropDown = "//div[contains(@class, 'select2-drop-active') and contains(@id, 'select2-drop')]"; + private string $tagsInputXpath = "//div[@id='app-content-systemtagsfilter']//li[@class='select2-search-field']//input"; + private string $tagsSuggestDropDown = "//div[contains(@class, 'select2-drop-active') and contains(@id, 'select2-drop')]"; /** * @return string diff --git a/tests/lib/APITest.php b/tests/lib/APITest.php index e6795e395559..848f2001cc03 100644 --- a/tests/lib/APITest.php +++ b/tests/lib/APITest.php @@ -72,7 +72,7 @@ public function versionDataScriptNameProvider() { * @param bool $expected */ public function testIsV2($scriptName, $expected) { - $request = $this->getMockBuilder('\OCP\IRequest') + $request = $this->getMockBuilder('\\' . \OCP\IRequest::class) ->disableOriginalConstructor() ->getMock(); $request diff --git a/tests/lib/Activity/ManagerTest.php b/tests/lib/Activity/ManagerTest.php index 3e3569427955..8690d1274818 100644 --- a/tests/lib/Activity/ManagerTest.php +++ b/tests/lib/Activity/ManagerTest.php @@ -14,8 +14,7 @@ use Test\TestCase; class ManagerTest extends TestCase { - /** @var \OC\Activity\Manager */ - private $activityManager; + private \OC\Activity\Manager $activityManager; /** @var \OCP\IRequest|\PHPUnit\Framework\MockObject\MockObject */ protected $request; @@ -29,13 +28,13 @@ class ManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder('OCP\IRequest') + $this->request = $this->getMockBuilder(\OCP\IRequest::class) ->disableOriginalConstructor() ->getMock(); - $this->session = $this->getMockBuilder('OCP\IUserSession') + $this->session = $this->getMockBuilder(\OCP\IUserSession::class) ->disableOriginalConstructor() ->getMock(); - $this->config = $this->getMockBuilder('OCP\IConfig') + $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); @@ -48,15 +47,9 @@ protected function setUp(): void { $this->assertSame([], self::invokePrivate($this->activityManager, 'getConsumers')); $this->assertSame([], self::invokePrivate($this->activityManager, 'getExtensions')); - $this->activityManager->registerConsumer(function () { - return new NoOpConsumer(); - }); - $this->activityManager->registerExtension(function () { - return new NoOpExtension(); - }); - $this->activityManager->registerExtension(function () { - return new SimpleExtension(); - }); + $this->activityManager->registerConsumer(fn () => new NoOpConsumer()); + $this->activityManager->registerExtension(fn () => new NoOpExtension()); + $this->activityManager->registerExtension(fn () => new SimpleExtension()); $this->assertNotEmpty(self::invokePrivate($this->activityManager, 'getConsumers')); $this->assertNotEmpty(self::invokePrivate($this->activityManager, 'getConsumers')); @@ -75,9 +68,7 @@ public function testGetConsumers() { public function testGetConsumersInvalidConsumer() { $this->expectException(\InvalidArgumentException::class); - $this->activityManager->registerConsumer(function () { - return new \stdClass(); - }); + $this->activityManager->registerConsumer(fn () => new \stdClass()); self::invokePrivate($this->activityManager, 'getConsumers'); } @@ -93,9 +84,7 @@ public function testGetExtensions() { public function testGetExtensionsInvalidExtension() { $this->expectException(\InvalidArgumentException::class); - $this->activityManager->registerExtension(function () { - return new \stdClass(); - }); + $this->activityManager->registerExtension(fn () => new \stdClass()); self::invokePrivate($this->activityManager, 'getExtensions'); } @@ -171,9 +160,7 @@ public function testFilterNotificationTypes() { public function testQueryForFilter() { // Register twice, to test the created sql part - $this->activityManager->registerExtension(function () { - return new SimpleExtension(); - }); + $this->activityManager->registerExtension(fn () => new SimpleExtension()); $result = $this->activityManager->getQueryForFilter('fv01'); $this->assertEquals( @@ -251,7 +238,7 @@ protected function mockRSSToken($requestToken, $userToken, $users) { } protected function mockUserSession($user) { - $mockUser = $this->getMockBuilder('\OCP\IUser') + $mockUser = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor() ->getMock(); $mockUser->expects($this->any()) @@ -329,7 +316,7 @@ public function dataPublish() { */ public function testPublish($author) { if ($author !== null) { - $authorObject = $this->getMockBuilder('OCP\IUser') + $authorObject = $this->getMockBuilder(\OCP\IUser::class) ->disableOriginalConstructor() ->getMock(); $authorObject->expects($this->once()) @@ -346,7 +333,7 @@ public function testPublish($author) { ->setSubject('test_subject', []) ->setAffectedUser('test_affected'); - $consumer = $this->getMockBuilder('OCP\Activity\IConsumer') + $consumer = $this->getMockBuilder(\OCP\Activity\IConsumer::class) ->disableOriginalConstructor() ->getMock(); $consumer->expects($this->once()) @@ -357,9 +344,7 @@ public function testPublish($author) { $this->assertGreaterThanOrEqual(\time() - 2, $event->getTimestamp(), 'Timestamp not set correctly'); $this->assertSame($author, $event->getAuthor(), 'Author name not set correctly'); }); - $this->activityManager->registerConsumer(function () use ($consumer) { - return $consumer; - }); + $this->activityManager->registerConsumer(fn () => $consumer); $this->activityManager->publish($event); } @@ -377,7 +362,7 @@ public function testPublishAllManually() { ->setLink('test_link') ; - $consumer = $this->getMockBuilder('OCP\Activity\IConsumer') + $consumer = $this->getMockBuilder(\OCP\Activity\IConsumer::class) ->disableOriginalConstructor() ->getMock(); $consumer->expects($this->once()) @@ -397,9 +382,7 @@ public function testPublishAllManually() { $this->assertSame('test_object_name', $event->getObjectName(), 'Object name not set correctly'); $this->assertSame('test_link', $event->getLink(), 'Link not set correctly'); }); - $this->activityManager->registerConsumer(function () use ($consumer) { - return $consumer; - }); + $this->activityManager->registerConsumer(fn () => $consumer); $this->activityManager->publish($event); } @@ -417,7 +400,7 @@ public function testDeprecatedPublishActivity() { ->setLink('test_link') ; - $consumer = $this->getMockBuilder('OCP\Activity\IConsumer') + $consumer = $this->getMockBuilder(\OCP\Activity\IConsumer::class) ->disableOriginalConstructor() ->getMock(); $consumer->expects($this->once()) @@ -440,9 +423,7 @@ public function testDeprecatedPublishActivity() { $this->assertSame('', $event->getObjectType(), 'Object type should not be set'); $this->assertSame(0, $event->getObjectId(), 'Object ID should not be set'); }); - $this->activityManager->registerConsumer(function () use ($consumer) { - return $consumer; - }); + $this->activityManager->registerConsumer(fn () => $consumer); $this->activityManager->publishActivity( $event->getApp(), diff --git a/tests/lib/Activity/NullSession/ManagerTest.php b/tests/lib/Activity/NullSession/ManagerTest.php index 4bb414c5f302..8912b8906d19 100644 --- a/tests/lib/Activity/NullSession/ManagerTest.php +++ b/tests/lib/Activity/NullSession/ManagerTest.php @@ -19,8 +19,7 @@ use Test\TestCase; class ManagerTest extends TestCase { - /** @var \OC\Activity\Manager */ - private $activityManager; + private \OC\Activity\Manager $activityManager; /** @var \OCP\IRequest|\PHPUnit\Framework\MockObject\MockObject */ protected $request; /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */ @@ -45,15 +44,9 @@ protected function setUp(): void { $this->assertSame([], self::invokePrivate($this->activityManager, 'getConsumers')); $this->assertSame([], self::invokePrivate($this->activityManager, 'getExtensions')); - $this->activityManager->registerConsumer(function () { - return new NoOpConsumer(); - }); - $this->activityManager->registerExtension(function () { - return new NoOpExtension(); - }); - $this->activityManager->registerExtension(function () { - return new SimpleExtension(); - }); + $this->activityManager->registerConsumer(fn () => new NoOpConsumer()); + $this->activityManager->registerExtension(fn () => new NoOpExtension()); + $this->activityManager->registerExtension(fn () => new SimpleExtension()); $this->assertNotEmpty(self::invokePrivate($this->activityManager, 'getConsumers')); $this->assertNotEmpty(self::invokePrivate($this->activityManager, 'getConsumers')); @@ -72,9 +65,7 @@ public function testGetConsumers() { public function testGetConsumersInvalidConsumer() { $this->expectException(\InvalidArgumentException::class); - $this->activityManager->registerConsumer(function () { - return new \stdClass(); - }); + $this->activityManager->registerConsumer(fn () => new \stdClass()); self::invokePrivate($this->activityManager, 'getConsumers'); } @@ -90,9 +81,7 @@ public function testGetExtensions() { public function testGetExtensionsInvalidExtension() { $this->expectException(\InvalidArgumentException::class); - $this->activityManager->registerExtension(function () { - return new \stdClass(); - }); + $this->activityManager->registerExtension(fn () => new \stdClass()); self::invokePrivate($this->activityManager, 'getExtensions'); } @@ -168,9 +157,7 @@ public function testFilterNotificationTypes() { public function testQueryForFilter() { // Register twice, to test the created sql part - $this->activityManager->registerExtension(function () { - return new SimpleExtension(); - }); + $this->activityManager->registerExtension(fn () => new SimpleExtension()); $result = $this->activityManager->getQueryForFilter('fv01'); $this->assertEquals( @@ -299,7 +286,7 @@ public function testPublish() { ->setSubject('test_subject', []) ->setAffectedUser('test_affected'); - $consumer = $this->getMockBuilder('OCP\Activity\IConsumer') + $consumer = $this->getMockBuilder(\OCP\Activity\IConsumer::class) ->disableOriginalConstructor() ->getMock(); $consumer->expects($this->once()) @@ -310,9 +297,7 @@ public function testPublish() { $this->assertGreaterThanOrEqual(\time() - 2, $event->getTimestamp(), 'Timestamp not set correctly'); $this->assertSame($author, $event->getAuthor(), 'Author name not set correctly'); }); - $this->activityManager->registerConsumer(function () use ($consumer) { - return $consumer; - }); + $this->activityManager->registerConsumer(fn () => $consumer); $this->activityManager->publish($event); } @@ -330,7 +315,7 @@ public function testPublishAllManually() { ->setLink('test_link') ; - $consumer = $this->getMockBuilder('OCP\Activity\IConsumer') + $consumer = $this->getMockBuilder(\OCP\Activity\IConsumer::class) ->disableOriginalConstructor() ->getMock(); $consumer->expects($this->once()) @@ -350,9 +335,7 @@ public function testPublishAllManually() { $this->assertSame('test_object_name', $event->getObjectName(), 'Object name not set correctly'); $this->assertSame('test_link', $event->getLink(), 'Link not set correctly'); }); - $this->activityManager->registerConsumer(function () use ($consumer) { - return $consumer; - }); + $this->activityManager->registerConsumer(fn () => $consumer); $this->activityManager->publish($event); } @@ -370,7 +353,7 @@ public function testDeprecatedPublishActivity() { ->setLink('test_link') ; - $consumer = $this->getMockBuilder('OCP\Activity\IConsumer') + $consumer = $this->getMockBuilder(\OCP\Activity\IConsumer::class) ->disableOriginalConstructor() ->getMock(); $consumer->expects($this->once()) @@ -393,9 +376,7 @@ public function testDeprecatedPublishActivity() { $this->assertSame('', $event->getObjectType(), 'Object type should not be set'); $this->assertSame(0, $event->getObjectId(), 'Object ID should not be set'); }); - $this->activityManager->registerConsumer(function () use ($consumer) { - return $consumer; - }); + $this->activityManager->registerConsumer(fn () => $consumer); $this->activityManager->publishActivity( $event->getApp(), diff --git a/tests/lib/AllConfigTest.php b/tests/lib/AllConfigTest.php index c4aaa2b019d1..0053009941f6 100644 --- a/tests/lib/AllConfigTest.php +++ b/tests/lib/AllConfigTest.php @@ -34,7 +34,7 @@ protected function getConfig($systemConfig = null, $connection = null) { $connection = $this->connection; } if ($systemConfig === null) { - $systemConfig = $this->getMockBuilder('\OC\SystemConfig') + $systemConfig = $this->getMockBuilder('\\' . \OC\SystemConfig::class) ->disableOriginalConstructor() ->getMock(); } @@ -220,13 +220,13 @@ public function testSetUserValueUnchanged() { // TODO - FIXME until the dependency injection is handled properly (in AllConfig) $this->markTestSkipped('Skipped because this is just testable if database connection can be injected'); - $resultMock = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement') + $resultMock = $this->getMockBuilder('\\' . \Doctrine\DBAL\Driver\Statement::class) ->disableOriginalConstructor()->getMock(); $resultMock->expects($this->once()) ->method('fetchColumn') ->will($this->returnValue('valueSetUnchanged')); - $connectionMock = $this->createMock('\OCP\IDBConnection'); + $connectionMock = $this->createMock('\\' . \OCP\IDBConnection::class); $connectionMock->expects($this->once()) ->method('executeQuery') ->with( @@ -463,7 +463,7 @@ public function testDeleteAppFromAllUsers() { public function testGetUsersForUserValue() { // mock the check for the database to run the correct SQL statements for each database type - $systemConfig = $this->getMockBuilder('\OC\SystemConfig') + $systemConfig = $this->getMockBuilder('\\' . \OC\SystemConfig::class) ->disableOriginalConstructor() ->getMock(); $config = $this->getConfig($systemConfig); diff --git a/tests/lib/App/CodeChecker/DeprecationCheckTest.php b/tests/lib/App/CodeChecker/DeprecationCheckTest.php index 5c51ba8f117e..03fa20ef29d7 100644 --- a/tests/lib/App/CodeChecker/DeprecationCheckTest.php +++ b/tests/lib/App/CodeChecker/DeprecationCheckTest.php @@ -33,8 +33,8 @@ public function testFindInvalidUsage($expectedErrorToken, $expectedErrorCode, $f public function providesFilesToCheck() { return [ - ['OCP\AppFramework\IApi', 1006, 'test-deprecated-use.php'], - ['OCP\AppFramework\IApi', 1006, 'test-deprecated-use-alias.php'], + [\OCP\AppFramework\IApi::class, 1006, 'test-deprecated-use.php'], + [\OCP\AppFramework\IApi::class, 1006, 'test-deprecated-use-alias.php'], ['AppFramework\IApi', 1001, 'test-deprecated-use-sub.php'], ['OAF\IApi', 1001, 'test-deprecated-use-sub-alias.php'], ['OC_API::ADMIN_AUTH', 1003, 'test-const.php'], diff --git a/tests/lib/App/CodeChecker/InfoCheckerTest.php b/tests/lib/App/CodeChecker/InfoCheckerTest.php index d40b71ffbc43..90eb656a7db5 100644 --- a/tests/lib/App/CodeChecker/InfoCheckerTest.php +++ b/tests/lib/App/CodeChecker/InfoCheckerTest.php @@ -42,9 +42,7 @@ protected function setUp(): void { ->method('getAppPath') ->will( $this->returnCallback( - function ($appId) { - return \OC::$SERVERROOT . '/tests/apps/' . $appId; - } + fn ($appId) => \OC::$SERVERROOT . '/tests/apps/' . $appId ) ); } diff --git a/tests/lib/App/CodeChecker/Mock/TestList.php b/tests/lib/App/CodeChecker/Mock/TestList.php index c3e4e9cbb562..3251d948f7fc 100644 --- a/tests/lib/App/CodeChecker/Mock/TestList.php +++ b/tests/lib/App/CodeChecker/Mock/TestList.php @@ -49,7 +49,7 @@ public function getDescription($errorCode, $errorObject) { public function getClasses() { return [ // Deprecated classes - 'OCP\AppFramework\IApi' => '8.0.0', + \OCP\AppFramework\IApi::class => '8.0.0', ]; } diff --git a/tests/lib/App/CodeChecker/NodeVisitorTest.php b/tests/lib/App/CodeChecker/NodeVisitorTest.php index acdd7da1b06f..6b6f338b04b9 100644 --- a/tests/lib/App/CodeChecker/NodeVisitorTest.php +++ b/tests/lib/App/CodeChecker/NodeVisitorTest.php @@ -16,8 +16,8 @@ class NodeVisitorTest extends TestCase { public function providesFilesToCheck() { return [ - [[['OCP\AppFramework\IApi', 1006]], 'test-deprecated-use.php'], - [[['OCP\AppFramework\IApi', 1006]], 'test-deprecated-use-alias.php'], + [[[\OCP\AppFramework\IApi::class, 1006]], 'test-deprecated-use.php'], + [[[\OCP\AppFramework\IApi::class, 1006]], 'test-deprecated-use-alias.php'], [[['AppFramework\IApi', 1001]], 'test-deprecated-use-sub.php'], [[['OAF\IApi', 1001]], 'test-deprecated-use-sub-alias.php'], diff --git a/tests/lib/App/DependencyAnalyzerTest.php b/tests/lib/App/DependencyAnalyzerTest.php index ef15a0e69835..d9b6314ae77a 100644 --- a/tests/lib/App/DependencyAnalyzerTest.php +++ b/tests/lib/App/DependencyAnalyzerTest.php @@ -16,13 +16,12 @@ class DependencyAnalyzerTest extends TestCase { /** @var Platform */ - private $platformMock; + private \PHPUnit\Framework\MockObject\MockObject $platformMock; /** @var IL10N */ - private $l10nMock; + private \PHPUnit\Framework\MockObject\MockObject $l10nMock; - /** @var DependencyAnalyzer */ - private $analyser; + private \OC\App\DependencyAnalyzer $analyser; public function setUp(): void { $this->platformMock = $this->getMockBuilder(Platform::class) @@ -42,9 +41,7 @@ public function setUp(): void { ->will($this->returnValue('Linux')); $this->platformMock->expects($this->any()) ->method('isCommandKnown') - ->will($this->returnCallback(function ($command) { - return ($command === 'grep'); - })); + ->will($this->returnCallback(fn ($command) => $command === 'grep')); $this->platformMock->expects($this->any()) ->method('getLibraryVersion') ->will($this->returnCallback(function ($lib) { @@ -57,14 +54,12 @@ public function setUp(): void { ->method('getOcVersion') ->will($this->returnValue('8.0.2')); - $this->l10nMock = $this->getMockBuilder('\OCP\IL10N') + $this->l10nMock = $this->getMockBuilder('\\' . \OCP\IL10N::class) ->disableOriginalConstructor() ->getMock(); $this->l10nMock->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $this->analyser = new DependencyAnalyzer($this->platformMock, $this->l10nMock); } diff --git a/tests/lib/App/InfoParserTest.php b/tests/lib/App/InfoParserTest.php index 4fa0ac3d55cb..ad31360d97b3 100644 --- a/tests/lib/App/InfoParserTest.php +++ b/tests/lib/App/InfoParserTest.php @@ -14,8 +14,7 @@ use Test\TestCase; class InfoParserTest extends TestCase { - /** @var InfoParser */ - private $parser; + private \OC\App\InfoParser $parser; public function setUp(): void { $this->parser = new InfoParser(); @@ -24,7 +23,9 @@ public function setUp(): void { public function testParsingValidXml() { $expectedData = \json_decode( \file_get_contents(OC::$SERVERROOT . "/tests/data/app/expected-info.json"), - true + true, + 512, + JSON_THROW_ON_ERROR ); $data = $this->parser->parse(OC::$SERVERROOT. "/tests/data/app/valid-info.xml"); $this->assertEquals($expectedData, $data); diff --git a/tests/lib/App/ManagerTest.php b/tests/lib/App/ManagerTest.php index 4aaaf8ec1bd1..0e4d7abca9d5 100644 --- a/tests/lib/App/ManagerTest.php +++ b/tests/lib/App/ManagerTest.php @@ -45,7 +45,7 @@ class ManagerTest extends TestCase { /** @var EventDispatcherInterface | \PHPUnit\Framework\MockObject\MockObject */ protected $eventDispatcher; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** * @return IAppConfig | \PHPUnit\Framework\MockObject\MockObject @@ -177,9 +177,7 @@ public function testEnableTheSameThemeTwice() { ->method('isTheme') ->will( $this->returnCallback( - function ($appId) use ($appThemeName) { - return $appId === $appThemeName; - } + fn ($appId) => $appId === $appThemeName ) ); @@ -245,7 +243,7 @@ public function testEnableAppForGroupsAllowedTypes(array $appInfo) { $this->expectClearCache(); /** @var AppManager|\PHPUnit\Framework\MockObject\MockObject $manager */ - $manager = $this->getMockBuilder('OC\App\AppManager') + $manager = $this->getMockBuilder(\OC\App\AppManager::class) ->setConstructorArgs([ $this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory, $this->eventDispatcher, $this->config @@ -290,7 +288,7 @@ public function testEnableAppForGroupsForbiddenTypes($type) { ]; /** @var AppManager|\PHPUnit\Framework\MockObject\MockObject $manager */ - $manager = $this->getMockBuilder('OC\App\AppManager') + $manager = $this->getMockBuilder(\OC\App\AppManager::class) ->setConstructorArgs([ $this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory, $this->eventDispatcher, $this->config @@ -418,7 +416,7 @@ public function testGetAppsForUser() { } public function testGetAppsNeedingUpgrade() { - $this->manager = $this->getMockBuilder('\OC\App\AppManager') + $this->manager = $this->getMockBuilder('\\' . \OC\App\AppManager::class) ->setConstructorArgs([$this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory, $this->eventDispatcher, $this->config]) ->setMethods(['getAppInfo']) @@ -439,9 +437,7 @@ public function testGetAppsNeedingUpgrade() { $this->manager->expects($this->any()) ->method('getAppInfo') ->will($this->returnCallback( - function ($appId) use ($appInfos) { - return $appInfos[$appId]; - } + fn ($appId) => $appInfos[$appId] )); $this->appConfig->setValue('test1', 'enabled', 'yes'); @@ -461,7 +457,7 @@ function ($appId) use ($appInfos) { } public function testGetIncompatibleApps() { - $this->manager = $this->getMockBuilder('\OC\App\AppManager') + $this->manager = $this->getMockBuilder('\\' . \OC\App\AppManager::class) ->setConstructorArgs([$this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory, $this->eventDispatcher, $this->config]) ->setMethods(['getAppInfo']) @@ -481,9 +477,7 @@ public function testGetIncompatibleApps() { $this->manager->expects($this->any()) ->method('getAppInfo') ->will($this->returnCallback( - function ($appId) use ($appInfos) { - return $appInfos[$appId]; - } + fn ($appId) => $appInfos[$appId] )); $this->appConfig->setValue('test1', 'enabled', 'yes'); diff --git a/tests/lib/AppConfigTest.php b/tests/lib/AppConfigTest.php index da4ea2a9d4c3..f60fefe55215 100644 --- a/tests/lib/AppConfigTest.php +++ b/tests/lib/AppConfigTest.php @@ -141,9 +141,7 @@ public function tearDown(): void { * @param \OCP\IAppConfig $appConfig */ protected function registerAppConfig($appConfig) { - \OC::$server->registerService('AppConfig', function () use ($appConfig) { - return $appConfig; - }); + \OC::$server->registerService('AppConfig', fn () => $appConfig); } public function testGetApps() { diff --git a/tests/lib/AppFramework/AppTest.php b/tests/lib/AppFramework/AppTest.php index 29fa24fe971b..c27f7877a19f 100644 --- a/tests/lib/AppFramework/AppTest.php +++ b/tests/lib/AppFramework/AppTest.php @@ -40,15 +40,15 @@ function rrmdir($directory) { class AppTest extends \Test\TestCase { private $container; - private $io; + private \PHPUnit\Framework\MockObject\MockObject $io; private $api; - private $controller; - private $dispatcher; + private \PHPUnit\Framework\MockObject\MockObject $controller; + private \PHPUnit\Framework\MockObject\MockObject $dispatcher; private $params; - private $headers; - private $output; - private $controllerName; - private $controllerMethod; + private array $headers; + private string $output; + private string $controllerName; + private string $controllerMethod; private $appPath; protected function setUp(): void { @@ -56,17 +56,17 @@ protected function setUp(): void { $this->container = new \OC\AppFramework\DependencyInjection\DIContainer('test', []); $this->controller = $this->getMockBuilder( - 'OCP\AppFramework\Controller' + \OCP\AppFramework\Controller::class ) ->disableOriginalConstructor() ->getMock(); $this->dispatcher = $this->getMockBuilder( - 'OC\AppFramework\Http\Dispatcher' + \OC\AppFramework\Http\Dispatcher::class ) ->disableOriginalConstructor() ->getMock(); - $this->io = $this->getMockBuilder('OCP\\AppFramework\\Http\\IOutput')->getMock(); + $this->io = $this->getMockBuilder(\OCP\AppFramework\Http\IOutput::class)->getMock(); $this->headers = ['key' => 'value']; $this->output = 'hi'; @@ -75,7 +75,7 @@ protected function setUp(): void { $this->container[$this->controllerName] = $this->controller; $this->container['Dispatcher'] = $this->dispatcher; - $this->container['OCP\\AppFramework\\Http\\IOutput'] = $this->io; + $this->container[\OCP\AppFramework\Http\IOutput::class] = $this->io; $this->container['urlParams'] = []; $this->appPath = __DIR__ . '/../../../apps/namespacetestapp'; @@ -146,7 +146,7 @@ public function testOutputIsPrinted() { } public function testCallbackIsCalled() { - $mock = $this->getMockBuilder('OCP\AppFramework\Http\ICallbackResponse') + $mock = $this->getMockBuilder(\OCP\AppFramework\Http\ICallbackResponse::class) ->getMock(); $return = [null, [], [], $this->output, $mock]; diff --git a/tests/lib/AppFramework/Controller/ApiControllerTest.php b/tests/lib/AppFramework/Controller/ApiControllerTest.php index 974d733eb1c8..cb85ebdb6985 100644 --- a/tests/lib/AppFramework/Controller/ApiControllerTest.php +++ b/tests/lib/AppFramework/Controller/ApiControllerTest.php @@ -36,8 +36,8 @@ class ApiControllerTest extends \Test\TestCase { public function testCors() { $request = new Request( ['server' => ['HTTP_ORIGIN' => 'test']], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') + $this->createMock('\\' . \OCP\Security\ISecureRandom::class), + $this->createMock('\\' . \OCP\IConfig::class) ); $this->controller = new ChildApiController( 'app', diff --git a/tests/lib/AppFramework/Controller/ControllerTest.php b/tests/lib/AppFramework/Controller/ControllerTest.php index ccc4b50add21..fca546ea4e02 100644 --- a/tests/lib/AppFramework/Controller/ControllerTest.php +++ b/tests/lib/AppFramework/Controller/ControllerTest.php @@ -36,15 +36,11 @@ class ChildController extends Controller { public function __construct($appName, $request) { parent::__construct($appName, $request); - $this->registerResponder('tom', function ($response) { - return 'hi'; - }); + $this->registerResponder('tom', fn ($response) => 'hi'); } public function custom($in) { - $this->registerResponder('json', function ($response) { - return new JSONResponse([\strlen($response)]); - }); + $this->registerResponder('json', fn ($response) => new JSONResponse([\strlen($response)])); return $in; } @@ -61,10 +57,9 @@ public function customDataResponse($in) { }; class ControllerTest extends TestCase { - /** @var ChildController */ - private $controller; + private \Test\AppFramework\Controller\ChildController $controller; /** @var DIContainer */ - private $app; + private \PHPUnit\Framework\MockObject\MockObject $app; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/AppFramework/Db/MapperTest.php b/tests/lib/AppFramework/Db/MapperTest.php index 4a4473d77ce4..c5d901dd0ba9 100644 --- a/tests/lib/AppFramework/Db/MapperTest.php +++ b/tests/lib/AppFramework/Db/MapperTest.php @@ -65,7 +65,7 @@ class MapperTest extends MapperTestUtility { /** * @var Mapper */ - private $mapper; + private \Test\AppFramework\Db\ExampleMapper $mapper; protected function setUp(): void { parent::setUp(); @@ -102,7 +102,7 @@ public function testFindNotFound() { $rows = []; $this->setMapperResult($sql, $params, $rows); $this->expectException( - '\OCP\AppFramework\Db\DoesNotExistException' + '\\' . \OCP\AppFramework\Db\DoesNotExistException::class ); $this->mapper->find($sql, $params); } @@ -113,7 +113,7 @@ public function testFindEntityNotFound() { $rows = []; $this->setMapperResult($sql, $params, $rows, null, null, true); $this->expectException( - '\OCP\AppFramework\Db\DoesNotExistException' + '\\' . \OCP\AppFramework\Db\DoesNotExistException::class ); $this->mapper->findOneEntity($sql, $params); } @@ -126,7 +126,7 @@ public function testFindMultiple() { ]; $this->setMapperResult($sql, $params, $rows, null, null, true); $this->expectException( - '\OCP\AppFramework\Db\MultipleObjectsReturnedException' + '\\' . \OCP\AppFramework\Db\MultipleObjectsReturnedException::class ); $this->mapper->find($sql, $params); } @@ -139,7 +139,7 @@ public function testFindEntityMultiple() { ]; $this->setMapperResult($sql, $params, $rows, null, null, true); $this->expectException( - '\OCP\AppFramework\Db\MultipleObjectsReturnedException' + '\\' . \OCP\AppFramework\Db\MultipleObjectsReturnedException::class ); $this->mapper->findOneEntity($sql, $params); } diff --git a/tests/lib/AppFramework/Db/MapperTestUtility.php b/tests/lib/AppFramework/Db/MapperTestUtility.php index 6019fbbd1dc3..442833c20e8d 100644 --- a/tests/lib/AppFramework/Db/MapperTestUtility.php +++ b/tests/lib/AppFramework/Db/MapperTestUtility.php @@ -28,8 +28,8 @@ */ abstract class MapperTestUtility extends \Test\TestCase { protected $db; - private $query; - private $fetchAt; + private \PHPUnit\Framework\MockObject\MockObject $query; + private int $fetchAt; private $iterators; /** @@ -40,7 +40,7 @@ protected function setUp(): void { parent::setUp(); $this->db = $this->getMockBuilder( - '\OCP\IDBConnection' + '\\' . \OCP\IDBConnection::class ) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php index d035fc697386..ae114c7e62eb 100644 --- a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php +++ b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php @@ -29,15 +29,15 @@ class DIContainerTest extends \Test\TestCase { private $container; - private $api; + private \PHPUnit\Framework\MockObject\MockObject $api; protected function setUp(): void { parent::setUp(); - $this->container = $this->getMockBuilder('OC\AppFramework\DependencyInjection\DIContainer') + $this->container = $this->getMockBuilder(\OC\AppFramework\DependencyInjection\DIContainer::class) ->setMethods(['isAdminUser']) ->setConstructorArgs(['name']) ->getMock(); - $this->api = $this->getMockBuilder('OC\AppFramework\Core\API') + $this->api = $this->getMockBuilder(\OC\AppFramework\Core\API::class) ->setConstructorArgs(['hi']) ->getMock(); } @@ -69,8 +69,8 @@ public function testAppNameIsSetCorrectly() { public function testMiddlewareDispatcherIncludesSecurityMiddleware() { $this->container['Request'] = new Request( ['method' => 'GET'], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') + $this->createMock('\\' . \OCP\Security\ISecureRandom::class), + $this->createMock('\\' . \OCP\IConfig::class) ); $security = $this->container['SecurityMiddleware']; $dispatcher = $this->container['MiddlewareDispatcher']; diff --git a/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php b/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php index 4fcf7d712d56..43a00a00a0a7 100644 --- a/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php +++ b/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php @@ -17,8 +17,7 @@ * @package OC\AppFramework\Http */ class ContentSecurityPolicyTest extends TestCase { - /** @var ContentSecurityPolicy */ - private $contentSecurityPolicy; + private \OCP\AppFramework\Http\ContentSecurityPolicy $contentSecurityPolicy; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/AppFramework/Http/DataResponseTest.php b/tests/lib/AppFramework/Http/DataResponseTest.php index 2509b63b2507..f1a897733335 100644 --- a/tests/lib/AppFramework/Http/DataResponseTest.php +++ b/tests/lib/AppFramework/Http/DataResponseTest.php @@ -28,10 +28,7 @@ use Test\TestCase; class DataResponseTest extends TestCase { - /** - * @var DataResponse - */ - private $response; + private \OCP\AppFramework\Http\DataResponse $response; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/AppFramework/Http/DispatcherTest.php b/tests/lib/AppFramework/Http/DispatcherTest.php index 81640667052f..6c268ea67f23 100644 --- a/tests/lib/AppFramework/Http/DispatcherTest.php +++ b/tests/lib/AppFramework/Http/DispatcherTest.php @@ -50,9 +50,7 @@ public function __construct($appName, $request) { * @return array */ public function exec($int, $bool, $test=4, $test2=1) { - $this->registerResponder('text', function ($in) { - return new JSONResponse(['text' => $in]); - }); + $this->registerResponder('text', fn ($in) => new JSONResponse(['text' => $in])); return [$int, $bool, $test, $test2]; } @@ -72,54 +70,54 @@ public function execDataResponse($int, $bool, $test=4, $test2=1) { class DispatcherTest extends \Test\TestCase { /** @var MiddlewareDispatcher | \PHPUnit\Framework\MockObject\MockObject */ - private $middlewareDispatcher; + private \PHPUnit\Framework\MockObject\MockObject $middlewareDispatcher; /** @var Dispatcher | \PHPUnit\Framework\MockObject\MockObject */ - private $dispatcher; - private $controllerMethod; + private \OC\AppFramework\Http\Dispatcher $dispatcher; + private string $controllerMethod; /** @var Response | \PHPUnit\Framework\MockObject\MockObject */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; private $request; - private $lastModified; - private $etag; + private \DateTime $lastModified; + private string $etag; /** @var Http | \PHPUnit\Framework\MockObject\MockObject */ - private $http; - private $reflector; + private \PHPUnit\Framework\MockObject\MockObject $http; + private \OC\AppFramework\Utility\ControllerMethodReflector $reflector; /** @var Controller | \PHPUnit\Framework\MockObject\MockObject */ - private $controller; + private \PHPUnit\Framework\MockObject\MockObject $controller; protected function setUp(): void { parent::setUp(); $this->controllerMethod = 'test'; $app = $this->getMockBuilder( - 'OC\AppFramework\DependencyInjection\DIContainer' + \OC\AppFramework\DependencyInjection\DIContainer::class ) ->disableOriginalConstructor() ->getMock(); $request = $this->getMockBuilder( - '\OC\AppFramework\Http\Request' + '\\' . \OC\AppFramework\Http\Request::class ) ->disableOriginalConstructor() ->getMock(); $this->http = $this->getMockBuilder( - '\OC\AppFramework\Http' + '\\' . \OC\AppFramework\Http::class ) ->disableOriginalConstructor() ->getMock(); $this->middlewareDispatcher = $this->getMockBuilder( - '\OC\AppFramework\Middleware\MiddlewareDispatcher' + '\\' . \OC\AppFramework\Middleware\MiddlewareDispatcher::class ) ->disableOriginalConstructor() ->getMock(); - $this->controller = $this->getMockBuilder('\OCP\AppFramework\Controller') + $this->controller = $this->getMockBuilder('\\' . \OCP\AppFramework\Controller::class) ->setMethods([$this->controllerMethod]) ->setConstructorArgs([$app, $request]) ->getMock(); $this->request = $this->getMockBuilder( - '\OC\AppFramework\Http\Request' + '\\' . \OC\AppFramework\Http\Request::class ) ->disableOriginalConstructor() ->getMock(); @@ -134,7 +132,7 @@ protected function setUp(): void { ); $this->response = $this->getMockBuilder( - '\OCP\AppFramework\Http\Response' + '\\' . \OCP\AppFramework\Http\Response::class ) ->disableOriginalConstructor() ->getMock(); @@ -309,14 +307,10 @@ private function dispatcherPassthrough() { ->method('beforeController'); $this->middlewareDispatcher->expects($this->once()) ->method('afterController') - ->will($this->returnCallback(function ($a, $b, $in) { - return $in; - })); + ->will($this->returnCallback(fn ($a, $b, $in) => $in)); $this->middlewareDispatcher->expects($this->once()) ->method('beforeOutput') - ->will($this->returnCallback(function ($a, $b, $in) { - return $in; - })); + ->will($this->returnCallback(fn ($a, $b, $in) => $in)); } public function testControllerParametersInjected() { @@ -328,8 +322,8 @@ public function testControllerParametersInjected() { ], 'method' => 'POST' ], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') + $this->createMock('\\' . \OCP\Security\ISecureRandom::class), + $this->createMock('\\' . \OCP\IConfig::class) ); $this->dispatcher = new Dispatcher( $this->http, @@ -356,8 +350,8 @@ public function testControllerParametersInjectedDefaultOverwritten() { ], 'method' => 'POST', ], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') + $this->createMock('\\' . \OCP\Security\ISecureRandom::class), + $this->createMock('\\' . \OCP\IConfig::class) ); $this->dispatcher = new Dispatcher( $this->http, @@ -386,8 +380,8 @@ public function testResponseTransformedByUrlFormat() { ], 'method' => 'GET' ], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') + $this->createMock('\\' . \OCP\Security\ISecureRandom::class), + $this->createMock('\\' . \OCP\IConfig::class) ); $this->dispatcher = new Dispatcher( $this->http, @@ -416,8 +410,8 @@ public function testResponseTransformsDataResponse() { ], 'method' => 'GET' ], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') + $this->createMock('\\' . \OCP\Security\ISecureRandom::class), + $this->createMock('\\' . \OCP\IConfig::class) ); $this->dispatcher = new Dispatcher( $this->http, @@ -447,8 +441,8 @@ public function testResponseTransformedByAcceptHeader() { ], 'method' => 'PUT' ], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') + $this->createMock('\\' . \OCP\Security\ISecureRandom::class), + $this->createMock('\\' . \OCP\IConfig::class) ); $this->dispatcher = new Dispatcher( $this->http, @@ -480,8 +474,8 @@ public function testResponsePrimarilyTransformedByParameterFormat() { ], 'method' => 'POST' ], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') + $this->createMock('\\' . \OCP\Security\ISecureRandom::class), + $this->createMock('\\' . \OCP\IConfig::class) ); $this->dispatcher = new Dispatcher( $this->http, diff --git a/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php b/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php index 6928775b514f..c18f8f5f912f 100644 --- a/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php +++ b/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php @@ -17,8 +17,7 @@ * @package OC\AppFramework\Http */ class EmptyContentSecurityPolicyTest extends TestCase { - /** @var EmptyContentSecurityPolicy */ - private $contentSecurityPolicy; + private \OCP\AppFramework\Http\EmptyContentSecurityPolicy $contentSecurityPolicy; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/AppFramework/Http/HttpTest.php b/tests/lib/AppFramework/Http/HttpTest.php index 881f9b0d1271..768b92b37359 100644 --- a/tests/lib/AppFramework/Http/HttpTest.php +++ b/tests/lib/AppFramework/Http/HttpTest.php @@ -26,12 +26,9 @@ use OC\AppFramework\Http; class HttpTest extends \Test\TestCase { - private $server; + private array $server; - /** - * @var Http - */ - private $http; + private \OC\AppFramework\Http $http; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/AppFramework/Http/JSONResponseTest.php b/tests/lib/AppFramework/Http/JSONResponseTest.php index 037b43a35ea5..ce9e86c566f5 100644 --- a/tests/lib/AppFramework/Http/JSONResponseTest.php +++ b/tests/lib/AppFramework/Http/JSONResponseTest.php @@ -29,10 +29,7 @@ use OCP\AppFramework\Http\JSONResponse; class JSONResponseTest extends \Test\TestCase { - /** - * @var JSONResponse - */ - private $json; + private \OCP\AppFramework\Http\JSONResponse $json; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/AppFramework/Http/RequestTest.php b/tests/lib/AppFramework/Http/RequestTest.php index 24aecbe42af6..5b36e0f9befd 100644 --- a/tests/lib/AppFramework/Http/RequestTest.php +++ b/tests/lib/AppFramework/Http/RequestTest.php @@ -39,11 +39,11 @@ protected function setUp(): void { if (\in_array('fakeinput', \stream_get_wrappers())) { \stream_wrapper_unregister('fakeinput'); } - \stream_wrapper_register('fakeinput', 'Test\AppFramework\Http\RequestStream'); + \stream_wrapper_register('fakeinput', \Test\AppFramework\Http\RequestStream::class); - $this->secureRandom = $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock(); - $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); - $this->csrfTokenManager = $this->getMockBuilder('\OC\Security\CSRF\CsrfTokenManager') + $this->secureRandom = $this->getMockBuilder('\\' . \OCP\Security\ISecureRandom::class)->getMock(); + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class)->getMock(); + $this->csrfTokenManager = $this->getMockBuilder('\\' . \OC\Security\CSRF\CsrfTokenManager::class) ->disableOriginalConstructor()->getMock(); } @@ -1449,7 +1449,7 @@ public function testGetRequestUriWithOverwrite($expectedUri, $overwriteWebRoot, ); /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->getMockBuilder('\OC\AppFramework\Http\Request') + $request = $this->getMockBuilder('\\' . \OC\AppFramework\Http\Request::class) ->setMethods(['getScriptName']) ->setConstructorArgs([ [ @@ -1474,7 +1474,7 @@ public function testGetRequestUriWithOverwrite($expectedUri, $overwriteWebRoot, public function testPassesCSRFCheckWithGet() { /** @var Request $request */ - $request = $this->getMockBuilder('\OC\AppFramework\Http\Request') + $request = $this->getMockBuilder('\\' . \OC\AppFramework\Http\Request::class) ->setMethods(['getScriptName']) ->setConstructorArgs([ [ @@ -1500,7 +1500,7 @@ public function testPassesCSRFCheckWithGet() { public function testPassesCSRFCheckWithPost() { /** @var Request $request */ - $request = $this->getMockBuilder('\OC\AppFramework\Http\Request') + $request = $this->getMockBuilder('\\' . \OC\AppFramework\Http\Request::class) ->setMethods(['getScriptName']) ->setConstructorArgs([ [ @@ -1526,7 +1526,7 @@ public function testPassesCSRFCheckWithPost() { public function testPassesCSRFCheckWithHeader() { /** @var Request $request */ - $request = $this->getMockBuilder('\OC\AppFramework\Http\Request') + $request = $this->getMockBuilder('\\' . \OC\AppFramework\Http\Request::class) ->setMethods(['getScriptName']) ->setConstructorArgs([ [ @@ -1568,7 +1568,7 @@ public function invalidTokenDataProvider() { */ public function testPassesCSRFCheckWithInvalidToken($invalidToken) { /** @var Request $request */ - $request = $this->getMockBuilder('\OC\AppFramework\Http\Request') + $request = $this->getMockBuilder('\\' . \OC\AppFramework\Http\Request::class) ->setMethods(['getScriptName']) ->setConstructorArgs([ [ @@ -1595,7 +1595,7 @@ public function testPassesCSRFCheckWithInvalidToken($invalidToken) { public function testPassesCSRFCheckWithoutTokenFail() { /** @var Request $request */ - $request = $this->getMockBuilder('\OC\AppFramework\Http\Request') + $request = $this->getMockBuilder('\\' . \OC\AppFramework\Http\Request::class) ->setMethods(['getScriptName']) ->setConstructorArgs([ [], diff --git a/tests/lib/AppFramework/Http/ResponseTest.php b/tests/lib/AppFramework/Http/ResponseTest.php index 2d17ba9ab659..8aff5b850bea 100644 --- a/tests/lib/AppFramework/Http/ResponseTest.php +++ b/tests/lib/AppFramework/Http/ResponseTest.php @@ -31,10 +31,7 @@ use Test\TestCase; class ResponseTest extends TestCase { - /** - * @var \OCP\AppFramework\Http\Response - */ - private $childResponse; + private \OCP\AppFramework\Http\Response $childResponse; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/AppFramework/Http/StreamResponseTest.php b/tests/lib/AppFramework/Http/StreamResponseTest.php index 1050634b0952..7cac9f20be7d 100644 --- a/tests/lib/AppFramework/Http/StreamResponseTest.php +++ b/tests/lib/AppFramework/Http/StreamResponseTest.php @@ -29,11 +29,11 @@ class StreamResponseTest extends \Test\TestCase { /** @var IOutput */ - private $output; + private \PHPUnit\Framework\MockObject\MockObject $output; protected function setUp(): void { parent::setUp(); - $this->output = $this->createMock('OCP\\AppFramework\\Http\\IOutput'); + $this->output = $this->createMock(\OCP\AppFramework\Http\IOutput::class); } public function testOutputNotModified() { diff --git a/tests/lib/AppFramework/Http/TemplateResponseTest.php b/tests/lib/AppFramework/Http/TemplateResponseTest.php index ae569ee2c159..6d8ee3d31fac 100644 --- a/tests/lib/AppFramework/Http/TemplateResponseTest.php +++ b/tests/lib/AppFramework/Http/TemplateResponseTest.php @@ -28,16 +28,15 @@ use Test\TestCase; class TemplateResponseTest extends TestCase { - /** @var \OCP\AppFramework\Http\TemplateResponse */ - private $tpl; + private \OCP\AppFramework\Http\TemplateResponse $tpl; /** @var \OCP\AppFramework\IApi */ - private $api; + private \PHPUnit\Framework\MockObject\MockObject $api; protected function setUp(): void { parent::setUp(); - $this->api = $this->getMockBuilder('OC\AppFramework\Core\API') + $this->api = $this->getMockBuilder(\OC\AppFramework\Core\API::class) ->setMethods(['getAppName']) ->setConstructorArgs(['test']) ->getMock(); diff --git a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php index b0056d85cc6e..a70b1c2c496a 100644 --- a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php +++ b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php @@ -100,14 +100,11 @@ public function beforeOutput($controller, $methodName, $output) { class MiddlewareDispatcherTest extends \Test\TestCase { public $exception; public $response; - private $out; - private $method; + private string $out; + private string $method; private $controller; - /** - * @var MiddlewareDispatcher - */ - private $dispatcher; + private \OC\AppFramework\Middleware\MiddlewareDispatcher $dispatcher; protected function setUp(): void { parent::setUp(); @@ -122,15 +119,7 @@ protected function setUp(): void { private function getControllerMock() { return $this->createMock( - 'OCP\AppFramework\Controller', - ['method'], - ['app', - new Request( - ['method' => 'GET'], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') - ) - ] + \OCP\AppFramework\Controller::class ); } @@ -143,15 +132,13 @@ private function getMiddleware($beforeControllerThrowsEx=false) { public function testAfterExceptionShouldReturnResponseOfMiddleware() { $response = new Response(); $m1 = $this->createMock( - '\OCP\AppFramework\Middleware', - ['afterException', 'beforeController'] + '\\' . \OCP\AppFramework\Middleware::class ); $m1->expects($this->never()) ->method('afterException'); $m2 = $this->createMock( - 'OCP\AppFramework\Middleware', - ['afterException', 'beforeController'] + \OCP\AppFramework\Middleware::class ); $m2->expects($this->once()) ->method('afterException') @@ -262,7 +249,7 @@ public function testBeforeOutputOrder() { public function testExceptionShouldRunAfterExceptionOfOnlyPreviouslyExecutedMiddlewares() { $m1 = $this->getMiddleware(); $m2 = $this->getMiddleware(true); - $m3 = $this->createMock('\OCP\AppFramework\Middleware'); + $m3 = $this->createMock('\\' . \OCP\AppFramework\Middleware::class); $m3->expects($this->never()) ->method('afterException'); $m3->expects($this->never()) diff --git a/tests/lib/AppFramework/Middleware/MiddlewareTest.php b/tests/lib/AppFramework/Middleware/MiddlewareTest.php index 413a81c2a46c..c195ecbee389 100644 --- a/tests/lib/AppFramework/Middleware/MiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/MiddlewareTest.php @@ -34,12 +34,12 @@ class MiddlewareTest extends \Test\TestCase { /** * @var Middleware */ - private $middleware; - private $controller; - private $exception; - private $api; + private \Test\AppFramework\Middleware\ChildMiddleware $middleware; + private \PHPUnit\Framework\MockObject\MockObject $controller; + private \Exception $exception; + private \PHPUnit\Framework\MockObject\MockObject $api; /** @var Response */ - private $response; + private \PHPUnit\Framework\MockObject\MockObject $response; protected function setUp(): void { parent::setUp(); @@ -47,25 +47,16 @@ protected function setUp(): void { $this->middleware = new ChildMiddleware(); $this->api = $this->getMockBuilder( - 'OC\AppFramework\DependencyInjection\DIContainer' + \OC\AppFramework\DependencyInjection\DIContainer::class ) ->disableOriginalConstructor() ->getMock(); $this->controller = $this->createMock( - 'OCP\AppFramework\Controller', - [], - [ - $this->api, - new Request( - [], - $this->createMock('\OCP\Security\ISecureRandom'), - $this->createMock('\OCP\IConfig') - ) - ] + \OCP\AppFramework\Controller::class ); $this->exception = new \Exception(); - $this->response = $this->createMock('OCP\AppFramework\Http\Response'); + $this->response = $this->createMock(\OCP\AppFramework\Http\Response::class); } public function testBeforeController() { diff --git a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php index 55eaf9add9f4..67bcef8832fd 100644 --- a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php @@ -27,14 +27,13 @@ * Class CORSMiddlewareTest */ class CORSMiddlewareTest extends \Test\TestCase { - /** @var ControllerMethodReflector */ - private $reflector; + private \OC\AppFramework\Utility\ControllerMethodReflector $reflector; /** @var Session */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject*/ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUserSession */ - private $fakeSession; + private \PHPUnit\Framework\MockObject\MockObject $fakeSession; public function providesConfigForPublicPageTest() { return [ diff --git a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php index 07aee1ceb9ca..fdbbae7ea8e6 100644 --- a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php @@ -56,23 +56,23 @@ class SecurityMiddlewareTest extends TestCase { /** @var SecurityMiddleware */ private $middleware; /** @var Controller | \PHPUnit\Framework\MockObject\MockObject */ - private $controller; - private $secException; - private $secAjaxException; + private \PHPUnit\Framework\MockObject\MockObject $controller; + private \OC\AppFramework\Middleware\Security\Exceptions\SecurityException $secException; + private \OC\AppFramework\Middleware\Security\Exceptions\SecurityException $secAjaxException; /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ private $request; /** @var ControllerMethodReflector | \PHPUnit\Framework\MockObject\MockObject */ - private $reader; + private \OC\AppFramework\Utility\ControllerMethodReflector $reader; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var INavigationManager | \PHPUnit\Framework\MockObject\MockObject */ - private $navigationManager; + private \PHPUnit\Framework\MockObject\MockObject $navigationManager; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var ContentSecurityPolicyManager | \PHPUnit\Framework\MockObject\MockObject */ - private $contentSecurityPolicyManager; + private \PHPUnit\Framework\MockObject\MockObject $contentSecurityPolicyManager; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $session; + private ?\PHPUnit\Framework\MockObject\MockObject $session = null; protected function setUp(): void { parent::setUp(); @@ -143,8 +143,8 @@ public function testSetNavigationEntry() { ->method('setActiveEntry') ->with($this->equalTo('files')); - $this->reader->reflect(__CLASS__, __FUNCTION__); - $this->middleware->beforeController(__CLASS__, __FUNCTION__); + $this->reader->reflect(self::class, __FUNCTION__); + $this->middleware->beforeController(self::class, __FUNCTION__); } /** @@ -165,8 +165,8 @@ private function ajaxExceptionStatus($method, $test, $status) { $sec = $this->getMiddleware($isLoggedIn, $isAdminUser); try { - $this->reader->reflect(__CLASS__, $method); - $sec->beforeController(__CLASS__, $method); + $this->reader->reflect(self::class, $method); + $sec->beforeController(self::class, $method); } catch (SecurityException $ex) { $this->assertEquals($status, $ex->getCode()); } @@ -254,8 +254,8 @@ public function testNoChecks() { $sec = $this->getMiddleware(false, false); - $this->reader->reflect(__CLASS__, __FUNCTION__); - $sec->beforeController(__CLASS__, __FUNCTION__); + $this->reader->reflect(self::class, __FUNCTION__); + $sec->beforeController(self::class, __FUNCTION__); } /** @@ -283,8 +283,8 @@ private function securityCheck($method, $expects, $shouldFail=false) { $this->assertTrue(true); } - $this->reader->reflect(__CLASS__, $method); - $sec->beforeController(__CLASS__, $method); + $this->reader->reflect(self::class, $method); + $sec->beforeController(self::class, $method); } /** @@ -299,8 +299,8 @@ public function testCsrfCheck() { ->method('passesCSRFCheck') ->will($this->returnValue(false)); - $this->reader->reflect(__CLASS__, __FUNCTION__); - $this->middleware->beforeController(__CLASS__, __FUNCTION__); + $this->reader->reflect(self::class, __FUNCTION__); + $this->middleware->beforeController(self::class, __FUNCTION__); } /** @@ -314,8 +314,8 @@ public function testNoCsrfCheck() { ->method('passesCSRFCheck') ->will($this->returnValue(false)); - $this->reader->reflect(__CLASS__, __FUNCTION__); - $this->middleware->beforeController(__CLASS__, __FUNCTION__); + $this->reader->reflect(self::class, __FUNCTION__); + $this->middleware->beforeController(self::class, __FUNCTION__); } /** @@ -328,8 +328,8 @@ public function testFailCsrfCheck() { ->method('passesCSRFCheck') ->will($this->returnValue(true)); - $this->reader->reflect(__CLASS__, __FUNCTION__); - $this->middleware->beforeController(__CLASS__, __FUNCTION__); + $this->reader->reflect(self::class, __FUNCTION__); + $this->middleware->beforeController(self::class, __FUNCTION__); } /** @@ -346,8 +346,8 @@ public function testFailCsrfCheckWithoutAuthHeader(): void { ->method('getHeader') ->willReturn(''); - $this->reader->reflect(__CLASS__, __FUNCTION__); - $this->middleware->beforeController(__CLASS__, __FUNCTION__); + $this->reader->reflect(self::class, __FUNCTION__); + $this->middleware->beforeController(self::class, __FUNCTION__); } /** diff --git a/tests/lib/AppFramework/Middleware/SessionMiddlewareTest.php b/tests/lib/AppFramework/Middleware/SessionMiddlewareTest.php index 66e4f5dfcb6f..f0bb58db3a83 100644 --- a/tests/lib/AppFramework/Middleware/SessionMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/SessionMiddlewareTest.php @@ -17,23 +17,17 @@ use OCP\AppFramework\Http\Response; class SessionMiddlewareTest extends \Test\TestCase { - /** - * @var ControllerMethodReflector - */ - private $reflector; + private \OC\AppFramework\Utility\ControllerMethodReflector $reflector; - /** - * @var Request - */ - private $request; + private \OC\AppFramework\Http\Request $request; protected function setUp(): void { parent::setUp(); $this->request = new Request( [], - $this->getMockBuilder('\OCP\Security\ISecureRandom')->getMock(), - $this->createMock('\OCP\IConfig') + $this->getMockBuilder('\\' . \OCP\Security\ISecureRandom::class)->getMock(), + $this->createMock('\\' . \OCP\IConfig::class) ); $this->reflector = new ControllerMethodReflector(); } @@ -80,7 +74,7 @@ public function testSessionNotClosedOnAfterController() { * @return mixed */ private function getSessionMock($expectedCloseCount) { - $session = $this->getMockBuilder('\OC\Session\Memory') + $session = $this->getMockBuilder('\\' . \OC\Session\Memory::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/AppFramework/Routing/RoutingTest.php b/tests/lib/AppFramework/Routing/RoutingTest.php index c6212c6f1c4e..717896af7a26 100644 --- a/tests/lib/AppFramework/Routing/RoutingTest.php +++ b/tests/lib/AppFramework/Routing/RoutingTest.php @@ -65,7 +65,7 @@ public function testSimpleRouteWithBrokenName() { ]]; // router mock - $router = $this->createMock("\OC\Route\Router", ['create'], [\OC::$server->getLogger()]); + $router = $this->createMock('\\' . \OC\Route\Router::class); // load route configuration $container = new DIContainer('app1'); @@ -111,7 +111,7 @@ private function assertSimpleRoute($routes, $name, $verb, $url, $controllerName, $route = $this->mockRoute($container, $verb, $controllerName, $actionName, $requirements, $defaults); // router mock - $router = $this->createMock("\OC\Route\Router", ['create'], [\OC::$server->getLogger()]); + $router = $this->createMock('\\' . \OC\Route\Router::class); // we expect create to be called once: $router @@ -134,7 +134,7 @@ private function assertSimpleRoute($routes, $name, $verb, $url, $controllerName, */ private function assertResource($yaml, $resourceName, $url, $controllerName, $paramName) { // router mock - $router = $this->createMock("\OC\Route\Router", ['create'], [\OC::$server->getLogger()]); + $router = $this->createMock('\\' . \OC\Route\Router::class); // route mocks $container = new DIContainer('app1'); @@ -187,7 +187,7 @@ private function mockRoute( array $requirements= [], array $defaults= [] ) { - $route = $this->createMock("\OC\Route\Route", ['method', 'action', 'requirements', 'defaults'], [], '', false); + $route = $this->createMock('\\' . \OC\Route\Route::class); $route ->expects($this->exactly(1)) ->method('method') diff --git a/tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php b/tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php index 6cab1ecb9833..2356a2809d9d 100644 --- a/tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php +++ b/tests/lib/AppFramework/Utility/ControllerMethodReflectorTest.php @@ -66,7 +66,7 @@ class ControllerMethodReflectorTest extends \Test\TestCase { public function testReadAnnotation() { $reader = new ControllerMethodReflector(); $reader->reflect( - '\Test\AppFramework\Utility\ControllerMethodReflectorTest', + '\\' . \Test\AppFramework\Utility\ControllerMethodReflectorTest::class, 'testReadAnnotation' ); @@ -80,7 +80,7 @@ public function testReadAnnotation() { public function testReadAnnotationNoLowercase() { $reader = new ControllerMethodReflector(); $reader->reflect( - '\Test\AppFramework\Utility\ControllerMethodReflectorTest', + '\\' . \Test\AppFramework\Utility\ControllerMethodReflectorTest::class, 'testReadAnnotationNoLowercase' ); @@ -95,7 +95,7 @@ public function testReadAnnotationNoLowercase() { public function testReadTypeIntAnnotations() { $reader = new ControllerMethodReflector(); $reader->reflect( - '\Test\AppFramework\Utility\ControllerMethodReflectorTest', + '\\' . \Test\AppFramework\Utility\ControllerMethodReflectorTest::class, 'testReadTypeIntAnnotations' ); @@ -116,7 +116,7 @@ public function arguments3($a, float $b, int $c, $d) { public function testReadTypeIntAnnotationsScalarTypes() { $reader = new ControllerMethodReflector(); $reader->reflect( - '\Test\AppFramework\Utility\ControllerMethodReflectorTest', + '\\' . \Test\AppFramework\Utility\ControllerMethodReflectorTest::class, 'arguments3' ); @@ -133,7 +133,7 @@ public function testReadTypeIntAnnotationsScalarTypes() { public function testReadTypeDoubleAnnotations() { $reader = new ControllerMethodReflector(); $reader->reflect( - '\Test\AppFramework\Utility\ControllerMethodReflectorTest', + '\\' . \Test\AppFramework\Utility\ControllerMethodReflectorTest::class, 'testReadTypeDoubleAnnotations' ); @@ -147,7 +147,7 @@ public function testReadTypeDoubleAnnotations() { public function testReadTypeWhitespaceAnnotations() { $reader = new ControllerMethodReflector(); $reader->reflect( - '\Test\AppFramework\Utility\ControllerMethodReflectorTest', + '\\' . \Test\AppFramework\Utility\ControllerMethodReflectorTest::class, 'testReadTypeWhitespaceAnnotations' ); @@ -159,7 +159,7 @@ public function arguments($arg, $arg2='hi') { public function testReflectParameters() { $reader = new ControllerMethodReflector(); $reader->reflect( - '\Test\AppFramework\Utility\ControllerMethodReflectorTest', + '\\' . \Test\AppFramework\Utility\ControllerMethodReflectorTest::class, 'arguments' ); @@ -171,7 +171,7 @@ public function arguments2($arg) { public function testReflectParameters2() { $reader = new ControllerMethodReflector(); $reader->reflect( - '\Test\AppFramework\Utility\ControllerMethodReflectorTest', + '\\' . \Test\AppFramework\Utility\ControllerMethodReflectorTest::class, 'arguments2' ); @@ -180,14 +180,14 @@ public function testReflectParameters2() { public function testInheritance() { $reader = new ControllerMethodReflector(); - $reader->reflect('Test\AppFramework\Utility\EndController', 'test'); + $reader->reflect(\Test\AppFramework\Utility\EndController::class, 'test'); $this->assertTrue($reader->hasAnnotation('Annotation')); } public function testInheritanceOverride() { $reader = new ControllerMethodReflector(); - $reader->reflect('Test\AppFramework\Utility\EndController', 'test2'); + $reader->reflect(\Test\AppFramework\Utility\EndController::class, 'test2'); $this->assertTrue($reader->hasAnnotation('NoAnnotation')); $this->assertFalse($reader->hasAnnotation('Annotation')); @@ -195,7 +195,7 @@ public function testInheritanceOverride() { public function testInheritanceOverrideNoDocblock() { $reader = new ControllerMethodReflector(); - $reader->reflect('Test\AppFramework\Utility\EndController', 'test3'); + $reader->reflect(\Test\AppFramework\Utility\EndController::class, 'test3'); $this->assertFalse($reader->hasAnnotation('Annotation')); } diff --git a/tests/lib/AppFramework/Utility/SimpleContainerTest.php b/tests/lib/AppFramework/Utility/SimpleContainerTest.php index bc6a3f464b55..5557c3e1bb4c 100644 --- a/tests/lib/AppFramework/Utility/SimpleContainerTest.php +++ b/tests/lib/AppFramework/Utility/SimpleContainerTest.php @@ -58,8 +58,7 @@ public function __construct(IInterfaceConstructor $class, $test) { } class SimpleContainerTest extends \Test\TestCase { - /** @var SimpleContainer */ - private $container; + private \OC\AppFramework\Utility\SimpleContainer $container; public function setUp(): void { $this->container = new SimpleContainer(); @@ -83,24 +82,24 @@ public function testNothingRegistered() { public function testNotAClass() { $this->expectException(\OCP\AppFramework\QueryException::class); - $this->container->query('Test\AppFramework\Utility\TestInterface'); + $this->container->query(\Test\AppFramework\Utility\TestInterface::class); } public function testNoConstructorClass() { - $object = $this->container->query('Test\AppFramework\Utility\ClassEmptyConstructor'); + $object = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class); $this->assertInstanceOf(ClassEmptyConstructor::class, $object); } public function testInstancesOnlyOnce() { - $object = $this->container->query('Test\AppFramework\Utility\ClassEmptyConstructor'); - $object2 = $this->container->query('Test\AppFramework\Utility\ClassEmptyConstructor'); + $object = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class); + $object2 = $this->container->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class); $this->assertSame($object, $object2); } public function testConstructorSimple() { $this->container->registerParameter('test', 'abc'); $object = $this->container->query( - 'Test\AppFramework\Utility\ClassSimpleConstructor' + \Test\AppFramework\Utility\ClassSimpleConstructor::class ); $this->assertInstanceOf(ClassSimpleConstructor::class, $object); $this->assertEquals('abc', $object->test); @@ -109,7 +108,7 @@ public function testConstructorSimple() { public function testConstructorComplex() { $this->container->registerParameter('test', 'abc'); $object = $this->container->query( - 'Test\AppFramework\Utility\ClassComplexConstructor' + \Test\AppFramework\Utility\ClassComplexConstructor::class ); $this->assertInstanceOf(ClassComplexConstructor::class, $object); $this->assertEquals('abc', $object->class->test); @@ -119,13 +118,11 @@ public function testConstructorComplex() { public function testConstructorComplexInterface() { $this->container->registerParameter('test', 'abc'); $this->container->registerService( - 'Test\AppFramework\Utility\IInterfaceConstructor', - function ($c) { - return $c->query('Test\AppFramework\Utility\ClassSimpleConstructor'); - } + \Test\AppFramework\Utility\IInterfaceConstructor::class, + fn ($c) => $c->query(\Test\AppFramework\Utility\ClassSimpleConstructor::class) ); $object = $this->container->query( - 'Test\AppFramework\Utility\ClassInterfaceConstructor' + \Test\AppFramework\Utility\ClassInterfaceConstructor::class ); $this->assertInstanceOf(ClassInterfaceConstructor::class, $object); $this->assertEquals('abc', $object->class->test); @@ -134,19 +131,15 @@ function ($c) { public function testOverrideService() { $this->container->registerService( - 'Test\AppFramework\Utility\IInterfaceConstructor', - function ($c) { - return $c->query('Test\AppFramework\Utility\ClassSimpleConstructor'); - } + \Test\AppFramework\Utility\IInterfaceConstructor::class, + fn ($c) => $c->query(\Test\AppFramework\Utility\ClassSimpleConstructor::class) ); $this->container->registerService( - 'Test\AppFramework\Utility\IInterfaceConstructor', - function ($c) { - return $c->query('Test\AppFramework\Utility\ClassEmptyConstructor'); - } + \Test\AppFramework\Utility\IInterfaceConstructor::class, + fn ($c) => $c->query(\Test\AppFramework\Utility\ClassEmptyConstructor::class) ); $object = $this->container->query( - 'Test\AppFramework\Utility\IInterfaceConstructor' + \Test\AppFramework\Utility\IInterfaceConstructor::class ); $this->assertInstanceOf(ClassEmptyConstructor::class, $object); } @@ -158,9 +151,7 @@ public function testRegisterAliasParameter() { } public function testRegisterAliasService() { - $this->container->registerService('test', function () { - return new \StdClass; - }, true); + $this->container->registerService('test', fn () => new \StdClass, true); $this->container->registerAlias('test1', 'test'); $this->assertSame( $this->container->query('test'), @@ -189,9 +180,7 @@ public function sanitizeNameProvider() { * @dataProvider sanitizeNameProvider */ public function testSanitizeName($register, $query) { - $this->container->registerService($register, function () { - return 'abc'; - }); + $this->container->registerService($register, fn () => 'abc'); $this->assertEquals('abc', $this->container->query($query)); } @@ -201,14 +190,12 @@ public function testConstructorComplexNoTestParameterFound() { $this->expectException(\OCP\AppFramework\QueryException::class); $object = $this->container->query( - 'Test\AppFramework\Utility\ClassComplexConstructor' + \Test\AppFramework\Utility\ClassComplexConstructor::class ); } public function testRegisterFactory() { - $this->container->registerService('test', function () { - return new \StdClass(); - }, false); + $this->container->registerService('test', fn () => new \StdClass(), false); $this->assertNotSame( $this->container->query('test'), $this->container->query('test') @@ -216,9 +203,7 @@ public function testRegisterFactory() { } public function testRegisterAliasFactory() { - $this->container->registerService('test', function () { - return new \StdClass(); - }, false); + $this->container->registerService('test', fn () => new \StdClass(), false); $this->container->registerAlias('test1', 'test'); $this->assertNotSame( $this->container->query('test'), diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php index 073504b81f25..82250f34e85b 100644 --- a/tests/lib/AppTest.php +++ b/tests/lib/AppTest.php @@ -477,11 +477,7 @@ public function testEnabledAppsCache() { private function setupAppConfigMock() { $appConfig = $this->createMock( - '\OC\AppConfig', - ['getValues'], - [\OC::$server->getDatabaseConnection()], - '', - false + '\\' . \OC\AppConfig::class ); $this->registerAppConfig($appConfig); @@ -494,38 +490,30 @@ private function setupAppConfigMock() { * @param IAppConfig $appConfig app config mock */ private function registerAppConfig(IAppConfig $appConfig) { - \OC::$server->registerService('AppConfig', function ($c) use ($appConfig) { - return $appConfig; - }); - \OC::$server->registerService('AppManager', function (\OC\Server $c) use ($appConfig) { - return new \OC\App\AppManager( - $c->getUserSession(), - $appConfig, - $c->getGroupManager(), - $c->getMemCacheFactory(), - $c->getEventDispatcher(), - $c->getConfig() - ); - }); + \OC::$server->registerService('AppConfig', fn ($c) => $appConfig); + \OC::$server->registerService('AppManager', fn (\OC\Server $c) => new \OC\App\AppManager( + $c->getUserSession(), + $appConfig, + $c->getGroupManager(), + $c->getMemCacheFactory(), + $c->getEventDispatcher(), + $c->getConfig() + )); } /** * Restore the original app config service. */ private function restoreAppConfig() { - \OC::$server->registerService('AppConfig', function (\OC\Server $c) { - return new \OC\AppConfig($c->getDatabaseConnection()); - }); - \OC::$server->registerService('AppManager', function (\OC\Server $c) { - return new \OC\App\AppManager( - $c->getUserSession(), - $c->getAppConfig(), - $c->getGroupManager(), - $c->getMemCacheFactory(), - $c->getEventDispatcher(), - $c->getConfig() - ); - }); + \OC::$server->registerService('AppConfig', fn (\OC\Server $c) => new \OC\AppConfig($c->getDatabaseConnection())); + \OC::$server->registerService('AppManager', fn (\OC\Server $c) => new \OC\App\AppManager( + $c->getUserSession(), + $c->getAppConfig(), + $c->getGroupManager(), + $c->getMemCacheFactory(), + $c->getEventDispatcher(), + $c->getConfig() + )); // Remove the cache of the mocked apps list with a forceRefresh \OC_App::getEnabledApps(); diff --git a/tests/lib/Authentication/AccountModule/ManagerTest.php b/tests/lib/Authentication/AccountModule/ManagerTest.php index b5a4c9a6546c..f50de7b45cf8 100644 --- a/tests/lib/Authentication/AccountModule/ManagerTest.php +++ b/tests/lib/Authentication/AccountModule/ManagerTest.php @@ -31,19 +31,18 @@ class ManagerTest extends TestCase { /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IServiceLoader|\PHPUnit\Framework\MockObject\MockObject */ - private $serviceLoader; + private \PHPUnit\Framework\MockObject\MockObject $serviceLoader; - /** @var Manager */ - private $manager; + private \OC\Authentication\AccountModule\Manager $manager; protected function setUp(): void { parent::setUp(); @@ -62,9 +61,7 @@ protected function setUp(): void { public function testGetAccountModules() { $fakeModule = $this->createMock(IAccountModule::class); - \OC::$server->registerService('\OCA\AccountModuleApp\Module', function () use ($fakeModule) { - return $fakeModule; - }); + \OC::$server->registerService('\OCA\AccountModuleApp\Module', fn () => $fakeModule); $this->config->method('getAppValue') ->with('core', 'account-module-order', '[]') diff --git a/tests/lib/Authentication/LoginPolicies/GroupLoginPolicyTest.php b/tests/lib/Authentication/LoginPolicies/GroupLoginPolicyTest.php index 787dcb74d796..5658878f10dc 100644 --- a/tests/lib/Authentication/LoginPolicies/GroupLoginPolicyTest.php +++ b/tests/lib/Authentication/LoginPolicies/GroupLoginPolicyTest.php @@ -29,13 +29,12 @@ class GroupLoginPolicyTest extends TestCase { /** @var IGroupManager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IL10N */ - private $l10n; - /** @var GroupLoginPolicy */ - private $groupLoginPolicy; + private \PHPUnit\Framework\MockObject\MockObject $l10n; + private \OC\Authentication\LoginPolicies\GroupLoginPolicy $groupLoginPolicy; protected function setUp(): void { parent::setUp(); @@ -98,9 +97,7 @@ public function testCheckPolicyInRejectGroup() { ]); $this->groupManager->method('isInGroup') - ->will($this->returnCallback(function ($userid, $groupid) { - return $userid === 'myuserid' && $groupid === 'g2'; - })); + ->will($this->returnCallback(fn ($userid, $groupid) => $userid === 'myuserid' && $groupid === 'g2')); $this->groupLoginPolicy->checkPolicy('customLogin', $user); } @@ -137,9 +134,7 @@ public function testCheckPolicyInAllowOnlyGroup() { ]); $this->groupManager->method('isInGroup') - ->will($this->returnCallback(function ($userid, $groupid) { - return $userid === 'myuserid' && $groupid === 'g2'; - })); + ->will($this->returnCallback(fn ($userid, $groupid) => $userid === 'myuserid' && $groupid === 'g2')); $this->assertTrue($this->groupLoginPolicy->checkPolicy('customLogin', $user)); } @@ -181,9 +176,7 @@ public function testCheckPolicyInRejectAndAllowOnlyGroup() { ]); $this->groupManager->method('isInGroup') - ->will($this->returnCallback(function ($userid, $groupid) { - return $userid === 'myuserid' && ($groupid === 'g2' || $groupid === 'g3'); - })); + ->will($this->returnCallback(fn ($userid, $groupid) => $userid === 'myuserid' && ($groupid === 'g2' || $groupid === 'g3'))); $this->groupLoginPolicy->checkPolicy('customLogin', $user); } diff --git a/tests/lib/Authentication/LoginPolicies/LoginPolicyManagerTest.php b/tests/lib/Authentication/LoginPolicies/LoginPolicyManagerTest.php index bbb8dd2e447a..4685429e63ac 100644 --- a/tests/lib/Authentication/LoginPolicies/LoginPolicyManagerTest.php +++ b/tests/lib/Authentication/LoginPolicies/LoginPolicyManagerTest.php @@ -30,13 +30,12 @@ class LoginPolicyManagerTest extends TestCase { /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IL10N */ - private $l10n; - /** @var LoginPolicyManager */ - private $loginPolicyManager; + private \PHPUnit\Framework\MockObject\MockObject $l10n; + private \OC\Authentication\LoginPolicies\LoginPolicyManager $loginPolicyManager; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Authentication/Token/DefaultTokenCleanupJobTest.php b/tests/lib/Authentication/Token/DefaultTokenCleanupJobTest.php index ab41d52f1777..cc207b626814 100644 --- a/tests/lib/Authentication/Token/DefaultTokenCleanupJobTest.php +++ b/tests/lib/Authentication/Token/DefaultTokenCleanupJobTest.php @@ -26,24 +26,23 @@ use Test\TestCase; class DefaultTokenCleanupJobTest extends TestCase { - /** @var DefaultTokenCleanupJob */ - private $job; - private $tokenProvider; + private \OC\Authentication\Token\DefaultTokenCleanupJob $job; + private \PHPUnit\Framework\MockObject\MockObject $tokenProvider; protected function setUp(): void { parent::setUp(); - $this->tokenProvider = $this->getMockBuilder('\OC\Authentication\Token\DefaultTokenProvider') + $this->tokenProvider = $this->getMockBuilder('\\' . \OC\Authentication\Token\DefaultTokenProvider::class) ->disableOriginalConstructor() ->getMock(); - $this->overwriteService('\OC\Authentication\Token\DefaultTokenProvider', $this->tokenProvider); + $this->overwriteService('\\' . \OC\Authentication\Token\DefaultTokenProvider::class, $this->tokenProvider); $this->job = new DefaultTokenCleanupJob(); } protected function tearDown(): void { parent::tearDown(); - $this->restoreService('\OC\Authentication\Token\DefaultTokenProvider'); + $this->restoreService('\\' . \OC\Authentication\Token\DefaultTokenProvider::class); } public function testRun() { diff --git a/tests/lib/Authentication/Token/DefaultTokenMapperTest.php b/tests/lib/Authentication/Token/DefaultTokenMapperTest.php index 5acf2f42f7ab..6afea07eb121 100644 --- a/tests/lib/Authentication/Token/DefaultTokenMapperTest.php +++ b/tests/lib/Authentication/Token/DefaultTokenMapperTest.php @@ -38,11 +38,10 @@ * @package Test\Authentication */ class DefaultTokenMapperTest extends TestCase { - /** @var DefaultTokenMapper */ - private $mapper; + private \OC\Authentication\Token\DefaultTokenMapper $mapper; /** @var IDBConnection */ private $dbConnection; - private $time; + private int $time; protected function setUp(): void { parent::setUp(); @@ -152,7 +151,7 @@ public function testGetInvalidToken() { } public function testGetTokenByUser() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') ->will($this->returnValue('user1')); @@ -162,7 +161,7 @@ public function testGetTokenByUser() { public function testGetTokenByUserNotFound() { /** @var IUser | \PHPUnit\Framework\MockObject\MockObject $user */ - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->once()) ->method('getUID') ->will($this->returnValue('user1000')); @@ -172,7 +171,7 @@ public function testGetTokenByUserNotFound() { public function testDeleteById() { /** @var IUser | \PHPUnit\Framework\MockObject\MockObject $user */ - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $qb = $this->dbConnection->getQueryBuilder(); $qb->select('id') ->from('authtoken') @@ -189,7 +188,7 @@ public function testDeleteById() { public function testDeleteByIdWrongUser() { /** @var IUser | \PHPUnit\Framework\MockObject\MockObject $user */ - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $id = 33; $user->expects($this->once()) ->method('getUID') diff --git a/tests/lib/Authentication/Token/DefaultTokenProviderTest.php b/tests/lib/Authentication/Token/DefaultTokenProviderTest.php index bb5695271f66..cd910f195ee6 100644 --- a/tests/lib/Authentication/Token/DefaultTokenProviderTest.php +++ b/tests/lib/Authentication/Token/DefaultTokenProviderTest.php @@ -28,26 +28,25 @@ use Test\TestCase; class DefaultTokenProviderTest extends TestCase { - /** @var DefaultTokenProvider */ - private $tokenProvider; - private $mapper; - private $crypto; - private $config; - private $logger; - private $timeFactory; - private $time; + private \OC\Authentication\Token\DefaultTokenProvider $tokenProvider; + private \PHPUnit\Framework\MockObject\MockObject $mapper; + private \PHPUnit\Framework\MockObject\MockObject $crypto; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \PHPUnit\Framework\MockObject\MockObject $logger; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; + private int $time; protected function setUp(): void { parent::setUp(); - $this->mapper = $this->getMockBuilder('\OC\Authentication\Token\DefaultTokenMapper') + $this->mapper = $this->getMockBuilder('\\' . \OC\Authentication\Token\DefaultTokenMapper::class) ->disableOriginalConstructor() ->getMock(); - $this->crypto = $this->createMock('\OCP\Security\ICrypto'); - $this->config = $this->createMock('\OCP\IConfig'); - $this->logger = $this->createMock('\OCP\ILogger'); - $this->timeFactory = $this->createMock('\OCP\AppFramework\Utility\ITimeFactory'); - $this->time = 1313131; + $this->crypto = $this->createMock('\\' . \OCP\Security\ICrypto::class); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->logger = $this->createMock('\\' . \OCP\ILogger::class); + $this->timeFactory = $this->createMock('\\' . \OCP\AppFramework\Utility\ITimeFactory::class); + $this->time = 1_313_131; $this->timeFactory->expects($this->any()) ->method('getTime') ->will($this->returnValue($this->time)); @@ -122,7 +121,7 @@ public function testUpdateTokenDebounce() { } public function testGetTokenByUser() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->mapper->expects($this->once()) ->method('getTokenByUser') ->with($user) @@ -170,7 +169,7 @@ public function testGetPasswordDeletesInvalidToken() { $tk = new DefaultToken(); $tk->setPassword('someencryptedvalue'); /* @var $tokenProvider DefaultTokenProvider */ - $tokenProvider = $this->getMockBuilder('\OC\Authentication\Token\DefaultTokenProvider') + $tokenProvider = $this->getMockBuilder('\\' . \OC\Authentication\Token\DefaultTokenProvider::class) ->setMethods([ 'invalidateToken' ]) @@ -219,7 +218,7 @@ public function testSetPassword() { public function testSetPasswordInvalidToken() { $this->expectException(\OC\Authentication\Exceptions\InvalidTokenException::class); - $token = $this->createMock('\OC\Authentication\Token\IToken'); + $token = $this->createMock('\\' . \OC\Authentication\Token\IToken::class); $tokenId = 'token123'; $password = '123456'; @@ -236,7 +235,7 @@ public function testInvalidateToken() { public function testInvalidateTokenById() { $id = 123; - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->mapper->expects($this->once()) ->method('deleteById') diff --git a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php index 9e7b332ab11a..45f164d2a7dc 100644 --- a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php @@ -28,60 +28,58 @@ class ManagerTest extends TestCase { /** @var \OCP\IUser|\PHPUnit\Framework\MockObject\MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var \OC\App\AppManager|\PHPUnit\Framework\MockObject\MockObject */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; /** @var \OCP\ISession|\PHPUnit\Framework\MockObject\MockObject */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; /** @var IGroupManager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var Manager */ - private $manager; + private \PHPUnit\Framework\MockObject\MockObject $manager; /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var \OCP\IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var \OCP\ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var \OCP\Authentication\TwoFactorAuth\IProvider|\PHPUnit\Framework\MockObject\MockObject */ - private $fakeProvider; + private \PHPUnit\Framework\MockObject\MockObject $fakeProvider; protected function setUp(): void { parent::setUp(); - $this->user = $this->createMock('\OCP\IUser'); - $this->appManager = $this->getMockBuilder('\OC\App\AppManager') + $this->user = $this->createMock('\\' . \OCP\IUser::class); + $this->appManager = $this->getMockBuilder('\\' . \OC\App\AppManager::class) ->disableOriginalConstructor() ->getMock(); - $this->session = $this->createMock('\OCP\ISession'); + $this->session = $this->createMock('\\' . \OCP\ISession::class); $this->groupManager = $this->createMock(IGroupManager::class); - $this->config = $this->createMock('\OCP\IConfig'); - $this->request = $this->createMock('\OCP\IRequest'); - $this->logger = $this->createMock('\OCP\ILogger'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->request = $this->createMock('\\' . \OCP\IRequest::class); + $this->logger = $this->createMock('\\' . \OCP\ILogger::class); - $this->manager = $this->getMockBuilder('\OC\Authentication\TwoFactorAuth\Manager') + $this->manager = $this->getMockBuilder('\\' . \OC\Authentication\TwoFactorAuth\Manager::class) ->setConstructorArgs([$this->appManager, $this->session, $this->groupManager, $this->config, $this->request, $this->logger]) ->setMethods(['loadTwoFactorApp']) // Do not actually load the apps ->getMock(); - $this->fakeProvider = $this->createMock('\OCP\Authentication\TwoFactorAuth\IProvider'); + $this->fakeProvider = $this->createMock('\\' . \OCP\Authentication\TwoFactorAuth\IProvider::class); $this->fakeProvider->expects($this->any()) ->method('getId') ->will($this->returnValue('email')); $this->fakeProvider->expects($this->any()) ->method('isTwoFactorAuthEnabledForUser') ->will($this->returnValue(true)); - \OC::$server->registerService('\OCA\MyCustom2faApp\FakeProvider', function () { - return $this->fakeProvider; - }); + \OC::$server->registerService('\OCA\MyCustom2faApp\FakeProvider', fn () => $this->fakeProvider); } private function prepareProviders() { diff --git a/tests/lib/AutoLoaderTest.php b/tests/lib/AutoLoaderTest.php index cc3ea677b551..12ef9fce6411 100644 --- a/tests/lib/AutoLoaderTest.php +++ b/tests/lib/AutoLoaderTest.php @@ -14,7 +14,7 @@ class AutoLoaderTest extends TestCase { /** * @var Autoloader $loader */ - private $loader; + private \OC\AutoLoader $loader; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/AvatarManagerTest.php b/tests/lib/AvatarManagerTest.php index faf22b1f6194..794eaa066f40 100644 --- a/tests/lib/AvatarManagerTest.php +++ b/tests/lib/AvatarManagerTest.php @@ -40,25 +40,24 @@ class AvatarManagerTest extends TestCase { use MountProviderTrait; /** @var AvatarManager | \PHPUnit\Framework\MockObject\MockObject */ - private $avatarManager; + private \OC\AvatarManager $avatarManager; /** @var \OC\Files\Storage\Temporary */ - private $storage; + private \PHPUnit\Framework\MockObject\MockObject $storage; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; - /** @var Folder */ - private $folder; + private \OC\Files\Storage\Folder $folder; /** @var IRootFolder | \PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/AvatarTest.php b/tests/lib/AvatarTest.php index 8a73a176b6f3..d9439f577b3f 100644 --- a/tests/lib/AvatarTest.php +++ b/tests/lib/AvatarTest.php @@ -19,13 +19,12 @@ class AvatarTest extends \Test\TestCase { /** @var IStorage | \PHPUnit\Framework\MockObject\MockObject */ - private $storage; + private \PHPUnit\Framework\MockObject\MockObject $storage; - /** @var \OC\Avatar */ - private $avatar; + private \OC\Avatar $avatar; /** @var \OC\User\User | \PHPUnit\Framework\MockObject\MockObject $user */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/BackgroundJob/DummyJobList.php b/tests/lib/BackgroundJob/DummyJobList.php index 4f3ae18b371f..e11be76261ba 100644 --- a/tests/lib/BackgroundJob/DummyJobList.php +++ b/tests/lib/BackgroundJob/DummyJobList.php @@ -17,7 +17,7 @@ class DummyJobList extends \OC\BackgroundJob\JobList { /** * @var \OC\BackgroundJob\Job[] */ - private $jobs = []; + private array $jobs = []; private $last = 0; diff --git a/tests/lib/BackgroundJob/JobListTest.php b/tests/lib/BackgroundJob/JobListTest.php index 8ab6b24a23ba..7e9b9f4dfd80 100644 --- a/tests/lib/BackgroundJob/JobListTest.php +++ b/tests/lib/BackgroundJob/JobListTest.php @@ -40,8 +40,8 @@ protected function setUp(): void { $this->connection = \OC::$server->getDatabaseConnection(); $this->clearJobsList(); - $this->config = $this->createMock('OCP\IConfig'); - $this->timeFactory = $this->createMock('OCP\AppFramework\Utility\ITimeFactory'); + $this->config = $this->createMock(\OCP\IConfig::class); + $this->timeFactory = $this->createMock(\OCP\AppFramework\Utility\ITimeFactory::class); $this->logger = $this->createMock(ILogger::class); $this->instance = new \OC\BackgroundJob\JobList( $this->connection, @@ -60,9 +60,7 @@ protected function clearJobsList() { protected function getAllSorted() { $jobs = $this->instance->getAll(); - \usort($jobs, function (IJob $job1, IJob $job2) { - return $job1->getId() - $job2->getId(); - }); + \usort($jobs, fn (IJob $job1, IJob $job2) => $job1->getId() - $job2->getId()); return $jobs; } @@ -85,7 +83,7 @@ public function argumentProvider() { * @param $argument */ public function testAddRemove($argument) { - $this->timeFactory->method('getTime')->willReturn(164419800); + $this->timeFactory->method('getTime')->willReturn(164_419_800); $existingJobs = $this->getAllSorted(); $job = new TestJob(); $this->instance->add($job, $argument); @@ -94,7 +92,7 @@ public function testAddRemove($argument) { $this->assertCount(\count($existingJobs) + 1, $jobs); $addedJob = $jobs[\count($jobs) - 1]; - $this->assertInstanceOf('\Test\BackgroundJob\TestJob', $addedJob); + $this->assertInstanceOf('\\' . \Test\BackgroundJob\TestJob::class, $addedJob); $this->assertEquals($argument, $addedJob->getArgument()); $this->instance->remove($job, $argument); @@ -108,7 +106,7 @@ public function testAddRemove($argument) { * @param $argument */ public function testRemoveDifferentArgument($argument) { - $this->timeFactory->method('getTime')->willReturn(164419800); + $this->timeFactory->method('getTime')->willReturn(164_419_800); $existingJobs = $this->getAllSorted(); $job = new TestJob(); $this->instance->add($job, $argument); @@ -130,7 +128,7 @@ public function testRemoveDifferentArgument($argument) { * @param $argument */ public function testJobIdExists($argument) { - $this->timeFactory->method('getTime')->willReturn(164419800); + $this->timeFactory->method('getTime')->willReturn(164_419_800); $job = new TestJob(); $this->instance->add($job, $argument); $jobs = $this->getAllSorted(); @@ -146,7 +144,7 @@ public function testJobIdExists($argument) { * @param $argument */ public function testHas($argument) { - $this->timeFactory->method('getTime')->willReturn(164419800); + $this->timeFactory->method('getTime')->willReturn(164_419_800); $job = new TestJob(); $this->assertFalse($this->instance->has($job, $argument)); $this->instance->add($job, $argument); @@ -163,7 +161,7 @@ public function testHas($argument) { * @param $argument */ public function testHasDifferentArgument($argument) { - $this->timeFactory->method('getTime')->willReturn(164419800); + $this->timeFactory->method('getTime')->willReturn(164_419_800); $job = new TestJob(); $this->instance->add($job, $argument); @@ -207,7 +205,7 @@ public function testGetNext() { $this->timeFactory->expects($this->atLeastOnce()) ->method('getTime') - ->willReturn(123456789); + ->willReturn(123_456_789); $nextJob = $this->instance->getNext(); $this->assertEquals($savedJob1, $nextJob); @@ -215,15 +213,15 @@ public function testGetNext() { public function testGetNextSkipReserved() { $job = new TestJob(); - $this->createTempJob(\get_class($job), 1, 123456789, 12345); + $this->createTempJob(\get_class($job), 1, 123_456_789, 12345); $this->createTempJob(\get_class($job), 2, 0, 12346); $this->timeFactory->expects($this->atLeastOnce()) ->method('getTime') - ->willReturn(123456789); + ->willReturn(123_456_789); $nextJob = $this->instance->getNext(); - $this->assertEquals(\get_class($job), \get_class($nextJob)); + $this->assertEquals(\get_class($job), $nextJob !== null ? \get_class($nextJob) : self::class); $this->assertEquals(2, $nextJob->getArgument()); } @@ -234,10 +232,10 @@ public function testGetNextSkipNonExisting() { $this->timeFactory->expects($this->atLeastOnce()) ->method('getTime') - ->willReturn(123456789); + ->willReturn(123_456_789); $nextJob = $this->instance->getNext(); - $this->assertEquals(\get_class($job), \get_class($nextJob)); + $this->assertEquals(\get_class($job), $nextJob !== null ? \get_class($nextJob) : self::class); $this->assertEquals(2, $nextJob->getArgument()); } @@ -246,7 +244,7 @@ public function testGetNextSkipNonExisting() { * @param $argument */ public function testGetById($argument) { - $this->timeFactory->method('getTime')->willReturn(164419800); + $this->timeFactory->method('getTime')->willReturn(164_419_800); $job = new TestJob(); $this->instance->add($job, $argument); @@ -258,7 +256,7 @@ public function testGetById($argument) { } public function testSetLastRun() { - $this->timeFactory->method('getTime')->willReturn(164419800); + $this->timeFactory->method('getTime')->willReturn(164_419_800); $job = new TestJob(); $this->instance->add($job); diff --git a/tests/lib/BackgroundJob/JobTest.php b/tests/lib/BackgroundJob/JobTest.php index 4c13798da25b..32e65703275c 100644 --- a/tests/lib/BackgroundJob/JobTest.php +++ b/tests/lib/BackgroundJob/JobTest.php @@ -9,7 +9,7 @@ namespace Test\BackgroundJob; class JobTest extends \Test\TestCase { - private $run = false; + private bool $run = false; protected function setUp(): void { parent::setUp(); @@ -24,7 +24,7 @@ public function testRemoveAfterException() { }); $jobList->add($job); - $logger = $this->getMockBuilder('OCP\ILogger') + $logger = $this->getMockBuilder(\OCP\ILogger::class) ->disableOriginalConstructor() ->getMock(); $logger->expects($this->once()) diff --git a/tests/lib/BackgroundJob/QueuedJobTest.php b/tests/lib/BackgroundJob/QueuedJobTest.php index 2ff39dd78f6c..5d25b7e8f9e0 100644 --- a/tests/lib/BackgroundJob/QueuedJobTest.php +++ b/tests/lib/BackgroundJob/QueuedJobTest.php @@ -24,16 +24,13 @@ public function run($argument) { } class QueuedJobTest extends \Test\TestCase { - /** - * @var DummyJobList $jobList - */ - private $jobList; + private \Test\BackgroundJob\DummyJobList $jobList; /** * @var \OC\BackgroundJob\TimedJob $job */ - private $job; + private \Test\BackgroundJob\TestQueuedJob $job; - private $jobRun = false; + private bool $jobRun = false; public function markRun() { $this->jobRun = true; diff --git a/tests/lib/BackgroundJob/TimedJobTest.php b/tests/lib/BackgroundJob/TimedJobTest.php index bdd44978bf01..8a76a0002a0f 100644 --- a/tests/lib/BackgroundJob/TimedJobTest.php +++ b/tests/lib/BackgroundJob/TimedJobTest.php @@ -25,16 +25,13 @@ public function run($argument) { } class TimedJobTest extends \Test\TestCase { - /** - * @var DummyJobList $jobList - */ - private $jobList; + private \Test\BackgroundJob\DummyJobList $jobList; /** * @var \OC\BackgroundJob\TimedJob $job */ - private $job; + private \Test\BackgroundJob\TestTimedJob $job; - private $jobRun = false; + private bool $jobRun = false; public function markRun() { $this->jobRun = true; diff --git a/tests/lib/Cache/FileCacheTest.php b/tests/lib/Cache/FileCacheTest.php index b7126ad4a368..64c8c16c407f 100644 --- a/tests/lib/Cache/FileCacheTest.php +++ b/tests/lib/Cache/FileCacheTest.php @@ -46,10 +46,7 @@ class FileCacheTest extends TestCache { * @var \OC\Files\Storage\Storage * */ private $storage; - /** - * @var \OC\Files\View - * */ - private $rootView; + private \OC\Files\View $rootView; protected function setUp(): void { parent::setUp(); @@ -99,7 +96,7 @@ protected function tearDown(): void { } private function setupMockStorage() { - $mockStorage = $this->getMockBuilder('\OC\Files\Storage\Local') + $mockStorage = $this->getMockBuilder('\\' . \OC\Files\Storage\Local::class) ->setMethods(['filemtime', 'unlink']) ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]]) ->getMock(); diff --git a/tests/lib/CapabilitiesManagerTest.php b/tests/lib/CapabilitiesManagerTest.php index bf5c483cb239..92484f7e1abd 100644 --- a/tests/lib/CapabilitiesManagerTest.php +++ b/tests/lib/CapabilitiesManagerTest.php @@ -37,9 +37,7 @@ public function testNoCapabilities() { public function testValidCapability() { $manager = new \OC\CapabilitiesManager(); - $manager->registerCapability(function () { - return new SimpleCapability(); - }); + $manager->registerCapability(fn () => new SimpleCapability()); $res = $manager->getCapabilities(); $this->assertEquals(['foo' => 1], $res); @@ -54,9 +52,7 @@ public function testNoICapability() { $manager = new \OC\CapabilitiesManager(); - $manager->registerCapability(function () { - return new NoCapability(); - }); + $manager->registerCapability(fn () => new NoCapability()); $res = $manager->getCapabilities(); $this->assertEquals([], $res); @@ -68,15 +64,9 @@ public function testNoICapability() { public function testMergedCapabilities() { $manager = new \OC\CapabilitiesManager(); - $manager->registerCapability(function () { - return new SimpleCapability(); - }); - $manager->registerCapability(function () { - return new SimpleCapability2(); - }); - $manager->registerCapability(function () { - return new SimpleCapability3(); - }); + $manager->registerCapability(fn () => new SimpleCapability()); + $manager->registerCapability(fn () => new SimpleCapability2()); + $manager->registerCapability(fn () => new SimpleCapability3()); $res = $manager->getCapabilities(); $expected = [ @@ -96,12 +86,8 @@ public function testMergedCapabilities() { public function testDeepIdenticalCapabilities() { $manager = new \OC\CapabilitiesManager(); - $manager->registerCapability(function () { - return new DeepCapability(); - }); - $manager->registerCapability(function () { - return new DeepCapability(); - }); + $manager->registerCapability(fn () => new DeepCapability()); + $manager->registerCapability(fn () => new DeepCapability()); $res = $manager->getCapabilities(); $expected = [ diff --git a/tests/lib/Command/AsyncBusTest.php b/tests/lib/Command/AsyncBusTest.php index c8153c5618c7..aacff50eebaa 100644 --- a/tests/lib/Command/AsyncBusTest.php +++ b/tests/lib/Command/AsyncBusTest.php @@ -69,12 +69,12 @@ class AsyncBusTest extends TestCase { /** * @var \OCP\BackgroundJob\IJobList */ - private $jobList; + private \Test\BackgroundJob\DummyJobList $jobList; /** * @var \OCP\Command\IBus */ - private $bus; + private \OC\Command\AsyncBus $bus; public static function DummyCommand() { self::$lastCommand = 'static'; @@ -101,7 +101,7 @@ public function testStateFullCommand() { } public function testStaticCallable() { - $this->bus->push(['\Test\Command\AsyncBusTest', 'DummyCommand']); + $this->bus->push(['\\' . \Test\Command\AsyncBusTest::class, 'DummyCommand']); $this->runJobs(); $this->assertEquals('static', self::$lastCommand); } @@ -152,7 +152,7 @@ public function testFileFileAccessCommand() { } public function testFileFileAccessCommandSync() { - $this->bus->requireSync('\OC\Command\FileAccess'); + $this->bus->requireSync('\\' . \OC\Command\FileAccess::class); $this->bus->push(new FilesystemCommand()); $this->assertEquals('FileAccess', self::$lastCommand); self::$lastCommand = ''; diff --git a/tests/lib/Command/Integrity/SignAppTest.php b/tests/lib/Command/Integrity/SignAppTest.php index 2ad753235f58..b686022b1c92 100644 --- a/tests/lib/Command/Integrity/SignAppTest.php +++ b/tests/lib/Command/Integrity/SignAppTest.php @@ -28,21 +28,20 @@ class SignAppTest extends TestCase { /** @var Checker */ - private $checker; - /** @var SignApp */ - private $signApp; + private \PHPUnit\Framework\MockObject\MockObject $checker; + private \OC\Core\Command\Integrity\SignApp $signApp; /** @var FileAccessHelper */ - private $fileAccessHelper; + private \PHPUnit\Framework\MockObject\MockObject $fileAccessHelper; /** @var IURLGenerator */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; public function setUp(): void { parent::setUp(); - $this->checker = $this->getMockBuilder('\OC\IntegrityCheck\Checker') + $this->checker = $this->getMockBuilder('\\' . \OC\IntegrityCheck\Checker::class) ->disableOriginalConstructor()->getMock(); - $this->fileAccessHelper = $this->getMockBuilder('\OC\IntegrityCheck\Helpers\FileAccessHelper') + $this->fileAccessHelper = $this->getMockBuilder('\\' . \OC\IntegrityCheck\Helpers\FileAccessHelper::class) ->disableOriginalConstructor()->getMock(); - $this->urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $this->urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor()->getMock(); $this->signApp = new SignApp( $this->checker, @@ -52,8 +51,8 @@ public function setUp(): void { } public function testExecuteWithMissingPath() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -79,8 +78,8 @@ public function testExecuteWithMissingPath() { } public function testExecuteWithMissingPrivateKey() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -106,8 +105,8 @@ public function testExecuteWithMissingPrivateKey() { } public function testExecuteWithMissingCertificate() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -133,8 +132,8 @@ public function testExecuteWithMissingCertificate() { } public function testExecuteWithNotExistingPrivateKey() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -170,8 +169,8 @@ public function testExecuteWithNotExistingPrivateKey() { } public function testExecuteWithNotExistingCertificate() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -207,8 +206,8 @@ public function testExecuteWithNotExistingCertificate() { } public function testExecute() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') diff --git a/tests/lib/Command/Integrity/SignCoreTest.php b/tests/lib/Command/Integrity/SignCoreTest.php index 111e69e0d5e5..c7c57a168d2a 100644 --- a/tests/lib/Command/Integrity/SignCoreTest.php +++ b/tests/lib/Command/Integrity/SignCoreTest.php @@ -27,17 +27,16 @@ class SignCoreTest extends TestCase { /** @var Checker */ - private $checker; - /** @var SignCore */ - private $signCore; + private \PHPUnit\Framework\MockObject\MockObject $checker; + private \OC\Core\Command\Integrity\SignCore $signCore; /** @var FileAccessHelper */ - private $fileAccessHelper; + private \PHPUnit\Framework\MockObject\MockObject $fileAccessHelper; public function setUp(): void { parent::setUp(); - $this->checker = $this->getMockBuilder('\OC\IntegrityCheck\Checker') + $this->checker = $this->getMockBuilder('\\' . \OC\IntegrityCheck\Checker::class) ->disableOriginalConstructor()->getMock(); - $this->fileAccessHelper = $this->getMockBuilder('\OC\IntegrityCheck\Helpers\FileAccessHelper') + $this->fileAccessHelper = $this->getMockBuilder('\\' . \OC\IntegrityCheck\Helpers\FileAccessHelper::class) ->disableOriginalConstructor()->getMock(); $this->signCore = new SignCore( $this->checker, @@ -46,8 +45,8 @@ public function setUp(): void { } public function testExecuteWithMissingPrivateKey() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -69,8 +68,8 @@ public function testExecuteWithMissingPrivateKey() { } public function testExecuteWithMissingCertificate() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -92,8 +91,8 @@ public function testExecuteWithMissingCertificate() { } public function testExecuteWithNotExistingPrivateKey() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -129,8 +128,8 @@ public function testExecuteWithNotExistingPrivateKey() { } public function testExecuteWithNotExistingCertificate() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') @@ -166,8 +165,8 @@ public function testExecuteWithNotExistingCertificate() { } public function testExecute() { - $inputInterface = $this->createMock('\Symfony\Component\Console\Input\InputInterface'); - $outputInterface = $this->createMock('\Symfony\Component\Console\Output\OutputInterface'); + $inputInterface = $this->createMock('\\' . \Symfony\Component\Console\Input\InputInterface::class); + $outputInterface = $this->createMock('\\' . \Symfony\Component\Console\Output\OutputInterface::class); $inputInterface ->method('getOption') diff --git a/tests/lib/Command/User/SyncBackendTest.php b/tests/lib/Command/User/SyncBackendTest.php index 543d14ba2a87..7677bbe397ff 100644 --- a/tests/lib/Command/User/SyncBackendTest.php +++ b/tests/lib/Command/User/SyncBackendTest.php @@ -36,18 +36,17 @@ class SyncBackendTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var AccountMapper | \PHPUnit\Framework\MockObject\MockObject */ - private $mapper; + private \PHPUnit\Framework\MockObject\MockObject $mapper; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - /** @var SyncBackend */ - private $command; + private \PHPUnit\Framework\MockObject\MockObject $userManager; + private \OC\Core\Command\User\SyncBackend $command; /** @var UserInterface | \PHPUnit\Framework\MockObject\MockObject */ - private $dummyBackend; + private \PHPUnit\Framework\MockObject\MockObject $dummyBackend; public function setUp(): void { parent::setUp(); @@ -305,9 +304,7 @@ public function testSingleUserSyncExistingUser() { $syncService->expects($this ->once())->method('run')->with( $this->dummyBackend, - $this->callback(function ($subject) { - return \count($subject) === 1 && $subject[0] === 'existing-uid'; - }), + $this->callback(fn ($subject) => \count($subject) === 1 && $subject[0] === 'existing-uid'), $this->anything() ); diff --git a/tests/lib/Comments/ManagerTest.php b/tests/lib/Comments/ManagerTest.php index 92cfc3e84ad8..9cd40554a59b 100644 --- a/tests/lib/Comments/ManagerTest.php +++ b/tests/lib/Comments/ManagerTest.php @@ -706,7 +706,7 @@ public function testDeleteCommentsAtObject() { } public function testSetMarkRead() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('alice')); @@ -722,7 +722,7 @@ public function testSetMarkRead() { } public function testSetMarkReadUpdate() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('alice')); @@ -741,7 +741,7 @@ public function testSetMarkReadUpdate() { } public function testReadMarkDeleteUser() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('alice')); @@ -758,7 +758,7 @@ public function testReadMarkDeleteUser() { } public function testReadMarkDeleteObject() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('alice')); diff --git a/tests/lib/ConfigTest.php b/tests/lib/ConfigTest.php index c0b93cd79b4c..df061f621c55 100644 --- a/tests/lib/ConfigTest.php +++ b/tests/lib/ConfigTest.php @@ -19,12 +19,9 @@ class ConfigTest extends TestCase { public const TESTCONTENT = '"bar", "beers" => array("Appenzeller", "Guinness", "Kölsch"), "alcohol_free" => false);'; - /** @var array */ - private $initialConfig = ['foo' => 'bar', 'beers' => ['Appenzeller', 'Guinness', 'Kölsch'], 'alcohol_free' => false]; - /** @var string */ - private $configFile; - /** @var \OC\Config */ - private $config; + private array $initialConfig = ['foo' => 'bar', 'beers' => ['Appenzeller', 'Guinness', 'Kölsch'], 'alcohol_free' => false]; + private string $configFile; + private \OC\Config $config; /** @var string */ private $randomTmpDir; diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php index 8b6d48f28e1d..f91397e8fa94 100644 --- a/tests/lib/ContactsManagerTest.php +++ b/tests/lib/ContactsManagerTest.php @@ -3,8 +3,7 @@ namespace Test; class ContactsManagerTest extends \Test\TestCase { - /** @var \OC\ContactsManager */ - private $cm; + private \OC\ContactsManager $cm; protected function setUp(): void { parent::setUp(); @@ -46,7 +45,7 @@ public function searchProvider() { ], ]; - $expectedResult = \array_merge($search1, $search2); + $expectedResult = [...$search1, ...$search2]; return [ [ $search1, @@ -60,7 +59,7 @@ public function searchProvider() { * @dataProvider searchProvider */ public function testSearch($search1, $search2, $expectedResult) { - $addressbook1 = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook1 = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); @@ -72,7 +71,7 @@ public function testSearch($search1, $search2, $expectedResult) { ->method('getKey') ->willReturn('simple:1'); - $addressbook2 = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook2 = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); @@ -91,7 +90,7 @@ public function testSearch($search1, $search2, $expectedResult) { } public function testDeleteHavePermission() { - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); @@ -109,7 +108,7 @@ public function testDeleteHavePermission() { } public function testDeleteNoPermission() { - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); @@ -126,7 +125,7 @@ public function testDeleteNoPermission() { } public function testDeleteNoAddressbook() { - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); @@ -139,7 +138,7 @@ public function testDeleteNoAddressbook() { } public function testCreateOrUpdateHavePermission() { - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); @@ -157,7 +156,7 @@ public function testCreateOrUpdateHavePermission() { } public function testCreateOrUpdateNoPermission() { - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); @@ -174,7 +173,7 @@ public function testCreateOrUpdateNoPermission() { } public function testCreateOrUpdateNOAddressbook() { - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); @@ -192,7 +191,7 @@ public function testIsEnabledIfNot() { } public function testIsEnabledIfSo() { - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + $addressbook = $this->getMockBuilder('\\' . \OCP\IAddressBook::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/DB/LegacyDBTest.php b/tests/lib/DB/LegacyDBTest.php index f32c50a3de3b..42ef5faeec74 100644 --- a/tests/lib/DB/LegacyDBTest.php +++ b/tests/lib/DB/LegacyDBTest.php @@ -21,35 +21,17 @@ class LegacyDBTest extends \Test\TestCase { protected static $schema_file = 'static://test_db_scheme'; protected $test_prefix; - /** - * @var string - */ - private $table1; + private string $table1; - /** - * @var string - */ - private $table2; + private string $table2; - /** - * @var string - */ - private $table3; + private string $table3; - /** - * @var string - */ - private $table4; + private string $table4; - /** - * @var string - */ - private $table5; + private string $table5; - /** - * @var string - */ - private $text_table; + private string $text_table; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/DB/MDB2SchemaReaderTest.php b/tests/lib/DB/MDB2SchemaReaderTest.php index 5d9f5e2228fa..0482aadb0e0c 100644 --- a/tests/lib/DB/MDB2SchemaReaderTest.php +++ b/tests/lib/DB/MDB2SchemaReaderTest.php @@ -57,7 +57,7 @@ public function testRead() { $this->assertFalse($table->getColumn('integerfield')->getAutoincrement()); $this->assertEquals(0, $table->getColumn('integerfield')->getDefault()); $this->assertTrue($table->getColumn('integerfield')->getNotnull()); - $this->assertInstanceOf('Doctrine\DBAL\Types\IntegerType', $table->getColumn('integerfield')->getType()); + $this->assertInstanceOf(\Doctrine\DBAL\Types\IntegerType::class, $table->getColumn('integerfield')->getType()); $this->assertSame(10, $table->getColumn('integerfield_default')->getDefault()); @@ -65,18 +65,18 @@ public function testRead() { $this->assertFalse($table->getColumn('textfield')->getAutoincrement()); $this->assertSame('foo', $table->getColumn('textfield')->getDefault()); $this->assertTrue($table->getColumn('textfield')->getNotnull()); - $this->assertInstanceOf('Doctrine\DBAL\Types\StringType', $table->getColumn('textfield')->getType()); + $this->assertInstanceOf(\Doctrine\DBAL\Types\StringType::class, $table->getColumn('textfield')->getType()); $this->assertNull($table->getColumn('clobfield')->getLength()); $this->assertFalse($table->getColumn('clobfield')->getAutoincrement()); $this->assertNull($table->getColumn('clobfield')->getDefault()); $this->assertFalse($table->getColumn('clobfield')->getNotnull()); - $this->assertInstanceOf('Doctrine\DBAL\Types\TextType', $table->getColumn('clobfield')->getType()); + $this->assertInstanceOf(\Doctrine\DBAL\Types\TextType::class, $table->getColumn('clobfield')->getType()); $this->assertNull($table->getColumn('booleanfield')->getLength()); $this->assertFalse($table->getColumn('booleanfield')->getAutoincrement()); $this->assertNull($table->getColumn('booleanfield')->getDefault()); - $this->assertInstanceOf('Doctrine\DBAL\Types\BooleanType', $table->getColumn('booleanfield')->getType()); + $this->assertInstanceOf(\Doctrine\DBAL\Types\BooleanType::class, $table->getColumn('booleanfield')->getType()); $this->assertTrue($table->getColumn('booleanfield_true')->getDefault()); $this->assertFalse($table->getColumn('booleanfield_false')->getDefault()); diff --git a/tests/lib/DB/MigrationsTest.php b/tests/lib/DB/MigrationsTest.php index 841d6c15f1f5..a6f07542efb7 100644 --- a/tests/lib/DB/MigrationsTest.php +++ b/tests/lib/DB/MigrationsTest.php @@ -25,7 +25,7 @@ class MigrationsTest extends \Test\TestCase { /** @var MigrationService | \PHPUnit\Framework\MockObject\MockObject */ private $migrationService; /** @var \PHPUnit\Framework\MockObject\MockObject | IDBConnection $db */ - private $db; + private \PHPUnit\Framework\MockObject\MockObject $db; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/DB/MigratorTest.php b/tests/lib/DB/MigratorTest.php index 0814f71d3cd1..94864fcdd048 100644 --- a/tests/lib/DB/MigratorTest.php +++ b/tests/lib/DB/MigratorTest.php @@ -28,10 +28,7 @@ class MigratorTest extends \Test\TestCase { */ private $connection; - /** - * @var \OC\DB\MDB2SchemaManager - */ - private $manager; + private \OC\DB\MDB2SchemaManager $manager; /** * @var IConfig @@ -121,7 +118,7 @@ public function testDuplicateKeyUpgrade() { if ($this->isOracle()) { $this->markTestSkipped('Does not work yet with Oracle, needs fixing index quoting'); } - list($startSchema, $endSchema) = $this->getDuplicateKeySchemas(); + [$startSchema, $endSchema] = $this->getDuplicateKeySchemas(); $migrator = $this->manager->getMigrator(); $migrator->migrate($startSchema); @@ -142,7 +139,7 @@ public function testDuplicateKeyUpgrade() { } public function testUpgrade() { - list($startSchema, $endSchema) = $this->getDuplicateKeySchemas(); + [$startSchema, $endSchema] = $this->getDuplicateKeySchemas(); $migrator = $this->manager->getMigrator(); $migrator->migrate($startSchema); @@ -160,7 +157,7 @@ public function testUpgradeDifferentPrefix() { $this->config->setSystemValue('dbtableprefix', 'ownc_'); $this->tableName = \strtolower(self::getUniqueID($this->config->getSystemValue('dbtableprefix') . 'test_')); - list($startSchema, $endSchema) = $this->getDuplicateKeySchemas(); + [$startSchema, $endSchema] = $this->getDuplicateKeySchemas(); $migrator = $this->manager->getMigrator(); $migrator->migrate($startSchema); @@ -175,7 +172,7 @@ public function testUpgradeDifferentPrefix() { } public function testInsertAfterUpgrade() { - list($startSchema, $endSchema) = $this->getDuplicateKeySchemas(); + [$startSchema, $endSchema] = $this->getDuplicateKeySchemas(); $migrator = $this->manager->getMigrator(); $migrator->migrate($startSchema); diff --git a/tests/lib/DB/MySqlToolsTest.php b/tests/lib/DB/MySqlToolsTest.php index 0f77f61f7085..53c12f9c58e1 100644 --- a/tests/lib/DB/MySqlToolsTest.php +++ b/tests/lib/DB/MySqlToolsTest.php @@ -37,7 +37,7 @@ class MySqlToolsTest extends TestCase { /** * @var IDBConnection */ - private $db; + private \PHPUnit\Framework\MockObject\MockObject $db; /** * @var MySqlTools diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php index d31d034aebec..1f9f735aca3b 100644 --- a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php @@ -76,8 +76,8 @@ public function dataComparison() { * @param bool $isInput2Literal */ public function testComparison($comparison, $input1, $isInput1Literal, $input2, $isInput2Literal) { - list($doctrineInput1, $ocInput1) = $this->helpWithLiteral($input1, $isInput1Literal); - list($doctrineInput2, $ocInput2) = $this->helpWithLiteral($input2, $isInput2Literal); + [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); + [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); $this->assertEquals( $this->doctrineExpressionBuilder->comparison($doctrineInput1, $comparison, $doctrineInput2), @@ -103,8 +103,8 @@ public function dataComparisons() { * @param bool $isInput2Literal */ public function testEquals($input1, $isInput1Literal, $input2, $isInput2Literal) { - list($doctrineInput1, $ocInput1) = $this->helpWithLiteral($input1, $isInput1Literal); - list($doctrineInput2, $ocInput2) = $this->helpWithLiteral($input2, $isInput2Literal); + [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); + [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); $this->assertEquals( $this->doctrineExpressionBuilder->eq($doctrineInput1, $doctrineInput2), @@ -121,8 +121,8 @@ public function testEquals($input1, $isInput1Literal, $input2, $isInput2Literal) * @param bool $isInput2Literal */ public function testNotEquals($input1, $isInput1Literal, $input2, $isInput2Literal) { - list($doctrineInput1, $ocInput1) = $this->helpWithLiteral($input1, $isInput1Literal); - list($doctrineInput2, $ocInput2) = $this->helpWithLiteral($input2, $isInput2Literal); + [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); + [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); $this->assertEquals( $this->doctrineExpressionBuilder->neq($doctrineInput1, $doctrineInput2), @@ -139,8 +139,8 @@ public function testNotEquals($input1, $isInput1Literal, $input2, $isInput2Liter * @param bool $isInput2Literal */ public function testLowerThan($input1, $isInput1Literal, $input2, $isInput2Literal) { - list($doctrineInput1, $ocInput1) = $this->helpWithLiteral($input1, $isInput1Literal); - list($doctrineInput2, $ocInput2) = $this->helpWithLiteral($input2, $isInput2Literal); + [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); + [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); $this->assertEquals( $this->doctrineExpressionBuilder->lt($doctrineInput1, $doctrineInput2), @@ -157,8 +157,8 @@ public function testLowerThan($input1, $isInput1Literal, $input2, $isInput2Liter * @param bool $isInput2Literal */ public function testLowerThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal) { - list($doctrineInput1, $ocInput1) = $this->helpWithLiteral($input1, $isInput1Literal); - list($doctrineInput2, $ocInput2) = $this->helpWithLiteral($input2, $isInput2Literal); + [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); + [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); $this->assertEquals( $this->doctrineExpressionBuilder->lte($doctrineInput1, $doctrineInput2), @@ -175,8 +175,8 @@ public function testLowerThanEquals($input1, $isInput1Literal, $input2, $isInput * @param bool $isInput2Literal */ public function testGreaterThan($input1, $isInput1Literal, $input2, $isInput2Literal) { - list($doctrineInput1, $ocInput1) = $this->helpWithLiteral($input1, $isInput1Literal); - list($doctrineInput2, $ocInput2) = $this->helpWithLiteral($input2, $isInput2Literal); + [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); + [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); $this->assertEquals( $this->doctrineExpressionBuilder->gt($doctrineInput1, $doctrineInput2), @@ -193,8 +193,8 @@ public function testGreaterThan($input1, $isInput1Literal, $input2, $isInput2Lit * @param bool $isInput2Literal */ public function testGreaterThanEquals($input1, $isInput1Literal, $input2, $isInput2Literal) { - list($doctrineInput1, $ocInput1) = $this->helpWithLiteral($input1, $isInput1Literal); - list($doctrineInput2, $ocInput2) = $this->helpWithLiteral($input2, $isInput2Literal); + [$doctrineInput1, $ocInput1] = $this->helpWithLiteral($input1, $isInput1Literal); + [$doctrineInput2, $ocInput2] = $this->helpWithLiteral($input2, $isInput2Literal); $this->assertEquals( $this->doctrineExpressionBuilder->gte($doctrineInput1, $doctrineInput2), @@ -230,7 +230,7 @@ public function dataLike() { * @param bool $isLiteral */ public function testLike($input, $isLiteral) { - list($doctrineInput, $ocInput) = $this->helpWithLiteral($input, $isLiteral); + [$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral); $this->assertEquals( $this->doctrineExpressionBuilder->like('`test`', $doctrineInput), @@ -245,7 +245,7 @@ public function testLike($input, $isLiteral) { * @param bool $isLiteral */ public function testNotLike($input, $isLiteral) { - list($doctrineInput, $ocInput) = $this->helpWithLiteral($input, $isLiteral); + [$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral); $this->assertEquals( $this->doctrineExpressionBuilder->notLike('`test`', $doctrineInput), @@ -269,7 +269,7 @@ public function dataIn() { * @param bool $isLiteral */ public function testIn($input, $isLiteral) { - list($doctrineInput, $ocInput) = $this->helpWithLiteral($input, $isLiteral); + [$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral); $this->assertEquals( $this->doctrineExpressionBuilder->in('`test`', $doctrineInput), @@ -284,7 +284,7 @@ public function testIn($input, $isLiteral) { * @param bool $isLiteral */ public function testNotIn($input, $isLiteral) { - list($doctrineInput, $ocInput) = $this->helpWithLiteral($input, $isLiteral); + [$doctrineInput, $ocInput] = $this->helpWithLiteral($input, $isLiteral); $this->assertEquals( $this->doctrineExpressionBuilder->notIn('`test`', $doctrineInput), @@ -295,21 +295,15 @@ public function testNotIn($input, $isLiteral) { protected function helpWithLiteral($input, $isLiteral) { if ($isLiteral) { if (\is_array($input)) { - $doctrineInput = \array_map(function ($ident) { - return $this->doctrineExpressionBuilder->literal($ident); - }, $input); - $ocInput = \array_map(function ($ident) { - return $this->expressionBuilder->literal($ident); - }, $input); + $doctrineInput = \array_map(fn ($ident) => $this->doctrineExpressionBuilder->literal($ident), $input); + $ocInput = \array_map(fn ($ident) => $this->expressionBuilder->literal($ident), $input); } else { $doctrineInput = $this->doctrineExpressionBuilder->literal($input); $ocInput = $this->expressionBuilder->literal($input); } } else { if (\is_array($input)) { - $doctrineInput = \array_map(function ($input) { - return '`' . $input . '`'; - }, $input); + $doctrineInput = \array_map(fn ($input) => '`' . $input . '`', $input); $ocInput = $input; } else { $doctrineInput = '`' . $input . '`'; @@ -341,7 +335,7 @@ public function testLiteral($input, $type) { /** @var \OC\DB\QueryBuilder\Literal $actual */ $actual = $this->expressionBuilder->literal($input, $type); - $this->assertInstanceOf('\OC\DB\QueryBuilder\Literal', $actual); + $this->assertInstanceOf('\\' . \OC\DB\QueryBuilder\Literal::class, $actual); $this->assertEquals( $this->doctrineExpressionBuilder->literal($input, $type), $actual->__toString() diff --git a/tests/lib/DB/QueryBuilder/QuoteHelperTest.php b/tests/lib/DB/QueryBuilder/QuoteHelperTest.php index 98ea8b58e4bb..6d832d31fa7b 100644 --- a/tests/lib/DB/QueryBuilder/QuoteHelperTest.php +++ b/tests/lib/DB/QueryBuilder/QuoteHelperTest.php @@ -136,7 +136,7 @@ public function quoteColumnName($string) { } if (\substr_count($string, '.')) { - list($alias, $columnName) = \explode('.', $string); + [$alias, $columnName] = \explode('.', $string); return '`' . $alias . '`.`' . $columnName . '`'; } diff --git a/tests/lib/DB/SchemaDiffTest.php b/tests/lib/DB/SchemaDiffTest.php index 60522ca74f69..f4f62adcb234 100644 --- a/tests/lib/DB/SchemaDiffTest.php +++ b/tests/lib/DB/SchemaDiffTest.php @@ -39,14 +39,12 @@ class SchemaDiffTest extends TestCase { /** @var \Doctrine\DBAL\Connection $connection */ private $connection; - /** @var MDB2SchemaManager */ - private $manager; + private \OC\DB\MDB2SchemaManager $manager; /** @var IConfig */ private $config; - /** @var string */ - private $testPrefix; + private string $testPrefix; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/DateTimeFormatterTest.php b/tests/lib/DateTimeFormatterTest.php index f6639798ac92..b17148b68a55 100644 --- a/tests/lib/DateTimeFormatterTest.php +++ b/tests/lib/DateTimeFormatterTest.php @@ -42,7 +42,7 @@ protected function getTimestampAgo($time, $seconds = 0, $minutes = 0, $hours = 0 } public function formatTimeSpanData() { - $time = 1416916800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo + $time = 1_416_916_800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo $deL10N = \OC::$server->getL10NFactory()->get('lib', 'de'); return [ ['seconds ago', $time, $time], @@ -80,7 +80,7 @@ public function testFormatTimeSpan($expected, $timestamp, $compare, $locale = nu } public function formatDateSpanData() { - $time = 1416916800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo + $time = 1_416_916_800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo $deL10N = \OC::$server->getL10NFactory()->get('lib', 'de'); return [ // Normal testing @@ -141,7 +141,7 @@ public function testFormatDateSpan($expected, $timestamp, $compare = null, $loca public function formatDateData() { return [ - [1102831200, 'December 12, 2004'], + [1_102_831_200, 'December 12, 2004'], ]; } @@ -155,8 +155,8 @@ public function testFormatDate($timestamp, $expected) { public function formatDateTimeData() { $narrowNoBreakSpace = "\xE2\x80\xAF"; return [ - [1350129205, null, "October 13, 2012, 11:53:25{$narrowNoBreakSpace}AM UTC"], - [1350129205, new \DateTimeZone('Europe/Berlin'), "October 13, 2012, 1:53:25{$narrowNoBreakSpace}PM GMT+2"], + [1_350_129_205, null, "October 13, 2012, 11:53:25{$narrowNoBreakSpace}AM UTC"], + [1_350_129_205, new \DateTimeZone('Europe/Berlin'), "October 13, 2012, 1:53:25{$narrowNoBreakSpace}PM GMT+2"], ]; } @@ -179,6 +179,6 @@ public function testFormatDateTime($timestamp, $timeZone, $expected) { public function testFormatDateWithInvalidTZ() { $this->expectException(\Exception::class); - $this->formatter->formatDate(1350129205, 'long', new \DateTimeZone('Mordor/Barad-dûr')); + $this->formatter->formatDate(1_350_129_205, 'long', new \DateTimeZone('Mordor/Barad-dûr')); } } diff --git a/tests/lib/Diagnostics/EventLoggerTest.php b/tests/lib/Diagnostics/EventLoggerTest.php index b92f8eb504f5..55627f28cbf4 100644 --- a/tests/lib/Diagnostics/EventLoggerTest.php +++ b/tests/lib/Diagnostics/EventLoggerTest.php @@ -25,8 +25,7 @@ use Test\TestCase; class EventLoggerTest extends TestCase { - /** @var \OC\Diagnostics\EventLogger */ - private $logger; + private \OC\Diagnostics\EventLogger $logger; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Diagnostics/QueryLoggerTest.php b/tests/lib/Diagnostics/QueryLoggerTest.php index 7af65790bd77..26e220ea20b5 100644 --- a/tests/lib/Diagnostics/QueryLoggerTest.php +++ b/tests/lib/Diagnostics/QueryLoggerTest.php @@ -25,8 +25,7 @@ use Test\TestCase; class QueryLoggerTest extends TestCase { - /** @var \OC\Diagnostics\QueryLogger */ - private $logger; + private \OC\Diagnostics\QueryLogger $logger; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Encryption/DecryptAllTest.php b/tests/lib/Encryption/DecryptAllTest.php index a5e0b4a7c244..db2e4ca52081 100644 --- a/tests/lib/Encryption/DecryptAllTest.php +++ b/tests/lib/Encryption/DecryptAllTest.php @@ -226,9 +226,7 @@ public function testPrepareEncryptionModules($success) { ->with($this->inputInterface, $this->outputInterface, $user) ->willReturn($success); - $callback = function () use ($dummyEncryptionModule) { - return $dummyEncryptionModule; - }; + $callback = fn () => $dummyEncryptionModule; $moduleDescription = [ 'id' => 'id', 'displayName' => 'displayName', @@ -364,7 +362,7 @@ public function testDecryptAllUsersFilesUsersSeen($prepareEncryptionModulesRetur 'display_name' => 'user1', 'quota' => null, 'last_login' => '1527174420', - 'backend' => 'OC\User\Database', + 'backend' => \OC\User\Database::class, 'home' => '', 'state' => 1 ]; @@ -475,9 +473,7 @@ public function testDecryptUsersFiles($decryptBehavior, $storageClass) { $storage = $this->createMock($storageClass); $storage->expects($this->any()) ->method('instanceOfStorage') - ->will($this->returnCallback(function ($className) use ($storage) { - return ($storage instanceof $className); - })); + ->will($this->returnCallback(fn ($className) => $storage instanceof $className)); /** @var DecryptAll | \PHPUnit\Framework\MockObject\MockObject $instance */ $instance = $this->getMockBuilder(DecryptAll::class) @@ -580,7 +576,7 @@ public function testDecryptFile() { $this->view->expects($this->once()) ->method('rename') ->with($path . '.decrypted.42.part', $path); - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $fileCache = $this->createMock(Cache::class); $fileCache->expects($this->once()) ->method('put') @@ -681,7 +677,7 @@ public function testDecryptFileFailure() { * @param $path */ private function markTestSkippedIfStorageHasOwnVersioning(View $view, $path) { - list($storage, $internalPath) = $view->resolvePath($path); + [$storage, $internalPath] = $view->resolvePath($path); if ($storage->instanceOfStorage(ObjectStoreStorage::class)) { $this->markTestSkipped(); } diff --git a/tests/lib/Encryption/EncryptionWrapperTest.php b/tests/lib/Encryption/EncryptionWrapperTest.php index dc08255c519a..7d0347be2eea 100644 --- a/tests/lib/Encryption/EncryptionWrapperTest.php +++ b/tests/lib/Encryption/EncryptionWrapperTest.php @@ -25,25 +25,24 @@ use Test\TestCase; class EncryptionWrapperTest extends TestCase { - /** @var EncryptionWrapper */ - private $instance; + private \OC\Encryption\EncryptionWrapper $instance; /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var \PHPUnit\Framework\MockObject\MockObject | \OC\Encryption\Manager */ - private $manager; + private \PHPUnit\Framework\MockObject\MockObject $manager; /** @var \PHPUnit\Framework\MockObject\MockObject | \OC\Memcache\ArrayCache */ - private $arrayCache; + private \PHPUnit\Framework\MockObject\MockObject $arrayCache; public function setUp(): void { parent::setUp(); - $this->arrayCache = $this->createMock('OC\Memcache\ArrayCache'); - $this->manager = $this->getMockBuilder('OC\Encryption\Manager') + $this->arrayCache = $this->createMock(\OC\Memcache\ArrayCache::class); + $this->manager = $this->getMockBuilder(\OC\Encryption\Manager::class) ->disableOriginalConstructor()->getMock(); - $this->logger = $this->createMock('OCP\ILogger'); + $this->logger = $this->createMock(\OCP\ILogger::class); $this->instance = new EncryptionWrapper($this->arrayCache, $this->manager, $this->logger); } @@ -52,7 +51,7 @@ public function setUp(): void { * @dataProvider provideWrapStorage */ public function testWrapStorage($expectedWrapped, $wrappedStorages) { - $storage = $this->getMockBuilder('OC\Files\Storage\Storage') + $storage = $this->getMockBuilder(\OC\Files\Storage\Storage::class) ->disableOriginalConstructor() ->getMock(); @@ -64,7 +63,7 @@ public function testWrapStorage($expectedWrapped, $wrappedStorages) { ]); } - $mount = $this->getMockBuilder('OCP\Files\Mount\IMountPoint') + $mount = $this->getMockBuilder(\OCP\Files\Mount\IMountPoint::class) ->disableOriginalConstructor() ->getMock(); @@ -72,7 +71,7 @@ public function testWrapStorage($expectedWrapped, $wrappedStorages) { $this->assertEquals( $expectedWrapped, - $returnedStorage->instanceOfStorage('OC\Files\Storage\Wrapper\Encryption'), + $returnedStorage->instanceOfStorage(\OC\Files\Storage\Wrapper\Encryption::class), 'Asserted that the storage is (not) wrapped with encryption' ); } @@ -81,16 +80,16 @@ public function provideWrapStorage() { return [ // Wrap when not wrapped or not wrapped with storage [true, []], - [true, ['OCA\Files_Trashbin\Storage']], + [true, [\OCA\Files_Trashbin\Storage::class]], // Do not wrap shared storages - [false, ['OCA\Files_Sharing\SharedStorage']], - [false, ['OCA\Files_Sharing\External\Storage']], + [false, [\OCA\Files_Sharing\SharedStorage::class]], + [false, [\OCA\Files_Sharing\External\Storage::class]], [false, ['OC\Files\Storage\OwnCloud']], - [false, ['OCA\Files_Sharing\SharedStorage', 'OCA\Files_Sharing\External\Storage']], - [false, ['OCA\Files_Sharing\SharedStorage', 'OC\Files\Storage\OwnCloud']], - [false, ['OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], - [false, ['OCA\Files_Sharing\SharedStorage', 'OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], + [false, [\OCA\Files_Sharing\SharedStorage::class, \OCA\Files_Sharing\External\Storage::class]], + [false, [\OCA\Files_Sharing\SharedStorage::class, 'OC\Files\Storage\OwnCloud']], + [false, [\OCA\Files_Sharing\External\Storage::class, 'OC\Files\Storage\OwnCloud']], + [false, [\OCA\Files_Sharing\SharedStorage::class, \OCA\Files_Sharing\External\Storage::class, 'OC\Files\Storage\OwnCloud']], ]; } } diff --git a/tests/lib/Encryption/Keys/StorageTest.php b/tests/lib/Encryption/Keys/StorageTest.php index d24cee79b749..cc711fb3e965 100644 --- a/tests/lib/Encryption/Keys/StorageTest.php +++ b/tests/lib/Encryption/Keys/StorageTest.php @@ -57,17 +57,17 @@ class StorageTest extends TestCase { public function setUp(): void { parent::setUp(); - $this->util = $this->getMockBuilder('OC\Encryption\Util') + $this->util = $this->getMockBuilder(\OC\Encryption\Util::class) ->disableOriginalConstructor() ->getMock(); $this->util->method('getKeyStorageRoot')->willReturn(''); - $this->view = $this->getMockBuilder('OC\Files\View') + $this->view = $this->getMockBuilder(\OC\Files\View::class) ->disableOriginalConstructor() ->getMock(); - $this->config = $this->getMockBuilder('OCP\IConfig') + $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); @@ -329,9 +329,7 @@ private function isUserHomeMounted($userId) { // verify that user2's FS got mounted when retrieving the key $mountManager = \OC::$server->getMountManager(); $mounts = $mountManager->getAll(); - $mounts = \array_filter($mounts, function ($mount) use ($userId) { - return ($mount->getMountPoint() === "/$userId/"); - }); + $mounts = \array_filter($mounts, fn ($mount) => $mount->getMountPoint() === "/$userId/"); return !empty($mounts); } diff --git a/tests/lib/Encryption/ManagerTest.php b/tests/lib/Encryption/ManagerTest.php index 7b746ac53929..b179ebe148f1 100644 --- a/tests/lib/Encryption/ManagerTest.php +++ b/tests/lib/Encryption/ManagerTest.php @@ -6,35 +6,29 @@ use Test\TestCase; class ManagerTest extends TestCase { - /** @var Manager */ - private $manager; + private \OC\Encryption\Manager $manager; - /** @var \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; - /** @var \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; - /** @var \PHPUnit\Framework\MockObject\MockObject */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; - /** @var \PHPUnit\Framework\MockObject\MockObject */ - private $view; + private \PHPUnit\Framework\MockObject\MockObject $view; - /** @var \PHPUnit\Framework\MockObject\MockObject */ - private $util; + private \PHPUnit\Framework\MockObject\MockObject $util; /** @var \PHPUnit\Framework\MockObject\MockObject | \OC\Memcache\ArrayCache */ - private $arrayCache; + private \PHPUnit\Framework\MockObject\MockObject $arrayCache; public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('\OCP\IConfig'); - $this->logger = $this->createMock('\OCP\ILogger'); - $this->l10n = $this->createMock('\OCP\Il10n'); - $this->view = $this->createMock('\OC\Files\View'); - $this->util = $this->getMockBuilder('\OC\Encryption\Util')->disableOriginalConstructor()->getMock(); - $this->arrayCache = $this->createMock('OC\Memcache\ArrayCache'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->logger = $this->createMock('\\' . \OCP\ILogger::class); + $this->l10n = $this->createMock('\\' . \OCP\Il10n::class); + $this->view = $this->createMock('\\' . \OC\Files\View::class); + $this->util = $this->getMockBuilder('\\' . \OC\Encryption\Util::class)->disableOriginalConstructor()->getMock(); + $this->arrayCache = $this->createMock(\OC\Memcache\ArrayCache::class); $this->manager = new Manager($this->config, $this->logger, $this->l10n, $this->view, $this->util, $this->arrayCache); } @@ -49,12 +43,10 @@ public function testManagerIsDisabledIfEnabledButNoModules() { public function testManagerIsDisabledIfDisabledButModules() { $this->config->expects($this->any())->method('getAppValue')->willReturn(false); - $em = $this->createMock('\OCP\Encryption\IEncryptionModule'); + $em = $this->createMock('\\' . \OCP\Encryption\IEncryptionModule::class); $em->expects($this->any())->method('getId')->willReturn('id'); $em->expects($this->any())->method('getDisplayName')->willReturn('TestDummyModule0'); - $this->manager->registerEncryptionModule('id', 'TestDummyModule0', function () use ($em) { - return $em; - }); + $this->manager->registerEncryptionModule('id', 'TestDummyModule0', fn () => $em); $this->assertFalse($this->manager->isEnabled()); } @@ -246,7 +238,7 @@ public function testSetDefaultEncryptionModule() { // } protected function addNewEncryptionModule(Manager $manager, $id) { - $encryptionModule = $this->createMock('\OCP\Encryption\IEncryptionModule'); + $encryptionModule = $this->createMock('\\' . \OCP\Encryption\IEncryptionModule::class); $encryptionModule->expects($this->any()) ->method('getId') ->willReturn('ID' . $id); @@ -254,8 +246,6 @@ protected function addNewEncryptionModule(Manager $manager, $id) { ->method('getDisplayName') ->willReturn('TestDummyModule' . $id); /** @var \OCP\Encryption\IEncryptionModule $encryptionModule */ - $manager->registerEncryptionModule('ID' . $id, 'TestDummyModule' . $id, function () use ($encryptionModule) { - return $encryptionModule; - }); + $manager->registerEncryptionModule('ID' . $id, 'TestDummyModule' . $id, fn () => $encryptionModule); } } diff --git a/tests/lib/Encryption/UpdateTest.php b/tests/lib/Encryption/UpdateTest.php index 65a2a33944de..532c8a4b26ed 100644 --- a/tests/lib/Encryption/UpdateTest.php +++ b/tests/lib/Encryption/UpdateTest.php @@ -25,44 +25,42 @@ use Test\TestCase; class UpdateTest extends TestCase { - /** @var \OC\Encryption\Update */ - private $update; + private \OC\Encryption\Update $update; - /** @var string */ - private $uid; + private string $uid; /** @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject */ - private $view; + private \PHPUnit\Framework\MockObject\MockObject $view; /** @var \OC\Encryption\Util | \PHPUnit\Framework\MockObject\MockObject */ - private $util; + private \PHPUnit\Framework\MockObject\MockObject $util; /** @var \OC\Files\Mount\Manager | \PHPUnit\Framework\MockObject\MockObject */ - private $mountManager; + private \PHPUnit\Framework\MockObject\MockObject $mountManager; /** @var \OC\Encryption\Manager | \PHPUnit\Framework\MockObject\MockObject */ - private $encryptionManager; + private \PHPUnit\Framework\MockObject\MockObject $encryptionManager; /** @var \OCP\Encryption\IEncryptionModule | \PHPUnit\Framework\MockObject\MockObject */ - private $encryptionModule; + private \PHPUnit\Framework\MockObject\MockObject $encryptionModule; /** @var \OC\Encryption\File | \PHPUnit\Framework\MockObject\MockObject */ - private $fileHelper; + private \PHPUnit\Framework\MockObject\MockObject $fileHelper; protected function setUp(): void { parent::setUp(); - $this->view = $this->getMockBuilder('\OC\Files\View') + $this->view = $this->getMockBuilder('\\' . \OC\Files\View::class) ->disableOriginalConstructor()->getMock(); - $this->util = $this->getMockBuilder('\OC\Encryption\Util') + $this->util = $this->getMockBuilder('\\' . \OC\Encryption\Util::class) ->disableOriginalConstructor()->getMock(); - $this->mountManager = $this->getMockBuilder('\OC\Files\Mount\Manager') + $this->mountManager = $this->getMockBuilder('\\' . \OC\Files\Mount\Manager::class) ->disableOriginalConstructor()->getMock(); - $this->encryptionManager = $this->getMockBuilder('\OC\Encryption\Manager') + $this->encryptionManager = $this->getMockBuilder('\\' . \OC\Encryption\Manager::class) ->disableOriginalConstructor()->getMock(); - $this->fileHelper = $this->getMockBuilder('\OC\Encryption\File') + $this->fileHelper = $this->getMockBuilder('\\' . \OC\Encryption\File::class) ->disableOriginalConstructor()->getMock(); - $this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') + $this->encryptionModule = $this->getMockBuilder('\\' . \OCP\Encryption\IEncryptionModule::class) ->disableOriginalConstructor()->getMock(); $this->uid = 'testUser1'; @@ -213,7 +211,7 @@ public function dataTestPostRestore() { * @return \OC\Encryption\Update | \PHPUnit\Framework\MockObject\MockObject */ protected function getUpdateMock($methods) { - return $this->getMockBuilder('\OC\Encryption\Update') + return $this->getMockBuilder('\\' . \OC\Encryption\Update::class) ->setConstructorArgs( [ $this->view, diff --git a/tests/lib/Encryption/UtilTest.php b/tests/lib/Encryption/UtilTest.php index e6d089f4d1b1..8f17c6d95308 100644 --- a/tests/lib/Encryption/UtilTest.php +++ b/tests/lib/Encryption/UtilTest.php @@ -22,27 +22,25 @@ class UtilTest extends TestCase { /** @var \PHPUnit\Framework\MockObject\MockObject */ protected $groupManager; - /** @var \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; - /** @var \OC\Encryption\Util */ - private $util; + private \OC\Encryption\Util $util; public function setUp(): void { parent::setUp(); - $this->view = $this->getMockBuilder('OC\Files\View') + $this->view = $this->getMockBuilder(\OC\Files\View::class) ->disableOriginalConstructor() ->getMock(); - $this->userManager = $this->getMockBuilder('OC\User\Manager') + $this->userManager = $this->getMockBuilder(\OC\User\Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->groupManager = $this->getMockBuilder('OC\Group\Manager') + $this->groupManager = $this->getMockBuilder(\OC\Group\Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->config = $this->getMockBuilder('OCP\IConfig') + $this->config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); @@ -74,7 +72,7 @@ public function providesHeadersForEncryptionModule() { * @dataProvider providesHeaders */ public function testCreateHeader($expected, $header, $moduleId) { - $em = $this->createMock('\OCP\Encryption\IEncryptionModule'); + $em = $this->createMock('\\' . \OCP\Encryption\IEncryptionModule::class); $em->expects($this->any())->method('getId')->willReturn($moduleId); $result = $this->util->createHeader($header, $em); @@ -97,7 +95,7 @@ public function testCreateHeaderFailed() { $header = ['header1' => 1, 'header2' => 2, 'oc_encryption_module' => 'foo']; - $em = $this->createMock('\OCP\Encryption\IEncryptionModule'); + $em = $this->createMock('\\' . \OCP\Encryption\IEncryptionModule::class); $em->expects($this->any())->method('getId')->willReturn('moduleId'); $this->util->createHeader($header, $em); diff --git a/tests/lib/Events/EventEmitterTraitTest.php b/tests/lib/Events/EventEmitterTraitTest.php index 8c96ddacaf56..2cf610e881e4 100644 --- a/tests/lib/Events/EventEmitterTraitTest.php +++ b/tests/lib/Events/EventEmitterTraitTest.php @@ -48,9 +48,7 @@ public function testEmittingCall($className, $eventName, $data) { $calledBeforeEvent[] = $event; }); - $this->emittingCall(function () { - return true; - }, ['before' => $data['before'], 'after' => $data['after']], $className, $eventName); + $this->emittingCall(fn () => true, ['before' => $data['before'], 'after' => $data['after']], $className, $eventName); if (isset($data['before']) and (\count($data['before']) > 0)) { $this->assertEquals($calledBeforeEvent[0], "$className.before$eventName"); diff --git a/tests/lib/FileChunkingTest.php b/tests/lib/FileChunkingTest.php index f0b5bc4b89cc..80631bb00c75 100644 --- a/tests/lib/FileChunkingTest.php +++ b/tests/lib/FileChunkingTest.php @@ -53,7 +53,7 @@ public function testIsComplete($total, array $present, $expected) { ]]) ->getMock(); - $cache = $this->createMock('\OCP\ICache'); + $cache = $this->createMock('\\' . \OCP\ICache::class); $cache->expects($this->atLeastOnce()) ->method('hasKey') diff --git a/tests/lib/Files/Cache/CacheTest.php b/tests/lib/Files/Cache/CacheTest.php index cfe4fc8948fd..1dfab511799c 100644 --- a/tests/lib/Files/Cache/CacheTest.php +++ b/tests/lib/Files/Cache/CacheTest.php @@ -365,9 +365,7 @@ public function testSearchByTag() { $this->assertCount(2, $results); - \usort($results, function ($value1, $value2) { - return \strcmp($value1['name'], $value2['name']); - }); + \usort($results, fn ($value1, $value2) => \strcmp($value1['name'], $value2['name'])); $this->assertEquals('folder', $results[0]['name']); $this->assertEquals('foo', $results[1]['name']); @@ -375,15 +373,11 @@ public function testSearchByTag() { // use tag id $tags = $tagManager->getTagsForUser($userId); $this->assertNotEmpty($tags); - $tags = \array_filter($tags, function ($tag) { - return $tag->getName() === 'tag2'; - }); + $tags = \array_filter($tags, fn ($tag) => $tag->getName() === 'tag2'); $results = $this->cache->searchByTag(\current($tags)->getId(), $userId); $this->assertCount(3, $results); - \usort($results, function ($value1, $value2) { - return \strcmp($value1['name'], $value2['name']); - }); + \usort($results, fn ($value1, $value2) => \strcmp($value1['name'], $value2['name'])); $this->assertEquals('folder', $results[0]['name']); $this->assertEquals('foo2', $results[1]['name']); @@ -529,7 +523,7 @@ public function testWithNormalizer(): void { $this->assertEquals($folderWith00F6, $unNormalizedFolderName['name']); // put normalized folder - $this->assertInstanceOf('\OCP\Files\Cache\ICacheEntry', $this->cache->get('folder/' . $folderWith00F6)); + $this->assertInstanceOf('\\' . \OCP\Files\Cache\ICacheEntry::class, $this->cache->get('folder/' . $folderWith00F6)); $this->assertGreaterThan(0, $this->cache->put('folder/' . $folderWith00F6, $data)); // at this point we should have only one folder named "Schön" diff --git a/tests/lib/Files/Cache/HomeCacheTest.php b/tests/lib/Files/Cache/HomeCacheTest.php index 09a5464e3aef..1c6e899b608b 100644 --- a/tests/lib/Files/Cache/HomeCacheTest.php +++ b/tests/lib/Files/Cache/HomeCacheTest.php @@ -51,10 +51,7 @@ public function getUID() { * @package Test\Files\Cache */ class HomeCacheTest extends \Test\TestCase { - /** - * @var \OC\Files\Storage\Home $storage - */ - private $storage; + private \OC\Files\Storage\Home $storage; /** * @var \OC\Files\Cache\HomeCache $cache @@ -64,7 +61,7 @@ class HomeCacheTest extends \Test\TestCase { /** * @var \OC\User\User $user */ - private $user; + private \Test\Files\Cache\DummyUser $user; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Cache/PropagatorTest.php b/tests/lib/Files/Cache/PropagatorTest.php index 97a40512fc9c..250f709577c9 100644 --- a/tests/lib/Files/Cache/PropagatorTest.php +++ b/tests/lib/Files/Cache/PropagatorTest.php @@ -18,7 +18,7 @@ */ class PropagatorTest extends TestCase { /** @var IStorage */ - private $storage; + private \OC\Files\Storage\Temporary $storage; public function setUp(): void { parent::setUp(); @@ -33,9 +33,7 @@ public function setUp(): void { * @return ICacheEntry[] */ private function getFileInfos($paths) { - $values = \array_map(function ($path) { - return $this->storage->getCache()->get($path); - }, $paths); + $values = \array_map(fn ($path) => $this->storage->getCache()->get($path), $paths); return \array_combine($paths, $values); } diff --git a/tests/lib/Files/Cache/ScannerTest.php b/tests/lib/Files/Cache/ScannerTest.php index 46e130ab73e0..5c46ba5bb613 100644 --- a/tests/lib/Files/Cache/ScannerTest.php +++ b/tests/lib/Files/Cache/ScannerTest.php @@ -27,15 +27,9 @@ class ScannerTest extends \Test\TestCase { */ private $storage; - /** - * @var \OC\Files\Cache\Scanner $scanner - */ - private $scanner; + private \OC\Files\Cache\Scanner $scanner; - /** - * @var \OC\Files\Cache\Cache $cache - */ - private $cache; + private \OC\Files\Cache\Cache $cache; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Cache/UpdaterLegacyTest.php b/tests/lib/Files/Cache/UpdaterLegacyTest.php index 7a689e2e2659..65a29685b137 100644 --- a/tests/lib/Files/Cache/UpdaterLegacyTest.php +++ b/tests/lib/Files/Cache/UpdaterLegacyTest.php @@ -22,7 +22,7 @@ class UpdaterLegacyTest extends \Test\TestCase { /** * @var \OC\Files\Storage\Storage $storage */ - private $storage; + private \OC\Files\Storage\Temporary $storage; /** * @var \OC\Files\Cache\Scanner $scanner @@ -289,7 +289,7 @@ public function testTouch() { $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $cachedData['mtime']); $rootCachedData = $cachedData; - $time = 1371006070; + $time = 1_371_006_070; $barCachedData = $this->cache->get('folder/bar.txt'); $folderCachedData = $this->cache->get('folder'); $this->cache->put('', ['mtime' => $time - 100]); diff --git a/tests/lib/Files/Cache/UpdaterTest.php b/tests/lib/Files/Cache/UpdaterTest.php index 8157bdc8126a..280cf601f288 100644 --- a/tests/lib/Files/Cache/UpdaterTest.php +++ b/tests/lib/Files/Cache/UpdaterTest.php @@ -182,7 +182,7 @@ public function testUpdateStorageMTime() { $this->storage->rename('sub/foo.txt', 'sub2/bar.txt'); // simulate storage having a different mtime - $testmtime = 1433323578; + $testmtime = 1_433_323_578; // source storage mtime change $this->storage->touch('sub', $testmtime); diff --git a/tests/lib/Files/Cache/WatcherTest.php b/tests/lib/Files/Cache/WatcherTest.php index 35f5b03174ad..faa4e992503e 100644 --- a/tests/lib/Files/Cache/WatcherTest.php +++ b/tests/lib/Files/Cache/WatcherTest.php @@ -19,7 +19,7 @@ class WatcherTest extends \Test\TestCase { /** * @var \OC\Files\Storage\Storage[] $storages */ - private $storages = []; + private array $storages = []; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Config/UserMountCacheTest.php b/tests/lib/Files/Config/UserMountCacheTest.php index 120f6d11c34e..5df4fa48f1b3 100644 --- a/tests/lib/Files/Config/UserMountCacheTest.php +++ b/tests/lib/Files/Config/UserMountCacheTest.php @@ -41,12 +41,9 @@ class UserMountCacheTest extends TestCase { /** * @var IUserManager */ - private $userManager; + private \OC\User\Manager $userManager; - /** - * @var UserMountCache - */ - private $cache; + private \OC\Files\Config\UserMountCache $cache; /** * @var \OCP\Util\UserSearch @@ -111,21 +108,21 @@ public function tearDown(): void { } private function getStorage($storageId, $rootId) { - $storageCache = $this->getMockBuilder('\OC\Files\Cache\Storage') + $storageCache = $this->getMockBuilder('\\' . \OC\Files\Cache\Storage::class) ->disableOriginalConstructor() ->getMock(); $storageCache->expects($this->any()) ->method('getNumericId') ->will($this->returnValue($storageId)); - $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') + $cache = $this->getMockBuilder('\\' . \OC\Files\Cache\Cache::class) ->disableOriginalConstructor() ->getMock(); $cache->expects($this->any()) ->method('getId') ->will($this->returnValue($rootId)); - $storage = $this->getMockBuilder('\OC\Files\Storage\Storage') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Storage::class) ->disableOriginalConstructor() ->getMock(); $storage->expects($this->any()) @@ -316,9 +313,7 @@ public function testGetMountsByRootId() { } private function sortMounts(&$mounts) { - \usort($mounts, function (ICachedMountInfo $a, ICachedMountInfo $b) { - return \strcmp($a->getUser()->getUID(), $b->getUser()->getUID()); - }); + \usort($mounts, fn (ICachedMountInfo $a, ICachedMountInfo $b) => \strcmp($a->getUser()->getUID(), $b->getUser()->getUID())); } private function createCacheEntry($internalPath, $storageId) { diff --git a/tests/lib/Files/EtagTest.php b/tests/lib/Files/EtagTest.php index 9585452b8aca..0a693a8f588b 100644 --- a/tests/lib/Files/EtagTest.php +++ b/tests/lib/Files/EtagTest.php @@ -32,8 +32,8 @@ protected function setUp(): void { \OC_Hook::clear('OC_Filesystem', 'setup'); $application = new \OCA\Files_Sharing\AppInfo\Application(); $application->registerMountProviders(); - \OCP\Share::registerBackend('file', 'OCA\Files_Sharing\ShareBackend\File'); - \OCP\Share::registerBackend('folder', 'OCA\Files_Sharing\ShareBackend\Folder', 'file'); + \OCP\Share::registerBackend('file', \OCA\Files_Sharing\ShareBackend\File::class); + \OCP\Share::registerBackend('folder', \OCA\Files_Sharing\ShareBackend\Folder::class, 'file'); $config = \OC::$server->getConfig(); $this->datadir = $config->getSystemValue('datadirectory'); diff --git a/tests/lib/Files/External/Auth/AuthMechanismTest.php b/tests/lib/Files/External/Auth/AuthMechanismTest.php index 1a2c33e39c0c..14a0a70407f2 100644 --- a/tests/lib/Files/External/Auth/AuthMechanismTest.php +++ b/tests/lib/Files/External/Auth/AuthMechanismTest.php @@ -23,7 +23,7 @@ class AuthMechanismTest extends \Test\TestCase { public function testJsonSerialization() { - $mechanism = $this->getMockBuilder('\OCP\Files\External\Auth\AuthMechanism') + $mechanism = $this->getMockBuilder('\\' . \OCP\Files\External\Auth\AuthMechanism::class) ->setMethods(['jsonSerializeDefinition']) ->getMock(); $mechanism->expects($this->once()) @@ -50,7 +50,7 @@ public function validateStorageProvider() { * @dataProvider validateStorageProvider */ public function testValidateStorage($expectedSuccess, $scheme, $definitionSuccess) { - $mechanism = $this->getMockBuilder('\OCP\Files\External\Auth\AuthMechanism') + $mechanism = $this->getMockBuilder('\\' . \OCP\Files\External\Auth\AuthMechanism::class) ->setMethods(['validateStorageDefinition']) ->getMock(); $mechanism->expects($this->atMost(1)) @@ -59,14 +59,14 @@ public function testValidateStorage($expectedSuccess, $scheme, $definitionSucces $mechanism->setScheme($scheme); - $backend = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->disableOriginalConstructor() ->getMock(); $backend->expects($this->once()) ->method('getAuthSchemes') ->willReturn(['scheme' => true, 'foobar' => true]); - $storageConfig = $this->getMockBuilder('\OCP\Files\External\IStorageConfig') + $storageConfig = $this->getMockBuilder('\\' . \OCP\Files\External\IStorageConfig::class) ->disableOriginalConstructor() ->getMock(); $storageConfig->expects($this->once()) diff --git a/tests/lib/Files/External/Auth/Password/SessionCredentialsTest.php b/tests/lib/Files/External/Auth/Password/SessionCredentialsTest.php index 9c0e9e40898f..2cb98c27456d 100644 --- a/tests/lib/Files/External/Auth/Password/SessionCredentialsTest.php +++ b/tests/lib/Files/External/Auth/Password/SessionCredentialsTest.php @@ -29,13 +29,13 @@ class SessionCredentialsTest extends \Test\TestCase { /** @var SessionCredentials | \PHPUnit\Framework\MockObject\MockObject */ - private $authMech; + private \OC\Files\External\Auth\Password\SessionCredentials $authMech; /** @var ISession | \PHPUnit\Framework\MockObject\MockObject */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; /** @var ICrypto | \PHPUnit\Framework\MockObject\MockObject */ - private $crypto; + private \PHPUnit\Framework\MockObject\MockObject $crypto; public function setUp(): void { parent::setUp(); @@ -87,9 +87,7 @@ public function testManipulateStorageConfigSetsBackendOptions($sessionData, $use } $this->session->method('get')->will($this->returnValueMap($sessionData)); - $this->session->method('exists')->will($this->returnCallback(function ($key) { - return $this->session->get($key) !== null; - })); + $this->session->method('exists')->will($this->returnCallback(fn ($key) => $this->session->get($key) !== null)); $this->crypto->expects($this->once()) ->method('decrypt') diff --git a/tests/lib/Files/External/Backend/BackendTest.php b/tests/lib/Files/External/Backend/BackendTest.php index 2355279180ca..be4355180526 100644 --- a/tests/lib/Files/External/Backend/BackendTest.php +++ b/tests/lib/Files/External/Backend/BackendTest.php @@ -23,7 +23,7 @@ class BackendTest extends \Test\TestCase { public function testJsonSerialization() { - $backend = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->setMethods(['jsonSerializeDefinition']) ->getMock(); $backend->expects($this->once()) @@ -55,14 +55,14 @@ public function validateStorageProvider() { * @dataProvider validateStorageProvider */ public function testValidateStorage($expectedSuccess, $definitionSuccess) { - $backend = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->setMethods(['validateStorageDefinition']) ->getMock(); $backend->expects($this->atMost(1)) ->method('validateStorageDefinition') ->willReturn($definitionSuccess); - $storageConfig = $this->getMockBuilder('\OCP\Files\External\IStorageConfig') + $storageConfig = $this->getMockBuilder('\\' . \OCP\Files\External\IStorageConfig::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Files/External/Backend/DummyBackend.php b/tests/lib/Files/External/Backend/DummyBackend.php index 047096f5aa78..55c05dab54db 100644 --- a/tests/lib/Files/External/Backend/DummyBackend.php +++ b/tests/lib/Files/External/Backend/DummyBackend.php @@ -29,8 +29,8 @@ class DummyBackend extends Backend { public function __construct() { $this ->setIdentifier('dummy') - ->addIdentifierAlias('\Test\Files\External\Backend\DummyBackend') // legacy compat - ->setStorageClass('\Test\Files\External\Backend\DummyStorage') + ->addIdentifierAlias('\\' . \Test\Files\External\Backend\DummyBackend::class) // legacy compat + ->setStorageClass('\\' . \Test\Files\External\Backend\DummyStorage::class) ->setText('Dummy') ->addParameters([ (new DefinitionParameter('param1', 'Param One')), diff --git a/tests/lib/Files/External/ConfigAdapterTest.php b/tests/lib/Files/External/ConfigAdapterTest.php index b87dd4cc15a4..ad11de9741f4 100644 --- a/tests/lib/Files/External/ConfigAdapterTest.php +++ b/tests/lib/Files/External/ConfigAdapterTest.php @@ -36,22 +36,21 @@ class ConfigAdapterTest extends \Test\TestCase { /** @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUserStoragesService */ - private $userStoragesService; + private \PHPUnit\Framework\MockObject\MockObject $userStoragesService; /** @var IUserGlobalStoragesService */ - private $userGlobalStoragesService; + private \PHPUnit\Framework\MockObject\MockObject $userGlobalStoragesService; /** @var IUser | \PHPUnit\Framework\MockObject\MockObject **/ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var ISession | \PHPUnit\Framework\MockObject\MockObject **/ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; - /** @var int */ - private $configId; + private int $configId; protected function setUp(): void { $this->config = $this->createMock(IConfig::class); @@ -86,7 +85,7 @@ private function createStorageConfig($mountPoint, $mountOptions, $storageOptions $backend->expects($this->once()) ->method('getStorageClass') - ->willReturn('\OC\Files\Storage\Temporary'); + ->willReturn('\\' . \OC\Files\Storage\Temporary::class); $backend->expects($this->once()) ->method('wrapStorage') diff --git a/tests/lib/Files/External/FrontendDefinitionTraitTest.php b/tests/lib/Files/External/FrontendDefinitionTraitTest.php index f1e062b6238d..e9fb1701426d 100644 --- a/tests/lib/Files/External/FrontendDefinitionTraitTest.php +++ b/tests/lib/Files/External/FrontendDefinitionTraitTest.php @@ -24,12 +24,12 @@ class FrontendDefinitionTraitTest extends \Test\TestCase { public function testJsonSerialization() { - $param = $this->getMockBuilder('\OCP\Files\External\DefinitionParameter') + $param = $this->getMockBuilder('\\' . \OCP\Files\External\DefinitionParameter::class) ->disableOriginalConstructor() ->getMock(); $param->method('getName')->willReturn('foo'); - $trait = $this->getMockForTrait('\OC\Files\External\FrontendDefinitionTrait'); + $trait = $this->getMockForTrait('\\' . \OC\Files\External\FrontendDefinitionTrait::class); $trait->setText('test'); $trait->addParameters([$param]); $trait->addCustomJs('foo/bar.js'); @@ -58,7 +58,7 @@ public function validateStorageProvider() { public function testValidateStorage($expectedSuccess, $params) { $backendParams = []; foreach ($params as $name => $valid) { - $param = $this->getMockBuilder('\OCP\Files\External\DefinitionParameter') + $param = $this->getMockBuilder('\\' . \OCP\Files\External\DefinitionParameter::class) ->disableOriginalConstructor() ->getMock(); $param->method('getName') @@ -71,7 +71,7 @@ public function testValidateStorage($expectedSuccess, $params) { $backendParams[] = $param; } - $storageConfig = $this->getMockBuilder('\OCP\Files\External\IStorageConfig') + $storageConfig = $this->getMockBuilder('\\' . \OCP\Files\External\IStorageConfig::class) ->disableOriginalConstructor() ->getMock(); $storageConfig->expects($this->any()) @@ -80,7 +80,7 @@ public function testValidateStorage($expectedSuccess, $params) { $storageConfig->expects($this->any()) ->method('setBackendOption'); - $trait = $this->getMockForTrait('\OC\Files\External\FrontendDefinitionTrait'); + $trait = $this->getMockForTrait('\\' . \OC\Files\External\FrontendDefinitionTrait::class); $trait->setText('test'); $trait->addParameters($backendParams); @@ -88,7 +88,7 @@ public function testValidateStorage($expectedSuccess, $params) { } public function testValidateStorageSet() { - $param = $this->getMockBuilder('\OCP\Files\External\DefinitionParameter') + $param = $this->getMockBuilder('\\' . \OCP\Files\External\DefinitionParameter::class) ->disableOriginalConstructor() ->getMock(); $param->method('getName') @@ -100,7 +100,7 @@ public function testValidateStorageSet() { return true; })); - $storageConfig = $this->getMockBuilder('\OCP\Files\External\IStorageConfig') + $storageConfig = $this->getMockBuilder('\\' . \OCP\Files\External\IStorageConfig::class) ->disableOriginalConstructor() ->getMock(); $storageConfig->expects($this->once()) @@ -111,7 +111,7 @@ public function testValidateStorageSet() { ->method('setBackendOption') ->with('param', 'foobar'); - $trait = $this->getMockForTrait('\OC\Files\External\FrontendDefinitionTrait'); + $trait = $this->getMockForTrait('\\' . \OC\Files\External\FrontendDefinitionTrait::class); $trait->setText('test'); $trait->addParameter($param); diff --git a/tests/lib/Files/External/PersonalMountTest.php b/tests/lib/Files/External/PersonalMountTest.php index 731c590d4847..04f2f34026b5 100644 --- a/tests/lib/Files/External/PersonalMountTest.php +++ b/tests/lib/Files/External/PersonalMountTest.php @@ -29,9 +29,9 @@ class PersonalMountTest extends TestCase { public function testFindByStorageId() { /** @var \OCP\Files\External\Service\IUserStoragesService $storageService */ - $storageService = $this->createMock('\OCP\Files\External\Service\IUserStoragesService'); + $storageService = $this->createMock('\\' . \OCP\Files\External\Service\IUserStoragesService::class); - $storage = $this->getMockBuilder('\OC\Files\Storage\Storage') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Storage::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Files/External/Service/CleaningDBConfig.php b/tests/lib/Files/External/Service/CleaningDBConfig.php index 81333907eb8b..ca101ccfbc9b 100644 --- a/tests/lib/Files/External/Service/CleaningDBConfig.php +++ b/tests/lib/Files/External/Service/CleaningDBConfig.php @@ -23,7 +23,7 @@ use OC\Files\External\Service\DBConfigService; class CleaningDBConfig extends DBConfigService { - private $mountIds = []; + private array $mountIds = []; public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) { $id = parent::addMount($mountPoint, $storageBackend, $authBackend, $priority, $type); // TODO: Change the autogenerated stub diff --git a/tests/lib/Files/External/Service/DBConfigServiceTest.php b/tests/lib/Files/External/Service/DBConfigServiceTest.php index 96888e04531a..8f10840cb4d1 100644 --- a/tests/lib/Files/External/Service/DBConfigServiceTest.php +++ b/tests/lib/Files/External/Service/DBConfigServiceTest.php @@ -30,17 +30,14 @@ * @group DB */ class DBConfigServiceTest extends TestCase { - /** - * @var DBConfigService - */ - private $dbConfig; + private \OC\Files\External\Service\DBConfigService $dbConfig; /** * @var IDBConnection */ private $connection; - private $mounts = []; + private array $mounts = []; public function setUp(): void { parent::setUp(); @@ -88,9 +85,7 @@ public function testAddApplicable() { $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null); $mount = $this->dbConfig->getMountById($id); - \usort($mount['applicable'], function ($m1, $m2) { - return $m1['type'] - $m2['type']; - }); + \usort($mount['applicable'], fn ($m1, $m2) => $m1['type'] - $m2['type']); $this->assertEquals([ ['type' => DBConfigService::APPLICABLE_TYPE_GLOBAL, 'value' => null, 'mount_id' => $id], diff --git a/tests/lib/Files/External/Service/GlobalStoragesServiceDeleteUserTest.php b/tests/lib/Files/External/Service/GlobalStoragesServiceDeleteUserTest.php index 67e36a61510f..306bcb098b2c 100644 --- a/tests/lib/Files/External/Service/GlobalStoragesServiceDeleteUserTest.php +++ b/tests/lib/Files/External/Service/GlobalStoragesServiceDeleteUserTest.php @@ -59,7 +59,7 @@ public function providesDeleteAllUser() { 'applicableGroups' => ['group1'], 'priority' => 12, 'authMechanism' => 'identifier:\Auth\Mechanism', - 'storageClass' => 'OC\Files\Storage\DAV', + 'storageClass' => \OC\Files\Storage\DAV::class, 'backendIdentifier' => 'identifier:\Test\Files\External\Backend\DummyBackend', 'backendOptions' => [ 'host' => 'http://localhost', @@ -74,7 +74,7 @@ public function providesDeleteAllUser() { 'applicableGroups' => [], 'priority' => 13, 'authMechanism' => 'identifier:\Auth\Mechanism', - 'storageClass' => 'OC\Files\Storage\DAV', + 'storageClass' => \OC\Files\Storage\DAV::class, 'backendIdentifier' => 'identifier:\Test\Files\External\Backend\DummyBackend2', 'backendOptions' => [ 'host' => 'http://localhost', @@ -88,7 +88,7 @@ public function providesDeleteAllUser() { 'applicableUsers' => ['user1', 'user4'], 'applicableGroups' => [], 'priority' => 14, - 'storageClass' => 'OC\Files\Storage\DAV', + 'storageClass' => \OC\Files\Storage\DAV::class, 'authMechanism' => 'identifier:\Auth\Mechanism', 'backendIdentifier' => 'identifier:\Test\Files\External\Backend\DummyBackend2', 'backendOptions' => [ @@ -105,7 +105,7 @@ public function providesDeleteAllUser() { 'applicableGroups' => [], 'priority' => 15, 'authMechanism' => 'identifier:\Auth\Mechanism', - 'storageClass' => 'OC\Files\Storage\DAV', + 'storageClass' => \OC\Files\Storage\DAV::class, 'backendIdentifier' => 'identifier:\Test\Files\External\Backend\DummyBackend2', 'backendOptions' => [ 'host' => 'http://localhost', diff --git a/tests/lib/Files/External/Service/StoragesServiceTest.php b/tests/lib/Files/External/Service/StoragesServiceTest.php index 519d358107ab..aac76208905e 100644 --- a/tests/lib/Files/External/Service/StoragesServiceTest.php +++ b/tests/lib/Files/External/Service/StoragesServiceTest.php @@ -88,11 +88,11 @@ public function setUp(): void { \OC::$SERVERROOT . '/data/' ); - $this->mountCache = $this->createMock('OCP\Files\Config\IUserMountCache'); + $this->mountCache = $this->createMock(\OCP\Files\Config\IUserMountCache::class); // prepare IStoragesBackendService mock $this->backendService = - $this->getMockBuilder('\OCP\Files\External\IStoragesBackendService') + $this->getMockBuilder('\\' . \OCP\Files\External\IStoragesBackendService::class) ->disableOriginalConstructor() ->getMock(); @@ -102,41 +102,26 @@ public function setUp(): void { 'identifier:\OC\Files\External\Auth\NullMechanism' => $this->getAuthMechMock(), ]; $this->backendService->method('getAuthMechanism') - ->will($this->returnCallback(function ($class) use ($authMechanisms) { - if (isset($authMechanisms[$class])) { - return $authMechanisms[$class]; - } - return null; - })); + ->will($this->returnCallback(fn ($class) => $authMechanisms[$class] ?? null)); $this->backendService->method('getAuthMechanismsByScheme') - ->will($this->returnCallback(function ($schemes) use ($authMechanisms) { - return \array_filter($authMechanisms, function ($authMech) use ($schemes) { - return \in_array($authMech->getScheme(), $schemes, true); - }); - })); + ->will($this->returnCallback(fn ($schemes) => \array_filter($authMechanisms, fn ($authMech) => \in_array($authMech->getScheme(), $schemes, true)))); $this->backendService->method('getAuthMechanisms') ->will($this->returnValue($authMechanisms)); - $sftpBackend = $this->getBackendMock('\OCA\Files_External\Lib\Backend\SFTP', '\OCA\Files_External\Lib\Storage\SFTP'); - $dummyBackend = $this->getBackendMock('\Test\Files\External\Backend\DummyBackend', '\Test\Files\External\Backend\DummyStorage'); + $sftpBackend = $this->getBackendMock('\\' . \OCA\Files_External\Lib\Backend\SFTP::class, '\\' . \OCA\Files_External\Lib\Storage\SFTP::class); + $dummyBackend = $this->getBackendMock('\\' . \Test\Files\External\Backend\DummyBackend::class, '\\' . \Test\Files\External\Backend\DummyStorage::class); $this->backends = [ - 'identifier:\OCA\Files_External\Lib\Backend\SMB' => $this->getBackendMock('\OCA\Files_External\Lib\Backend\SMB', '\OCA\Files_External\Lib\Storage\SMB'), + 'identifier:\OCA\Files_External\Lib\Backend\SMB' => $this->getBackendMock('\\' . \OCA\Files_External\Lib\Backend\SMB::class, '\\' . \OCA\Files_External\Lib\Storage\SMB::class), 'identifier:\OCA\Files_External\Lib\Backend\SFTP' => $sftpBackend, 'identifier:\Test\Files\External\Backend\DummyBackend' => $dummyBackend, 'identifier:sftp_alias' => $sftpBackend, ]; $this->backendService->method('getBackend') - ->will($this->returnCallback(function ($backendClass) { - if (isset($this->backends[$backendClass])) { - return $this->backends[$backendClass]; - } - return null; - })); + ->will($this->returnCallback(fn ($backendClass) => $this->backends[$backendClass] ?? null)); $this->backendService->method('getBackends') - ->will($this->returnCallback(function () { - // in case they changed - return $this->backends; - })); + ->will($this->returnCallback(fn () => + // in case they changed + $this->backends)); \OCP\Util::connectHook( Filesystem::CLASSNAME, @@ -151,19 +136,17 @@ public function setUp(): void { 'deleteHookCallback' ); - $containerMock = $this->createMock('\OCP\AppFramework\IAppContainer'); + $containerMock = $this->createMock('\\' . \OCP\AppFramework\IAppContainer::class); $containerMock->method('query') ->will($this->returnCallback(function ($name) { - if ($name === 'OCP\Files\External\IStoragesBackendService') { + if ($name === \OCP\Files\External\IStoragesBackendService::class) { return $this->backendService; } })); $this->crypto = $this->createMock(ICrypto::class); $this->crypto->method('encrypt') - ->will($this->returnCallback(function ($value) { - return "-$value-"; - })); + ->will($this->returnCallback(fn ($value) => "-$value-")); $this->crypto->method('decrypt') ->will($this->returnCallback(function ($value) { $expectedDecrypt = \trim($value, '-'); @@ -183,8 +166,8 @@ public function tearDown(): void { parent::tearDown(); } - protected function getBackendMock($class = '\OCA\Files_External\Lib\Backend\SMB', $storageClass = '\OCA\Files_External\Lib\Storage\SMB') { - $backend = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + protected function getBackendMock($class = '\\' . \OCA\Files_External\Lib\Backend\SMB::class, $storageClass = '\\' . \OCA\Files_External\Lib\Storage\SMB::class) { + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->disableOriginalConstructor() ->getMock(); $backend->method('getStorageClass') @@ -196,8 +179,8 @@ protected function getBackendMock($class = '\OCA\Files_External\Lib\Backend\SMB' return $backend; } - protected function getAuthMechMock($scheme = 'null', $class = '\OC\Files\External\Auth\NullMechanism') { - $authMech = $this->getMockBuilder('\OCP\Files\External\Auth\AuthMechanism') + protected function getAuthMechMock($scheme = 'null', $class = '\\' . \OC\Files\External\Auth\NullMechanism::class) { + $authMech = $this->getMockBuilder('\\' . \OCP\Files\External\Auth\AuthMechanism::class) ->disableOriginalConstructor() ->getMock(); $authMech->method('getScheme') diff --git a/tests/lib/Files/External/Service/UserGlobalStoragesServiceTest.php b/tests/lib/Files/External/Service/UserGlobalStoragesServiceTest.php index 7079a9a8b516..fa8be778bef1 100644 --- a/tests/lib/Files/External/Service/UserGlobalStoragesServiceTest.php +++ b/tests/lib/Files/External/Service/UserGlobalStoragesServiceTest.php @@ -63,13 +63,13 @@ public function setUp(): void { $this->user = $this->createUser(self::USER_ID, self::USER_ID); /** @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject $userSession */ - $userSession = $this->createMock('\OCP\IUserSession'); + $userSession = $this->createMock('\\' . \OCP\IUserSession::class); $userSession ->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $this->groupManager = $this->createMock('\OCP\IGroupManager'); + $this->groupManager = $this->createMock('\\' . \OCP\IGroupManager::class); $this->groupManager->method('isInGroup') ->will($this->returnCallback(function ($userId, $groupId) { if ($userId === self::USER_ID) { diff --git a/tests/lib/Files/External/Service/UserStoragesServiceTest.php b/tests/lib/Files/External/Service/UserStoragesServiceTest.php index 70875a3e2504..df7d1dd1b734 100644 --- a/tests/lib/Files/External/Service/UserStoragesServiceTest.php +++ b/tests/lib/Files/External/Service/UserStoragesServiceTest.php @@ -59,7 +59,7 @@ public function setUp(): void { $this->user = $this->createUser($this->userId, $this->userId); /** @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject $userSession */ - $userSession = $this->createMock('\OCP\IUserSession'); + $userSession = $this->createMock('\\' . \OCP\IUserSession::class); $userSession ->expects($this->any()) ->method('getUser') @@ -205,27 +205,27 @@ public function testGetAdminStorage() { $newStorage = $this->globalStoragesService->addStorage($storage); - $this->assertInstanceOf('\OC\Files\External\StorageConfig', $this->globalStoragesService->getStorage($newStorage->getId())); + $this->assertInstanceOf('\\' . \OC\Files\External\StorageConfig::class, $this->globalStoragesService->getStorage($newStorage->getId())); $this->service->getStorage($newStorage->getId()); } private function getStorage($storageId, $rootId) { - $storageCache = $this->getMockBuilder('\OC\Files\Cache\Storage') + $storageCache = $this->getMockBuilder('\\' . \OC\Files\Cache\Storage::class) ->disableOriginalConstructor() ->getMock(); $storageCache->expects($this->any()) ->method('getNumericId') ->will($this->returnValue($storageId)); - $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') + $cache = $this->getMockBuilder('\\' . \OC\Files\Cache\Cache::class) ->disableOriginalConstructor() ->getMock(); $cache->expects($this->any()) ->method('getId') ->will($this->returnValue($rootId)); - $storage = $this->getMockBuilder('\OC\Files\Storage\Storage') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Storage::class) ->disableOriginalConstructor() ->getMock(); $storage->expects($this->any()) diff --git a/tests/lib/Files/External/StorageConfigTest.php b/tests/lib/Files/External/StorageConfigTest.php index 226fee4884e0..44c0eb1e3655 100644 --- a/tests/lib/Files/External/StorageConfigTest.php +++ b/tests/lib/Files/External/StorageConfigTest.php @@ -28,10 +28,10 @@ class StorageConfigTest extends \Test\TestCase { public function testJsonSerialization() { - $backend = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->disableOriginalConstructor() ->getMock(); - $parameter = $this->getMockBuilder('\OCP\Files\External\DefinitionParameter') + $parameter = $this->getMockBuilder('\\' . \OCP\Files\External\DefinitionParameter::class) ->disableOriginalConstructor() ->getMock(); $parameter @@ -45,7 +45,7 @@ public function testJsonSerialization() { $backend->method('getIdentifier') ->willReturn('storage::identifier'); - $authMech = $this->getMockBuilder('\OCP\Files\External\Auth\AuthMechanism') + $authMech = $this->getMockBuilder('\\' . \OCP\Files\External\Auth\AuthMechanism::class) ->disableOriginalConstructor() ->getMock(); $authMech->method('getIdentifier') diff --git a/tests/lib/Files/External/StoragesBackendServiceTest.php b/tests/lib/Files/External/StoragesBackendServiceTest.php index f9897563ea2e..436a7dfe9514 100644 --- a/tests/lib/Files/External/StoragesBackendServiceTest.php +++ b/tests/lib/Files/External/StoragesBackendServiceTest.php @@ -28,7 +28,7 @@ class StoragesBackendServiceTest extends \Test\TestCase { protected $config; protected function setUp(): void { - $this->config = $this->createMock('\OCP\IConfig'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); } /** @@ -37,7 +37,7 @@ protected function setUp(): void { * @return \OCP\Files\External\Backend\Backend */ protected function getBackendMock($class) { - $backend = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->disableOriginalConstructor() ->getMock(); $backend->method('getIdentifier')->will($this->returnValue('identifier:'.$class)); @@ -51,7 +51,7 @@ protected function getBackendMock($class) { * @return \OCP\Files\External\Auth\AuthMechanism */ protected function getAuthMechanismMock($class) { - $backend = $this->getMockBuilder('\OCP\Files\External\Auth\AuthMechanism') + $backend = $this->getMockBuilder('\\' . \OCP\Files\External\Auth\AuthMechanism::class) ->disableOriginalConstructor() ->getMock(); $backend->method('getIdentifier')->will($this->returnValue('identifier:'.$class)); @@ -64,7 +64,7 @@ public function testRegisterBackend() { $backend = $this->getBackendMock('\Foo\Bar'); - $backendAlias = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + $backendAlias = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->disableOriginalConstructor() ->getMock(); $backendAlias->method('getIdentifierAliases') @@ -92,7 +92,7 @@ public function testBackendProvider() { $backend1 = $this->getBackendMock('\Foo\Bar'); $backend2 = $this->getBackendMock('\Bar\Foo'); - $providerMock = $this->createMock('\OCP\Files\External\Config\IBackendProvider'); + $providerMock = $this->createMock('\\' . \OCP\Files\External\Config\IBackendProvider::class); $providerMock->expects($this->once()) ->method('getBackends') ->willReturn([$backend1, $backend2]); @@ -110,7 +110,7 @@ public function testAuthMechanismProvider() { $backend1 = $this->getAuthMechanismMock('\Foo\Bar'); $backend2 = $this->getAuthMechanismMock('\Bar\Foo'); - $providerMock = $this->createMock('\OCP\Files\External\Config\IAuthMechanismProvider'); + $providerMock = $this->createMock('\\' . \OCP\Files\External\Config\IAuthMechanismProvider::class); $providerMock->expects($this->once()) ->method('getAuthMechanisms') ->willReturn([$backend1, $backend2]); @@ -130,12 +130,12 @@ public function testMultipleBackendProviders() { $backend2 = $this->getBackendMock('\Dead\Beef'); - $provider1Mock = $this->createMock('\OCP\Files\External\Config\IBackendProvider'); + $provider1Mock = $this->createMock('\\' . \OCP\Files\External\Config\IBackendProvider::class); $provider1Mock->expects($this->once()) ->method('getBackends') ->willReturn([$backend1a, $backend1b]); $service->registerBackendProvider($provider1Mock); - $provider2Mock = $this->createMock('\OCP\Files\External\Config\IBackendProvider'); + $provider2Mock = $this->createMock('\\' . \OCP\Files\External\Config\IBackendProvider::class); $provider2Mock->expects($this->once()) ->method('getBackends') ->willReturn([$backend2]); @@ -166,7 +166,7 @@ public function testUserMountingBackends() { ->method('removeVisibility') ->with(IStoragesBackendService::VISIBILITY_PERSONAL); - $backendAlias = $this->getMockBuilder('\OCP\Files\External\Backend\Backend') + $backendAlias = $this->getMockBuilder('\\' . \OCP\Files\External\Backend\Backend::class) ->disableOriginalConstructor() ->getMock(); $backendAlias->method('getIdentifierAliases') @@ -190,7 +190,7 @@ public function testGetAvailableBackends() { $backendNotAvailable->expects($this->once()) ->method('checkDependencies') ->will($this->returnValue([ - $this->getMockBuilder('\OC\Files\External\MissingDependency') + $this->getMockBuilder('\\' . \OC\Files\External\MissingDependency::class) ->disableOriginalConstructor() ->getMock() ])); diff --git a/tests/lib/Files/FilesystemTest.php b/tests/lib/Files/FilesystemTest.php index 31a9eeef00a2..0d4423a806aa 100644 --- a/tests/lib/Files/FilesystemTest.php +++ b/tests/lib/Files/FilesystemTest.php @@ -34,7 +34,7 @@ use Test\Traits\UserTrait; class DummyMountProvider implements IMountProvider { - private $mounts = []; + private array $mounts = []; /** * @param array $mounts @@ -51,7 +51,7 @@ public function __construct(array $mounts) { * @return \OCP\Files\Mount\IMountPoint[] */ public function getMountsForUser(IUser $user, IStorageFactory $loader) { - return isset($this->mounts[$user->getUID()]) ? $this->mounts[$user->getUID()] : []; + return $this->mounts[$user->getUID()] ?? []; } } @@ -71,7 +71,7 @@ class FilesystemTest extends TestCase { /** * @var array tmpDirs */ - private $tmpDirs = []; + private array $tmpDirs = []; /** * @return array @@ -95,26 +95,26 @@ protected function tearDown(): void { } self::logout(); - self::invokePrivate('\OC\Files\Filesystem', 'normalizedPathCache', [null]); + self::invokePrivate('\\' . \OC\Files\Filesystem::class, 'normalizedPathCache', [null]); \OC_User::clearBackends(); parent::tearDown(); } public function testMount() { - Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/'); + Filesystem::mount('\\' . \OC\Files\Storage\Local::class, self::getStorageData(), '/'); $this->assertEquals('/', Filesystem::getMountPoint('/')); $this->assertEquals('/', Filesystem::getMountPoint('/some/folder')); - list(, $internalPath) = Filesystem::resolvePath('/'); + [, $internalPath] = Filesystem::resolvePath('/'); $this->assertEquals('', $internalPath); - list(, $internalPath) = Filesystem::resolvePath('/some/folder'); + [, $internalPath] = Filesystem::resolvePath('/some/folder'); $this->assertEquals('some/folder', $internalPath); - Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some'); + Filesystem::mount('\\' . \OC\Files\Storage\Local::class, self::getStorageData(), '/some'); $this->assertEquals('/', Filesystem::getMountPoint('/')); $this->assertEquals('/some/', Filesystem::getMountPoint('/some/folder')); $this->assertEquals('/some/', Filesystem::getMountPoint('/some/')); $this->assertEquals('/some/', Filesystem::getMountPoint('/some')); - list(, $internalPath) = Filesystem::resolvePath('/some/folder'); + [, $internalPath] = Filesystem::resolvePath('/some/folder'); $this->assertEquals('folder', $internalPath); } @@ -365,7 +365,7 @@ public function testHooks() { \OC_Hook::clear('OC_Filesystem'); \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook'); - Filesystem::mount('OC\Files\Storage\Temporary', [], '/'); + Filesystem::mount(\OC\Files\Storage\Temporary::class, [], '/'); $rootView = new View(''); $rootView->mkdir('/' . $user); @@ -448,10 +448,10 @@ public function testUserNameCasing() { Filesystem::initMountPoints(\strtoupper($userId)); - list($storage1, $path1) = $view->resolvePath('/' . $userId); - list($storage2, $path2) = $view->resolvePath('/' . \strtoupper($userId)); + [$storage1, $path1] = $view->resolvePath('/' . $userId); + [$storage2, $path2] = $view->resolvePath('/' . \strtoupper($userId)); - $this->assertTrue($storage1->instanceOfStorage('\OCP\Files\IHomeStorage')); + $this->assertTrue($storage1->instanceOfStorage('\\' . \OCP\Files\IHomeStorage::class)); $this->assertEquals('', $path1); // not mounted, still on the local root storage @@ -470,12 +470,12 @@ public function testHomeMount() { $homeMount = Filesystem::getStorage('/' . $userId . '/'); - $this->assertTrue($homeMount->instanceOfStorage('\OCP\Files\IHomeStorage')); + $this->assertTrue($homeMount->instanceOfStorage('\\' . \OCP\Files\IHomeStorage::class)); if ($this->runsWithPrimaryObjectstorage()) { - $this->assertTrue($homeMount->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')); + $this->assertTrue($homeMount->instanceOfStorage('\\' . \OC\Files\ObjectStore\HomeObjectStoreStorage::class)); $this->assertEquals('object::user:' . $userId, $homeMount->getId()); } else { - $this->assertTrue($homeMount->instanceOfStorage('\OC\Files\Storage\Home')); + $this->assertTrue($homeMount->instanceOfStorage('\\' . \OC\Files\Storage\Home::class)); $this->assertEquals('home::' . $userId, $homeMount->getId()); } @@ -507,8 +507,8 @@ public function testMountDefaultCacheDir() { '/' . $userId . '/', Filesystem::getMountPoint('/' . $userId . '/cache') ); - list($storage, $internalPath) = Filesystem::resolvePath('/' . $userId . '/cache'); - $this->assertTrue($storage->instanceOfStorage('\OCP\Files\IHomeStorage')); + [$storage, $internalPath] = Filesystem::resolvePath('/' . $userId . '/cache'); + $this->assertTrue($storage->instanceOfStorage('\\' . \OCP\Files\IHomeStorage::class)); $this->assertEquals('cache', $internalPath); $user = \OC::$server->getUserManager()->get($userId); if ($user !== null) { @@ -538,8 +538,8 @@ public function testMountExternalCacheDir() { '/' . $userId . '/cache/', Filesystem::getMountPoint('/' . $userId . '/cache') ); - list($storage, $internalPath) = Filesystem::resolvePath('/' . $userId . '/cache'); - $this->assertTrue($storage->instanceOfStorage('\OC\Files\Storage\Local')); + [$storage, $internalPath] = Filesystem::resolvePath('/' . $userId . '/cache'); + $this->assertTrue($storage->instanceOfStorage('\\' . \OC\Files\Storage\Local::class)); $this->assertEquals('', $internalPath); $user = \OC::$server->getUserManager()->get($userId); if ($user !== null) { diff --git a/tests/lib/Files/MetaVersionCollectionTest.php b/tests/lib/Files/MetaVersionCollectionTest.php index ffdd08fc1dc3..fe552aa8fe34 100644 --- a/tests/lib/Files/MetaVersionCollectionTest.php +++ b/tests/lib/Files/MetaVersionCollectionTest.php @@ -38,22 +38,19 @@ class MetaVersionCollectionTest extends TestCase { /** * @var Node */ - private $node; + private \PHPUnit\Framework\MockObject\MockObject $node; /** * @var IRootFolder */ - private $rootFolder; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; - /** - * @var MetaVersionCollection - */ - private $collection; + private \OC\Files\Meta\MetaVersionCollection $collection; /** * @var Common */ - private $storage; + private \PHPUnit\Framework\MockObject\MockObject $storage; protected function setUp(): void { parent::setUp(); @@ -81,8 +78,8 @@ public function testGetDirectoryListing() { ->method('getVersions') ->with('/abc') ->willReturn([ - ['version' => '1014', 'timestamp' => 12345678], - ['version' => '1015', 'mimetype' => 'text/plain', 'timestamp' => 12345679], + ['version' => '1014', 'timestamp' => 12_345_678], + ['version' => '1015', 'mimetype' => 'text/plain', 'timestamp' => 12_345_679], ]); $children = $this->collection->getDirectoryListing(); @@ -91,11 +88,11 @@ public function testGetDirectoryListing() { $this->assertInstanceOf(MetaFileVersionNode::class, $children[0]); $this->assertEquals('1014', $children[0]->getName()); $this->assertEquals('application/json', $children[0]->getMimetype()); - $this->assertEquals(12345678, $children[0]->getMtime()); + $this->assertEquals(12_345_678, $children[0]->getMtime()); $this->assertInstanceOf(MetaFileVersionNode::class, $children[1]); $this->assertEquals('1015', $children[1]->getName()); $this->assertEquals('text/plain', $children[1]->getMimetype()); - $this->assertEquals(12345679, $children[1]->getMtime()); + $this->assertEquals(12_345_679, $children[1]->getMtime()); } public function testGetDirectoryListingNonVersionedStorage() { @@ -125,14 +122,14 @@ public function testGet() { $this->storage->expects($this->once()) ->method('getVersion') ->with('/abc', '1014') - ->willReturn(['version' => '1014', 'timestamp' => 12345678]); + ->willReturn(['version' => '1014', 'timestamp' => 12_345_678]); $result = $this->collection->get('1014'); $this->assertInstanceOf(MetaFileVersionNode::class, $result); $this->assertEquals('1014', $result->getName()); $this->assertEquals('application/json', $result->getMimetype()); - $this->assertEquals(12345678, $result->getMtime()); + $this->assertEquals(12_345_678, $result->getMtime()); } /** diff --git a/tests/lib/Files/Mount/CacheMountProviderTest.php b/tests/lib/Files/Mount/CacheMountProviderTest.php index 1181bac5a516..d43188d80820 100644 --- a/tests/lib/Files/Mount/CacheMountProviderTest.php +++ b/tests/lib/Files/Mount/CacheMountProviderTest.php @@ -73,7 +73,7 @@ public function testConfiguredCachePath() { $this->loader->expects($this->once()) ->method('getInstance') - ->with($mount, '\OC\Files\Storage\Local', $storageArgs); + ->with($mount, '\\' . \OC\Files\Storage\Local::class, $storageArgs); // trigger storage creation which will pass config args above $mount->getStorage(); diff --git a/tests/lib/Files/Mount/ManagerTest.php b/tests/lib/Files/Mount/ManagerTest.php index 1c579c24d3c2..6a48ee0cf055 100644 --- a/tests/lib/Files/Mount/ManagerTest.php +++ b/tests/lib/Files/Mount/ManagerTest.php @@ -17,10 +17,7 @@ public function getId() { } class ManagerTest extends \Test\TestCase { - /** - * @var \OC\Files\Mount\Manager - */ - private $manager; + private \OC\Files\Mount\Manager $manager; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Mount/MountPointTest.php b/tests/lib/Files/Mount/MountPointTest.php index 11930da7f677..c93cdea05786 100644 --- a/tests/lib/Files/Mount/MountPointTest.php +++ b/tests/lib/Files/Mount/MountPointTest.php @@ -10,12 +10,12 @@ class MountPointTest extends \Test\TestCase { public function testGetStorage() { - $cache = $this->createMock('\OC\Files\Cache\Cache'); + $cache = $this->createMock('\\' . \OC\Files\Cache\Cache::class); $cache->expects($this->once()) ->method('getId') ->will($this->returnValue(123)); - $storage = $this->createMock('\OCP\Files\Storage'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); $storage->expects($this->once()) ->method('getId') ->will($this->returnValue('home:12345')); @@ -23,14 +23,14 @@ public function testGetStorage() { ->method('getCache') ->will($this->returnValue($cache)); - $loader = $this->createMock('\OCP\Files\Storage\IStorageFactory'); + $loader = $this->createMock('\\' . \OCP\Files\Storage\IStorageFactory::class); $loader->expects($this->once()) ->method('getInstance') ->will($this->returnValue($storage)); $mountPoint = new \OC\Files\Mount\MountPoint( // just use this because a real class is needed - '\Test\Files\Mount\MountPointTest', + '\\' . \Test\Files\Mount\MountPointTest::class, '/mountpoint', null, $loader @@ -46,7 +46,7 @@ public function testGetStorage() { } public function testInvalidStorage() { - $loader = $this->createMock('\OCP\Files\Storage\IStorageFactory'); + $loader = $this->createMock('\\' . \OCP\Files\Storage\IStorageFactory::class); $loader->expects($this->once()) ->method('getInstance') ->will($this->throwException(new \Exception('Test storage init exception'))); @@ -58,7 +58,7 @@ public function testInvalidStorage() { $mountPoint = new \OC\Files\Mount\MountPoint( // just use this because a real class is needed - '\Test\Files\Mount\MountPointTest', + '\\' . \Test\Files\Mount\MountPointTest::class, '/mountpoint', null, $loader @@ -82,19 +82,19 @@ public function testInvalidStorage() { } public function testGetRootIdNullCache() { - $storage = $this->createMock('\OCP\Files\Storage'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); $storage->expects($this->any()) ->method('getCache') ->will($this->returnValue(null)); - $loader = $this->createMock('\OCP\Files\Storage\IStorageFactory'); + $loader = $this->createMock('\\' . \OCP\Files\Storage\IStorageFactory::class); $loader->expects($this->once()) ->method('getInstance') ->will($this->returnValue($storage)); $mountPoint = new \OC\Files\Mount\MountPoint( // just use this because a real class is needed - '\Test\Files\Mount\MountPointTest', + '\\' . \Test\Files\Mount\MountPointTest::class, '/mountpoint', null, $loader diff --git a/tests/lib/Files/Mount/MountTest.php b/tests/lib/Files/Mount/MountTest.php index 340e6931c1d8..ee4e612442ad 100644 --- a/tests/lib/Files/Mount/MountTest.php +++ b/tests/lib/Files/Mount/MountTest.php @@ -13,33 +13,33 @@ class MountTest extends \Test\TestCase { public function testFromStorageObject() { - $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Temporary::class) ->disableOriginalConstructor() ->getMock(); $mount = new \OC\Files\Mount\MountPoint($storage, '/foo'); - $this->assertInstanceOf('\OC\Files\Storage\Temporary', $mount->getStorage()); + $this->assertInstanceOf('\\' . \OC\Files\Storage\Temporary::class, $mount->getStorage()); } public function testFromStorageClassname() { - $mount = new \OC\Files\Mount\MountPoint('\OC\Files\Storage\Temporary', '/foo'); - $this->assertInstanceOf('\OC\Files\Storage\Temporary', $mount->getStorage()); + $mount = new \OC\Files\Mount\MountPoint('\\' . \OC\Files\Storage\Temporary::class, '/foo'); + $this->assertInstanceOf('\\' . \OC\Files\Storage\Temporary::class, $mount->getStorage()); } public function testWrapper() { $test = $this; $wrapper = function ($mountPoint, $storage) use (&$test) { $test->assertEquals('/foo/', $mountPoint); - $test->assertInstanceOf('\OC\Files\Storage\Storage', $storage); + $test->assertInstanceOf('\\' . \OC\Files\Storage\Storage::class, $storage); return new Wrapper(['storage' => $storage]); }; $loader = new StorageFactory(); $loader->addStorageWrapper('test_wrapper', $wrapper); - $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Temporary::class) ->disableOriginalConstructor() ->getMock(); $mount = new \OC\Files\Mount\MountPoint($storage, '/foo', [], $loader); - $this->assertInstanceOf('\OC\Files\Storage\Wrapper\Wrapper', $mount->getStorage()); + $this->assertInstanceOf('\\' . \OC\Files\Storage\Wrapper\Wrapper::class, $mount->getStorage()); } } diff --git a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php index cce52c7bdc68..4ea4b4201ca3 100644 --- a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php +++ b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php @@ -23,9 +23,9 @@ class ObjectHomeMountProviderTest extends \Test\TestCase { public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('OCP\IConfig'); - $this->user = $this->createMock('OCP\IUser'); - $this->loader = $this->createMock('OCP\Files\Storage\IStorageFactory'); + $this->config = $this->createMock(\OCP\IConfig::class); + $this->user = $this->createMock(\OCP\IUser::class); + $this->loader = $this->createMock(\OCP\Files\Storage\IStorageFactory::class); $this->provider = new ObjectHomeMountProvider($this->config); } @@ -35,7 +35,7 @@ public function testSingleBucket() { ->method('getSystemValue') ->with($this->equalTo('objectstore'), '') ->willReturn([ - 'class' => 'Test\Files\Mount\FakeObjectStore', + 'class' => \Test\Files\Mount\FakeObjectStore::class, ]); $this->user->expects($this->never())->method($this->anything()); @@ -44,12 +44,12 @@ public function testSingleBucket() { $config = self::invokePrivate($this->provider, 'getSingleBucketObjectStoreConfig', [$this->user, $this->loader]); $this->assertArrayHasKey('class', $config); - $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore'); + $this->assertEquals($config['class'], \Test\Files\Mount\FakeObjectStore::class); $this->assertArrayHasKey('arguments', $config); $this->assertArrayHasKey('user', $config['arguments']); $this->assertSame($this->user, $config['arguments']['user']); $this->assertArrayHasKey('objectstore', $config['arguments']); - $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']); + $this->assertInstanceOf(\Test\Files\Mount\FakeObjectStore::class, $config['arguments']['objectstore']); } public function testMultiBucket() { @@ -57,7 +57,7 @@ public function testMultiBucket() { ->method('getSystemValue') ->with($this->equalTo('objectstore_multibucket'), '') ->willReturn([ - 'class' => 'Test\Files\Mount\FakeObjectStore', + 'class' => \Test\Files\Mount\FakeObjectStore::class, ]); $this->user->method('getUID') @@ -86,12 +86,12 @@ public function testMultiBucket() { $config = self::invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]); $this->assertArrayHasKey('class', $config); - $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore'); + $this->assertEquals($config['class'], \Test\Files\Mount\FakeObjectStore::class); $this->assertArrayHasKey('arguments', $config); $this->assertArrayHasKey('user', $config['arguments']); $this->assertSame($this->user, $config['arguments']['user']); $this->assertArrayHasKey('objectstore', $config['arguments']); - $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']); + $this->assertInstanceOf(\Test\Files\Mount\FakeObjectStore::class, $config['arguments']['objectstore']); $this->assertArrayHasKey('bucket', $config['arguments']); $this->assertEquals('987', $config['arguments']['bucket']); } @@ -101,7 +101,7 @@ public function testMultiBucketWithPrefix() { ->method('getSystemValue') ->with($this->equalTo('objectstore_multibucket'), '') ->willReturn([ - 'class' => 'Test\Files\Mount\FakeObjectStore', + 'class' => \Test\Files\Mount\FakeObjectStore::class, 'arguments' => [ 'bucket' => 'myBucketPrefix', ], @@ -133,12 +133,12 @@ public function testMultiBucketWithPrefix() { $config = self::invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]); $this->assertArrayHasKey('class', $config); - $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore'); + $this->assertEquals($config['class'], \Test\Files\Mount\FakeObjectStore::class); $this->assertArrayHasKey('arguments', $config); $this->assertArrayHasKey('user', $config['arguments']); $this->assertSame($this->user, $config['arguments']['user']); $this->assertArrayHasKey('objectstore', $config['arguments']); - $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']); + $this->assertInstanceOf(\Test\Files\Mount\FakeObjectStore::class, $config['arguments']['objectstore']); $this->assertArrayHasKey('bucket', $config['arguments']); $this->assertEquals('myBucketPrefix987', $config['arguments']['bucket']); } @@ -148,7 +148,7 @@ public function testMultiBucketBucketAlreadySet() { ->method('getSystemValue') ->with($this->equalTo('objectstore_multibucket'), '') ->willReturn([ - 'class' => 'Test\Files\Mount\FakeObjectStore', + 'class' => \Test\Files\Mount\FakeObjectStore::class, 'arguments' => [ 'bucket' => 'myBucketPrefix', ], @@ -173,12 +173,12 @@ public function testMultiBucketBucketAlreadySet() { $config = self::invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]); $this->assertArrayHasKey('class', $config); - $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore'); + $this->assertEquals($config['class'], \Test\Files\Mount\FakeObjectStore::class); $this->assertArrayHasKey('arguments', $config); $this->assertArrayHasKey('user', $config['arguments']); $this->assertSame($this->user, $config['arguments']['user']); $this->assertArrayHasKey('objectstore', $config['arguments']); - $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']); + $this->assertInstanceOf(\Test\Files\Mount\FakeObjectStore::class, $config['arguments']['objectstore']); $this->assertArrayHasKey('bucket', $config['arguments']); $this->assertEquals('awesomeBucket1', $config['arguments']['bucket']); } @@ -188,7 +188,7 @@ public function testMultiBucketConfigFirst() { ->method('getSystemValue') ->with($this->equalTo('objectstore_multibucket')) ->willReturn([ - 'class' => 'Test\Files\Mount\FakeObjectStore', + 'class' => \Test\Files\Mount\FakeObjectStore::class, ]); $this->user->method('getUID') @@ -196,7 +196,7 @@ public function testMultiBucketConfigFirst() { $this->loader->expects($this->never())->method($this->anything()); $mount = $this->provider->getHomeMountForUser($this->user, $this->loader); - $this->assertInstanceOf('OC\Files\Mount\MountPoint', $mount); + $this->assertInstanceOf(\OC\Files\Mount\MountPoint::class, $mount); } public function testMultiBucketConfigFirstFallBackSingle() { @@ -209,7 +209,7 @@ public function testMultiBucketConfigFirstFallBackSingle() { ) ->willReturnOnConsecutiveCalls( '', - ['class' => 'Test\Files\Mount\FakeObjectStore'], + ['class' => \Test\Files\Mount\FakeObjectStore::class], ); $this->user->method('getUID') @@ -217,7 +217,7 @@ public function testMultiBucketConfigFirstFallBackSingle() { $this->loader->expects($this->never())->method($this->anything()); $mount = $this->provider->getHomeMountForUser($this->user, $this->loader); - $this->assertInstanceOf('OC\Files\Mount\MountPoint', $mount); + $this->assertInstanceOf(\OC\Files\Mount\MountPoint::class, $mount); } public function testNoObjectStore() { @@ -231,7 +231,7 @@ public function testNoObjectStore() { } class FakeObjectStore { - private $arguments; + private array $arguments; public function __construct(array $arguments) { $this->arguments = $arguments; diff --git a/tests/lib/Files/Mount/PreviewsMountProviderTest.php b/tests/lib/Files/Mount/PreviewsMountProviderTest.php index 87014d31d28c..ba3d5239ed94 100644 --- a/tests/lib/Files/Mount/PreviewsMountProviderTest.php +++ b/tests/lib/Files/Mount/PreviewsMountProviderTest.php @@ -73,7 +73,7 @@ public function testConfiguredPreviewsPath() { $this->loader->expects($this->once()) ->method('getInstance') - ->with($mount, '\OC\Files\Storage\Local', $storageArgs); + ->with($mount, '\\' . \OC\Files\Storage\Local::class, $storageArgs); // trigger storage creation which will pass config args above $mount->getStorage(); diff --git a/tests/lib/Files/Node/FolderTest.php b/tests/lib/Files/Node/FolderTest.php index 754dc1b8de81..fe4d46dbbe57 100644 --- a/tests/lib/Files/Node/FolderTest.php +++ b/tests/lib/Files/Node/FolderTest.php @@ -30,20 +30,20 @@ */ class FolderTest extends NodeTest { public $viewDeleteMethod = 'rmdir'; - public $nodeClass = '\OC\Files\Node\Folder'; - public $nonExistingNodeClass = '\OC\Files\Node\NonExistingFolder'; + public $nodeClass = '\\' . \OC\Files\Node\Folder::class; + public $nonExistingNodeClass = '\\' . \OC\Files\Node\NonExistingFolder::class; protected function createTestNode($root, $view, $path) { return new \OC\Files\Node\Folder($root, $view, $path); } public function testGetDirectoryContent() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -61,8 +61,8 @@ public function testGetDirectoryContent() { $node = new Folder($root, $view, '/bar/foo'); $children = $node->getDirectoryListing(); $this->assertCount(2, $children); - $this->assertInstanceOf('\OC\Files\Node\File', $children[0]); - $this->assertInstanceOf('\OC\Files\Node\Folder', $children[1]); + $this->assertInstanceOf('\\' . \OC\Files\Node\File::class, $children[0]); + $this->assertInstanceOf('\\' . \OC\Files\Node\Folder::class, $children[1]); $this->assertEquals('asd', $children[0]->getName()); $this->assertEquals('qwerty', $children[1]->getName()); $this->assertEquals(2, $children[0]->getId()); @@ -70,12 +70,12 @@ public function testGetDirectoryContent() { } public function testGet() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -91,12 +91,12 @@ public function testGet() { } public function testNodeExists() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -115,12 +115,12 @@ public function testNodeExists() { } public function testNodeExistsNotExists() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -137,12 +137,12 @@ public function testNodeExistsNotExists() { } public function testNewFolder() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -170,12 +170,12 @@ public function testNewFolder() { public function testNewFolderNotPermitted() { $this->expectException(\OCP\Files\NotPermittedException::class); - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -192,12 +192,12 @@ public function testNewFolderNotPermitted() { } public function testNewFile() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -225,12 +225,12 @@ public function testNewFile() { public function testNewFileNotPermitted() { $this->expectException(\OCP\Files\NotPermittedException::class); - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -247,12 +247,12 @@ public function testNewFileNotPermitted() { } public function testGetFreeSpace() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) @@ -269,19 +269,19 @@ public function testGetFreeSpace() { } public function testSearch() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $storage = $this->createMock('\OC\Files\Storage\Storage'); - $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); + $cache = $this->getMockBuilder('\\' . \OC\Files\Cache\Cache::class) ->setConstructorArgs(['']) ->getMock(); @@ -289,7 +289,7 @@ public function testSearch() { ->method('getCache') ->will($this->returnValue($cache)); - $mount = $this->createMock('\OCP\Files\Mount\IMountPoint'); + $mount = $this->createMock('\\' . \OCP\Files\Mount\IMountPoint::class); $mount->expects($this->once()) ->method('getStorage') ->will($this->returnValue($storage)); @@ -321,12 +321,12 @@ public function testSearch() { } public function testSearchInRoot() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); @@ -334,12 +334,12 @@ public function testSearchInRoot() { $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $storage = $this->createMock('\OC\Files\Storage\Storage'); - $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); + $cache = $this->getMockBuilder('\\' . \OC\Files\Cache\Cache::class) ->setConstructorArgs(['']) ->getMock(); - $mount = $this->createMock('\OCP\Files\Mount\IMountPoint'); + $mount = $this->createMock('\\' . \OCP\Files\Mount\IMountPoint::class); $mount->expects($this->once()) ->method('getStorage') ->will($this->returnValue($storage)); @@ -375,21 +375,21 @@ public function testSearchInRoot() { } public function testSearchInStorageRoot() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $cache = $this->createMock(Cache::class); - $mount = $this->createMock('\OCP\Files\Mount\IMountPoint'); + $mount = $this->createMock('\\' . \OCP\Files\Mount\IMountPoint::class); $mount->expects($this->once()) ->method('getStorage') ->will($this->returnValue($storage)); @@ -425,22 +425,22 @@ public function testSearchInStorageRoot() { } public function testSearchByTag() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $cache = $this->createMock(Cache::class); - $mount = $this->createMock('\OCP\Files\Mount\IMountPoint'); + $mount = $this->createMock('\\' . \OCP\Files\Mount\IMountPoint::class); $mount->expects($this->once()) ->method('getStorage') ->will($this->returnValue($storage)); @@ -476,25 +476,25 @@ public function testSearchByTag() { } public function testSearchSubStorages() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $cache = $this->createMock(Cache::class); $subCache = $this->createMock(Cache::class); - $subStorage = $this->createMock('\OC\Files\Storage\Storage'); - $subMount = $this->createMock('\OC\Files\Mount\MountPoint', [], [null, '']); + $subStorage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); + $subMount = $this->createMock('\\' . \OC\Files\Mount\MountPoint::class); - $mount = $this->createMock('\OCP\Files\Mount\IMountPoint'); + $mount = $this->createMock('\\' . \OCP\Files\Mount\IMountPoint::class); $mount->expects($this->once()) ->method('getStorage') ->will($this->returnValue($storage)); @@ -604,19 +604,19 @@ public function testGetById(): void { } public function testGetByIdOutsideFolder() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $mount = new MountPoint($storage, '/bar'); $cache = $this->createMock(Cache::class); @@ -645,19 +645,19 @@ public function testGetByIdOutsideFolder() { } public function testGetByIdMultipleStorages() { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $mount1 = new MountPoint($storage, '/bar'); $mount2 = new MountPoint($storage, '/bar/foo/asd'); $cache = $this->createMock(Cache::class); @@ -704,13 +704,13 @@ public function uniqueNameProvider() { * @dataProvider uniqueNameProvider */ public function testGetUniqueName($name, $existingFiles, $expected) { - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); $folderPath = '/bar/foo'; /** * @var View | MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user]) ->getMock(); diff --git a/tests/lib/Files/Node/HookConnectorTest.php b/tests/lib/Files/Node/HookConnectorTest.php index 73622bb8d62b..558833a15fe3 100644 --- a/tests/lib/Files/Node/HookConnectorTest.php +++ b/tests/lib/Files/Node/HookConnectorTest.php @@ -28,15 +28,9 @@ class HookConnectorTest extends TestCase { use UserTrait; use MountProviderTrait; - /** - * @var View - */ - private $view; + private \OC\Files\View $view; - /** - * @var Root - */ - private $root; + private \OC\Files\Node\Root $root; /** * @var string diff --git a/tests/lib/Files/Node/IntegrationTest.php b/tests/lib/Files/Node/IntegrationTest.php index 8185f78e6557..9a4350bd14e4 100644 --- a/tests/lib/Files/Node/IntegrationTest.php +++ b/tests/lib/Files/Node/IntegrationTest.php @@ -25,20 +25,14 @@ class IntegrationTest extends TestCase { use UserTrait; - /** - * @var \OC\Files\Node\Root $root - */ - private $root; + private \OC\Files\Node\Root $root; /** * @var \OC\Files\Storage\Storage[] */ - private $storages; + private array $storages; - /** - * @var \OC\Files\View $view - */ - private $view; + private \OC\Files\View $view; protected function setUp(): void { parent::setUp(); @@ -74,7 +68,7 @@ public function testBasicFile() { $this->assertCount(3, $this->root->getDirectoryListing()); $this->assertTrue($this->root->nodeExists('/foo.txt')); $id = $file->getId(); - $this->assertInstanceOf('\OC\Files\Node\File', $file); + $this->assertInstanceOf('\\' . \OC\Files\Node\File::class, $file); $file->putContent('qwerty'); $this->assertEquals('text/plain', $file->getMimeType()); $this->assertEquals('qwerty', $file->getContent()); @@ -112,7 +106,7 @@ public function testBasicFolder() { * @var \OC\Files\Node\File $file */ $file = $folder->get('/bar'); - $this->assertInstanceOf('\OC\Files\Node\File', $file); + $this->assertInstanceOf('\\' . \OC\Files\Node\File::class, $file); $this->assertFalse($this->root->nodeExists('/foo/bar')); $this->assertTrue($this->root->nodeExists('/asd/bar')); $this->assertEquals('qwerty', $file->getContent()); @@ -121,7 +115,7 @@ public function testBasicFolder() { * @var \OC\Files\Node\File $file */ $file = $folder->get('/bar'); - $this->assertInstanceOf('\OC\Files\Node\File', $file); + $this->assertInstanceOf('\\' . \OC\Files\Node\File::class, $file); $this->assertTrue($this->root->nodeExists('/substorage/foo/bar')); $this->assertEquals('qwerty', $file->getContent()); } diff --git a/tests/lib/Files/Node/NodeTest.php b/tests/lib/Files/Node/NodeTest.php index 713aee1389c7..5160868a3dd9 100644 --- a/tests/lib/Files/Node/NodeTest.php +++ b/tests/lib/Files/Node/NodeTest.php @@ -33,7 +33,7 @@ protected function setUp(): void { abstract protected function createTestNode($root, $view, $path); protected function getMockStorage() { - $storage = $this->createMock('\OCP\Files\Storage'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); $storage->expects($this->any()) ->method('getId') ->will($this->returnValue('home::someuser')); @@ -48,9 +48,9 @@ public function testDelete() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); - $root = $this->createMock('\OC\Files\Node\Root'); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->exactly(2)) ->method('emit') ->will($this->returnValue(true)); @@ -101,11 +101,11 @@ public function testDeleteHooks() { /** * @var \OC\Files\Mount\Manager $manager */ - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); $root = new \OC\Files\Node\Root($manager, $view, $this->user); $root->listen('\OC\Files', 'preDelete', $preListener); $root->listen('\OC\Files', 'postDelete', $postListener); @@ -138,8 +138,8 @@ public function testDeleteNotPermitted() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') @@ -158,8 +158,8 @@ public function testStat() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -185,8 +185,8 @@ public function testGetId() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -211,8 +211,8 @@ public function testGetSize() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -237,8 +237,8 @@ public function testGetEtag() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -263,8 +263,8 @@ public function testGetMTime() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -289,15 +289,15 @@ public function testGetStorage() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); /** * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage */ - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $view->expects($this->once()) ->method('resolvePath') @@ -312,8 +312,8 @@ public function testGetPath() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -326,15 +326,15 @@ public function testGetInternalPath() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); /** * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage */ - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $view->expects($this->once()) ->method('resolvePath') @@ -349,8 +349,8 @@ public function testGetName() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -363,8 +363,8 @@ public function testTouchSetMTime() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -408,11 +408,11 @@ public function testTouchHooks() { /** * @var \OC\Files\Mount\Manager $manager */ - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); $root = new \OC\Files\Node\Root($manager, $view, $this->user); $root->listen('\OC\Files', 'preTouch', $preListener); $root->listen('\OC\Files', 'postTouch', $postListener); @@ -445,8 +445,8 @@ public function testTouchNotPermitted() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); @@ -468,8 +468,8 @@ public function testInvalidPath() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $node = $this->createTestNode($root, $view, '/../foo'); $node->getFileInfo(); @@ -479,8 +479,8 @@ public function testCopySameStorage() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $view->expects($this->any()) ->method('copy') @@ -515,12 +515,12 @@ public function testCopyNotPermitted() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); /** * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage */ - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $root->expects($this->never()) ->method('getMount'); @@ -552,8 +552,8 @@ public function testCopyNoParent() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $view->expects($this->never()) ->method('copy'); @@ -576,8 +576,8 @@ public function testCopyParentIsFile() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $view->expects($this->never()) ->method('copy'); @@ -598,8 +598,8 @@ public function testMoveSameStorage() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $view->expects($this->any()) ->method('rename') @@ -639,12 +639,12 @@ public function testMoveCopyHooks($operationMethod, $viewMethod, $preHookName, $ /** * @var \OC\Files\Mount\Manager $manager */ - $manager = $this->createMock('\OC\Files\Mount\Manager'); + $manager = $this->createMock('\\' . \OC\Files\Mount\Manager::class); /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->getMockBuilder('\\' . \OC\Files\Node\Root::class) ->setConstructorArgs([$manager, $view, $this->user]) ->setMethods(['get']) ->getMock(); @@ -725,8 +725,8 @@ public function testMoveNotPermitted() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $view->expects($this->any()) ->method('getFileInfo') @@ -754,12 +754,12 @@ public function testMoveNoParent() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); /** * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage */ - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); $storage->expects($this->never()) ->method('rename'); @@ -783,8 +783,8 @@ public function testMoveParentIsFile() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $view->expects($this->never()) ->method('rename'); @@ -808,8 +808,8 @@ public function testMoveFailed() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $view->expects($this->any()) ->method('rename') @@ -838,8 +838,8 @@ public function testCopyFailed() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); - $root = $this->createMock('\OC\Files\Node\Root'); + $view = $this->createMock('\\' . \OC\Files\View::class); + $root = $this->createMock('\\' . \OC\Files\Node\Root::class); $view->expects($this->any()) ->method('copy') diff --git a/tests/lib/Files/Node/RootTest.php b/tests/lib/Files/Node/RootTest.php index 8208372e1dd1..72f3658e6064 100644 --- a/tests/lib/Files/Node/RootTest.php +++ b/tests/lib/Files/Node/RootTest.php @@ -20,7 +20,7 @@ class RootTest extends TestCase { use UserTrait; - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; protected function setUp(): void { parent::setUp(); @@ -36,11 +36,11 @@ public function testGet() { /** * @var \OC\Files\Storage\Storage $storage */ - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); $root = new \OC\Files\Node\Root($manager, $view, $this->user); $view->expects($this->once()) @@ -55,7 +55,7 @@ public function testGet() { $root->mount($storage, ''); $node = $root->get('/bar/foo'); $this->assertEquals(10, $node->getId()); - $this->assertInstanceOf('\OC\Files\Node\File', $node); + $this->assertInstanceOf('\\' . \OC\Files\Node\File::class, $node); } /** @@ -67,11 +67,11 @@ public function testGetNotFound() { /** * @var \OC\Files\Storage\Storage $storage */ - $storage = $this->createMock('\OC\Files\Storage\Storage'); + $storage = $this->createMock('\\' . \OC\Files\Storage\Storage::class); /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); $root = new \OC\Files\Node\Root($manager, $view, $this->user); $view->expects($this->once()) @@ -92,7 +92,7 @@ public function testGetInvalidPath() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); $root = new \OC\Files\Node\Root($manager, $view, $this->user); $root->get('/../foo'); @@ -107,7 +107,7 @@ public function testGetNoStorages() { /** * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view */ - $view = $this->createMock('\OC\Files\View'); + $view = $this->createMock('\\' . \OC\Files\View::class); $root = new \OC\Files\Node\Root($manager, $view, $this->user); $root->get('/bar/foo'); diff --git a/tests/lib/Files/ObjectStore/MapperTest.php b/tests/lib/Files/ObjectStore/MapperTest.php index b71ccfd6cb82..f1286f2efd79 100644 --- a/tests/lib/Files/ObjectStore/MapperTest.php +++ b/tests/lib/Files/ObjectStore/MapperTest.php @@ -37,7 +37,7 @@ public function dataGetBucket() { * @param string $expectedBucket */ public function testGetBucket($username, $expectedBucket) { - $user = $this->createMock('OCP\IUser'); + $user = $this->createMock(\OCP\IUser::class); $user->method('getUID') ->willReturn($username); diff --git a/tests/lib/Files/ObjectStore/NoopScannerTest.php b/tests/lib/Files/ObjectStore/NoopScannerTest.php index fbca38b2a785..317cd85a8e40 100644 --- a/tests/lib/Files/ObjectStore/NoopScannerTest.php +++ b/tests/lib/Files/ObjectStore/NoopScannerTest.php @@ -13,10 +13,9 @@ class NoopScannerTest extends \Test\TestCase { /** @var \OC\Files\Storage\Storage $storage */ - private $storage; + private \OC\Files\Storage\Temporary $storage; - /** @var \OC\Files\ObjectStore\NoopScanner $scanner */ - private $scanner; + private \OC\Files\ObjectStore\NoopScanner $scanner; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/ObjectStore/ObjectStoreTest.php b/tests/lib/Files/ObjectStore/ObjectStoreTest.php index ad033051712e..83e8d1a2a29b 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreTest.php @@ -46,9 +46,9 @@ interface IObjectStoreTest extends IObjectStore, IVersionedObjectStorage { */ class ObjectStoreTest extends TestCase { /** @var IObjectStoreTest | \PHPUnit\Framework\MockObject\MockObject */ - private $impl; + private \PHPUnit\Framework\MockObject\MockObject $impl; /** @var ObjectStoreStorage | \PHPUnit\Framework\MockObject\MockObject */ - private $objectStore; + private \PHPUnit\Framework\MockObject\MockObject $objectStore; public function setUp(): void { parent::setUp(); @@ -193,7 +193,7 @@ public function testGetVersionsOfUnknownFile($method, $ignore = false) { throw new NotFoundException(); } $this->impl->expects($this->never())->method($method)->willReturn([]); - $this->assertEquals([], $this->objectStore->$method('unknown-file.txt', '1')); + $this->assertEquals([], $this->objectStore->$method('unknown-file.txt')); } /** @@ -203,7 +203,7 @@ public function testGetVersions($method) { $path = 'file-with-versions.txt'; $this->assertTrue($this->objectStore->touch($path)); $this->impl->expects($this->once())->method($method)->willReturn([]); - $this->assertEquals([], $this->objectStore->$method($path, '1')); + $this->assertEquals([], $this->objectStore->$method($path)); } public function providesMethods() { diff --git a/tests/lib/Files/PathVerificationTest.php b/tests/lib/Files/PathVerificationTest.php index 5557790520c8..17216f90f0d1 100644 --- a/tests/lib/Files/PathVerificationTest.php +++ b/tests/lib/Files/PathVerificationTest.php @@ -19,10 +19,7 @@ * @package Test\Files */ class PathVerificationTest extends \Test\TestCase { - /** - * @var \OC\Files\View - */ - private $view; + private \OC\Files\View $view; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Storage/DavTest.php b/tests/lib/Files/Storage/DavTest.php index 641c344fd813..691fc3ade357 100644 --- a/tests/lib/Files/Storage/DavTest.php +++ b/tests/lib/Files/Storage/DavTest.php @@ -57,32 +57,32 @@ class DavTest extends TestCase { /** * @var IClientService | \PHPUnit\Framework\MockObject\MockObject */ - private $httpClientService; + private \PHPUnit\Framework\MockObject\MockObject $httpClientService; /** * @var IWebDavClientService | \PHPUnit\Framework\MockObject\MockObject */ - private $webDavClientService; + private \PHPUnit\Framework\MockObject\MockObject $webDavClientService; /** * @var Client | \PHPUnit\Framework\MockObject\MockObject */ - private $davClient; + private \PHPUnit\Framework\MockObject\MockObject $davClient; /** * @var IClient | \PHPUnit\Framework\MockObject\MockObject **/ - private $httpClient; + private \PHPUnit\Framework\MockObject\MockObject $httpClient; /** * @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** * @var Cache | \PHPUnit\Framework\MockObject\MockObject */ - private $cache; + private \PHPUnit\Framework\MockObject\MockObject $cache; protected function setUp(): void { parent::setUp(); @@ -768,11 +768,11 @@ public function testFreeSpaceException() { public function touchProvider() { return [ // server accepted mtime - [1508496363, null, '2017-10-20T12:46:03+02:00', true], + [1_508_496_363, null, '2017-10-20T12:46:03+02:00', true], // server did not accept mtime - [1508496363, null, '2017-10-20T12:40:00+02:00', false], + [1_508_496_363, null, '2017-10-20T12:40:00+02:00', false], // time factory generated mtime - [null, 1508496363, '2017-10-20T12:46:03+02:00', true], + [null, 1_508_496_363, '2017-10-20T12:46:03+02:00', true], ]; } @@ -854,7 +854,7 @@ public function testTouchException() { ->method('proppatch') ->willThrowException($this->createClientHttpException(Http::STATUS_FORBIDDEN)); - $this->instance->touch('/some%dir', 1508496363); + $this->instance->touch('/some%dir', 1_508_496_363); } public function testTouchNotFound() { @@ -874,7 +874,7 @@ public function testTouchNotFound() { ->expects($this->once()) ->method('proppatch'); - $this->assertFalse($this->instance->touch('/some%dir', 1508496363)); + $this->assertFalse($this->instance->touch('/some%dir', 1_508_496_363)); } public function testTouchNoServerSupport() { @@ -890,7 +890,7 @@ public function testTouchNoServerSupport() { ->method('proppatch') ->willThrowException($this->createClientHttpException(Http::STATUS_NOT_IMPLEMENTED)); - $this->assertFalse($this->instance->touch('/some%dir', 1508496363)); + $this->assertFalse($this->instance->touch('/some%dir', 1_508_496_363)); } public function renameDataProvider() { @@ -927,13 +927,13 @@ public function statDataProvider() { '{DAV:}getlastmodified' => '2017-10-20T12:46:03+02:00', '{DAV:}getcontentlength' => 1024, ], [ - 'mtime' => 1508496363, + 'mtime' => 1_508_496_363, 'size' => 1024 ]], [[ '{DAV:}getlastmodified' => '2017-10-20T12:46:03+02:00', ], [ - 'mtime' => 1508496363, + 'mtime' => 1_508_496_363, 'size' => 0 ]], ]; @@ -957,8 +957,8 @@ public function testStatRoot() { ->with('', $this->logicalAnd($this->containsIdentical('{DAV:}getlastmodified'), $this->containsIdentical('{DAV:}getcontentlength'))) ->willReturn(['{DAV:}getlastmodified' => '2017-10-20T12:46:03+02:00']); - $this->assertEquals(['mtime' => 1508496363, 'size' => 0], $this->instance->stat('')); - $this->assertEquals(['mtime' => 1508496363, 'size' => 0], $this->instance->stat('')); + $this->assertEquals(['mtime' => 1_508_496_363, 'size' => 0], $this->instance->stat('')); + $this->assertEquals(['mtime' => 1_508_496_363, 'size' => 0], $this->instance->stat('')); } /** @@ -1288,7 +1288,7 @@ public function testHasUpdated($davResponse, $cacheResponse, $expectedResult) { ->method('get'); } - $this->assertEquals($expectedResult, $this->instance->hasUpdated('some%dir', 1508496363)); + $this->assertEquals($expectedResult, $this->instance->hasUpdated('some%dir', 1_508_496_363)); } public function testHasUpdatedPathNotfound() { @@ -1296,7 +1296,7 @@ public function testHasUpdatedPathNotfound() { ->method('propfind') ->willReturn(false); - $this->assertFalse($this->instance->hasUpdated('some%dir', 1508496363)); + $this->assertFalse($this->instance->hasUpdated('some%dir', 1_508_496_363)); } /** @@ -1308,7 +1308,7 @@ public function testHasUpdatedRootPathNotfound() { ->method('propfind') ->willReturn(false); - $this->instance->hasUpdated('', 1508496363); + $this->instance->hasUpdated('', 1_508_496_363); } /** @@ -1320,7 +1320,7 @@ public function testHasUpdatedRootPathMethodNotAllowed() { ->method('propfind') ->willThrowException($this->createClientHttpException(Http::STATUS_METHOD_NOT_ALLOWED)); - $this->instance->hasUpdated('', 1508496363); + $this->instance->hasUpdated('', 1_508_496_363); } /** @@ -1332,7 +1332,7 @@ public function testHasUpdatedMethodNotAllowed() { ->method('propfind') ->willThrowException($this->createClientHttpException(Http::STATUS_METHOD_NOT_ALLOWED)); - $this->assertFalse($this->instance->hasUpdated('some%dir', 1508496363)); + $this->assertFalse($this->instance->hasUpdated('some%dir', 1_508_496_363)); } /** @@ -1344,7 +1344,7 @@ public function testHasUpdatedException() { ->method('propfind') ->willThrowException($this->createClientHttpException(Http::STATUS_FORBIDDEN)); - $this->instance->hasUpdated('some%dir', 1508496363); + $this->instance->hasUpdated('some%dir', 1_508_496_363); } public function testPropfindNotFoundOnCurlException() { diff --git a/tests/lib/Files/Storage/HomeStorageQuotaTest.php b/tests/lib/Files/Storage/HomeStorageQuotaTest.php index 0642fa82f27d..bbaaaca8fcd9 100644 --- a/tests/lib/Files/Storage/HomeStorageQuotaTest.php +++ b/tests/lib/Files/Storage/HomeStorageQuotaTest.php @@ -40,7 +40,7 @@ public function testHomeStorageWrapperWithoutQuota() { $userMount = \OC\Files\Filesystem::getMountManager()->find('/' . $user1 . '/'); $this->assertNotNull($userMount); - $this->assertNotInstanceOf('\OC\Files\Storage\Wrapper\Quota', $userMount->getStorage()); + $this->assertNotInstanceOf('\\' . \OC\Files\Storage\Wrapper\Quota::class, $userMount->getStorage()); // clean up \OC_User::setUserId(''); @@ -65,12 +65,12 @@ public function testHomeStorageWrapperWithQuota() { $userMount = \OC\Files\Filesystem::getMountManager()->find('/' . $user1 . '/'); $this->assertNotNull($userMount); - $this->assertTrue($userMount->getStorage()->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')); + $this->assertTrue($userMount->getStorage()->instanceOfStorage('\\' . \OC\Files\Storage\Wrapper\Quota::class)); // ensure that root wasn't wrapped $rootMount = \OC\Files\Filesystem::getMountManager()->find('/'); $this->assertNotNull($rootMount); - $this->assertNotInstanceOf('\OC\Files\Storage\Wrapper\Quota', $rootMount->getStorage()); + $this->assertNotInstanceOf('\\' . \OC\Files\Storage\Wrapper\Quota::class, $rootMount->getStorage()); // clean up \OC_User::setUserId(''); diff --git a/tests/lib/Files/Storage/HomeTest.php b/tests/lib/Files/Storage/HomeTest.php index 2aec75767964..87f6b7e24703 100644 --- a/tests/lib/Files/Storage/HomeTest.php +++ b/tests/lib/Files/Storage/HomeTest.php @@ -65,7 +65,7 @@ class HomeTest extends Storage { /** * @var \OC\User\User $user */ - private $user; + private \Test\Files\Storage\DummyUser $user; protected function setUp(): void { parent::setUp(); @@ -92,7 +92,7 @@ public function testId() { * Tests that getCache() returns an instance of HomeCache */ public function testGetCacheReturnsHomeCache() { - $this->assertInstanceOf('\OC\Files\Cache\HomeCache', $this->instance->getCache()); + $this->assertInstanceOf('\\' . \OC\Files\Cache\HomeCache::class, $this->instance->getCache()); } public function testGetOwner() { diff --git a/tests/lib/Files/Storage/LockingTests.php b/tests/lib/Files/Storage/LockingTests.php index e24aa3219320..fee400dce91d 100644 --- a/tests/lib/Files/Storage/LockingTests.php +++ b/tests/lib/Files/Storage/LockingTests.php @@ -52,7 +52,7 @@ protected function setUp(): void { $this->view->mkdir('foo'); $this->view->file_put_contents('foo/bar.txt', 'abcdef'); $this->fileId = $this->view->getFileInfo('foo/bar.txt')->getId(); - list($this->storage, ) = $this->view->resolvePath('foo/bar.txt'); + [$this->storage, ] = $this->view->resolvePath('foo/bar.txt'); } protected function tearDown(): void { diff --git a/tests/lib/Files/Storage/Storage.php b/tests/lib/Files/Storage/Storage.php index 7de43918e08c..d792a36db57c 100644 --- a/tests/lib/Files/Storage/Storage.php +++ b/tests/lib/Files/Storage/Storage.php @@ -37,7 +37,7 @@ abstract class Storage extends \Test\TestCase { */ protected function wait() { if ($this->waitDelay > 0) { - \usleep($this->waitDelay * 1000000); + \usleep($this->waitDelay * 1_000_000); } } @@ -582,7 +582,7 @@ public function testCopyOverWriteDirectoryOverFile() { } public function testInstanceOfStorage() { - $this->assertTrue($this->instance->instanceOfStorage('\OCP\Files\Storage')); + $this->assertTrue($this->instance->instanceOfStorage('\\' . \OCP\Files\Storage::class)); $this->assertTrue($this->instance->instanceOfStorage(\get_class($this->instance))); $this->assertFalse($this->instance->instanceOfStorage('\OC')); } diff --git a/tests/lib/Files/Storage/StorageFactoryTest.php b/tests/lib/Files/Storage/StorageFactoryTest.php index 20b51cdda223..87f4cf6c0184 100644 --- a/tests/lib/Files/Storage/StorageFactoryTest.php +++ b/tests/lib/Files/Storage/StorageFactoryTest.php @@ -28,43 +28,35 @@ public function __construct($arguments) { class StorageFactoryTest extends TestCase { public function testSimpleWrapper() { $instance = new \OC\Files\Storage\StorageFactory(); - $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); + $mount = new MountPoint('\\' . \OC\Files\Storage\Temporary::class, '/foo', [[]], $instance); $instance->addStorageWrapper('dummy', function ($mountPoint, IStorage $storage, IMountPoint $mount) { - $this->assertInstanceOf('\OC\Files\Storage\Temporary', $storage); + $this->assertInstanceOf('\\' . \OC\Files\Storage\Temporary::class, $storage); $this->assertEquals('/foo/', $mount->getMountPoint()); $this->assertEquals('/foo/', $mountPoint); return new DummyWrapper(['storage' => $storage]); }); $wrapped = $mount->getStorage(); - $this->assertInstanceOf('\Test\Files\Storage\DummyWrapper', $wrapped); + $this->assertInstanceOf('\\' . \Test\Files\Storage\DummyWrapper::class, $wrapped); } public function testRemoveWrapper() { $instance = new \OC\Files\Storage\StorageFactory(); - $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); - $instance->addStorageWrapper('dummy', function ($mountPoint, IStorage $storage) { - return new DummyWrapper(['storage' => $storage]); - }); + $mount = new MountPoint('\\' . \OC\Files\Storage\Temporary::class, '/foo', [[]], $instance); + $instance->addStorageWrapper('dummy', fn ($mountPoint, IStorage $storage) => new DummyWrapper(['storage' => $storage])); $instance->removeStorageWrapper('dummy'); $wrapped = $mount->getStorage(); - $this->assertInstanceOf('\OC\Files\Storage\Temporary', $wrapped); + $this->assertInstanceOf('\\' . \OC\Files\Storage\Temporary::class, $wrapped); } public function testWrapperPriority() { $instance = new \OC\Files\Storage\StorageFactory(); - $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); - $instance->addStorageWrapper('dummy1', function ($mountPoint, IStorage $storage) { - return new DummyWrapper(['storage' => $storage, 'data' => 1]); - }, 1); - $instance->addStorageWrapper('dummy2', function ($mountPoint, IStorage $storage) { - return new DummyWrapper(['storage' => $storage, 'data' => 100]); - }, 100); - $instance->addStorageWrapper('dummy3', function ($mountPoint, IStorage $storage) { - return new DummyWrapper(['storage' => $storage, 'data' => 50]); - }, 50); + $mount = new MountPoint('\\' . \OC\Files\Storage\Temporary::class, '/foo', [[]], $instance); + $instance->addStorageWrapper('dummy1', fn ($mountPoint, IStorage $storage) => new DummyWrapper(['storage' => $storage, 'data' => 1]), 1); + $instance->addStorageWrapper('dummy2', fn ($mountPoint, IStorage $storage) => new DummyWrapper(['storage' => $storage, 'data' => 100]), 100); + $instance->addStorageWrapper('dummy3', fn ($mountPoint, IStorage $storage) => new DummyWrapper(['storage' => $storage, 'data' => 50]), 50); /** @var \Test\Files\Storage\DummyWrapper $wrapped */ $wrapped = $mount->getStorage(); - $this->assertInstanceOf('\Test\Files\Storage\DummyWrapper', $wrapped); + $this->assertInstanceOf('\\' . \Test\Files\Storage\DummyWrapper::class, $wrapped); $this->assertEquals(1, $wrapped->data);// lowest priority is applied last, called first $this->assertEquals(50, $wrapped->getWrapperStorage()->data); $this->assertEquals(100, $wrapped->getWrapperStorage()->getWrapperStorage()->data); diff --git a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php index 58ebdeff6511..0b6edfa7d069 100644 --- a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php +++ b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php @@ -23,7 +23,7 @@ class AvailabilityTest extends \Test\TestCase { protected function getWrapperInstance() { - $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Temporary::class) ->disableOriginalConstructor() ->getMock(); $wrapper = new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]); @@ -34,7 +34,7 @@ protected function getWrapperInstance() { * Storage is available */ public function testAvailable() { - list($storage, $wrapper) = $this->getWrapperInstance(); + [$storage, $wrapper] = $this->getWrapperInstance(); $storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => true, 'last_checked' => 0]); @@ -53,7 +53,7 @@ public function testAvailable() { public function testUnavailable() { $this->expectException(\OCP\Files\StorageNotAvailableException::class); - list($storage, $wrapper) = $this->getWrapperInstance(); + [$storage, $wrapper] = $this->getWrapperInstance(); $storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => false, 'last_checked' => \time()]); @@ -69,7 +69,7 @@ public function testUnavailable() { * Storage marked unavailable, TTL expired */ public function testUnavailableRecheck() { - list($storage, $wrapper) = $this->getWrapperInstance(); + [$storage, $wrapper] = $this->getWrapperInstance(); $storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => false, 'last_checked' => 0]); @@ -95,7 +95,7 @@ public function testUnavailableRecheck() { public function testAvailableThrowStorageNotAvailable() { $this->expectException(\OCP\Files\StorageNotAvailableException::class); - list($storage, $wrapper) = $this->getWrapperInstance(); + [$storage, $wrapper] = $this->getWrapperInstance(); $storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => true, 'last_checked' => 0]); @@ -116,7 +116,7 @@ public function testAvailableThrowStorageNotAvailable() { * Method failure does not indicate storage unavailability */ public function testAvailableFailure() { - list($storage, $wrapper) = $this->getWrapperInstance(); + [$storage, $wrapper] = $this->getWrapperInstance(); $storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => true, 'last_checked' => 0]); @@ -139,7 +139,7 @@ public function testAvailableFailure() { public function testAvailableThrow() { $this->expectException(\Exception::class); - list($storage, $wrapper) = $this->getWrapperInstance(); + [$storage, $wrapper] = $this->getWrapperInstance(); $storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => true, 'last_checked' => 0]); diff --git a/tests/lib/Files/Storage/Wrapper/ChecksumTest.php b/tests/lib/Files/Storage/Wrapper/ChecksumTest.php index 692b3308c8a9..63097fca9190 100644 --- a/tests/lib/Files/Storage/Wrapper/ChecksumTest.php +++ b/tests/lib/Files/Storage/Wrapper/ChecksumTest.php @@ -27,16 +27,10 @@ * @group DB */ class ChecksumTest extends \Test\TestCase { - /** - * @var \OC\Files\Storage\Temporary - */ - private $sourceStorage; - /** - * @var Checksum - */ - private $instance; + private \OC\Files\Storage\Temporary $sourceStorage; + private \OC\Files\Storage\Wrapper\Checksum $instance; - private $testFileName; + private string $testFileName; public const TEST_DATA = 'somedata'; public const EXPECTED_CHECKSUMS = 'SHA1:efaa311ae448a7374c122061bfed952d940e9e37 MD5:aefaf7502d52994c3b01957636a3cdd2 ADLER32:0f2c034f'; diff --git a/tests/lib/Files/Storage/Wrapper/DirMaskTest.php b/tests/lib/Files/Storage/Wrapper/DirMaskTest.php index a4ea8e2208d5..e89a808d323b 100644 --- a/tests/lib/Files/Storage/Wrapper/DirMaskTest.php +++ b/tests/lib/Files/Storage/Wrapper/DirMaskTest.php @@ -27,8 +27,7 @@ use PHPUnit\Framework\TestCase; class DirMaskTest extends TestCase { - /** @var Temporary */ - private $sourceStorage; + private \OC\Files\Storage\Temporary $sourceStorage; /** * @param $mask diff --git a/tests/lib/Files/Storage/Wrapper/EncodingTest.php b/tests/lib/Files/Storage/Wrapper/EncodingTest.php index f30be9f2550f..7a1166155a80 100644 --- a/tests/lib/Files/Storage/Wrapper/EncodingTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncodingTest.php @@ -12,10 +12,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { public const NFD_NAME = 'ümlaut'; public const NFC_NAME = 'ümlaut'; - /** - * @var \OC\Files\Storage\Temporary - */ - private $sourceStorage; + private \OC\Files\Storage\Temporary $sourceStorage; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php index cea5dd32520b..91ceb9f1d2d9 100644 --- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php @@ -20,10 +20,7 @@ class EncryptionTest extends Storage { */ protected $headerSize = 8192; - /** - * @var Temporary - */ - private $sourceStorage; + private \OC\Files\Storage\Temporary $sourceStorage; /** * @var Encryption | MockObject @@ -33,68 +30,68 @@ class EncryptionTest extends Storage { /** * @var \OC\Encryption\Keys\Storage | MockObject */ - private $keyStore; + private \PHPUnit\Framework\MockObject\MockObject $keyStore; /** * @var Util | MockObject */ - private $util; + private \PHPUnit\Framework\MockObject\MockObject $util; /** * @var \OC\Encryption\Manager | MockObject */ - private $encryptionManager; + private \PHPUnit\Framework\MockObject\MockObject $encryptionManager; /** * @var \OCP\Encryption\IEncryptionModule | MockObject */ - private $encryptionModule; + private ?\PHPUnit\Framework\MockObject\MockObject $encryptionModule = null; /** * @var \OC\Encryption\Update | MockObject */ - private $update; + private \PHPUnit\Framework\MockObject\MockObject $update; /** * @var Cache | MockObject */ - private $cache; + private \PHPUnit\Framework\MockObject\MockObject $cache; /** * @var \OC\Log | MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** * @var \OC\Encryption\File | MockObject */ - private $file; + private \PHPUnit\Framework\MockObject\MockObject $file; /** * @var \OC\Files\Mount\MountPoint | MockObject */ - private $mount; + private \PHPUnit\Framework\MockObject\MockObject $mount; /** * @var \OC\Files\Mount\Manager | MockObject */ - private $mountManager; + private \PHPUnit\Framework\MockObject\MockObject $mountManager; /** * @var \OC\Group\Manager | MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** * @var \OCP\IConfig | MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var \OC\Memcache\ArrayCache | MockObject */ - private $arrayCache; + private \PHPUnit\Framework\MockObject\MockObject $arrayCache; /** @var integer dummy unencrypted size */ - private $dummySize = -1; + private int $dummySize = -1; protected function setUp(): void { parent::setUp(); @@ -124,9 +121,7 @@ protected function setUp(): void { ->getMock(); $this->util->expects($this->any()) ->method('getUidAndFilename') - ->willReturnCallback(function ($path) { - return ['user1', $path]; - }); + ->willReturnCallback(fn ($path) => ['user1', $path]); $this->file = $this->getMockBuilder(\OC\Encryption\File::class) ->disableOriginalConstructor() @@ -162,9 +157,7 @@ protected function setUp(): void { ->disableOriginalConstructor()->getMock(); $this->cache->expects($this->any()) ->method('get') - ->willReturnCallback(function ($path) { - return ['encrypted' => false, 'path' => $path]; - }); + ->willReturnCallback(fn ($path) => ['encrypted' => false, 'path' => $path]); $this->mountManager = $this->getMockBuilder(\OC\Files\Mount\Manager::class) ->disableOriginalConstructor()->getMock(); @@ -187,9 +180,7 @@ protected function setUp(): void { $this->instance->expects($this->any()) ->method('getMetaData') - ->willReturnCallback(function ($path) { - return ['encrypted' => true, 'size' => $this->dummySize, 'path' => $path]; - }); + ->willReturnCallback(fn ($path) => ['encrypted' => true, 'size' => $this->dummySize, 'path' => $path]); $this->instance->expects($this->any()) ->method('getCache') @@ -241,9 +232,7 @@ public function testGetMetaData($path, $metaData, $encrypted, $unencryptedSizeSe $cache->expects($this->any()) ->method('get') ->willReturnCallback( - function ($path) use ($encrypted) { - return ['encrypted' => $encrypted, 'path' => $path, 'size' => 0, 'fileid' => 1]; - } + fn ($path) => ['encrypted' => $encrypted, 'path' => $path, 'size' => 0, 'fileid' => 1] ); $this->instance = $this->getMockBuilder(Encryption::class) @@ -732,9 +721,7 @@ public function testGetHeaderAddLegacyModule($header, $isEncrypted, $exists, $ex $sourceStorage->expects($this->once()) ->method('file_exists') - ->willReturnCallback(function ($path) use ($exists) { - return $exists; - }); + ->willReturnCallback(fn ($path) => $exists); $userManager = $this->createMock(Manager::class); $util = $this->getMockBuilder(Util::class) @@ -745,9 +732,7 @@ public function testGetHeaderAddLegacyModule($header, $isEncrypted, $exists, $ex ->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('get') - ->willReturnCallback(function ($path) use ($isEncrypted) { - return ['encrypted' => $isEncrypted, 'path' => $path]; - }); + ->willReturnCallback(fn ($path) => ['encrypted' => $isEncrypted, 'path' => $path]); $instance = $this->getMockBuilder(Encryption::class) ->setConstructorArgs( @@ -844,7 +829,7 @@ public function dataCopyBetweenStorage() { } public function testCopyBetweenStorageMinimumEncryptedVersion() { - $storage2 = $this->getMockBuilder('OCP\Files\Storage') + $storage2 = $this->getMockBuilder(\OCP\Files\Storage::class) ->disableOriginalConstructor() ->getMock(); @@ -857,7 +842,7 @@ public function testCopyBetweenStorageMinimumEncryptedVersion() { $temp = \OC::$server->getTempManager(); return \fopen($temp->getTemporaryFile(), $mode); }); - $cache = $this->createMock('\OCP\Files\Cache\ICache'); + $cache = $this->createMock('\\' . \OCP\Files\Cache\ICache::class); $cache->expects($this->once()) ->method('get') ->with($sourceInternalPath) @@ -893,7 +878,7 @@ public function testCopyBetweenStorageMinimumEncryptedVersion() { * @param bool $expectedEncrypted */ public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted) { - $storage2 = $this->getMockBuilder('OCP\Files\Storage') + $storage2 = $this->getMockBuilder(\OCP\Files\Storage::class) ->disableOriginalConstructor() ->getMock(); @@ -907,7 +892,7 @@ public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryption return \fopen($temp->getTemporaryFile(), $mode); }); if ($expectedEncrypted) { - $cache = $this->createMock('\OCP\Files\Cache\ICache'); + $cache = $this->createMock('\\' . \OCP\Files\Cache\ICache::class); $cache->expects($this->once()) ->method('get') ->with($sourceInternalPath) @@ -955,11 +940,11 @@ public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryption * @param bool $encrypted */ public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted) { - $sourceStorage = $this->getMockBuilder('OCP\Files\Storage') + $sourceStorage = $this->getMockBuilder(\OCP\Files\Storage::class) ->disableOriginalConstructor() ->getMock(); - $targetStorage = $this->getMockBuilder('OCP\Files\Storage') + $targetStorage = $this->getMockBuilder(\OCP\Files\Storage::class) ->disableOriginalConstructor() ->getMock(); @@ -1077,9 +1062,7 @@ public function testFOpenRawEncrypted($isEncrypted) { ->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('get') - ->willReturnCallback(function ($path) use ($isEncrypted) { - return ['encrypted' => $isEncrypted, 'path' => $path]; - }); + ->willReturnCallback(fn ($path) => ['encrypted' => $isEncrypted, 'path' => $path]); $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class) ->disableOriginalConstructor()->getMock(); diff --git a/tests/lib/Files/Storage/Wrapper/JailTest.php b/tests/lib/Files/Storage/Wrapper/JailTest.php index b76c3347c7cf..6fc0f5bccbd0 100644 --- a/tests/lib/Files/Storage/Wrapper/JailTest.php +++ b/tests/lib/Files/Storage/Wrapper/JailTest.php @@ -11,10 +11,7 @@ use OC\Files\Storage\Common; class JailTest extends \Test\Files\Storage\Storage { - /** - * @var \OC\Files\Storage\Temporary - */ - private $sourceStorage; + private \OC\Files\Storage\Temporary $sourceStorage; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php index 5e6e16dc0bdc..324e47787eb8 100644 --- a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php +++ b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php @@ -11,10 +11,7 @@ use OCP\Constants; class PermissionsMaskTest extends \Test\Files\Storage\Storage { - /** - * @var \OC\Files\Storage\Temporary - */ - private $sourceStorage; + private \OC\Files\Storage\Temporary $sourceStorage; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Storage/Wrapper/QuotaTest.php b/tests/lib/Files/Storage/Wrapper/QuotaTest.php index f6b3b627aeb2..8cf0d7b46384 100644 --- a/tests/lib/Files/Storage/Wrapper/QuotaTest.php +++ b/tests/lib/Files/Storage/Wrapper/QuotaTest.php @@ -12,7 +12,7 @@ use OC\Files\Cache\CacheEntry; use OC\Files\Storage\Local; -\OC::$loader->load('\OC\Files\Filesystem'); +\OC::$loader->load('\\' . \OC\Files\Filesystem::class); /** * Class QuotaTest @@ -32,7 +32,7 @@ protected function setUp(): void { $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); - $this->instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 10000000]); + $this->instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 10_000_000]); } protected function tearDown(): void { @@ -117,7 +117,7 @@ public function testStreamCopyWithEnoughSpace() { $instance = $this->getLimitedStorage(16); $inputStream = \fopen('data://text/plain,foobarqwerty', 'r'); $outputStream = $instance->fopen('files/foo', 'w+'); - list($count, $result) = \OC_Helper::streamCopy($inputStream, $outputStream); + [$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream); $this->assertEquals(12, $count); $this->assertTrue($result); \fclose($inputStream); @@ -128,7 +128,7 @@ public function testStreamCopyNotEnoughSpace() { $instance = $this->getLimitedStorage(9); $inputStream = \fopen('data://text/plain,foobarqwerty', 'r'); $outputStream = $instance->fopen('files/foo', 'w+'); - list($count, $result) = \OC_Helper::streamCopy($inputStream, $outputStream); + [$count, $result] = \OC_Helper::streamCopy($inputStream, $outputStream); $this->assertEquals(9, $count); $this->assertFalse($result); \fclose($inputStream); @@ -136,7 +136,7 @@ public function testStreamCopyNotEnoughSpace() { } public function testReturnFalseWhenFopenFailed() { - $failStorage = $this->getMockBuilder('\OC\Files\Storage\Local') + $failStorage = $this->getMockBuilder('\\' . \OC\Files\Storage\Local::class) ->setMethods(['fopen']) ->setConstructorArgs([['datadir' => $this->tmpDir]]) ->getMock(); @@ -190,8 +190,8 @@ public function testReturnQuotaStreamOnWrite() { } public function testSpaceRoot() { - $storage = $this->getMockBuilder('\OC\Files\Storage\Local')->disableOriginalConstructor()->getMock(); - $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')->disableOriginalConstructor()->getMock(); + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Local::class)->disableOriginalConstructor()->getMock(); + $cache = $this->getMockBuilder('\\' . \OC\Files\Cache\Cache::class)->disableOriginalConstructor()->getMock(); $storage->expects($this->once()) ->method('getCache') ->will($this->returnValue($cache)); @@ -209,8 +209,8 @@ public function testSpaceRoot() { } public function testInstanceOfStorageWrapper() { - $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Local')); - $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Wrapper')); - $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')); + $this->assertTrue($this->instance->instanceOfStorage('\\' . \OC\Files\Storage\Local::class)); + $this->assertTrue($this->instance->instanceOfStorage('\\' . \OC\Files\Storage\Wrapper\Wrapper::class)); + $this->assertTrue($this->instance->instanceOfStorage('\\' . \OC\Files\Storage\Wrapper\Quota::class)); } } diff --git a/tests/lib/Files/Storage/Wrapper/ReadOnlyJailTest.php b/tests/lib/Files/Storage/Wrapper/ReadOnlyJailTest.php index c6d6681214d9..74cfc7817d8d 100644 --- a/tests/lib/Files/Storage/Wrapper/ReadOnlyJailTest.php +++ b/tests/lib/Files/Storage/Wrapper/ReadOnlyJailTest.php @@ -8,10 +8,8 @@ use PHPUnit\Framework\TestCase; class ReadOnlyJailTest extends TestCase { - /** @var ReadOnlyJail */ - private $sut; - /** @var Temporary */ - private $sourceStorage; + private \OC\Files\Storage\Wrapper\ReadOnlyJail $sut; + private \OC\Files\Storage\Temporary $sourceStorage; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Storage/Wrapper/WrapperTest.php b/tests/lib/Files/Storage/Wrapper/WrapperTest.php index e63267dfd706..6d387df4c85e 100644 --- a/tests/lib/Files/Storage/Wrapper/WrapperTest.php +++ b/tests/lib/Files/Storage/Wrapper/WrapperTest.php @@ -27,7 +27,7 @@ class WrapperTest extends Storage { /** * @var IStorage $storage */ - private $storage; + private \OC\Files\Storage\Local $storage; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Stream/ChecksumTest.php b/tests/lib/Files/Stream/ChecksumTest.php index da7b845cb557..24693b722a38 100644 --- a/tests/lib/Files/Stream/ChecksumTest.php +++ b/tests/lib/Files/Stream/ChecksumTest.php @@ -25,7 +25,7 @@ class ChecksumTest extends \Test\TestCase { private $root; - private $fileList = []; + private array $fileList = []; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Stream/EncryptionTest.php b/tests/lib/Files/Stream/EncryptionTest.php index 1e576db22dea..67f8ca2d5163 100644 --- a/tests/lib/Files/Stream/EncryptionTest.php +++ b/tests/lib/Files/Stream/EncryptionTest.php @@ -16,7 +16,7 @@ class EncryptionTest extends TestCase { * @param integer $unencryptedSize * @return resource */ - protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = '\OC\Files\Stream\Encryption') { + protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = '\\' . \OC\Files\Stream\Encryption::class) { \clearstatcache(); $size = \filesize($fileName); $source = \fopen($fileName, $mode); @@ -25,25 +25,25 @@ protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = '\OC $header = []; $uid = ''; $this->encryptionModule = $this->buildMockModule(); - $storage = $this->getMockBuilder('\OC\Files\Storage\Storage') + $storage = $this->getMockBuilder('\\' . \OC\Files\Storage\Storage::class) ->disableOriginalConstructor()->getMock(); - $encStorage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') + $encStorage = $this->getMockBuilder('\\' . \OC\Files\Storage\Wrapper\Encryption::class) ->disableOriginalConstructor()->getMock(); - $config = $this->getMockBuilder('\OCP\IConfig') + $config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $arrayCache = $this->createMock('OC\Memcache\ArrayCache'); - $groupManager = $this->getMockBuilder('\OC\Group\Manager') + $arrayCache = $this->createMock(\OC\Memcache\ArrayCache::class); + $groupManager = $this->getMockBuilder('\\' . \OC\Group\Manager::class) ->disableOriginalConstructor() ->getMock(); - $file = $this->getMockBuilder('\OC\Encryption\File') + $file = $this->getMockBuilder('\\' . \OC\Encryption\File::class) ->disableOriginalConstructor() ->setMethods(['getAccessList']) ->getMock(); $file->expects($this->any())->method('getAccessList')->willReturn([]); $userManager = $this->createMock(Manager::class); - $util = $this->getMockBuilder('\OC\Encryption\Util') + $util = $this->getMockBuilder('\\' . \OC\Encryption\Util::class) ->setMethods(['getUidAndFilename']) ->setConstructorArgs([new View(), $userManager, $groupManager, $config, $arrayCache]) ->getMock(); @@ -83,18 +83,18 @@ public function testStreamOpen( $expectedReadOnly ) { // build mocks - $encryptionModuleMock = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') + $encryptionModuleMock = $this->getMockBuilder('\\' . \OCP\Encryption\IEncryptionModule::class) ->disableOriginalConstructor()->getMock(); $encryptionModuleMock->expects($this->once()) ->method('getUnencryptedBlockSize')->willReturn(99); $encryptionModuleMock->expects($this->once()) ->method('begin')->willReturn(true); - $storageMock = $this->getMockBuilder('\OC\Files\Storage\Storage') + $storageMock = $this->getMockBuilder('\\' . \OC\Files\Storage\Storage::class) ->disableOriginalConstructor()->getMock(); $storageMock->expects($this->once())->method('file_exists')->willReturn($fileExists); - $fileMock = $this->getMockBuilder('\OC\Encryption\File') + $fileMock = $this->getMockBuilder('\\' . \OC\Encryption\File::class) ->disableOriginalConstructor()->getMock(); $fileMock->expects($this->once())->method('getAccessList') ->will($this->returnCallback(function ($sharePath) use ($expectedSharePath) { @@ -102,14 +102,14 @@ public function testStreamOpen( return []; })); - $utilMock = $this->getMockBuilder('\OC\Encryption\Util') + $utilMock = $this->getMockBuilder('\\' . \OC\Encryption\Util::class) ->disableOriginalConstructor()->getMock(); $utilMock->expects($this->any()) ->method('getHeaderSize') ->willReturn(8192); // get a instance of the stream wrapper - $streamWrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption') + $streamWrapper = $this->getMockBuilder('\\' . \OC\Files\Stream\Encryption::class) ->setMethods(['loadContext', 'writeHeader', 'skipHeader'])->disableOriginalConstructor()->getMock(); $streamWrapper->expects($this->once()) ->method('loadContext') @@ -117,7 +117,7 @@ public function testStreamOpen( ->willReturn(['sourceFileOfRename' => 'dummyfile']); // set internal properties of the stream wrapper - $stream = new \ReflectionClass('\OC\Files\Stream\Encryption'); + $stream = new \ReflectionClass('\\' . \OC\Files\Stream\Encryption::class); $encryptionModule = $stream->getProperty('encryptionModule'); $encryptionModule->setAccessible(true); $encryptionModule->setValue($streamWrapper, $encryptionModuleMock); @@ -293,14 +293,14 @@ public function testWriteReadBigFile($testFile) { * @dataProvider dataFilesProvider */ public function testWriteToNonSeekableStorage($testFile) { - $wrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption') + $wrapper = $this->getMockBuilder('\\' . \OC\Files\Stream\Encryption::class) ->setMethods(['parentSeekStream'])->getMock(); $wrapper->expects($this->any())->method('parentSeekStream')->willReturn(false); $expectedData = \file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile); // write it $fileName = \tempnam("/tmp", "FOO"); - $stream = $this->getStream($fileName, 'w+', 0, '\Test\Files\Stream\DummyEncryptionWrapper'); + $stream = $this->getStream($fileName, 'w+', 0, '\\' . \Test\Files\Stream\DummyEncryptionWrapper::class); // while writing the file from the beginning to the end we should never try // to read parts of the file. This should only happen for write operations // in the middle of a file @@ -309,7 +309,7 @@ public function testWriteToNonSeekableStorage($testFile) { \fclose($stream); // read it all - $stream = $this->getStream($fileName, 'r', \strlen($expectedData), '\Test\Files\Stream\DummyEncryptionWrapper'); + $stream = $this->getStream($fileName, 'r', \strlen($expectedData), '\\' . \Test\Files\Stream\DummyEncryptionWrapper::class); $data = \stream_get_contents($stream); \fclose($stream); @@ -332,7 +332,7 @@ public function testWriteToNonSeekableStorage($testFile) { * @return \PHPUnit\Framework\MockObject\MockObject */ protected function buildMockModule() { - $encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') + $encryptionModule = $this->getMockBuilder('\\' . \OCP\Encryption\IEncryptionModule::class) ->disableOriginalConstructor() ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser']) ->getMock(); diff --git a/tests/lib/Files/Stream/StaticStreamTest.php b/tests/lib/Files/Stream/StaticStreamTest.php index 40a34b2caa09..a929bbd26b71 100644 --- a/tests/lib/Files/Stream/StaticStreamTest.php +++ b/tests/lib/Files/Stream/StaticStreamTest.php @@ -9,7 +9,7 @@ namespace Test\Files\Stream; class StaticStreamTest extends \Test\TestCase { - private $sourceFile; + private string $sourceFile; private $sourceText; protected function setUp(): void { diff --git a/tests/lib/Files/Type/DetectionTest.php b/tests/lib/Files/Type/DetectionTest.php index b0671c055139..fd44272d4a3c 100644 --- a/tests/lib/Files/Type/DetectionTest.php +++ b/tests/lib/Files/Type/DetectionTest.php @@ -25,8 +25,7 @@ use org\bovigo\vfs\vfsStream; class DetectionTest extends \Test\TestCase { - /** @var Detection */ - private $detection; + private \OC\Files\Type\Detection $detection; public function setUp(): void { parent::setUp(); @@ -104,7 +103,7 @@ public function testMimeTypeIcon(): void { $mimetypealiases_dist->setContent(\json_encode([], JSON_FORCE_OBJECT)); //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(); @@ -122,7 +121,7 @@ public function testMimeTypeIcon(): void { * Test dir-shareed mimetype */ //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(); @@ -141,7 +140,7 @@ public function testMimeTypeIcon(): void { */ //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(); @@ -160,7 +159,7 @@ public function testMimeTypeIcon(): void { */ //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(); @@ -179,7 +178,7 @@ public function testMimeTypeIcon(): void { */ //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(); @@ -206,7 +205,7 @@ public function testMimeTypeIcon(): void { */ //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(); @@ -234,7 +233,7 @@ public function testMimeTypeIcon(): void { */ //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(); @@ -258,7 +257,7 @@ public function testMimeTypeIcon(): void { $mimetypealiases_dist->setContent(\json_encode(['foo' => 'foobar/baz'], JSON_FORCE_OBJECT)); //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + $urlGenerator = $this->getMockBuilder('\\' . \OCP\IURLGenerator::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Files/Utils/ScannerTest.php b/tests/lib/Files/Utils/ScannerTest.php index 9327aa17705b..3503070ad7e4 100644 --- a/tests/lib/Files/Utils/ScannerTest.php +++ b/tests/lib/Files/Utils/ScannerTest.php @@ -22,7 +22,7 @@ class TestScanner extends \OC\Files\Utils\Scanner { /** * @var \OC\Files\Mount\MountPoint[] $mounts */ - private $mounts = []; + private array $mounts = []; /** * @param \OC\Files\Mount\MountPoint $mount @@ -105,7 +105,7 @@ public function testScanSubMount() { $uid = self::getUniqueID(); $this->createUser($uid); - $mountProvider = $this->createMock('\OCP\Files\Config\IMountProvider'); + $mountProvider = $this->createMock('\\' . \OCP\Files\Config\IMountProvider::class); $storage = new Temporary([]); $mount = new MountPoint($storage, '/' . $uid . '/files/foo'); @@ -188,14 +188,14 @@ public function testPropagateEtag() { } public function testSkipLocalShares() { - $sharedStorage = $this->createMock('OCA\Files_Sharing\SharedStorage'); + $sharedStorage = $this->createMock(\OCA\Files_Sharing\SharedStorage::class); $sharedMount = new MountPoint($sharedStorage, '/share'); Filesystem::getMountManager()->addMount($sharedMount); $sharedStorage->expects($this->any()) ->method('instanceOfStorage') ->will($this->returnValueMap([ - ['OCA\Files_Sharing\ISharedStorage', true], + [\OCA\Files_Sharing\ISharedStorage::class, true], ])); $sharedStorage->expects($this->never()) ->method('getScanner'); @@ -229,7 +229,7 @@ public function testSkipNonReadyHomes($isCreatableValues, $rootFileExists = fals $homeStorage->expects($this->any()) ->method('instanceOfStorage') ->will($this->returnValueMap([ - ['\OC\Files\Storage\Home', true], + ['\\' . \OC\Files\Storage\Home::class, true], ])); $homeStorage->expects($this->never()) diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php index 61b15a2dd5f6..44cf86a8a0cd 100644 --- a/tests/lib/Files/ViewTest.php +++ b/tests/lib/Files/ViewTest.php @@ -43,7 +43,7 @@ public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceIntern class TemporaryNoLocal extends Temporary { public function instanceOfStorage($className) { - if ($className === '\OC\Files\Storage\Local') { + if ($className === '\\' . \OC\Files\Storage\Local::class) { return false; } @@ -63,12 +63,9 @@ class ViewTest extends TestCase { /** * @var Storage[] $storages */ - private $storages = []; + private array $storages = []; - /** - * @var string - */ - private $user; + private string $user; /** * @var \OCP\IUser @@ -80,11 +77,10 @@ class ViewTest extends TestCase { */ private $groupObject; - /** @var Storage */ - private $tempStorage; + private ?\OC\Files\Storage\Temporary $tempStorage = null; /** @var \OC\AllConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; protected function setUp(): void { parent::setUp(); @@ -1661,7 +1657,7 @@ private function createTestMovableMountPoints($mountPoints, $isTargetAllowed = t public function testMountPointMove() { static::loginAsUser($this->user); - list($mount1, $mount2) = $this->createTestMovableMountPoints([ + [$mount1, $mount2] = $this->createTestMovableMountPoints([ $this->user . '/files/mount1', $this->user . '/files/mount2', ]); @@ -1686,7 +1682,7 @@ public function testMountPointMove() { public function testMoveMountPointIntoAnother() { static::loginAsUser($this->user); - list($mount1, $mount2) = $this->createTestMovableMountPoints([ + [$mount1, $mount2] = $this->createTestMovableMountPoints([ $this->user . '/files/mount1', $this->user . '/files/mount2', ]); @@ -1711,7 +1707,7 @@ public function testMoveMountPointNotAllowed() { $userFolder = \OC::$server->getUserFolder($this->user); - list($mount1) = $this->createTestMovableMountPoints([ + [$mount1] = $this->createTestMovableMountPoints([ $this->user . '/files/mount1', ], false); @@ -2167,7 +2163,7 @@ public function testLockFileRename($operation, $expectedLockTypeSourceDuring) { $storage->expects($this->any()) ->method('filemtime') - ->will($this->returnValue(123456789)); + ->will($this->returnValue(123_456_789)); $sourcePath = 'original.txt'; $targetPath = 'target.txt'; @@ -2299,9 +2295,7 @@ public function testGetOwner() { $this->assertEquals('test', $view->getFileInfo($path)->getOwner()->getUID()); $folderInfo = $view->getDirectoryContent(''); - $folderInfo = \array_values(\array_filter($folderInfo, function (FileInfo $info) { - return $info->getName() === 'foo.txt'; - })); + $folderInfo = \array_values(\array_filter($folderInfo, fn (FileInfo $info) => $info->getName() === 'foo.txt')); $this->assertEquals('test', $folderInfo[0]->getOwner()->getUID()); @@ -2309,9 +2303,7 @@ public function testGetOwner() { Filesystem::mount($subStorage, [], '/test/files/asd'); $folderInfo = $view->getDirectoryContent(''); - $folderInfo = \array_values(\array_filter($folderInfo, function (FileInfo $info) { - return $info->getName() === 'asd'; - })); + $folderInfo = \array_values(\array_filter($folderInfo, fn (FileInfo $info) => $info->getName() === 'asd')); $this->assertEquals('test', $folderInfo[0]->getOwner()->getUID()); } @@ -2347,7 +2339,7 @@ public function testLockFileRenameCrossStorage($viewOperation, $storageOperation $storage2->expects($this->any()) ->method('filemtime') - ->will($this->returnValue(123456789)); + ->will($this->returnValue(123_456_789)); $sourcePath = 'original.txt'; $targetPath = 'substorage/target.txt'; @@ -2396,7 +2388,7 @@ function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lock public function testLockMoveMountPoint() { static::loginAsUser('test'); - list($mount) = $this->createTestMovableMountPoints([ + [$mount] = $this->createTestMovableMountPoints([ $this->user . '/files/substorage', ]); @@ -2615,9 +2607,7 @@ public function testGetDirectoryContentMimeFilter($filter, $expected) { $content = $view->getDirectoryContent('', $filter); - $files = \array_map(function (FileInfo $info) { - return $info->getName(); - }, $content); + $files = \array_map(fn (FileInfo $info) => $info->getName(), $content); \sort($files); $this->assertEquals($expected, $files); diff --git a/tests/lib/Group/DatabaseTest.php b/tests/lib/Group/DatabaseTest.php index b582211ba650..46a6a9bef4f3 100644 --- a/tests/lib/Group/DatabaseTest.php +++ b/tests/lib/Group/DatabaseTest.php @@ -31,7 +31,7 @@ * @group DB */ class DatabaseTest extends Backend { - private $groups = []; + private array $groups = []; /** * get a new unique group name diff --git a/tests/lib/Group/GroupTest.php b/tests/lib/Group/GroupTest.php index 7b8390bdea50..26ed108027de 100644 --- a/tests/lib/Group/GroupTest.php +++ b/tests/lib/Group/GroupTest.php @@ -25,7 +25,7 @@ protected function getUserManager() { $user2->expects($this->any())->method('getUID')->willReturn('user2'); $user3 = $this->createMock(IUser::class); $user3->expects($this->any())->method('getUID')->willReturn('user3'); - $userManager = $this->createMock('\OC\User\Manager'); + $userManager = $this->createMock('\\' . \OC\User\Manager::class); $userManager->expects($this->any()) ->method('get') ->will($this->returnValueMap([ @@ -62,7 +62,7 @@ private function getEventDispatcherMock() { } public function testGetUsersSingleBackend() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend], $userManager, $this->getEventDispatcherMock()); @@ -81,8 +81,8 @@ public function testGetUsersSingleBackend() { } public function testGetUsersMultipleBackends() { - $backend1 = $this->createMock('OC\Group\Database'); - $backend2 = $this->createMock('OC\Group\Database'); + $backend1 = $this->createMock(\OC\Group\Database::class); + $backend2 = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend1, $backend2], $userManager, $this->getEventDispatcherMock()); @@ -108,7 +108,7 @@ public function testGetUsersMultipleBackends() { } public function testInGroupSingleBackend() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend], $userManager, $this->getEventDispatcherMock()); @@ -124,8 +124,8 @@ public function testInGroupSingleBackend() { } public function testInGroupMultipleBackends() { - $backend1 = $this->createMock('OC\Group\Database'); - $backend2 = $this->createMock('OC\Group\Database'); + $backend1 = $this->createMock(\OC\Group\Database::class); + $backend2 = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend1, $backend2], $userManager, $this->getEventDispatcherMock()); @@ -146,7 +146,7 @@ public function testInGroupMultipleBackends() { } public function testAddUser() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend], $userManager, $this->getEventDispatcherMock()); @@ -169,7 +169,7 @@ public function testAddUser() { } public function testAddUserWithDispatcher() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $eventsCalled = ['group.preAddUser' => [], 'group.postAddUser' => []]; @@ -211,7 +211,7 @@ public function testAddUserWithDispatcher() { } public function testAddUserAlreadyInGroup() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend], $userManager, $this->getEventDispatcherMock()); @@ -233,7 +233,7 @@ public function testAddUserAlreadyInGroup() { } public function testAddUserAlreadyInGroupWithDispatcher() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $eventsCalled = ['group.preAddUser' => [], 'group.postAddUser' => []]; @@ -270,7 +270,7 @@ public function testAddUserAlreadyInGroupWithDispatcher() { } public function testRemoveUser() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend], $userManager, $this->getEventDispatcherMock()); @@ -293,7 +293,7 @@ public function testRemoveUser() { } public function testRemoveUserWithDispatcher() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $eventsCalled = ['group.preRemoveUser' => [], 'group.postRemoveUser' => []]; @@ -335,7 +335,7 @@ public function testRemoveUserWithDispatcher() { } public function testRemoveUserNotInGroup() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $eventsCalled = ['group.preRemoveUser' => [], 'group.postRemoveUser' => []]; @@ -374,8 +374,8 @@ public function testRemoveUserNotInGroup() { } public function testRemoveUserMultipleBackends() { - $backend1 = $this->createMock('OC\Group\Database'); - $backend2 = $this->createMock('OC\Group\Database'); + $backend1 = $this->createMock(\OC\Group\Database::class); + $backend2 = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend1, $backend2], $userManager, $this->getEventDispatcherMock()); @@ -410,7 +410,7 @@ public function testRemoveUserMultipleBackends() { } public function testSearchUsers() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend], $userManager, $this->getEventDispatcherMock()); @@ -427,8 +427,8 @@ public function testSearchUsers() { } public function testSearchUsersMultipleBackends() { - $backend1 = $this->createMock('OC\Group\Database'); - $backend2 = $this->createMock('OC\Group\Database'); + $backend1 = $this->createMock(\OC\Group\Database::class); + $backend2 = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend1, $backend2], $userManager, $this->getEventDispatcherMock()); @@ -449,7 +449,7 @@ public function testSearchUsersMultipleBackends() { } public function testSearchUsersLimitAndOffset() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend], $userManager, $this->getEventDispatcherMock()); @@ -466,8 +466,8 @@ public function testSearchUsersLimitAndOffset() { } public function testSearchUsersMultipleBackendsLimitAndOffset() { - $backend1 = $this->createMock('OC\Group\Database'); - $backend2 = $this->createMock('OC\Group\Database'); + $backend1 = $this->createMock(\OC\Group\Database::class); + $backend2 = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend1, $backend2], $userManager, $this->getEventDispatcherMock()); @@ -490,7 +490,7 @@ public function testSearchUsersMultipleBackendsLimitAndOffset() { } public function testCountUsers() { - $backend1 = $this->createMock('OC\Group\Database'); + $backend1 = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend1], $userManager, $this->getEventDispatcherMock()); @@ -509,8 +509,8 @@ public function testCountUsers() { } public function testCountUsersMultipleBackends() { - $backend1 = $this->createMock('OC\Group\Database'); - $backend2 = $this->createMock('OC\Group\Database'); + $backend1 = $this->createMock(\OC\Group\Database::class); + $backend2 = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend1, $backend2], $userManager, $this->getEventDispatcherMock()); @@ -536,7 +536,7 @@ public function testCountUsersMultipleBackends() { } public function testCountUsersNoMethod() { - $backend1 = $this->createMock('OC\Group\Database'); + $backend1 = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend1], $userManager, $this->getEventDispatcherMock()); @@ -552,7 +552,7 @@ public function testCountUsersNoMethod() { } public function testDelete() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $group = new \OC\Group\Group('group1', [$backend], $userManager, $this->getEventDispatcherMock()); @@ -567,7 +567,7 @@ public function testDelete() { } public function testDeleteWithDispatcher() { - $backend = $this->createMock('OC\Group\Database'); + $backend = $this->createMock(\OC\Group\Database::class); $userManager = $this->getUserManager(); $eventsCalled = ['group.preDelete' => [], 'group.postDelete' => []]; diff --git a/tests/lib/Group/ManagerTest.php b/tests/lib/Group/ManagerTest.php index 9a1bbfa7333a..dfacaf5f43bf 100644 --- a/tests/lib/Group/ManagerTest.php +++ b/tests/lib/Group/ManagerTest.php @@ -103,9 +103,7 @@ private function getTestBackend($implementedActions = null, $visibleForScopes = ->getMock(); $backend->expects($this->any()) ->method('implementsActions') - ->will($this->returnCallback(function ($actions) use ($implementedActions) { - return (bool)($actions & $implementedActions); - })); + ->will($this->returnCallback(fn ($actions) => (bool)($actions & $implementedActions))); if ($visibleForScopes === null) { $backend->expects($this->any()) ->method('isVisibleForScope') @@ -537,7 +535,7 @@ public function testGetUserGroups() { public function testGetUserGroupIds() { /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Manager $manager */ - $manager = $this->getMockBuilder('OC\Group\Manager') + $manager = $this->getMockBuilder(\OC\Group\Manager::class) ->disableOriginalConstructor() ->setMethods(['getUserGroups']) ->getMock(); @@ -549,7 +547,7 @@ public function testGetUserGroupIds() { ]); /** @var \OC\User\User $user */ - $user = $this->getMockBuilder('OC\User\User') + $user = $this->getMockBuilder(\OC\User\User::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Group/MetaDataTest.php b/tests/lib/Group/MetaDataTest.php index addb50dab3af..b4c738f67e64 100644 --- a/tests/lib/Group/MetaDataTest.php +++ b/tests/lib/Group/MetaDataTest.php @@ -26,20 +26,18 @@ class MetaDataTest extends \Test\TestCase { /** @var \OC\Group\Manager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var \OCP\IUserSession */ - private $userSession; - /** @var \OC\Group\MetaData */ - private $groupMetadata; - /** @var bool */ - private $isAdmin = true; + private \PHPUnit\Framework\MockObject\MockObject $userSession; + private \OC\Group\MetaData $groupMetadata; + private bool $isAdmin = true; public function setUp(): void { parent::setUp(); - $this->groupManager = $this->getMockBuilder('\OC\Group\Manager') + $this->groupManager = $this->getMockBuilder('\\' . \OC\Group\Manager::class) ->disableOriginalConstructor() ->getMock(); - $this->userSession = $this->createMock('\OCP\IUserSession'); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); $this->groupMetadata = new \OC\Group\MetaData( 'foo', $this->isAdmin, @@ -69,7 +67,7 @@ public function testGet() { ->with('') ->will($this->returnValue($groups)); - list($adminGroups, $ordinaryGroups) = $this->groupMetadata->get(); + [$adminGroups, $ordinaryGroups] = $this->groupMetadata->get(); $this->assertCount(1, $adminGroups); $this->assertCount(2, $ordinaryGroups); @@ -102,7 +100,7 @@ public function testGetWithSorting() { ->with('') ->will($this->returnValue($groups)); - list($adminGroups, $ordinaryGroups) = $this->groupMetadata->get(); + [$adminGroups, $ordinaryGroups] = $this->groupMetadata->get(); $this->assertCount(1, $adminGroups); $this->assertCount(2, $ordinaryGroups); diff --git a/tests/lib/HTTPHelperTest.php b/tests/lib/HTTPHelperTest.php index 04079ce3abd0..9017efd23bbc 100644 --- a/tests/lib/HTTPHelperTest.php +++ b/tests/lib/HTTPHelperTest.php @@ -10,19 +10,19 @@ class HTTPHelperTest extends \Test\TestCase { /** @var \OCP\IConfig*/ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var \OC\HTTPHelper */ - private $httpHelperMock; + private \PHPUnit\Framework\MockObject\MockObject $httpHelperMock; /** @var \OCP\Http\Client\IClientService */ - private $clientService; + private \PHPUnit\Framework\MockObject\MockObject $clientService; protected function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder('\OCP\IConfig') + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor()->getMock(); - $this->clientService = $this->createMock('\OCP\Http\Client\IClientService'); - $this->httpHelperMock = $this->getMockBuilder('\OC\HTTPHelper') + $this->clientService = $this->createMock('\\' . \OCP\Http\Client\IClientService::class); + $this->httpHelperMock = $this->getMockBuilder('\\' . \OC\HTTPHelper::class) ->setConstructorArgs([$this->config, $this->clientService]) ->setMethods(['getHeaders']) ->getMock(); @@ -49,13 +49,13 @@ public function testIsHTTP($url, $expected) { } public function testPostSuccess() { - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); $this->clientService ->expects($this->once()) ->method('newClient') ->will($this->returnValue($client)); - $response = $this->getMockBuilder('\OCP\Http\Client\IResponse') + $response = $this->getMockBuilder('\\' . \OCP\Http\Client\IResponse::class) ->disableOriginalConstructor()->getMock(); $client ->expects($this->once()) @@ -85,7 +85,7 @@ public function testPostSuccess() { } public function testPostException() { - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + $client = $this->getMockBuilder('\\' . \OCP\Http\Client\IClient::class) ->disableOriginalConstructor()->getMock(); $this->clientService ->expects($this->once()) diff --git a/tests/lib/Helper/EnvironmentHelperTest.php b/tests/lib/Helper/EnvironmentHelperTest.php index 7380673c8c30..eb7847c383ad 100644 --- a/tests/lib/Helper/EnvironmentHelperTest.php +++ b/tests/lib/Helper/EnvironmentHelperTest.php @@ -25,7 +25,7 @@ use Test\TestCase; class EnvironmentHelperTest extends TestCase { - private $environmentHelper; + private \OC\Helper\EnvironmentHelper $environmentHelper; public function setUp(): void { $this->environmentHelper = new EnvironmentHelper(); diff --git a/tests/lib/Helper/LocaleHelperTest.php b/tests/lib/Helper/LocaleHelperTest.php index db5effcfdf98..e2f9f7fbe159 100644 --- a/tests/lib/Helper/LocaleHelperTest.php +++ b/tests/lib/Helper/LocaleHelperTest.php @@ -140,11 +140,7 @@ public function testNormalization( ->method('get') ->willReturn($l10n); - list( - $userLang, - $commonLanguages, - $languages - ) = $this->localeHelper->getNormalizedLanguages($langFactory, $currentCode); + [$userLang, $commonLanguages, $languages] = $this->localeHelper->getNormalizedLanguages($langFactory, $currentCode); $this->assertEquals($expectedUserLang, $userLang); $this->assertEquals($expectedCommonLanguages, $commonLanguages); $this->assertEquals($expectedLanguages, $languages); diff --git a/tests/lib/HelperStorageTest.php b/tests/lib/HelperStorageTest.php index 0f1f7ae32e77..b783e4026e66 100644 --- a/tests/lib/HelperStorageTest.php +++ b/tests/lib/HelperStorageTest.php @@ -19,8 +19,7 @@ class HelperStorageTest extends TestCase { /** @var string */ private $user; - /** @var \OC\Files\Storage\Storage */ - private $storageMock; + private ?\PHPUnit\Framework\MockObject\MockObject $storageMock = null; /** @var \OC\Files\Storage\Storage */ private $storage; /** @var IUser */ @@ -67,7 +66,7 @@ protected function tearDown(): void { * @return \OC\Files\Storage\Storage */ private function getStorageMock($freeSpace = 12) { - $this->storageMock = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $this->storageMock = $this->getMockBuilder('\\' . \OC\Files\Storage\Temporary::class) ->setMethods(['free_space']) ->setConstructorArgs(['']) ->getMock(); diff --git a/tests/lib/HookHelper.php b/tests/lib/HookHelper.php index 5e040724d90f..4a56c45e324f 100644 --- a/tests/lib/HookHelper.php +++ b/tests/lib/HookHelper.php @@ -21,38 +21,38 @@ public static function setUpHooks() { \OCP\Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_create, - '\Test\HookHelper', + '\\' . \Test\HookHelper::class, 'createCallback' ); \OCP\Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_update, - '\Test\HookHelper', + '\\' . \Test\HookHelper::class, 'updateCallback' ); \OCP\Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_write, - '\Test\HookHelper', + '\\' . \Test\HookHelper::class, 'writeCallback' ); \OCP\Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_post_create, - '\Test\HookHelper', + '\\' . \Test\HookHelper::class, 'postCreateCallback' ); \OCP\Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_post_update, - '\Test\HookHelper', + '\\' . \Test\HookHelper::class, 'postUpdateCallback' ); \OCP\Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_post_write, - '\Test\HookHelper', + '\\' . \Test\HookHelper::class, 'postWriteCallback' ); } diff --git a/tests/lib/Hooks/BasicEmitterTest.php b/tests/lib/Hooks/BasicEmitterTest.php index 004fa19cd4ee..f658a714bd77 100644 --- a/tests/lib/Hooks/BasicEmitterTest.php +++ b/tests/lib/Hooks/BasicEmitterTest.php @@ -66,7 +66,7 @@ public function testAnonymousFunction() { public function testStaticCallback() { $this->expectException(\Test\Hooks\EmittedException::class); - $this->emitter->listen('Test', 'test', ['\Test\Hooks\BasicEmitterTest', 'staticCallBack']); + $this->emitter->listen('Test', 'test', ['\\' . \Test\Hooks\BasicEmitterTest::class, 'staticCallBack']); $this->emitter->emitEvent('Test', 'test'); } diff --git a/tests/lib/Hooks/LegacyEmitterTest.php b/tests/lib/Hooks/LegacyEmitterTest.php index e3266531d01f..70cda300d86e 100644 --- a/tests/lib/Hooks/LegacyEmitterTest.php +++ b/tests/lib/Hooks/LegacyEmitterTest.php @@ -23,7 +23,7 @@ public function emitEvent($scope, $method, $arguments = []) { class LegacyEmitterTest extends BasicEmitterTest { //we can't use exceptions here since OC_Hooks catches all exceptions - private static $emitted = false; + private static bool $emitted = false; protected function setUp(): void { parent::setUp(); @@ -44,13 +44,13 @@ public static function staticLegacyArgumentsCallBack($arguments) { } public function testLegacyHook() { - \OC_Hook::connect('Test', 'test', '\Test\Hooks\LegacyEmitterTest', 'staticLegacyCallBack'); + \OC_Hook::connect('Test', 'test', '\\' . \Test\Hooks\LegacyEmitterTest::class, 'staticLegacyCallBack'); $this->emitter->emitEvent('Test', 'test'); $this->assertTrue(self::$emitted); } public function testLegacyArguments() { - \OC_Hook::connect('Test', 'test', '\Test\Hooks\LegacyEmitterTest', 'staticLegacyArgumentsCallBack'); + \OC_Hook::connect('Test', 'test', '\\' . \Test\Hooks\LegacyEmitterTest::class, 'staticLegacyArgumentsCallBack'); $this->emitter->emitEvent('Test', 'test', ['foo' => 'foo', 'bar' => 'bar']); $this->assertTrue(self::$emitted); } diff --git a/tests/lib/Http/Client/ClientServiceTest.php b/tests/lib/Http/Client/ClientServiceTest.php index 248568f75718..87b6cd94810d 100644 --- a/tests/lib/Http/Client/ClientServiceTest.php +++ b/tests/lib/Http/Client/ClientServiceTest.php @@ -17,8 +17,8 @@ */ class ClientServiceTest extends \Test\TestCase { public function testNewClient() { - $config = $this->createMock('\OCP\IConfig'); - $certificateManager = $this->createMock('\OCP\ICertificateManager'); + $config = $this->createMock('\\' . \OCP\IConfig::class); + $certificateManager = $this->createMock('\\' . \OCP\ICertificateManager::class); $expected = new Client($config, $certificateManager, new GuzzleClient()); $clientService = new ClientService($config, $certificateManager); diff --git a/tests/lib/Http/Client/ClientTest.php b/tests/lib/Http/Client/ClientTest.php index ab3a612a86dc..1848b3b5562d 100644 --- a/tests/lib/Http/Client/ClientTest.php +++ b/tests/lib/Http/Client/ClientTest.php @@ -18,17 +18,16 @@ */ class ClientTest extends \Test\TestCase { /** @var GuzzleClient */ - private $guzzleClient; - /** @var Client */ - private $client; + private \PHPUnit\Framework\MockObject\MockObject $guzzleClient; + private \OC\Http\Client\Client $client; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; public function setUp(): void { parent::setUp(); - $this->config = $this->createMock('\OCP\IConfig'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); $this->guzzleClient = $this->createMock(GuzzleClient::class); - $certificateManager = $this->createMock('\OCP\ICertificateManager'); + $certificateManager = $this->createMock('\\' . \OCP\ICertificateManager::class); $this->client = new Client( $this->config, $certificateManager, diff --git a/tests/lib/Http/Client/ResponseTest.php b/tests/lib/Http/Client/ResponseTest.php index f11a023c9419..920038250596 100644 --- a/tests/lib/Http/Client/ResponseTest.php +++ b/tests/lib/Http/Client/ResponseTest.php @@ -15,10 +15,8 @@ * Class ResponseTest */ class ResponseTest extends \Test\TestCase { - /** @var Response */ - private $response; - /** @var GuzzleResponse */ - private $guzzleResponse; + private \OC\Http\Client\Response $response; + private \GuzzleHttp\Psr7\Response $guzzleResponse; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Image/BmpToResourceTest.php b/tests/lib/Image/BmpToResourceTest.php index 0e03e841d634..0758711fb85a 100644 --- a/tests/lib/Image/BmpToResourceTest.php +++ b/tests/lib/Image/BmpToResourceTest.php @@ -67,7 +67,7 @@ public function testReadDibHeader() { $this->assertEquals(32, $dibHeader['imagesize']); $this->assertEquals(2836, $dibHeader['xres']); $this->assertEquals(2835, $dibHeader['yres']); - $this->assertEquals(\pow(2, $dibHeader['bits']), $dibHeader['colors']); + $this->assertEquals(2 ** $dibHeader['bits'], $dibHeader['colors']); $this->assertEquals(0, $dibHeader['important']); } diff --git a/tests/lib/ImageTest.php b/tests/lib/ImageTest.php index eb43bcf1b40c..59aaed2eda8a 100644 --- a/tests/lib/ImageTest.php +++ b/tests/lib/ImageTest.php @@ -35,24 +35,24 @@ public function testGetMimeTypeForFile() { public function testConstructDestruct() { $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); $this->assertInstanceOf('\OC_Image', $img); - $this->assertInstanceOf('\OCP\IImage', $img); + $this->assertInstanceOf('\\' . \OCP\IImage::class, $img); unset($img); $imgcreate = \imagecreatefromjpeg(OC::$SERVERROOT.'/tests/data/testimage.jpg'); $img = new \OC_Image($imgcreate); $this->assertInstanceOf('\OC_Image', $img); - $this->assertInstanceOf('\OCP\IImage', $img); + $this->assertInstanceOf('\\' . \OCP\IImage::class, $img); unset($img); $base64 = \base64_encode(\file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif')); $img = new \OC_Image($base64); $this->assertInstanceOf('\OC_Image', $img); - $this->assertInstanceOf('\OCP\IImage', $img); + $this->assertInstanceOf('\\' . \OCP\IImage::class, $img); unset($img); $img = new \OC_Image(null); $this->assertInstanceOf('\OC_Image', $img); - $this->assertInstanceOf('\OCP\IImage', $img); + $this->assertInstanceOf('\\' . \OCP\IImage::class, $img); unset($img); } diff --git a/tests/lib/InstallerTest.php b/tests/lib/InstallerTest.php index c173997ceb8b..0dcc59f76cf6 100644 --- a/tests/lib/InstallerTest.php +++ b/tests/lib/InstallerTest.php @@ -11,7 +11,7 @@ use OC\Installer; class InstallerTest extends TestCase { - private static $appid = 'testapp'; + private static string $appid = 'testapp'; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/IntegrityCheck/CheckerTest.php b/tests/lib/IntegrityCheck/CheckerTest.php index 1a26fe82ec8a..62559cf42e40 100644 --- a/tests/lib/IntegrityCheck/CheckerTest.php +++ b/tests/lib/IntegrityCheck/CheckerTest.php @@ -45,19 +45,19 @@ */ class CheckerTest extends TestCase { /** @var EnvironmentHelper | \PHPUnit\Framework\MockObject\MockObject */ - private $environmentHelper; + private \PHPUnit\Framework\MockObject\MockObject $environmentHelper; /** @var AppLocator | \PHPUnit\Framework\MockObject\MockObject */ - private $appLocator; + private \PHPUnit\Framework\MockObject\MockObject $appLocator; /** @var Checker */ private $checker; /** @var FileAccessHelper | \PHPUnit\Framework\MockObject\MockObject */ - private $fileAccessHelper; + private \PHPUnit\Framework\MockObject\MockObject $fileAccessHelper; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ICacheFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $cacheFactory; + private \PHPUnit\Framework\MockObject\MockObject $cacheFactory; /** @var IAppManager | \PHPUnit\Framework\MockObject\MockObject */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; public function setUp(): void { parent::setUp(); @@ -135,7 +135,7 @@ public function testWriteAppSignature() { $this->callback(function ($arg) use ($expectedSignatureFileData) { $this->assertEquals( \json_decode($expectedSignatureFileData, true), - \json_decode($arg, true) + \json_decode($arg, true, 512, JSON_THROW_ON_ERROR) ); return true; }) @@ -184,7 +184,7 @@ public function testVerifyAppSignatureWithoutSignatureData() { $expected = [ 'EXCEPTION' => [ - 'class' => 'OC\IntegrityCheck\Exceptions\MissingSignatureException', + 'class' => \OC\IntegrityCheck\Exceptions\MissingSignatureException::class, 'message' => 'Signature data not found.', ], ]; @@ -268,7 +268,7 @@ public function testVerifyAppSignatureWithTamperedSignatureData() { $expected = [ 'EXCEPTION' => [ - 'class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', + 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature could not get verified.', ], ]; @@ -488,7 +488,7 @@ public function testVerifyAppWithDifferentScope() { $expected = [ 'EXCEPTION' => [ - 'class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', + 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Certificate is not valid for required scope. (Requested: SomeApp, current: CN=AnotherScope)', ], ]; @@ -556,7 +556,7 @@ public function testWriteCoreSignature() { $this->callback(function ($arg) use ($expectedSignatureFileData) { $this->assertEquals( \json_decode($expectedSignatureFileData, true), - \json_decode($arg, true) + \json_decode($arg, true, 512, JSON_THROW_ON_ERROR) ); return true; }) @@ -592,7 +592,7 @@ public function testWriteCoreSignatureWithUnmodifiedHtaccess() { $this->callback(function ($arg) use ($expectedSignatureFileData) { $this->assertEquals( \json_decode($expectedSignatureFileData, true), - \json_decode($arg, true) + \json_decode($arg, true, 512, JSON_THROW_ON_ERROR) ); return true; }) @@ -623,7 +623,7 @@ public function testWriteCoreSignatureWithInvalidModifiedHtaccess() { $this->callback(function ($arg) use ($expectedSignatureFileData) { $this->assertEquals( \json_decode($expectedSignatureFileData, true), - \json_decode($arg, true) + \json_decode($arg, true, 512, JSON_THROW_ON_ERROR) ); return true; }) @@ -664,7 +664,7 @@ public function testWriteCoreSignatureWithValidModifiedHtaccessAndUserIni() { $this->callback(function ($arg) use ($expectedSignatureFileData) { $this->assertEquals( \json_decode($expectedSignatureFileData, true), - \json_decode($arg, true) + \json_decode($arg, true, 512, JSON_THROW_ON_ERROR) ); return true; }) @@ -692,7 +692,7 @@ public function testVerifyCoreSignatureWithoutSignatureData() { $expected = [ 'EXCEPTION' => [ - 'class' => 'OC\\IntegrityCheck\\Exceptions\\MissingSignatureException', + 'class' => \OC\IntegrityCheck\Exceptions\MissingSignatureException::class, 'message' => 'Signature data not found.', ], ]; @@ -853,7 +853,7 @@ public function testVerifyCoreSignatureWithTamperedSignatureData() { $expected = [ 'EXCEPTION' => [ - 'class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', + 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Signature could not get verified.', ] ]; @@ -1010,7 +1010,7 @@ public function testVerifyCoreWithInvalidCertificate() { $expected = [ 'EXCEPTION' => [ - 'class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', + 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'App Certificate is not valid.', ] ]; @@ -1053,7 +1053,7 @@ public function testVerifyCoreWithDifferentScope() { $expected = [ 'EXCEPTION' => [ - 'class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', + 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Certificate is not valid for required scope. (Requested: core, current: CN=SomeApp)', ] ]; @@ -1061,7 +1061,7 @@ public function testVerifyCoreWithDifferentScope() { } public function testRunInstanceVerification() { - $this->checker = $this->getMockBuilder('\OC\IntegrityCheck\Checker') + $this->checker = $this->getMockBuilder('\\' . \OC\IntegrityCheck\Checker::class) ->setConstructorArgs([ $this->environmentHelper, $this->fileAccessHelper, @@ -1233,7 +1233,7 @@ public function testCertRevocation() { ); $expected = [ 'EXCEPTION' => [ - 'class' => 'OC\\IntegrityCheck\\Exceptions\\InvalidSignatureException', + 'class' => \OC\IntegrityCheck\Exceptions\InvalidSignatureException::class, 'message' => 'Certificate has been revoked.', ] ]; diff --git a/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php b/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php index 9c86657fd2b3..edde17165f4f 100644 --- a/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php +++ b/tests/lib/IntegrityCheck/Helpers/AppLocatorTest.php @@ -25,8 +25,7 @@ use Test\TestCase; class AppLocatorTest extends TestCase { - /** @var AppLocator */ - private $locator; + private \OC\IntegrityCheck\Helpers\AppLocator $locator; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php b/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php index 688c7d56fe77..72205e2ccc50 100644 --- a/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php +++ b/tests/lib/IntegrityCheck/Helpers/EnvironmentHelperTest.php @@ -25,8 +25,7 @@ use Test\TestCase; class EnvironmentHelperTest extends TestCase { - /** @var EnvironmentHelper */ - private $environmentHelper; + private \OC\IntegrityCheck\Helpers\EnvironmentHelper $environmentHelper; public function setUp(): void { $this->environmentHelper = new EnvironmentHelper(); diff --git a/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php b/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php index 5e48fc9764ca..0bb27c7d9bba 100644 --- a/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php +++ b/tests/lib/IntegrityCheck/Helpers/FileAccessHelperTest.php @@ -24,8 +24,7 @@ use Test\TestCase; class FileAccessHelperTest extends TestCase { - /** @var FileAccessHelper */ - private $fileAccessHelper; + private \OC\IntegrityCheck\Helpers\FileAccessHelper $fileAccessHelper; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/L10N/L10nTest.php b/tests/lib/L10N/L10nTest.php index c3a67a5d7e67..f788814ff201 100644 --- a/tests/lib/L10N/L10nTest.php +++ b/tests/lib/L10N/L10nTest.php @@ -26,15 +26,15 @@ class L10nTest extends TestCase { */ protected function getFactory() { /** @var \OCP\IConfig $config */ - $config = $this->createMock('OCP\IConfig'); + $config = $this->createMock(\OCP\IConfig::class); /** @var \OCP\IRequest $request */ - $request = $this->createMock('OCP\IRequest'); + $request = $this->createMock(\OCP\IRequest::class); /** @var IThemeService $themeService */ $themeService = $this->getMockBuilder(IThemeService::class) ->disableOriginalConstructor() ->getMock(); /** @var IUserSession $userSession */ - $userSession = $this->createMock('OCP\IUserSession'); + $userSession = $this->createMock(\OCP\IUserSession::class); return new Factory($config, $request, $themeService, $userSession, \OC::$SERVERROOT); } @@ -47,7 +47,7 @@ public function testGermanPluralTranslations() { } public function testMalformedTranslations() { - $lMock = $this->createMock('OC\L10N\L10N'); + $lMock = $this->createMock(\OC\L10N\L10N::class); $lMock->method('getTranslations')->willReturn(['malformed' => 'malformed %']); $lString = new \OC_L10N_String($lMock, "malformed", []); @@ -99,12 +99,12 @@ public function localizationData() { ['23:31:30 UTC', 'de', 'time', '1234567890'], // timestamp as int - ["February 13, 2009, 11:31:30{$narrowNoBreakSpace}PM UTC", 'en', 'datetime', 1234567890], - ['13. Februar 2009, 23:31:30 UTC', 'de', 'datetime', 1234567890], - ['February 13, 2009', 'en', 'date', 1234567890], - ['13. Februar 2009', 'de', 'date', 1234567890], - ["11:31:30{$narrowNoBreakSpace}PM UTC", 'en', 'time', 1234567890], - ['23:31:30 UTC', 'de', 'time', 1234567890], + ["February 13, 2009, 11:31:30{$narrowNoBreakSpace}PM UTC", 'en', 'datetime', 1_234_567_890], + ['13. Februar 2009, 23:31:30 UTC', 'de', 'datetime', 1_234_567_890], + ['February 13, 2009', 'en', 'date', 1_234_567_890], + ['13. Februar 2009', 'de', 'date', 1_234_567_890], + ["11:31:30{$narrowNoBreakSpace}PM UTC", 'en', 'time', 1_234_567_890], + ['23:31:30 UTC', 'de', 'time', 1_234_567_890], // DateTime object ["February 13, 2009, 11:31:30{$narrowNoBreakSpace}PM GMT+0", 'en', 'datetime', new DateTime('@1234567890')], diff --git a/tests/lib/LargeFileHelperTest.php b/tests/lib/LargeFileHelperTest.php index 697a4966d931..f5b2e8cd463c 100644 --- a/tests/lib/LargeFileHelperTest.php +++ b/tests/lib/LargeFileHelperTest.php @@ -19,7 +19,7 @@ protected function setUp(): void { public function testFormatUnsignedIntegerFloat() { $this->assertSame( '9007199254740992', - $this->helper->formatUnsignedInteger((float) 9007199254740992) + $this->helper->formatUnsignedInteger((float) 9_007_199_254_740_992) ); } diff --git a/tests/lib/LegacyHelperTest.php b/tests/lib/LegacyHelperTest.php index 0f4e092ac6e3..34c020b2f357 100644 --- a/tests/lib/LegacyHelperTest.php +++ b/tests/lib/LegacyHelperTest.php @@ -23,11 +23,11 @@ public function humanFileSizeProvider() { return [ ['0 B', 0], ['1 KB', 1024], - ['9.5 MB', 10000000], - ['1.3 GB', 1395864371], - ['465.7 GB', 500000000000], - ['454.7 TB', 500000000000000], - ['444.1 PB', 500000000000000000], + ['9.5 MB', 10_000_000], + ['1.3 GB', 1_395_864_371], + ['465.7 GB', 500_000_000_000], + ['454.7 TB', 500_000_000_000_000], + ['444.1 PB', 500_000_000_000_000_000], ]; } @@ -43,11 +43,11 @@ public function phpFileSizeProvider() { return [ ['0B', 0], ['1K', 1024], - ['9.5M', 10000000], - ['1.3G', 1395864371], - ['465.7G', 500000000000], - ['465661.3G', 500000000000000], - ['465661287.3G', 500000000000000000], + ['9.5M', 10_000_000], + ['1.3G', 1_395_864_371], + ['465.7G', 500_000_000_000], + ['465661.3G', 500_000_000_000_000], + ['465661287.3G', 500_000_000_000_000_000], ]; } @@ -63,9 +63,9 @@ public function providesComputerFileSize() { return [ [0.0, "0 B"], [1024.0, "1 KB"], - [1395864371.0, '1.3 GB'], - [9961472.0, "9.5 MB"], - [500041567437.0, "465.7 GB"], + [1_395_864_371.0, '1.3 GB'], + [9_961_472.0, "9.5 MB"], + [500_041_567_437.0, "465.7 GB"], [false, "12 GB etfrhzui"] ]; } @@ -124,7 +124,7 @@ public function testRecursiveArraySearch() { } public function testBuildNotExistingFileNameForView() { - $viewMock = $this->createMock('\OC\Files\View', [], [], '', false); + $viewMock = $this->createMock('\\' . \OC\Files\View::class); $this->assertEquals('/filename', OC_Helper::buildNotExistingFileNameForView('/', 'filename', $viewMock)); $this->assertEquals('dir/filename.ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); @@ -178,7 +178,7 @@ public function testStreamCopy($expectedCount, $expectedResult, $source, $target $target = \fopen($target, 'w'); } - list($count, $result) = \OC_Helper::streamCopy($source, $target); + [$count, $result] = \OC_Helper::streamCopy($source, $target); if (\is_resource($source)) { \fclose($source); diff --git a/tests/lib/License/LicenseFetcherTest.php b/tests/lib/License/LicenseFetcherTest.php index 24d310052915..ab8b8644b69f 100644 --- a/tests/lib/License/LicenseFetcherTest.php +++ b/tests/lib/License/LicenseFetcherTest.php @@ -29,11 +29,10 @@ class LicenseFetcherTest extends TestCase { /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ITimeFactory */ - private $timeFactory; - /** @var LicenseFetcher */ - private $licenseFetcher; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; + private \OC\License\LicenseFetcher $licenseFetcher; protected function setUp(): void { $this->config = $this->createMock(IConfig::class); @@ -69,7 +68,7 @@ public function testGetOwncloudLicense(): void { public function testGetOwncloudLicenseFromDB(): void { $this->timeFactory->method('getTime') - ->willReturn(1010000000); + ->willReturn(1_010_000_000); $this->config->expects(self::once()) ->method('getAppValue') @@ -89,7 +88,7 @@ public function testGetOwncloudLicenseFromDB(): void { public function testGetOwncloudLicenseDBExpired(): void { $this->timeFactory->method('getTime') - ->willReturn(1010000000); + ->willReturn(1_010_000_000); $this->config->expects(self::once()) ->method('getAppValue') @@ -116,7 +115,7 @@ public function testGetOwncloudLicenseDBExpired(): void { public function testGetOwncloudLicenseDBInvalid(): void { $this->timeFactory->method('getTime') - ->willReturn(1010000000); + ->willReturn(1_010_000_000); $this->config->expects(self::once()) ->method('getAppValue') @@ -143,7 +142,7 @@ public function testGetOwncloudLicenseDBInvalid(): void { public function testGetOwncloudLicenseDBInvalidConfigMissing(): void { $this->timeFactory->method('getTime') - ->willReturn(1010000000); + ->willReturn(1_010_000_000); $this->config->expects(self::exactly(2)) ->method('getSystemValue') diff --git a/tests/lib/License/LicenseManagerTest.php b/tests/lib/License/LicenseManagerTest.php index 5e47bd240e50..760f33daf66d 100644 --- a/tests/lib/License/LicenseManagerTest.php +++ b/tests/lib/License/LicenseManagerTest.php @@ -33,19 +33,18 @@ class LicenseManagerTest extends TestCase { /** @var LicenseFetcher */ - private $licenseFetcher; + private \PHPUnit\Framework\MockObject\MockObject $licenseFetcher; /**@var MessageService */ - private $messageService; + private \PHPUnit\Framework\MockObject\MockObject $messageService; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IAppManager */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; /** @var ITimeFactory */ - private $timeFactory; - /** @var LicenseManager */ - private $licenseManager; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; + private \OC\License\LicenseManager $licenseManager; /** @var ILogger */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; protected function setUp(): void { $this->licenseFetcher = $this->createMock(LicenseFetcher::class); @@ -67,10 +66,10 @@ protected function setUp(): void { public function getGracePeriodProviderWrong() { return [ - [null, 1581945782, false], // no grace period started - [null, 1581945782, true], - [1581945782 - (LicenseManager::GRACE_PERIOD * 2), 1581945782, false], // grace period expired - [1581945782 - (LicenseManager::GRACE_PERIOD * 2), 1581945782, true], + [null, 1_581_945_782, false], // no grace period started + [null, 1_581_945_782, true], + [1_581_945_782 - (LicenseManager::GRACE_PERIOD * 2), 1_581_945_782, false], // grace period expired + [1_581_945_782 - (LicenseManager::GRACE_PERIOD * 2), 1_581_945_782, true], ]; } @@ -110,16 +109,16 @@ public function getGracePeriodProvider() { $ocLicenseInvalidExpired->method('getExpirationTime')->willReturn(PHP_INT_MIN); $ocLicenseInvalidExpired->method('getLicenseString')->willReturn('dummy-license-string'); return [ - [1581945782, 1581945782, null], // no license set - [1581945782, 1581945782 + LicenseManager::GRACE_PERIOD, null], - [1581945782, 1581945782, $ocLicenseValid], - [1581945782, 1581945782 + LicenseManager::GRACE_PERIOD, $ocLicenseValid], - [1581945782, 1581945782, $ocLicenseInvalid], - [1581945782, 1581945782 + LicenseManager::GRACE_PERIOD, $ocLicenseInvalid], - [1581945782, 1581945782, $ocLicenseExpired], - [1581945782, 1581945782 + LicenseManager::GRACE_PERIOD, $ocLicenseExpired], - [1581945782, 1581945782, $ocLicenseInvalidExpired], - [1581945782, 1581945782 + LicenseManager::GRACE_PERIOD, $ocLicenseInvalidExpired], + [1_581_945_782, 1_581_945_782, null], // no license set + [1_581_945_782, 1_581_945_782 + LicenseManager::GRACE_PERIOD, null], + [1_581_945_782, 1_581_945_782, $ocLicenseValid], + [1_581_945_782, 1_581_945_782 + LicenseManager::GRACE_PERIOD, $ocLicenseValid], + [1_581_945_782, 1_581_945_782, $ocLicenseInvalid], + [1_581_945_782, 1_581_945_782 + LicenseManager::GRACE_PERIOD, $ocLicenseInvalid], + [1_581_945_782, 1_581_945_782, $ocLicenseExpired], + [1_581_945_782, 1_581_945_782 + LicenseManager::GRACE_PERIOD, $ocLicenseExpired], + [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired], + [1_581_945_782, 1_581_945_782 + LicenseManager::GRACE_PERIOD, $ocLicenseInvalidExpired], ]; } @@ -251,7 +250,7 @@ public function getLicenseStateForProvider() { $ocLicenseAboutExpire = $this->createMock(ILicense::class); $ocLicenseAboutExpire->method('isValid')->willReturn(true); - $ocLicenseAboutExpire->method('getExpirationTime')->willReturn(100300500 + 3600); + $ocLicenseAboutExpire->method('getExpirationTime')->willReturn(100_300_500 + 3600); $ocLicenseAboutExpire->method('getLicenseString')->willReturn('dummy-license-string'); $ocLicenseInvalid = $this->createMock(ILicense::class); @@ -282,7 +281,7 @@ public function getLicenseStateForProvider() { * @dataProvider getLicenseStateForProvider */ public function testGetLicenseStateFor($ocLicense, $expectedState) { - $this->timeFactory->method('getTime')->willReturn(100300500); + $this->timeFactory->method('getTime')->willReturn(100_300_500); $this->licenseFetcher->method('getOwncloudLicense')->willReturn($ocLicense); $this->assertSame($expectedState, $this->licenseManager->getLicenseStateFor('dummyApp')); @@ -296,7 +295,7 @@ public function getLicenseMessageForProvider() { $ocLicenseAboutExpire = $this->createMock(ILicense::class); $ocLicenseAboutExpire->method('isValid')->willReturn(true); - $ocLicenseAboutExpire->method('getExpirationTime')->willReturn(100300500 + 3600); + $ocLicenseAboutExpire->method('getExpirationTime')->willReturn(100_300_500 + 3600); $ocLicenseAboutExpire->method('getLicenseString')->willReturn('dummy-license-string'); $ocLicenseInvalid = $this->createMock(ILicense::class); @@ -333,7 +332,7 @@ public function getLicenseMessageForProvider() { * @dataProvider getLicenseMessageForProvider */ public function testGetLicenseMessageFor($license, $expectedLicenseState, $expectedMessageInfo) { - $this->timeFactory->method('getTime')->willReturn(100300500); + $this->timeFactory->method('getTime')->willReturn(100_300_500); $this->licenseFetcher->method('getOwncloudLicense')->willReturn($license); $this->messageService->method('getMessageForLicense')->willReturn($expectedMessageInfo); @@ -370,7 +369,7 @@ public function checkLicenseForProvider() { $ocLicenseAboutExpire = $this->createMock(ILicense::class); $ocLicenseAboutExpire->method('isValid')->willReturn(true); - $ocLicenseAboutExpire->method('getExpirationTime')->willReturn(1581945782 + 60); + $ocLicenseAboutExpire->method('getExpirationTime')->willReturn(1_581_945_782 + 60); $ocLicenseAboutExpire->method('getLicenseString')->willReturn('dummy-license-string'); $options0 = []; @@ -383,176 +382,176 @@ public function checkLicenseForProvider() { $options7 = ['startGracePeriod' => true, 'disableApp' => false]; $options8 = ['startGracePeriod' => true, 'disableApp' => true]; return [ - /*0*/ [null, 1581945782, null, $options0, true], - /*1*/ [1581945782, 1581945782, null, $options0, true], // no license set - /*2*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options0, false], - /*3*/ [null, 1581945782, $ocLicenseValid, $options0, true], - /*4*/ [1581945782, 1581945782, $ocLicenseValid, $options0, true], - /*5*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options0, true], - /*6*/ [null, 1581945782, $ocLicenseInvalid, $options0, true], - /*7*/ [1581945782, 1581945782, $ocLicenseInvalid, $options0, true], - /*8*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options0, false], - /*9*/ [null, 1581945782, $ocLicenseExpired, $options0, true], - /*10*/ [1581945782, 1581945782, $ocLicenseExpired, $options0, true], - /*11*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options0, false], - /*12*/ [null, 1581945782, $ocLicenseInvalidExpired, $options0, true], - /*13*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options0, true], - /*14*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options0, false], - /*15*/ [null, 1581945782, $ocLicenseAboutExpire, $options0, true], - /*16*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options0, true], - /*17*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options0, false], - - /*18*/ [null, 1581945782, null, $options1, false], - /*19*/ [1581945782, 1581945782, null, $options1, true], // no license set - /*20*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options1, false], - /*21*/ [null, 1581945782, $ocLicenseValid, $options1, true], - /*22*/ [1581945782, 1581945782, $ocLicenseValid, $options1, true], - /*23*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options1, true], - /*24*/ [null, 1581945782, $ocLicenseInvalid, $options1, false], - /*25*/ [1581945782, 1581945782, $ocLicenseInvalid, $options1, true], - /*26*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options1, false], - /*27*/ [null, 1581945782, $ocLicenseExpired, $options1, false], - /*28*/ [1581945782, 1581945782, $ocLicenseExpired, $options1, true], - /*29*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options1, false], - /*30*/ [null, 1581945782, $ocLicenseInvalidExpired, $options1, false], - /*31*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options1, true], - /*32*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options1, false], - /*33*/ [null, 1581945782, $ocLicenseAboutExpire, $options1, true], - /*34*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options1, true], - /*35*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options1, false], - - /*36*/ [null, 1581945782, null, $options2, true], - /*37*/ [1581945782, 1581945782, null, $options2, true], // no license set - /*38*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options2, false], - /*39*/ [null, 1581945782, $ocLicenseValid, $options2, true], - /*40*/ [1581945782, 1581945782, $ocLicenseValid, $options2, true], - /*41*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options2, true], - /*42*/ [null, 1581945782, $ocLicenseInvalid, $options2, true], - /*43*/ [1581945782, 1581945782, $ocLicenseInvalid, $options2, true], - /*44*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options2, false], - /*45*/ [null, 1581945782, $ocLicenseExpired, $options2, true], - /*46*/ [1581945782, 1581945782, $ocLicenseExpired, $options2, true], - /*47*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options2, false], - /*48*/ [null, 1581945782, $ocLicenseInvalidExpired, $options2, true], - /*49*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options2, true], - /*50*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options2, false], - /*51*/ [null, 1581945782, $ocLicenseAboutExpire, $options2, true], - /*52*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options2, true], - /*53*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options2, false], - - /*54*/ [null, 1581945782, null, $options3, true], - /*55*/ [1581945782, 1581945782, null, $options3, true], // no license set - /*56*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options3, false], - /*57*/ [null, 1581945782, $ocLicenseValid, $options3, true], - /*58*/ [1581945782, 1581945782, $ocLicenseValid, $options3, true], - /*59*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options3, true], - /*60*/ [null, 1581945782, $ocLicenseInvalid, $options3, true], - /*61*/ [1581945782, 1581945782, $ocLicenseInvalid, $options3, true], - /*62*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options3, false], - /*63*/ [null, 1581945782, $ocLicenseExpired, $options3, true], - /*64*/ [1581945782, 1581945782, $ocLicenseExpired, $options3, true], - /*65*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options3, false], - /*66*/ [null, 1581945782, $ocLicenseInvalidExpired, $options3, true], - /*67*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options3, true], - /*68*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options3, false], - /*69*/ [null, 1581945782, $ocLicenseAboutExpire, $options3, true], - /*70*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options3, true], - /*71*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options3, false], - - /*72*/ [null, 1581945782, null, $options4, true], - /*73*/ [1581945782, 1581945782, null, $options4, true], // no license set - /*74*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options4, false], - /*75*/ [null, 1581945782, $ocLicenseValid, $options4, true], - /*76*/ [1581945782, 1581945782, $ocLicenseValid, $options4, true], - /*77*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options4, true], - /*78*/ [null, 1581945782, $ocLicenseInvalid, $options4, true], - /*79*/ [1581945782, 1581945782, $ocLicenseInvalid, $options4, true], - /*80*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options4, false], - /*81*/ [null, 1581945782, $ocLicenseExpired, $options4, true], - /*82*/ [1581945782, 1581945782, $ocLicenseExpired, $options4, true], - /*83*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options4, false], - /*84*/ [null, 1581945782, $ocLicenseInvalidExpired, $options4, true], - /*85*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options4, true], - /*86*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options4, false], - /*87*/ [null, 1581945782, $ocLicenseAboutExpire, $options4, true], - /*88*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options4, true], - /*89*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options4, false], - - /*90*/ [null, 1581945782, null, $options5, false], - /*91*/ [1581945782, 1581945782, null, $options5, true], // no license set - /*92*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options5, false], - /*93*/ [null, 1581945782, $ocLicenseValid, $options5, true], - /*94*/ [1581945782, 1581945782, $ocLicenseValid, $options5, true], - /*95*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options5, true], - /*96*/ [null, 1581945782, $ocLicenseInvalid, $options5, false], - /*97*/ [1581945782, 1581945782, $ocLicenseInvalid, $options5, true], - /*98*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options5, false], - /*99*/ [null, 1581945782, $ocLicenseExpired, $options5, false], - /*100*/ [1581945782, 1581945782, $ocLicenseExpired, $options5, true], - /*101*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options5, false], - /*102*/ [null, 1581945782, $ocLicenseInvalidExpired, $options5, false], - /*103*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options5, true], - /*104*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options5, false], - /*105*/ [null, 1581945782, $ocLicenseAboutExpire, $options5, true], - /*106*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options5, true], - /*107*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options5, false], - - /*108*/ [null, 1581945782, null, $options6, false], - /*109*/ [1581945782, 1581945782, null, $options6, true], // no license set - /*110*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options6, false], - /*111*/ [null, 1581945782, $ocLicenseValid, $options6, true], - /*112*/ [1581945782, 1581945782, $ocLicenseValid, $options6, true], - /*113*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options6, true], - /*114*/ [null, 1581945782, $ocLicenseInvalid, $options6, false], - /*115*/ [1581945782, 1581945782, $ocLicenseInvalid, $options6, true], - /*116*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options6, false], - /*117*/ [null, 1581945782, $ocLicenseExpired, $options6, false], - /*118*/ [1581945782, 1581945782, $ocLicenseExpired, $options6, true], - /*119*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options6, false], - /*120*/ [null, 1581945782, $ocLicenseInvalidExpired, $options6, false], - /*121*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options6, true], - /*122*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options6, false], - /*123*/ [null, 1581945782, $ocLicenseAboutExpire, $options6, true], - /*124*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options6, true], - /*125*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options6, false], - - /*126*/ [null, 1581945782, null, $options7, true], - /*127*/ [1581945782, 1581945782, null, $options7, true], // no license set - /*128*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options7, false], - /*129*/ [null, 1581945782, $ocLicenseValid, $options7, true], - /*130*/ [1581945782, 1581945782, $ocLicenseValid, $options7, true], - /*131*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options7, true], - /*132*/ [null, 1581945782, $ocLicenseInvalid, $options7, true], - /*133*/ [1581945782, 1581945782, $ocLicenseInvalid, $options7, true], - /*134*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options7, false], - /*135*/ [null, 1581945782, $ocLicenseExpired, $options7, true], - /*136*/ [1581945782, 1581945782, $ocLicenseExpired, $options7, true], - /*137*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options7, false], - /*138*/ [null, 1581945782, $ocLicenseInvalidExpired, $options7, true], - /*139*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options7, true], - /*140*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options7, false], - /*141*/ [null, 1581945782, $ocLicenseAboutExpire, $options7, true], - /*142*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options7, true], - /*143*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options7, false], - - /*144*/ [null, 1581945782, null, $options8, true], - /*145*/ [1581945782, 1581945782, null, $options8, true], // no license set - /*146*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), null, $options8, false], - /*147*/ [null, 1581945782, $ocLicenseValid, $options8, true], - /*148*/ [1581945782, 1581945782, $ocLicenseValid, $options8, true], - /*149*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options8, true], - /*150*/ [null, 1581945782, $ocLicenseInvalid, $options8, true], - /*151*/ [1581945782, 1581945782, $ocLicenseInvalid, $options8, true], - /*152*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options8, false], - /*153*/ [null, 1581945782, $ocLicenseExpired, $options8, true], - /*154*/ [1581945782, 1581945782, $ocLicenseExpired, $options8, true], - /*155*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options8, false], - /*156*/ [null, 1581945782, $ocLicenseInvalidExpired, $options8, true], - /*157*/ [1581945782, 1581945782, $ocLicenseInvalidExpired, $options8, true], - /*158*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options8, false], - /*159*/ [null, 1581945782, $ocLicenseAboutExpire, $options8, true], - /*160*/ [1581945782, 1581945782, $ocLicenseAboutExpire, $options8, true], - /*161*/ [1581945782, 1581945782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options8, false], + /*0*/ [null, 1_581_945_782, null, $options0, true], + /*1*/ [1_581_945_782, 1_581_945_782, null, $options0, true], // no license set + /*2*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options0, false], + /*3*/ [null, 1_581_945_782, $ocLicenseValid, $options0, true], + /*4*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options0, true], + /*5*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options0, true], + /*6*/ [null, 1_581_945_782, $ocLicenseInvalid, $options0, true], + /*7*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options0, true], + /*8*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options0, false], + /*9*/ [null, 1_581_945_782, $ocLicenseExpired, $options0, true], + /*10*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options0, true], + /*11*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options0, false], + /*12*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options0, true], + /*13*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options0, true], + /*14*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options0, false], + /*15*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options0, true], + /*16*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options0, true], + /*17*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options0, false], + + /*18*/ [null, 1_581_945_782, null, $options1, false], + /*19*/ [1_581_945_782, 1_581_945_782, null, $options1, true], // no license set + /*20*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options1, false], + /*21*/ [null, 1_581_945_782, $ocLicenseValid, $options1, true], + /*22*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options1, true], + /*23*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options1, true], + /*24*/ [null, 1_581_945_782, $ocLicenseInvalid, $options1, false], + /*25*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options1, true], + /*26*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options1, false], + /*27*/ [null, 1_581_945_782, $ocLicenseExpired, $options1, false], + /*28*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options1, true], + /*29*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options1, false], + /*30*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options1, false], + /*31*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options1, true], + /*32*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options1, false], + /*33*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options1, true], + /*34*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options1, true], + /*35*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options1, false], + + /*36*/ [null, 1_581_945_782, null, $options2, true], + /*37*/ [1_581_945_782, 1_581_945_782, null, $options2, true], // no license set + /*38*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options2, false], + /*39*/ [null, 1_581_945_782, $ocLicenseValid, $options2, true], + /*40*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options2, true], + /*41*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options2, true], + /*42*/ [null, 1_581_945_782, $ocLicenseInvalid, $options2, true], + /*43*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options2, true], + /*44*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options2, false], + /*45*/ [null, 1_581_945_782, $ocLicenseExpired, $options2, true], + /*46*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options2, true], + /*47*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options2, false], + /*48*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options2, true], + /*49*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options2, true], + /*50*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options2, false], + /*51*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options2, true], + /*52*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options2, true], + /*53*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options2, false], + + /*54*/ [null, 1_581_945_782, null, $options3, true], + /*55*/ [1_581_945_782, 1_581_945_782, null, $options3, true], // no license set + /*56*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options3, false], + /*57*/ [null, 1_581_945_782, $ocLicenseValid, $options3, true], + /*58*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options3, true], + /*59*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options3, true], + /*60*/ [null, 1_581_945_782, $ocLicenseInvalid, $options3, true], + /*61*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options3, true], + /*62*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options3, false], + /*63*/ [null, 1_581_945_782, $ocLicenseExpired, $options3, true], + /*64*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options3, true], + /*65*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options3, false], + /*66*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options3, true], + /*67*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options3, true], + /*68*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options3, false], + /*69*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options3, true], + /*70*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options3, true], + /*71*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options3, false], + + /*72*/ [null, 1_581_945_782, null, $options4, true], + /*73*/ [1_581_945_782, 1_581_945_782, null, $options4, true], // no license set + /*74*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options4, false], + /*75*/ [null, 1_581_945_782, $ocLicenseValid, $options4, true], + /*76*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options4, true], + /*77*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options4, true], + /*78*/ [null, 1_581_945_782, $ocLicenseInvalid, $options4, true], + /*79*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options4, true], + /*80*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options4, false], + /*81*/ [null, 1_581_945_782, $ocLicenseExpired, $options4, true], + /*82*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options4, true], + /*83*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options4, false], + /*84*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options4, true], + /*85*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options4, true], + /*86*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options4, false], + /*87*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options4, true], + /*88*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options4, true], + /*89*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options4, false], + + /*90*/ [null, 1_581_945_782, null, $options5, false], + /*91*/ [1_581_945_782, 1_581_945_782, null, $options5, true], // no license set + /*92*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options5, false], + /*93*/ [null, 1_581_945_782, $ocLicenseValid, $options5, true], + /*94*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options5, true], + /*95*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options5, true], + /*96*/ [null, 1_581_945_782, $ocLicenseInvalid, $options5, false], + /*97*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options5, true], + /*98*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options5, false], + /*99*/ [null, 1_581_945_782, $ocLicenseExpired, $options5, false], + /*100*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options5, true], + /*101*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options5, false], + /*102*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options5, false], + /*103*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options5, true], + /*104*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options5, false], + /*105*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options5, true], + /*106*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options5, true], + /*107*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options5, false], + + /*108*/ [null, 1_581_945_782, null, $options6, false], + /*109*/ [1_581_945_782, 1_581_945_782, null, $options6, true], // no license set + /*110*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options6, false], + /*111*/ [null, 1_581_945_782, $ocLicenseValid, $options6, true], + /*112*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options6, true], + /*113*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options6, true], + /*114*/ [null, 1_581_945_782, $ocLicenseInvalid, $options6, false], + /*115*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options6, true], + /*116*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options6, false], + /*117*/ [null, 1_581_945_782, $ocLicenseExpired, $options6, false], + /*118*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options6, true], + /*119*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options6, false], + /*120*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options6, false], + /*121*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options6, true], + /*122*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options6, false], + /*123*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options6, true], + /*124*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options6, true], + /*125*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options6, false], + + /*126*/ [null, 1_581_945_782, null, $options7, true], + /*127*/ [1_581_945_782, 1_581_945_782, null, $options7, true], // no license set + /*128*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options7, false], + /*129*/ [null, 1_581_945_782, $ocLicenseValid, $options7, true], + /*130*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options7, true], + /*131*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options7, true], + /*132*/ [null, 1_581_945_782, $ocLicenseInvalid, $options7, true], + /*133*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options7, true], + /*134*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options7, false], + /*135*/ [null, 1_581_945_782, $ocLicenseExpired, $options7, true], + /*136*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options7, true], + /*137*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options7, false], + /*138*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options7, true], + /*139*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options7, true], + /*140*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options7, false], + /*141*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options7, true], + /*142*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options7, true], + /*143*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options7, false], + + /*144*/ [null, 1_581_945_782, null, $options8, true], + /*145*/ [1_581_945_782, 1_581_945_782, null, $options8, true], // no license set + /*146*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), null, $options8, false], + /*147*/ [null, 1_581_945_782, $ocLicenseValid, $options8, true], + /*148*/ [1_581_945_782, 1_581_945_782, $ocLicenseValid, $options8, true], + /*149*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseValid, $options8, true], + /*150*/ [null, 1_581_945_782, $ocLicenseInvalid, $options8, true], + /*151*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalid, $options8, true], + /*152*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalid, $options8, false], + /*153*/ [null, 1_581_945_782, $ocLicenseExpired, $options8, true], + /*154*/ [1_581_945_782, 1_581_945_782, $ocLicenseExpired, $options8, true], + /*155*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseExpired, $options8, false], + /*156*/ [null, 1_581_945_782, $ocLicenseInvalidExpired, $options8, true], + /*157*/ [1_581_945_782, 1_581_945_782, $ocLicenseInvalidExpired, $options8, true], + /*158*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseInvalidExpired, $options8, false], + /*159*/ [null, 1_581_945_782, $ocLicenseAboutExpire, $options8, true], + /*160*/ [1_581_945_782, 1_581_945_782, $ocLicenseAboutExpire, $options8, true], + /*161*/ [1_581_945_782, 1_581_945_782 + (LicenseManager::GRACE_PERIOD * 2), $ocLicenseAboutExpire, $options8, false], ]; } @@ -611,7 +610,7 @@ public function checkLicenseForInvalidProvider() { * @dataProvider checkLicenseForInvalidProvider */ public function testCheckLicenseForWithoutGracePeriodStartedInvalidLicense($ocLicense) { - $this->timeFactory->method('getTime')->willReturn(100300500); + $this->timeFactory->method('getTime')->willReturn(100_300_500); $this->config->method('getAppValue') ->will($this->returnValueMap([ @@ -632,7 +631,7 @@ public function testCheckLicenseForWithoutGracePeriodStartedInvalidLicense($ocLi $this->config->expects($this->exactly(2)) ->method('setAppValue') ->withConsecutive( - ['core', 'grace_period', 100300500], + ['core', 'grace_period', 100_300_500], ['core-license-complains', 'dummyApp', $expectedString] ); @@ -643,11 +642,11 @@ public function testCheckLicenseForWithoutGracePeriodStartedInvalidLicense($ocLi * @dataProvider checkLicenseForInvalidProvider */ public function testCheckLicenseForWithGracePeriodExpiredInvalidLicense($ocLicense) { - $this->timeFactory->method('getTime')->willReturn(100300500); + $this->timeFactory->method('getTime')->willReturn(100_300_500); $this->config->method('getAppValue') ->will($this->returnValueMap([ - ['core', 'grace_period', null, -100300500], + ['core', 'grace_period', null, -100_300_500], ])); $this->licenseFetcher->method('getOwncloudLicense')->willReturn($ocLicense); diff --git a/tests/lib/License/MessageServiceTest.php b/tests/lib/License/MessageServiceTest.php index bc1550613560..ff3e094f9e58 100644 --- a/tests/lib/License/MessageServiceTest.php +++ b/tests/lib/License/MessageServiceTest.php @@ -29,9 +29,8 @@ class MessageServiceTest extends TestCase { /** @var IFactory */ - private $l10Factory; - /** @var MessageService */ - private $messageService; + private \PHPUnit\Framework\MockObject\MockObject $l10Factory; + private \OC\License\MessageService $messageService; protected function setUp(): void { parent::setUp(); @@ -217,10 +216,9 @@ public function getMessageForLicenseProvider() { public function testGetMessageForLicense($licenseInfo, $expectedResult) { $l10n = $this->createMock(IL10n::class); $l10n->method('t') - ->will($this->returnCallback(function ($text, $params) { - // change the text to camel case so the translated text is more predictable - return \vsprintf(\ucwords($text), $params); - })); + ->will($this->returnCallback(fn ($text, $params) => + // change the text to camel case so the translated text is more predictable + \vsprintf(\ucwords($text), $params))); $this->l10Factory->method('get') ->willReturn($l10n); diff --git a/tests/lib/Lock/DBLockingProviderTest.php b/tests/lib/Lock/DBLockingProviderTest.php index d05b91f74e56..312caf78ba93 100644 --- a/tests/lib/Lock/DBLockingProviderTest.php +++ b/tests/lib/Lock/DBLockingProviderTest.php @@ -49,18 +49,16 @@ class DBLockingProviderTest extends LockingProvider { /** * @var \OCP\AppFramework\Utility\ITimeFactory */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; private $currentTime; public function setUp(): void { $this->currentTime = \time(); - $this->timeFactory = $this->createMock('\OCP\AppFramework\Utility\ITimeFactory'); + $this->timeFactory = $this->createMock('\\' . \OCP\AppFramework\Utility\ITimeFactory::class); $this->timeFactory->expects($this->any()) ->method('getTime') - ->will($this->returnCallback(function () { - return $this->currentTime; - })); + ->will($this->returnCallback(fn () => $this->currentTime)); parent::setUp(); # we shall operate on a clean table $this->connection->executeQuery('DELETE FROM `*PREFIX*file_locks`'); @@ -125,6 +123,6 @@ private function getLockEntries() { protected function assertLocks(array $expected) { $locks = $this->getLockEntries(); - $this->assertCount(\count($expected), $locks, \json_encode($locks)); + $this->assertCount(\count($expected), $locks, \json_encode($locks, JSON_THROW_ON_ERROR)); } } diff --git a/tests/lib/Lock/MemcacheLockingProviderTest.php b/tests/lib/Lock/MemcacheLockingProviderTest.php index fd5861a2f7f0..758755c50952 100644 --- a/tests/lib/Lock/MemcacheLockingProviderTest.php +++ b/tests/lib/Lock/MemcacheLockingProviderTest.php @@ -24,10 +24,7 @@ use OC\Memcache\ArrayCache; class MemcacheLockingProviderTest extends LockingProvider { - /** - * @var \OCP\IMemcache - */ - private $memcache; + private ?\OC\Memcache\ArrayCache $memcache = null; /** * @return \OCP\Lock\ILockingProvider diff --git a/tests/lib/Lock/Persistent/LockManagerTest.php b/tests/lib/Lock/Persistent/LockManagerTest.php index 91f5efd9807e..f99a258ab8b6 100644 --- a/tests/lib/Lock/Persistent/LockManagerTest.php +++ b/tests/lib/Lock/Persistent/LockManagerTest.php @@ -39,17 +39,16 @@ */ class LockManagerTest extends TestCase { /** @var LockMapper | \PHPUnit\Framework\MockObject\MockObject */ - private $lockMapper; + private \PHPUnit\Framework\MockObject\MockObject $lockMapper; /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; - /** @var LockManager */ - private $manager; + private \PHPUnit\Framework\MockObject\MockObject $userSession; + private \OC\Lock\Persistent\LockManager $manager; /** @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IUser | \PHPUnit\Framework\MockObject\MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Lock/Persistent/LockMapperTest.php b/tests/lib/Lock/Persistent/LockMapperTest.php index 7b4a09461a29..c6b2e911e02d 100644 --- a/tests/lib/Lock/Persistent/LockMapperTest.php +++ b/tests/lib/Lock/Persistent/LockMapperTest.php @@ -39,32 +39,24 @@ class LockMapperTest extends TestCase { /** @var IDBConnection */ private $db; - /** @var Account */ - private $account; + private \OC\User\Account $account; /** @var int */ private $fileCacheId; /** @var int */ private $fileCacheChildId; /** @var int */ private $fileCacheParentId; - /** @var int */ - private $storageId; - /** @var int */ - private $unrelatedStorageId; - /** @var LockMapper */ - private $mapper; + private int $storageId; + private int $unrelatedStorageId; + private \OC\Lock\Persistent\LockMapper $mapper; /** @var Lock[] */ - private $locks = []; - /** @var string */ - private $parentPath; - /** @var string */ - private $path; - /** @var string */ - private $childPath; - /** @var string */ - private $unrelatedPath; + private array $locks = []; + private string $parentPath; + private string $path; + private string $childPath; + private string $unrelatedPath; /** @var ITimeFactory */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; public function setUp(): void { parent::setUp(); @@ -161,19 +153,19 @@ public function testGetLocksByPathDepth0() { $l = $this->mapper->getLocksByPath($this->storageId, $this->path, false); $this->assertCount(1, $l); - $this->assertLock($lock, $l[0], 'query on locked path returns lock from locked path itself'); + $this->assertLock($lock, $l[0]); $l = $this->mapper->getLocksByPath($this->storageId, $this->parentPath, false); $this->assertCount(0, $l, 'query on parent path returns no lock'); $l = $this->mapper->getLocksByPath($this->storageId, $this->path, true); $this->assertCount(1, $l); - $this->assertLock($lock, $l[0], 'query on locked path including children returns lock from locked path itself'); + $this->assertLock($lock, $l[0]); // parent is able to retrieve for children when asking for children $l = $this->mapper->getLocksByPath($this->storageId, $this->parentPath, true); $this->assertCount(1, $l); - $this->assertLock($lock, $l[0], 'query on parent path and including children returns lock from locked path'); + $this->assertLock($lock, $l[0]); // unrelated storage with same paths $l = $this->mapper->getLocksByPath($this->unrelatedStorageId, $this->path, false); @@ -204,19 +196,19 @@ public function testGetLocksByPathDepthInfinity() { $l = $this->mapper->getLocksByPath($this->storageId, $this->path, false); $this->assertCount(1, $l); - $this->assertLock($lock, $l[0], 'query on child path returns lock from parent due to infinite depth'); + $this->assertLock($lock, $l[0]); $l = $this->mapper->getLocksByPath($this->storageId, $this->parentPath, false); $this->assertCount(1, $l); - $this->assertLock($lock, $l[0], 'query on parent path returns lock from parent path itself'); + $this->assertLock($lock, $l[0]); $l = $this->mapper->getLocksByPath($this->storageId, $this->path, true); $this->assertCount(1, $l); - $this->assertLock($lock, $l[0], 'query on child path including children returns lock from parent path due to infinite depth'); + $this->assertLock($lock, $l[0]); $l = $this->mapper->getLocksByPath($this->storageId, $this->parentPath, true); $this->assertCount(1, $l); - $this->assertLock($lock, $l[0], 'query on parent path including children returns lock from parent path itself'); + $this->assertLock($lock, $l[0]); // unrelated storage with same paths $l = $this->mapper->getLocksByPath($this->unrelatedStorageId, $this->path, false); @@ -248,19 +240,19 @@ public function testGetLocksByPathWithoutChildren() { $l = $this->mapper->getLocksByPath($this->storageId, $this->path, false); $this->sortLocks($l); $this->assertCount(2, $l); - $this->assertLock($parentLock, $l[0], 'parent lock returned due to infinite depth'); - $this->assertLock($lock, $l[1], 'path lock returned due to it being direct target'); + $this->assertLock($parentLock, $l[0]); + $this->assertLock($lock, $l[1]); $l = $this->mapper->getLocksByPath($this->storageId, $this->parentPath, false); $this->assertCount(1, $l); - $this->assertLock($parentLock, $l[0], 'parent lock returned due to it being direct target'); + $this->assertLock($parentLock, $l[0]); $l = $this->mapper->getLocksByPath($this->storageId, $this->childPath, false); $this->sortLocks($l); $this->assertCount(2, $l); - $this->assertLock($parentLock, $l[0], 'parent lock returned due to infinite depth'); + $this->assertLock($parentLock, $l[0]); // $lock not included because it has Depth 0 - $this->assertLock($childLock, $l[1], 'child lock returned'); + $this->assertLock($childLock, $l[1]); } /** @@ -278,23 +270,23 @@ public function testGetLocksByPathMultipleWithChildren() { $l = $this->mapper->getLocksByPath($this->storageId, $this->path, true); $this->sortLocks($l); $this->assertCount(3, $l); - $this->assertLock($parentLock, $l[0], 'parent lock returned due to infinite depth'); - $this->assertLock($lock, $l[1], 'path lock returned due to it being direct target'); - $this->assertLock($childLock, $l[2], 'child lock returned'); + $this->assertLock($parentLock, $l[0]); + $this->assertLock($lock, $l[1]); + $this->assertLock($childLock, $l[2]); $l = $this->mapper->getLocksByPath($this->storageId, $this->parentPath, true); $this->sortLocks($l); $this->assertCount(3, $l); - $this->assertLock($parentLock, $l[0], 'parent lock returned due to it being direct target'); - $this->assertLock($lock, $l[1], 'path lock returned due to it being a child'); - $this->assertLock($childLock, $l[2], 'child lock returned'); + $this->assertLock($parentLock, $l[0]); + $this->assertLock($lock, $l[1]); + $this->assertLock($childLock, $l[2]); $l = $this->mapper->getLocksByPath($this->storageId, $this->childPath, true); $this->sortLocks($l); $this->assertCount(2, $l); - $this->assertLock($parentLock, $l[0], 'parent lock returned due to infinite depth'); + $this->assertLock($parentLock, $l[0]); // $lock not included because it has Depth 0 - $this->assertLock($childLock, $l[1], 'child lock returned'); + $this->assertLock($childLock, $l[1]); } /** @@ -429,8 +421,6 @@ private function insertLock($fileId, $scope, $depth = 0) { * Sorts an array of locks by file id for easier matching */ private function sortLocks(&$l) { - \usort($l, function ($a, $b) { - return $a->getId() - $b->getId(); - }); + \usort($l, fn ($a, $b) => $a->getId() - $b->getId()); } } diff --git a/tests/lib/Log/OwncloudTest.php b/tests/lib/Log/OwncloudTest.php index e3486c0bb960..3d62565212a2 100644 --- a/tests/lib/Log/OwncloudTest.php +++ b/tests/lib/Log/OwncloudTest.php @@ -69,7 +69,7 @@ public function testMicrosecondsLogTimestamp() { \fclose($handle); # check timestamp has microseconds part - $values = (array) \json_decode($line); + $values = (array) \json_decode($line, null, 512, JSON_THROW_ON_ERROR); $microseconds = $values['time']; $this->assertMatchesRegularExpression('/^\d{6}$/', $microseconds); } diff --git a/tests/lib/LoggerTest.php b/tests/lib/LoggerTest.php index 0f5c2ed0024a..f08ef4da1d74 100644 --- a/tests/lib/LoggerTest.php +++ b/tests/lib/LoggerTest.php @@ -26,14 +26,14 @@ class LoggerTest extends TestCase { /** @var ILogger */ - private $logger; + private \OC\Log $logger; private static $logs = []; /** @var IConfig | MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var EventDispatcherInterface | MockObject */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; public function providesCreateSessionToken(): array { return [ @@ -51,7 +51,7 @@ protected function setUp(): void { ->disableOriginalConstructor() ->getMock(); $this->eventDispatcher = new EventDispatcher(); - $this->logger = new Log(__CLASS__, $this->config, null, $this->eventDispatcher); + $this->logger = new Log(self::class, $this->config, null, $this->eventDispatcher); } public function testInterpolation(): void { @@ -130,7 +130,7 @@ public static function write($app, $message, $level): void { } public static function writeExtra($app, $message, $level, $logConditionFile, $extraFields): void { - $encodedFields = \json_encode($extraFields); + $encodedFields = \json_encode($extraFields, JSON_THROW_ON_ERROR); self::$logs[]= "$level $message fields=$encodedFields"; } diff --git a/tests/lib/LoggerWithoutWriteExtraTest.php b/tests/lib/LoggerWithoutWriteExtraTest.php index 5ea451a49266..f4ed1575e605 100644 --- a/tests/lib/LoggerWithoutWriteExtraTest.php +++ b/tests/lib/LoggerWithoutWriteExtraTest.php @@ -14,23 +14,23 @@ class LoggerWithoutWriteExtraTest extends TestCase { /** @var \OCP\ILogger */ - private $logger; + private \OC\Log $logger; private static $logs = []; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; protected function setUp(): void { parent::setUp(); self::$logs = []; $this->config = $this->getMockBuilder( - '\OC\SystemConfig' + '\\' . \OC\SystemConfig::class ) ->disableOriginalConstructor() ->getMock(); $this->logger = new Log( - 'Test\LoggerWithoutWriteExtraTest', + \Test\LoggerWithoutWriteExtraTest::class, $this->config, null, new EventDispatcher() diff --git a/tests/lib/Mail/MailerTest.php b/tests/lib/Mail/MailerTest.php index fc02360b0a6b..112cbcdba4ed 100644 --- a/tests/lib/Mail/MailerTest.php +++ b/tests/lib/Mail/MailerTest.php @@ -17,11 +17,11 @@ class MailerTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var OC_Defaults */ - private $defaults; + private \PHPUnit\Framework\MockObject\MockObject $defaults; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var Mailer */ private $mailer; diff --git a/tests/lib/Mail/MessageTest.php b/tests/lib/Mail/MessageTest.php index 8fd493883ac5..913d465b3432 100644 --- a/tests/lib/Mail/MessageTest.php +++ b/tests/lib/Mail/MessageTest.php @@ -14,9 +14,8 @@ class MessageTest extends TestCase { /** @var Swift_Message */ - private $swiftMessage; - /** @var Message */ - private $message; + private \PHPUnit\Framework\MockObject\MockObject $swiftMessage; + private \OC\Mail\Message $message; /** * @return array diff --git a/tests/lib/Memcache/CasTraitTest.php b/tests/lib/Memcache/CasTraitTest.php index 943daf88e603..603534e1d7bc 100644 --- a/tests/lib/Memcache/CasTraitTest.php +++ b/tests/lib/Memcache/CasTraitTest.php @@ -29,31 +29,23 @@ class CasTraitTest extends TestCase { */ private function getCache() { $sourceCache = new \OC\Memcache\ArrayCache(); - $mock = $this->getMockForTrait('\OC\Memcache\CasTrait'); + $mock = $this->getMockForTrait('\\' . \OC\Memcache\CasTrait::class); $mock->expects($this->any()) ->method('set') - ->will($this->returnCallback(function ($key, $value, $ttl) use ($sourceCache) { - return $sourceCache->set($key, $value, $ttl); - })); + ->will($this->returnCallback(fn ($key, $value, $ttl) => $sourceCache->set($key, $value, $ttl))); $mock->expects($this->any()) ->method('get') - ->will($this->returnCallback(function ($key) use ($sourceCache) { - return $sourceCache->get($key); - })); + ->will($this->returnCallback(fn ($key) => $sourceCache->get($key))); $mock->expects($this->any()) ->method('add') - ->will($this->returnCallback(function ($key, $value, $ttl) use ($sourceCache) { - return $sourceCache->add($key, $value, $ttl); - })); + ->will($this->returnCallback(fn ($key, $value, $ttl) => $sourceCache->add($key, $value, $ttl))); $mock->expects($this->any()) ->method('remove') - ->will($this->returnCallback(function ($key) use ($sourceCache) { - return $sourceCache->remove($key); - })); + ->will($this->returnCallback(fn ($key) => $sourceCache->remove($key))); return $mock; } diff --git a/tests/lib/Memcache/FactoryTest.php b/tests/lib/Memcache/FactoryTest.php index 31b232a69d2c..1b59f84c0d26 100644 --- a/tests/lib/Memcache/FactoryTest.php +++ b/tests/lib/Memcache/FactoryTest.php @@ -120,7 +120,7 @@ public function testCacheAvailability( $expectedDistributedCache, $expectedLockingCache ) { - $logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); + $logger = $this->getMockBuilder('\\' . \OCP\ILogger::class)->getMock(); $factory = new \OC\Memcache\Factory('abc', $logger, $localCache, $distributedCache, $lockingCache); $this->assertTrue(\is_a($factory->createLocal(), $expectedLocalCache)); $this->assertTrue(\is_a($factory->createDistributed(), $expectedDistributedCache)); @@ -133,7 +133,7 @@ public function testCacheAvailability( public function testCacheNotAvailableException($localCache, $distributedCache) { $this->expectException(\OC\HintException::class); - $logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); + $logger = $this->getMockBuilder('\\' . \OCP\ILogger::class)->getMock(); new \OC\Memcache\Factory('abc', $logger, $localCache, $distributedCache); } } diff --git a/tests/lib/Migration/BackgroundRepairTest.php b/tests/lib/Migration/BackgroundRepairTest.php index 2a1a0d55b55b..fb5978e5fdbf 100644 --- a/tests/lib/Migration/BackgroundRepairTest.php +++ b/tests/lib/Migration/BackgroundRepairTest.php @@ -55,24 +55,24 @@ public function run(IOutput $output) { class BackgroundRepairTest extends TestCase { /** @var \OC\BackgroundJob\JobList | \PHPUnit\Framework\MockObject\MockObject */ - private $jobList; + private \PHPUnit\Framework\MockObject\MockObject $jobList; /** @var BackgroundRepair | \PHPUnit\Framework\MockObject\MockObject */ - private $job; + private \PHPUnit\Framework\MockObject\MockObject $job; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; public function setUp(): void { parent::setUp(); - $this->jobList = $this->getMockBuilder('OC\BackgroundJob\JobList') + $this->jobList = $this->getMockBuilder(\OC\BackgroundJob\JobList::class) ->disableOriginalConstructor() ->getMock(); - $this->logger = $this->getMockBuilder('OCP\ILogger') + $this->logger = $this->getMockBuilder(\OCP\ILogger::class) ->disableOriginalConstructor() ->getMock(); - $this->job = $this->getMockBuilder('OC\Migration\BackgroundRepair') + $this->job = $this->getMockBuilder(\OC\Migration\BackgroundRepair::class) ->setMethods(['loadApp']) ->getMock(); } @@ -104,7 +104,7 @@ public function testUnknownStep() { public function testWorkingStep() { /** @var EventDispatcher | \PHPUnit\Framework\MockObject\MockObject $dispatcher */ - $dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcher'); + $dispatcher = $this->createMock(\Symfony\Component\EventDispatcher\EventDispatcher::class); $dispatcher->expects($this->once())->method('dispatch') ->with(new GenericEvent('\OC\Repair::step', ['A test repair step']), '\OC\Repair::step'); @@ -112,7 +112,7 @@ public function testWorkingStep() { $this->job->setDispatcher($dispatcher); $this->job->setArgument([ 'app' => 'test', - 'step' => '\Test\Migration\TestRepairStep' + 'step' => '\\' . \Test\Migration\TestRepairStep::class ]); $this->job->execute($this->jobList, $this->logger); } diff --git a/tests/lib/NavigationManagerTest.php b/tests/lib/NavigationManagerTest.php index 607a626f3115..10c5bdfd2684 100644 --- a/tests/lib/NavigationManagerTest.php +++ b/tests/lib/NavigationManagerTest.php @@ -177,16 +177,12 @@ public function testWithAppManager($expected, $config, $isAdmin = false): void { $groupManager = $this->createMock(IGroupManager::class); $systemConfig = $this->createMock(IConfig::class); $l = $this->createMock(IL10N::class); - $l->method('t')->willReturnCallback(static function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - }); + $l->method('t')->willReturnCallback(static fn ($text, $parameters = []) => \vsprintf($text, $parameters)); $appManager->expects($this->once())->method('getInstalledApps')->willReturn(['test']); $appManager->expects($this->once())->method('getAppInfo')->with('test')->willReturn($config); $l10nFac->expects($this->exactly(\count($expected)))->method('get')->with('test')->willReturn($l); - $urlGenerator->method('imagePath')->willReturnCallback(static function ($appName, $file) { - return "/apps/$appName/img/$file"; - }); + $urlGenerator->method('imagePath')->willReturnCallback(static fn ($appName, $file) => "/apps/$appName/img/$file"); if (isset($config['navigation']['static'])) { $urlGenerator->expects($this->never())->method('linkToRoute')->willReturn('/apps/test/'); $urlGenerator->expects($this->once())->method('linkTo')->willReturn('link-to-static'); diff --git a/tests/lib/Notification/ManagerTest.php b/tests/lib/Notification/ManagerTest.php index 7b3adfae643a..013c0d53fedc 100644 --- a/tests/lib/Notification/ManagerTest.php +++ b/tests/lib/Notification/ManagerTest.php @@ -71,9 +71,7 @@ public function testRegisterApp() { ->disableOriginalConstructor() ->getMock(); - $closure = function () use ($app) { - return $app; - }; + $closure = fn () => $app; $this->assertEquals([], self::invokePrivate($this->manager, 'getApps')); @@ -96,9 +94,7 @@ public function testRegisterAppInvalid() { ->disableOriginalConstructor() ->getMock(); - $closure = function () use ($notifier) { - return $notifier; - }; + $closure = fn () => $notifier; $this->manager->registerApp($closure); @@ -136,25 +132,19 @@ public function testRegisterNotifier() { ->disableOriginalConstructor() ->getMock(); - $closure = function () use ($notifier) { - return $notifier; - }; + $closure = fn () => $notifier; $this->assertEquals([], self::invokePrivate($this->manager, 'getNotifiers')); $this->assertEquals([], self::invokePrivate($this->manager, 'listNotifiers')); - $this->manager->registerNotifier($closure, function () { - return ['id' => 'test1', 'name' => 'Test One']; - }); + $this->manager->registerNotifier($closure, fn () => ['id' => 'test1', 'name' => 'Test One']); $this->assertEquals([$notifier], self::invokePrivate($this->manager, 'getNotifiers')); $this->assertEquals(['test1' => 'Test One'], self::invokePrivate($this->manager, 'listNotifiers')); $this->assertEquals([$notifier], self::invokePrivate($this->manager, 'getNotifiers')); $this->assertEquals(['test1' => 'Test One'], self::invokePrivate($this->manager, 'listNotifiers')); - $this->manager->registerNotifier($closure, function () { - return ['id' => 'test2', 'name' => 'Test Two']; - }); + $this->manager->registerNotifier($closure, fn () => ['id' => 'test2', 'name' => 'Test Two']); $this->assertEquals([$notifier, $notifier], self::invokePrivate($this->manager, 'getNotifiers')); $this->assertEquals(['test1' => 'Test One', 'test2' => 'Test Two'], self::invokePrivate($this->manager, 'listNotifiers')); @@ -169,13 +159,9 @@ public function testRegisterNotifierInvalid() { ->disableOriginalConstructor() ->getMock(); - $closure = function () use ($app) { - return $app; - }; + $closure = fn () => $app; - $this->manager->registerNotifier($closure, function () { - return ['id' => 'test1', 'name' => 'Test One']; - }); + $this->manager->registerNotifier($closure, fn () => ['id' => 'test1', 'name' => 'Test One']); self::invokePrivate($this->manager, 'getNotifiers'); } @@ -201,13 +187,9 @@ public function testRegisterNotifierInfoInvalid($data) { ->disableOriginalConstructor() ->getMock(); - $closure = function () use ($app) { - return $app; - }; + $closure = fn () => $app; - $this->manager->registerNotifier($closure, function () use ($data) { - return $data; - }); + $this->manager->registerNotifier($closure, fn () => $data); $this->manager->listNotifiers(); } @@ -222,17 +204,11 @@ public function testRegisterNotifierInfoDuplicate() { ->disableOriginalConstructor() ->getMock(); - $closure = function () use ($app) { - return $app; - }; + $closure = fn () => $app; - $this->manager->registerNotifier($closure, function () { - return ['id' => 'test1', 'name' => 'Test One']; - }); + $this->manager->registerNotifier($closure, fn () => ['id' => 'test1', 'name' => 'Test One']); - $this->manager->registerNotifier($closure, function () { - return ['id' => 'test1', 'name' => 'Test One']; - }); + $this->manager->registerNotifier($closure, fn () => ['id' => 'test1', 'name' => 'Test One']); $this->manager->listNotifiers(); } @@ -365,9 +341,7 @@ public function testRegisterNotifierNewDuplicatedIdCompatibleWithOld() { ->disableOriginalConstructor() ->getMock(); - $closure = function () use ($notifier) { - return $notifier; - }; + $closure = fn () => $notifier; $callbackCalledCount = 0; @@ -379,9 +353,7 @@ function (RegisterNotifierEvent $event) use ($notifier, &$callbackCalledCount) { } ); - $this->manager->registerNotifier($closure, function () { - return ['id' => 'testid1', 'name' => 'test app name']; - }); + $this->manager->registerNotifier($closure, fn () => ['id' => 'testid1', 'name' => 'test app name']); $notifiers = self::invokePrivate($this->manager, 'getNotifiers'); $this->assertEquals(1, $callbackCalledCount); @@ -458,12 +430,8 @@ public function testNotify() { ->method('notify') ->with($notification); - $this->manager->registerApp(function () use ($app) { - return $app; - }); - $this->manager->registerApp(function () use ($app2) { - return $app2; - }); + $this->manager->registerApp(fn () => $app); + $this->manager->registerApp(fn () => $app2); $this->manager->notify($notification); } @@ -518,16 +486,8 @@ public function testPrepare() { ->with($notification, 'en') ->willReturn($notification2); - $this->manager->registerNotifier(function () use ($notifier) { - return $notifier; - }, function () { - return ['id' => 'test1', 'name' => 'Test One']; - }); - $this->manager->registerNotifier(function () use ($notifier2) { - return $notifier2; - }, function () { - return ['id' => 'test2', 'name' => 'Test Two']; - }); + $this->manager->registerNotifier(fn () => $notifier, fn () => ['id' => 'test1', 'name' => 'Test One']); + $this->manager->registerNotifier(fn () => $notifier2, fn () => ['id' => 'test2', 'name' => 'Test Two']); $this->assertEquals($notification2, $this->manager->prepare($notification, 'en')); } @@ -554,11 +514,7 @@ public function testPrepareInvalid() { ->with($notification, 'de') ->willReturnArgument(0); - $this->manager->registerNotifier(function () use ($notifier) { - return $notifier; - }, function () { - return ['id' => 'test1', 'name' => 'Test One']; - }); + $this->manager->registerNotifier(fn () => $notifier, fn () => ['id' => 'test1', 'name' => 'Test One']); $this->manager->prepare($notification, 'de'); } @@ -581,11 +537,7 @@ public function testPrepareNotifierThrows() { ->with($notification, 'de') ->willThrowException(new \InvalidArgumentException); - $this->manager->registerNotifier(function () use ($notifier) { - return $notifier; - }, function () { - return ['id' => 'test1', 'name' => 'Test One']; - }); + $this->manager->registerNotifier(fn () => $notifier, fn () => ['id' => 'test1', 'name' => 'Test One']); $this->assertEquals($notification, $this->manager->prepare($notification, 'de')); } @@ -628,12 +580,8 @@ public function testMarkProcessed() { ->method('markProcessed') ->with($notification); - $this->manager->registerApp(function () use ($app) { - return $app; - }); - $this->manager->registerApp(function () use ($app2) { - return $app2; - }); + $this->manager->registerApp(fn () => $app); + $this->manager->registerApp(fn () => $app2); $this->manager->markProcessed($notification); } @@ -662,12 +610,8 @@ public function testGetCount() { ->with($notification) ->willReturn(42); - $this->manager->registerApp(function () use ($app) { - return $app; - }); - $this->manager->registerApp(function () use ($app2) { - return $app2; - }); + $this->manager->registerApp(fn () => $app); + $this->manager->registerApp(fn () => $app2); $this->assertSame(63, $this->manager->getCount($notification)); } diff --git a/tests/lib/Notification/NotificationTest.php b/tests/lib/Notification/NotificationTest.php index 9f125279d57a..1ad557feeb12 100644 --- a/tests/lib/Notification/NotificationTest.php +++ b/tests/lib/Notification/NotificationTest.php @@ -397,12 +397,12 @@ public function testSetLinkInvalid($link) { public function testCreateAction() { $action = $this->notification->createAction(); - $this->assertInstanceOf('OCP\Notification\IAction', $action); + $this->assertInstanceOf(\OCP\Notification\IAction::class, $action); } public function testAddAction() { /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */ - $action = $this->getMockBuilder('OCP\Notification\IAction') + $action = $this->getMockBuilder(\OCP\Notification\IAction::class) ->disableOriginalConstructor() ->getMock(); $action->expects($this->once()) @@ -423,7 +423,7 @@ public function testAddActionInvalid() { $this->expectException(\InvalidArgumentException::class); /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */ - $action = $this->getMockBuilder('OCP\Notification\IAction') + $action = $this->getMockBuilder(\OCP\Notification\IAction::class) ->disableOriginalConstructor() ->getMock(); $action->expects($this->once()) @@ -437,7 +437,7 @@ public function testAddActionInvalid() { public function testAddActionSecondPrimary() { /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */ - $action = $this->getMockBuilder('OCP\Notification\IAction') + $action = $this->getMockBuilder(\OCP\Notification\IAction::class) ->disableOriginalConstructor() ->getMock(); $action->expects($this->exactly(2)) @@ -455,7 +455,7 @@ public function testAddActionSecondPrimary() { public function testAddParsedAction() { /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */ - $action = $this->getMockBuilder('OCP\Notification\IAction') + $action = $this->getMockBuilder(\OCP\Notification\IAction::class) ->disableOriginalConstructor() ->getMock(); $action->expects($this->once()) @@ -476,7 +476,7 @@ public function testAddParsedActionInvalid() { $this->expectException(\InvalidArgumentException::class); /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */ - $action = $this->getMockBuilder('OCP\Notification\IAction') + $action = $this->getMockBuilder(\OCP\Notification\IAction::class) ->disableOriginalConstructor() ->getMock(); $action->expects($this->once()) @@ -490,7 +490,7 @@ public function testAddParsedActionInvalid() { public function testAddActionSecondParsedPrimary() { /** @var \OCP\Notification\IAction|\PHPUnit\Framework\MockObject\MockObject $action */ - $action = $this->getMockBuilder('OCP\Notification\IAction') + $action = $this->getMockBuilder(\OCP\Notification\IAction::class) ->disableOriginalConstructor() ->getMock(); $action->expects($this->exactly(2)) @@ -524,7 +524,7 @@ public function dataIsValid() { */ public function testIsValid($isValidCommon, $subject, $expected) { /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ - $notification = $this->getMockBuilder('\OC\Notification\Notification') + $notification = $this->getMockBuilder('\\' . \OC\Notification\Notification::class) ->setMethods([ 'isValidCommon', 'getSubject', @@ -556,7 +556,7 @@ public function testIsValid($isValidCommon, $subject, $expected) { */ public function testIsParsedValid($isValidCommon, $subject, $expected) { /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ - $notification = $this->getMockBuilder('\OC\Notification\Notification') + $notification = $this->getMockBuilder('\\' . \OC\Notification\Notification::class) ->setMethods([ 'isValidCommon', 'getParsedSubject', @@ -602,7 +602,7 @@ public function dataIsValidCommon() { */ public function testIsValidCommon($app, $user, $timestamp, $objectType, $objectId, $expected) { /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ - $notification = $this->getMockBuilder('\OC\Notification\Notification') + $notification = $this->getMockBuilder('\\' . \OC\Notification\Notification::class) ->setMethods([ 'getApp', 'getUser', diff --git a/tests/lib/OCS/ProviderTest.php b/tests/lib/OCS/ProviderTest.php index b358bd29395c..b1998a280209 100644 --- a/tests/lib/OCS/ProviderTest.php +++ b/tests/lib/OCS/ProviderTest.php @@ -25,17 +25,16 @@ class ProviderTest extends \Test\TestCase { /** @var \OCP\IRequest */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var \OCP\App\IAppManager */ - private $appManager; - /** @var Provider */ - private $ocsProvider; + private \PHPUnit\Framework\MockObject\MockObject $appManager; + private \OC\OCS\Provider $ocsProvider; public function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder('\\OCP\\IRequest')->getMock(); - $this->appManager = $this->getMockBuilder('\\OCP\\App\\IAppManager')->getMock(); + $this->request = $this->getMockBuilder('\\' . \OCP\IRequest::class)->getMock(); + $this->appManager = $this->getMockBuilder('\\' . \OCP\App\IAppManager::class)->getMock(); $this->ocsProvider = new Provider('ocs_provider', $this->request, $this->appManager); } diff --git a/tests/lib/PreviewManagerTest.php b/tests/lib/PreviewManagerTest.php index 6b8f4d55a0bb..0362b393a8c5 100644 --- a/tests/lib/PreviewManagerTest.php +++ b/tests/lib/PreviewManagerTest.php @@ -50,12 +50,11 @@ class PreviewManagerTest extends TestCase { /** @var IUser */ private $user; - /** @var View */ - private $rootView; + private \OC\Files\View $rootView; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IPreview */ - private $previewManager; + private \OC\PreviewManager $previewManager; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/PreviewTest.php b/tests/lib/PreviewTest.php index 1365fcaf6a4d..d55e0641fc86 100644 --- a/tests/lib/PreviewTest.php +++ b/tests/lib/PreviewTest.php @@ -48,25 +48,24 @@ class PreviewTest extends TestCase { public const TEST_PREVIEW_USER1 = "test-preview-user1"; - /** @var View */ - private $rootView; + private \OC\Files\View $rootView; /** * Note that using 756 with an image with a ratio of 1.6 brings interesting rounding issues * * @var int maximum width allowed for a preview * */ - private $configMaxWidth = 756; + private int $configMaxWidth = 756; /** @var int maximum height allowed for a preview */ - private $configMaxHeight = 756; + private int $configMaxHeight = 756; private $keepAspect; private $scalingUp; - private $samples = []; + private array $samples = []; private $sampleFileId; private $sampleFilename; private $sampleWidth; private $sampleHeight; - private $maxScaleFactor; + private int $maxScaleFactor; /** @var int width of the max preview */ private $maxPreviewWidth; /** @var int height of the max preview */ @@ -103,21 +102,20 @@ protected function setUp(): void { // We need to enable the providers we're going to use in the tests $providers = [ - 'OC\\Preview\\JPEG', - 'OC\\Preview\\PNG', - 'OC\\Preview\\GIF', - 'OC\\Preview\\TXT', - 'OC\\Preview\\Postscript' + \OC\Preview\JPEG::class, + \OC\Preview\PNG::class, + \OC\Preview\GIF::class, + \OC\Preview\TXT::class, + \OC\Preview\Postscript::class ]; \OC::$server->getConfig() ->setSystemValue('enabledPreviewProviders', $providers); //re-initialize the preview manager due to config change above unset(\OC::$server['PreviewManager']); - \OC::$server->registerService('PreviewManager', function ($c) { - /** @var Server $c */ - return new PreviewManager($c->getConfig(), $c->getLazyRootFolder(), $c->getUserSession()); - }); + \OC::$server->registerService('PreviewManager', fn ($c) => + /** @var Server $c */ + new PreviewManager($c->getConfig(), $c->getLazyRootFolder(), $c->getUserSession())); // Sample is 1680x1050 JPEG $this->prepareSample('testimage.jpg', 1680, 1050); // Sample is 2400x1707 EPS @@ -246,20 +244,20 @@ public static function dimensionsDataProvider() { for ($d = 0; $d < 4; $d++) { $coordinates = [ [ - -\rand($samples[$a][0], $samples[$a][1]), - -\rand($samples[$a][0], $samples[$a][1]) + -random_int($samples[$a][0], $samples[$a][1]), + -random_int($samples[$a][0], $samples[$a][1]) ], [ - \rand($samples[$a][0], $samples[$a][1]), - \rand($samples[$a][0], $samples[$a][1]) + random_int($samples[$a][0], $samples[$a][1]), + random_int($samples[$a][0], $samples[$a][1]) ], [ - -\rand($samples[$a][0], $samples[$a][1]), - \rand($samples[$a][0], $samples[$a][1]) + -random_int($samples[$a][0], $samples[$a][1]), + random_int($samples[$a][0], $samples[$a][1]) ], [ - \rand($samples[$a][0], $samples[$a][1]), - -\rand($samples[$a][0], $samples[$a][1]) + random_int($samples[$a][0], $samples[$a][1]), + -random_int($samples[$a][0], $samples[$a][1]) ] ]; $row = [$a]; @@ -337,7 +335,7 @@ public function testCreateMaxAndNormalPreviewsAtFirstRequest( $this->assertEquals($this->maxPreviewHeight, \imagesy($maxPreview)); // A thumbnail of the asked dimensions should also have been created (within the constraints of the max preview) - list($limitedPreviewWidth, $limitedPreviewHeight) = + [$limitedPreviewWidth, $limitedPreviewHeight] = $this->simulatePreviewDimensions($previewWidth, $previewHeight); $actualWidth = $image->width(); @@ -460,7 +458,7 @@ public function testDoNotCreatePreviewsLargerThanConfigMax( $image = $preview->getPreview(); $this->assertNotFalse($image); - list($expectedWidth, $expectedHeight) = + [$expectedWidth, $expectedHeight] = $this->simulatePreviewDimensions($previewWidth, $previewHeight); $this->assertEquals($expectedWidth, $image->width()); $this->assertEquals($expectedHeight, $image->height()); @@ -532,7 +530,7 @@ public function testIsBiggerWithAspectRatioCached( $this->getCachedSmallThumbnail($fileId, 32, 32); // We create a preview in order to be able to delete the cache - $preview = $this->createPreview(\rand(), \rand()); + $preview = $this->createPreview(random_int(0, mt_getrandmax()), random_int(0, mt_getrandmax())); $this->cachedBigger = []; } @@ -626,7 +624,7 @@ private function getSmallerThanMaxPreview($fileId, $previewWidth, $previewHeight $this->assertNotFalse($image); // A thumbnail of the asked dimensions should also have been created (within the constraints of the max preview) - list($limitedPreviewWidth, $limitedPreviewHeight) = + [$limitedPreviewWidth, $limitedPreviewHeight] = $this->simulatePreviewDimensions($previewWidth, $previewHeight); $this->assertEquals($limitedPreviewWidth, $image->width()); @@ -744,7 +742,7 @@ private function prepareSample($fileName, $sampleWidth, $sampleHeight) { $this->rootView->file_put_contents($imgPath, $imgData); $fileInfo = $this->rootView->getFileInfo($imgPath); - list($maxPreviewWidth, $maxPreviewHeight) = + [$maxPreviewWidth, $maxPreviewHeight] = $this->setMaxPreview($sampleWidth, $sampleHeight); $this->samples[] = @@ -795,7 +793,7 @@ private function setMaxPreview($sampleWidth, $sampleHeight) { $this->maxPreviewRatio = $sampleWidth / $sampleHeight; $maxPreviewWidth = \min($sampleWidth, $this->configMaxWidth); $maxPreviewHeight = \min($sampleHeight, $this->configMaxHeight); - list($maxPreviewWidth, $maxPreviewHeight) = + [$maxPreviewWidth, $maxPreviewHeight] = $this->applyAspectRatio($maxPreviewWidth, $maxPreviewHeight); return [$maxPreviewWidth, $maxPreviewHeight]; @@ -819,10 +817,10 @@ private function simulatePreviewDimensions($askedWidth, $askedHeight) { $scaleFactor = $this->scalingUp ? $this->maxScaleFactor : 1; $newPreviewWidth = \min($askedWidth, $this->maxPreviewWidth * $scaleFactor); $newPreviewHeight = \min($askedHeight, $this->maxPreviewHeight * $scaleFactor); - list($newPreviewWidth, $newPreviewHeight) = + [$newPreviewWidth, $newPreviewHeight] = $this->applyAspectRatio($newPreviewWidth, $newPreviewHeight); } else { - list($newPreviewWidth, $newPreviewHeight) = + [$newPreviewWidth, $newPreviewHeight] = $this->fixSize($askedWidth, $askedHeight); } diff --git a/tests/lib/PublicNamespace/ContactsTest.php b/tests/lib/PublicNamespace/ContactsTest.php index 1cf5487371d8..78afda469dd3 100644 --- a/tests/lib/PublicNamespace/ContactsTest.php +++ b/tests/lib/PublicNamespace/ContactsTest.php @@ -34,7 +34,7 @@ public function testDisabledIfEmpty() { public function testEnabledAfterRegister() { // create mock for the addressbook - $stub = $this->getMockForAbstractClass("OCP\IAddressBook"); + $stub = $this->getMockForAbstractClass(\OCP\IAddressBook::class); // we expect getKey to be called twice: // first time on register @@ -60,7 +60,7 @@ public function testEnabledAfterRegister() { public function testAddressBookEnumeration() { // create mock for the addressbook - $stub = $this->getMockForAbstractClass("OCP\IAddressBook"); + $stub = $this->getMockForAbstractClass(\OCP\IAddressBook::class); // setup return for method calls $stub->expects($this->any()) @@ -80,8 +80,8 @@ public function testAddressBookEnumeration() { public function testSearchInAddressBook() { // create mock for the addressbook - $stub1 = $this->getMockForAbstractClass("OCP\IAddressBook"); - $stub2 = $this->getMockForAbstractClass("OCP\IAddressBook"); + $stub1 = $this->getMockForAbstractClass(\OCP\IAddressBook::class); + $stub2 = $this->getMockForAbstractClass(\OCP\IAddressBook::class); $searchResult1 = [ ['id' => 0, 'FN' => 'Frank Karlitschek', 'EMAIL' => 'a@b.c', 'GEO' => '37.386013;-122.082932'], diff --git a/tests/lib/PublicNamespace/UtilTest.php b/tests/lib/PublicNamespace/UtilTest.php index bdfb19965c08..f06cb0776493 100644 --- a/tests/lib/PublicNamespace/UtilTest.php +++ b/tests/lib/PublicNamespace/UtilTest.php @@ -34,7 +34,7 @@ protected function setUp(): void { */ public function testOverrideChannel($channel) { \OCP\Util::setChannel($channel); - $actual = \OCP\Util::getChannel($channel); + $actual = \OCP\Util::getChannel(); $this->assertEquals($channel, $actual); } diff --git a/tests/lib/Repair/AppsTest.php b/tests/lib/Repair/AppsTest.php index f86fe571f716..bf0b5d83201b 100644 --- a/tests/lib/Repair/AppsTest.php +++ b/tests/lib/Repair/AppsTest.php @@ -42,7 +42,7 @@ class AppsTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject*/ protected $config; /** @var \OC_Defaults | \PHPUnit\Framework\MockObject\MockObject */ - private $defaults; + private \PHPUnit\Framework\MockObject\MockObject $defaults; protected function setUp(): void { parent::setUp(); @@ -51,9 +51,7 @@ protected function setUp(): void { $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); $this->eventDispatcher->expects($this->any())->method('dispatch') ->will( - $this->returnCallback(function ($object) { - return $object; - }) + $this->returnCallback(fn ($object) => $object) ); $this->config = $this->createMock(IConfig::class); $this->repair = new Apps( diff --git a/tests/lib/Repair/CleanTagsTest.php b/tests/lib/Repair/CleanTagsTest.php index 72c3f8226c23..71106b0ffa09 100644 --- a/tests/lib/Repair/CleanTagsTest.php +++ b/tests/lib/Repair/CleanTagsTest.php @@ -31,16 +31,16 @@ class CleanTagsTest extends \Test\TestCase { protected $createdFile; /** @var IOutput */ - private $outputMock; + private \PHPUnit\Framework\MockObject\MockObject $outputMock; protected function setUp(): void { parent::setUp(); - $this->outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $this->outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); - $this->userManager = $this->getMockBuilder('\OCP\IUserManager') + $this->userManager = $this->getMockBuilder('\\' . \OCP\IUserManager::class) ->disableOriginalConstructor() ->getMock(); @@ -75,7 +75,7 @@ public function testRun() { $this->addTagEntry($this->getFileID(), $cat2, 'files'); // Retained $this->addTagEntry($this->getFileID() + 1, $cat1, 'files'); // Deleted: File is NULL - $this->addTagEntry(9999999, $cat3, 'contacts'); // Retained + $this->addTagEntry(9_999_999, $cat3, 'contacts'); // Retained $this->addTagEntry($this->getFileID(), $cat3 + 1, 'files'); // Deleted: Category is NULL $this->assertEntryCount('vcategory_to_object', 4, 'Assert tag entries count before repair step'); diff --git a/tests/lib/Repair/DropOldJobsTest.php b/tests/lib/Repair/DropOldJobsTest.php index e076ade39f40..6847be6e1c5b 100644 --- a/tests/lib/Repair/DropOldJobsTest.php +++ b/tests/lib/Repair/DropOldJobsTest.php @@ -35,7 +35,7 @@ public function testRun() { $this->assertTrue($this->jobList->has('OC_Cache_FileGlobalGC', null), 'Asserting that the job OC_Cache_FileGlobalGC exists before repairing'); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/DropOldTablesTest.php b/tests/lib/Repair/DropOldTablesTest.php index 6be77ac26e5f..cffb86900aba 100644 --- a/tests/lib/Repair/DropOldTablesTest.php +++ b/tests/lib/Repair/DropOldTablesTest.php @@ -33,7 +33,7 @@ public function testRun() { $this->assertTrue($this->connection->tableExists('permissions'), 'Asserting that the table oc_permissions does exist before repairing'); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/OldGroupMembershipSharesTest.php b/tests/lib/Repair/OldGroupMembershipSharesTest.php index 027a3966e662..31731811c425 100644 --- a/tests/lib/Repair/OldGroupMembershipSharesTest.php +++ b/tests/lib/Repair/OldGroupMembershipSharesTest.php @@ -33,7 +33,7 @@ protected function setUp(): void { parent::setUp(); /** \OCP\IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - $this->groupManager = $this->getMockBuilder('OCP\IGroupManager') + $this->groupManager = $this->getMockBuilder(\OCP\IGroupManager::class) ->disableOriginalConstructor() ->getMock(); $this->connection = \OC::$server->getDatabaseConnection(); @@ -83,7 +83,7 @@ public function testRun() { $result->closeCursor(); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RemoveGetETagEntriesTest.php b/tests/lib/Repair/RemoveGetETagEntriesTest.php index 8462a50682a5..0f71d284e6cf 100644 --- a/tests/lib/Repair/RemoveGetETagEntriesTest.php +++ b/tests/lib/Repair/RemoveGetETagEntriesTest.php @@ -65,7 +65,7 @@ public function testRun() { } /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RemoveRootSharesTest.php b/tests/lib/Repair/RemoveRootSharesTest.php index 6aa5a786f439..648de4cd4c53 100644 --- a/tests/lib/Repair/RemoveRootSharesTest.php +++ b/tests/lib/Repair/RemoveRootSharesTest.php @@ -43,7 +43,7 @@ class RemoveRootSharesTest extends \Test\TestCase { protected $connection; /** @var IOutput */ - private $outputMock; + private \PHPUnit\Framework\MockObject\MockObject $outputMock; /** @var IUserManager */ private $userManager; @@ -54,7 +54,7 @@ class RemoveRootSharesTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $this->outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RepairCollationTest.php b/tests/lib/Repair/RepairCollationTest.php index b26761bf1f4a..458e326d9fb1 100644 --- a/tests/lib/Repair/RepairCollationTest.php +++ b/tests/lib/Repair/RepairCollationTest.php @@ -34,10 +34,7 @@ public function getAllNonUTF8BinTables(IDBConnection $connection) { * @see \OC\Repair\RepairMimeTypes */ class RepairCollationTest extends TestCase { - /** - * @var TestCollationRepair - */ - private $repair; + private \Test\Repair\TestCollationRepair $repair; /** * @var Connection | IDBConnection @@ -80,7 +77,7 @@ public function testCollationConvert() { $this->assertGreaterThanOrEqual(1, \count($tables)); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RepairInnoDBTest.php b/tests/lib/Repair/RepairInnoDBTest.php index 7d7a87c583ce..3a6f1a3eff72 100644 --- a/tests/lib/Repair/RepairInnoDBTest.php +++ b/tests/lib/Repair/RepairInnoDBTest.php @@ -18,7 +18,7 @@ */ class RepairInnoDBTest extends \Test\TestCase { /** @var IRepairStep */ - private $repair; + private \OC\Repair\InnoDB $repair; /** @var \Doctrine\DBAL\Connection */ private $connection; @@ -51,7 +51,7 @@ public function testInnoDBConvert() { $this->assertEquals(1, $result); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RepairInvalidSharesTest.php b/tests/lib/Repair/RepairInvalidSharesTest.php index cb9e31673d81..bbbc2ba9a5fe 100644 --- a/tests/lib/Repair/RepairInvalidSharesTest.php +++ b/tests/lib/Repair/RepairInvalidSharesTest.php @@ -23,7 +23,7 @@ */ class RepairInvalidSharesTest extends TestCase { /** @var IRepairStep */ - private $repair; + private \OC\Repair\RepairInvalidShares $repair; /** @var \OCP\IDBConnection */ private $connection; @@ -31,7 +31,7 @@ class RepairInvalidSharesTest extends TestCase { protected function setUp(): void { parent::setUp(); - $config = $this->getMockBuilder('OCP\IConfig') + $config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); $config->expects($this->any()) @@ -99,7 +99,7 @@ public function testRemoveExpirationDateForNonLinkShares() { ])->execute(); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); @@ -184,7 +184,7 @@ public function testAddShareLinkDeletePermission() { $keepThisShareId2 = $this->getLastShareId(); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); @@ -260,7 +260,7 @@ public function testSharesNonExistingParent() { $result->closeCursor(); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); @@ -323,7 +323,7 @@ public function testFileSharePermissions($itemType, $testPerms, $expectedPerms) $shareId = $this->getLastShareId(); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RepairMimeTypesTest.php b/tests/lib/Repair/RepairMimeTypesTest.php index 4d9073a91ce0..69c8eacc9904 100644 --- a/tests/lib/Repair/RepairMimeTypesTest.php +++ b/tests/lib/Repair/RepairMimeTypesTest.php @@ -24,10 +24,9 @@ */ class RepairMimeTypesTest extends TestCase { /** @var IRepairStep */ - private $repair; + private \OC\Repair\RepairMimeTypes $repair; - /** @var Temporary */ - private $storage; + private \OC\Files\Storage\Temporary $storage; /** @var IMimeTypeLoader */ private $mimetypeLoader; @@ -38,7 +37,7 @@ protected function setUp(): void { $this->mimetypeLoader = \OC::$server->getMimeTypeLoader(); /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject $config */ - $config = $this->getMockBuilder('OCP\IConfig') + $config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); $config->expects($this->any()) @@ -106,7 +105,7 @@ private function renameMimeTypes($currentMimeTypes, $fixedMimeTypes) { $this->addEntries($currentMimeTypes); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RepairMismatchFileCachePathTest.php b/tests/lib/Repair/RepairMismatchFileCachePathTest.php index a32f548c8a67..0c25fb89c52d 100644 --- a/tests/lib/Repair/RepairMismatchFileCachePathTest.php +++ b/tests/lib/Repair/RepairMismatchFileCachePathTest.php @@ -25,12 +25,12 @@ */ class RepairMismatchFileCachePathTest extends TestCase { /** @var IRepairStep */ - private $repair; + private \OC\Repair\RepairMismatchFileCachePath $repair; /** @var \OCP\IDBConnection */ private $connection; - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Repair/RepairOrphanedSubshareTest.php b/tests/lib/Repair/RepairOrphanedSubshareTest.php index 532776e5392f..1a05e5dfe57c 100644 --- a/tests/lib/Repair/RepairOrphanedSubshareTest.php +++ b/tests/lib/Repair/RepairOrphanedSubshareTest.php @@ -42,7 +42,7 @@ class RepairOrphanedSubshareTest extends TestCase { private $connection; /** @var IRepairStep */ - private $repair; + private \OC\Repair\RepairOrphanedSubshare $repair; protected function setUp(): void { parent::setUp(); @@ -80,7 +80,7 @@ public function testPopulateDBAndRemoveOrphanShares() { //Lets create 10 entries in oc_share to share $parentReshareCount = 1; for ($i=1; $i <= 10; $i++) { - $time = 1522762088 + $i * 60; + $time = 1_522_762_088 + $i * 60; if ($i <= 5) { $shareWithUser = $user1; $uidOwner = 'admin'; @@ -183,7 +183,7 @@ public function testLargeSharesWithOrphans() { $firstIdSet = false; foreach ($totalUsers as $user) { for ($i=1; $i <= 100; $i++) { - $time = 1522762088 + $i * 60; + $time = 1_522_762_088 + $i * 60; $userIndex = \array_search($user, $totalUsers, true); if (($userIndex+1) === \count($totalUsers)) { break; @@ -313,7 +313,7 @@ public function testLargeOrphanSharesDistributedAmongUsers() { if (($userIndex+1) === \count($totalUsers)) { break; } - $time = 1522762088 + $userIndex + 1 + $i * 60; + $time = 1_522_762_088 + $userIndex + 1 + $i * 60; $shareWithUser = $totalUsers[$userIndex+1]; $uidOwner = $user; diff --git a/tests/lib/Repair/RepairSharePropagationTest.php b/tests/lib/Repair/RepairSharePropagationTest.php index ccd9520b09cc..55df1bb49ba9 100644 --- a/tests/lib/Repair/RepairSharePropagationTest.php +++ b/tests/lib/Repair/RepairSharePropagationTest.php @@ -27,7 +27,7 @@ public function keyProvider() { */ public function testRemovePropagationEntries(array $startKeys, array $expectedRemovedKeys) { /** @var \PHPUnit\Framework\MockObject\MockObject|\OCP\IConfig $config */ - $config = $this->createMock('\OCP\IConfig'); + $config = $this->createMock('\\' . \OCP\IConfig::class); $config->expects($this->once()) ->method('getAppKeys') ->with('files_sharing') @@ -42,7 +42,7 @@ public function testRemovePropagationEntries(array $startKeys, array $expectedRe })); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RepairSqliteAutoincrementTest.php b/tests/lib/Repair/RepairSqliteAutoincrementTest.php index efc8bf34740b..2375f9167d6f 100644 --- a/tests/lib/Repair/RepairSqliteAutoincrementTest.php +++ b/tests/lib/Repair/RepairSqliteAutoincrementTest.php @@ -15,10 +15,7 @@ * @group DB */ class RepairSqliteAutoincrementTest extends \Test\TestCase { - /** - * @var \OC\Repair\SqliteAutoincrement - */ - private $repair; + private \OC\Repair\SqliteAutoincrement $repair; /** * @var \Doctrine\DBAL\Connection @@ -77,7 +74,7 @@ public function testConvertIdColumn() { $this->assertFalse($this->checkAutoincrement()); /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Repair/RepairSubSharesTest.php b/tests/lib/Repair/RepairSubSharesTest.php index 3c205c3e8809..e055bd4d8089 100644 --- a/tests/lib/Repair/RepairSubSharesTest.php +++ b/tests/lib/Repair/RepairSubSharesTest.php @@ -42,7 +42,7 @@ class RepairSubSharesTest extends TestCase { private $connection; /** @var IRepairStep */ - private $repair; + private \OC\Repair\RepairSubShares $repair; protected function setUp(): void { parent::setUp(); @@ -81,7 +81,7 @@ public function testRemoveDuplicateSubShare() { */ $userName = "user"; $groupName = "group1"; - $time = 1523892; + $time = 1_523_892; //This array holds the id, share_with and parent per user $getAllIdsPerUser = []; \OC::$server->getGroupManager()->createGroup($groupName); @@ -163,7 +163,7 @@ public function testPopulateDBAndRemoveDuplicates() { $userName = "user"; $groupName = "group"; $folderName = "/test"; - $time = 1523892; + $time = 1_523_892; $groupCount = 1; $totalGroups = 3; $parent = 1; @@ -244,7 +244,7 @@ public function testPopulateDBAndRemoveDuplicates() { public function testLargeDuplicateShareRows() { $qb = $this->connection->getQueryBuilder(); $userName = "user"; - $time = 15238923; + $time = 15_238_923; $groupCount = 0; $folderName = "/test"; $maxUsersPerGroup = 1000; diff --git a/tests/lib/Repair/RepairUnmergedSharesTest.php b/tests/lib/Repair/RepairUnmergedSharesTest.php index 9532e4ff2eaa..9898305e60ff 100644 --- a/tests/lib/Repair/RepairUnmergedSharesTest.php +++ b/tests/lib/Repair/RepairUnmergedSharesTest.php @@ -40,24 +40,23 @@ */ class RepairUnmergedSharesTest extends TestCase { /** @var IRepairStep */ - private $repair; + private \OC\Repair\RepairUnmergedShares $repair; /** @var \OCP\IDBConnection */ private $connection; - /** @var int */ - private $lastShareTime; + private int $lastShareTime; /** @var IUserManager */ - private $userManager; + private \PHPUnit\Framework\MockObject\MockObject $userManager; /** @var IGroupManager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; protected function setUp(): void { parent::setUp(); - $config = $this->getMockBuilder('OCP\IConfig') + $config = $this->getMockBuilder(\OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); $config->expects($this->any()) @@ -108,7 +107,7 @@ public function testDisabledVersions($version, $ran) { /** @var \OCP\IConfig $config */ $this->repair = new RepairUnmergedShares($config, $this->connection, $this->userManager, $this->groupManager); - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); @@ -534,12 +533,12 @@ public function sharesDataProvider() { * @dataProvider sharesDataProvider */ public function xtestMergeGroupShares($shares, $expectedShares) { - $user1 = $this->createMock('\OCP\IUser'); + $user1 = $this->createMock('\\' . \OCP\IUser::class); $user1->expects($this->any()) ->method('getUID') ->will($this->returnValue('user1')); - $user2 = $this->createMock('\OCP\IUser'); + $user2 = $this->createMock('\\' . \OCP\IUser::class); $user2->expects($this->any()) ->method('getUID') ->will($this->returnValue('user2')); @@ -580,7 +579,7 @@ public function xtestMergeGroupShares($shares, $expectedShares) { } /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + $outputMock = $this->getMockBuilder('\\' . \OCP\Migration\IOutput::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/RepairStepTest.php b/tests/lib/RepairStepTest.php index 442b4e468d72..74a5a6c22ae5 100644 --- a/tests/lib/RepairStepTest.php +++ b/tests/lib/RepairStepTest.php @@ -32,11 +32,10 @@ public function run(\OCP\Migration\IOutput $out) { } class RepairTest extends TestCase { - /** @var \OC\Repair */ - private $repair; + private \OC\Repair $repair; /** @var string[] */ - private $outputArray; + private ?array $outputArray = null; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Route/RouterTest.php b/tests/lib/Route/RouterTest.php index f0fa7aacee65..e4749a8b92a2 100644 --- a/tests/lib/Route/RouterTest.php +++ b/tests/lib/Route/RouterTest.php @@ -37,7 +37,7 @@ public function setLoaded($loaded) { class RouterTest extends \Test\TestCase { /** @var ILogger */ - private $l; + private \PHPUnit\Framework\MockObject\MockObject $l; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php b/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php index 7d554942884c..3b5afd7e6667 100644 --- a/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php +++ b/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php @@ -27,8 +27,7 @@ use Test\TestCase; class ContentSecurityPolicyManagerTest extends TestCase { - /** @var ContentSecurityPolicyManager */ - private $contentSecurityPolicyManager; + private \OC\Security\CSP\ContentSecurityPolicyManager $contentSecurityPolicyManager; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php index b894dc93e1f0..c65e9441a1ca 100644 --- a/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenGeneratorTest.php @@ -23,13 +23,12 @@ class CsrfTokenGeneratorTest extends \Test\TestCase { /** @var \OCP\Security\ISecureRandom */ - private $random; - /** @var \OC\Security\CSRF\CsrfTokenGenerator */ - private $csrfTokenGenerator; + private \PHPUnit\Framework\MockObject\MockObject $random; + private \OC\Security\CSRF\CsrfTokenGenerator $csrfTokenGenerator; public function setUp(): void { parent::setUp(); - $this->random = $this->getMockBuilder('\OCP\Security\ISecureRandom') + $this->random = $this->getMockBuilder('\\' . \OCP\Security\ISecureRandom::class) ->disableOriginalConstructor()->getMock(); $this->csrfTokenGenerator = new \OC\Security\CSRF\CsrfTokenGenerator($this->random); } diff --git a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php index bad88190a9d6..13a2e9b3918a 100644 --- a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php @@ -22,18 +22,17 @@ namespace Test\Security\CSRF; class CsrfTokenManagerTest extends \Test\TestCase { - /** @var \OC\Security\CSRF\CsrfTokenManager */ - private $csrfTokenManager; + private \OC\Security\CSRF\CsrfTokenManager $csrfTokenManager; /** @var \OC\Security\CSRF\CsrfTokenGenerator */ - private $tokenGenerator; + private \PHPUnit\Framework\MockObject\MockObject $tokenGenerator; /** @var \OC\Security\CSRF\TokenStorage\SessionStorage */ - private $storageInterface; + private \PHPUnit\Framework\MockObject\MockObject $storageInterface; public function setUp(): void { parent::setUp(); - $this->tokenGenerator = $this->getMockBuilder('\OC\Security\CSRF\CsrfTokenGenerator') + $this->tokenGenerator = $this->getMockBuilder('\\' . \OC\Security\CSRF\CsrfTokenGenerator::class) ->disableOriginalConstructor()->getMock(); - $this->storageInterface = $this->getMockBuilder('\OC\Security\CSRF\TokenStorage\SessionStorage') + $this->storageInterface = $this->getMockBuilder('\\' . \OC\Security\CSRF\TokenStorage\SessionStorage::class) ->disableOriginalConstructor()->getMock(); $this->csrfTokenManager = new \OC\Security\CSRF\CsrfTokenManager( diff --git a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php index e4569b5a7bfa..8e1598e4c249 100644 --- a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php +++ b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php @@ -23,13 +23,12 @@ class SessionStorageTest extends \Test\TestCase { /** @var \OCP\ISession */ - private $session; - /** @var \OC\Security\CSRF\TokenStorage\SessionStorage */ - private $sessionStorage; + private \PHPUnit\Framework\MockObject\MockObject $session; + private \OC\Security\CSRF\TokenStorage\SessionStorage $sessionStorage; public function setUp(): void { parent::setUp(); - $this->session = $this->getMockBuilder('\OCP\ISession') + $this->session = $this->getMockBuilder('\\' . \OCP\ISession::class) ->disableOriginalConstructor()->getMock(); $this->sessionStorage = new \OC\Security\CSRF\TokenStorage\SessionStorage($this->session); } diff --git a/tests/lib/Security/CertificateManagerTest.php b/tests/lib/Security/CertificateManagerTest.php index 76a784bffa3b..4fba383263bc 100644 --- a/tests/lib/Security/CertificateManagerTest.php +++ b/tests/lib/Security/CertificateManagerTest.php @@ -19,8 +19,7 @@ class CertificateManagerTest extends \Test\TestCase { use \Test\Traits\UserTrait; use \Test\Traits\MountProviderTrait; - /** @var CertificateManager */ - private $certificateManager; + private \OC\Security\CertificateManager $certificateManager; /** @var String */ private $username; @@ -38,7 +37,7 @@ protected function setUp(): void { \OC\Files\Filesystem::tearDown(); \OC_Util::setupFS($this->username); - $config = $this->createMock('OCP\IConfig'); + $config = $this->createMock(\OCP\IConfig::class); $config->expects($this->any())->method('getSystemValue') ->with('installed', false)->willReturn(true); diff --git a/tests/lib/Security/CredentialsManagerTest.php b/tests/lib/Security/CredentialsManagerTest.php index be581b212903..c1c8bc02d018 100644 --- a/tests/lib/Security/CredentialsManagerTest.php +++ b/tests/lib/Security/CredentialsManagerTest.php @@ -37,15 +37,15 @@ class CredentialsManagerTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->crypto = $this->createMock('\OCP\Security\ICrypto'); - $this->dbConnection = $this->getMockBuilder('\OC\DB\Connection') + $this->crypto = $this->createMock('\\' . \OCP\Security\ICrypto::class); + $this->dbConnection = $this->getMockBuilder('\\' . \OC\DB\Connection::class) ->disableOriginalConstructor() ->getMock(); $this->manager = new CredentialsManager($this->crypto, $this->dbConnection); } private function getQueryResult($row) { - $result = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement') + $result = $this->getMockBuilder('\\' . \Doctrine\DBAL\Driver\Statement::class) ->disableOriginalConstructor() ->getMock(); @@ -86,7 +86,7 @@ public function testRetrieve() { ->with('baz') ->willReturn(\json_encode('bar')); - $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder') + $qb = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\QueryBuilder::class) ->setConstructorArgs([$this->dbConnection]) ->setMethods(['execute']) ->getMock(); diff --git a/tests/lib/Security/HasherTest.php b/tests/lib/Security/HasherTest.php index 25acf522ec30..b8e2af1ff88e 100644 --- a/tests/lib/Security/HasherTest.php +++ b/tests/lib/Security/HasherTest.php @@ -78,7 +78,7 @@ public function allHashProviders() { protected function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder('\OCP\IConfig') + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor()->getMock(); $this->hasher = new Hasher($this->config); diff --git a/tests/lib/Security/TrustedDomainHelperTest.php b/tests/lib/Security/TrustedDomainHelperTest.php index c001115a8ca8..28fea7ce53d5 100644 --- a/tests/lib/Security/TrustedDomainHelperTest.php +++ b/tests/lib/Security/TrustedDomainHelperTest.php @@ -21,7 +21,7 @@ class TrustedDomainHelperTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class)->getMock(); } /** diff --git a/tests/lib/Session/CryptoSessionDataTest.php b/tests/lib/Session/CryptoSessionDataTest.php index c294d8f25058..d2cdc3dfdf27 100644 --- a/tests/lib/Session/CryptoSessionDataTest.php +++ b/tests/lib/Session/CryptoSessionDataTest.php @@ -37,19 +37,15 @@ protected function setUp(): void { parent::setUp(); $this->wrappedSession = new \OC\Session\Memory(static::getUniqueID()); - $this->crypto = $this->getMockBuilder('OCP\Security\ICrypto') + $this->crypto = $this->getMockBuilder(\OCP\Security\ICrypto::class) ->disableOriginalConstructor() ->getMock(); $this->crypto->expects($this->any()) ->method('encrypt') - ->willReturnCallback(function ($input) { - return '#' . $input . '#'; - }); + ->willReturnCallback(fn ($input) => '#' . $input . '#'); $this->crypto->expects($this->any()) ->method('decrypt') - ->willReturnCallback(function ($input) { - return \substr($input, 1, -1); - }); + ->willReturnCallback(fn ($input) => \substr($input, 1, -1)); $this->instance = new CryptoSessionData($this->wrappedSession, $this->crypto, 'PASS'); } diff --git a/tests/lib/Session/CryptoWrappingTest.php b/tests/lib/Session/CryptoWrappingTest.php index 0e83122743a8..dd80d6048f64 100644 --- a/tests/lib/Session/CryptoWrappingTest.php +++ b/tests/lib/Session/CryptoWrappingTest.php @@ -37,22 +37,18 @@ class CryptoWrappingTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->wrappedSession = $this->getMockBuilder('OCP\ISession') + $this->wrappedSession = $this->getMockBuilder(\OCP\ISession::class) ->disableOriginalConstructor() ->getMock(); - $this->crypto = $this->getMockBuilder('OCP\Security\ICrypto') + $this->crypto = $this->getMockBuilder(\OCP\Security\ICrypto::class) ->disableOriginalConstructor() ->getMock(); $this->crypto->expects($this->any()) ->method('encrypt') - ->willReturnCallback(function ($input) { - return $input; - }); + ->willReturnCallback(fn ($input) => $input); $this->crypto->expects($this->any()) ->method('decrypt') - ->willReturnCallback(function ($input) { - return \substr($input, 1, -1); - }); + ->willReturnCallback(fn ($input) => \substr($input, 1, -1)); $this->instance = new CryptoSessionData($this->wrappedSession, $this->crypto, 'PASS'); } @@ -64,9 +60,7 @@ public function testUnwrappingGet() { $this->wrappedSession->expects($this->once()) ->method('get') ->with('encrypted_session_data') - ->willReturnCallback(function () use ($encryptedValue) { - return $encryptedValue; - }); + ->willReturnCallback(fn () => $encryptedValue); $this->assertSame($unencryptedValue, $this->wrappedSession->get('encrypted_session_data')); } diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php index b5226622000f..ff4d3fb39816 100644 --- a/tests/lib/Settings/ManagerTest.php +++ b/tests/lib/Settings/ManagerTest.php @@ -45,20 +45,20 @@ class SettingsManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->l = $this->getMockBuilder('\OCP\IL10N')->getMock(); - $this->appManager = $this->getMockBuilder('\OCP\App\IAppManager')->getMock(); - $this->userSession = $this->getMockBuilder('\OCP\IUserSession')->getMock(); - $this->logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); - $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager')->getMock(); - $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); - $this->defaults = $this->getMockBuilder('\OCP\Defaults')->getMock(); - $this->urlGenerator = $this->getMockBuilder('\OCP\IUrlGenerator')->getMock(); - $this->helper = $this->getMockBuilder('\OC\Settings\Panels\Helper')->getMock(); - $this->lockingProvider = $this->getMockBuilder('\OCP\Lock\ILockingProvider')->getMock(); - $this->dbconnection = $this->getMockBuilder('\OCP\IDBConnection')->getMock(); - $this->certificateManager = $this->getMockBuilder('\OC\Security\CertificateManager') + $this->l = $this->getMockBuilder('\\' . \OCP\IL10N::class)->getMock(); + $this->appManager = $this->getMockBuilder('\\' . \OCP\App\IAppManager::class)->getMock(); + $this->userSession = $this->getMockBuilder('\\' . \OCP\IUserSession::class)->getMock(); + $this->logger = $this->getMockBuilder('\\' . \OCP\ILogger::class)->getMock(); + $this->groupManager = $this->getMockBuilder('\\' . \OCP\IGroupManager::class)->getMock(); + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class)->getMock(); + $this->defaults = $this->getMockBuilder('\\' . \OCP\Defaults::class)->getMock(); + $this->urlGenerator = $this->getMockBuilder('\\' . \OCP\IUrlGenerator::class)->getMock(); + $this->helper = $this->getMockBuilder('\\' . \OC\Settings\Panels\Helper::class)->getMock(); + $this->lockingProvider = $this->getMockBuilder('\\' . \OCP\Lock\ILockingProvider::class)->getMock(); + $this->dbconnection = $this->getMockBuilder('\\' . \OCP\IDBConnection::class)->getMock(); + $this->certificateManager = $this->getMockBuilder('\\' . \OC\Security\CertificateManager::class) ->disableOriginalConstructor()->getMock(); - $this->factory = $this->getMockBuilder('\OCP\L10N\IFactory')->getMock(); + $this->factory = $this->getMockBuilder('\\' . \OCP\L10N\IFactory::class)->getMock(); $this->licenseManager = $this->createMock(ILicenseManager::class); $this->settingsManager = new SettingsManager( @@ -85,22 +85,22 @@ public function testGetBuiltInSections() { } public function testGetBuiltInPanel() { - $panel = $this->settingsManager->getBuiltInPanel('OC\Settings\Panels\Personal\Profile'); + $panel = $this->settingsManager->getBuiltInPanel(\OC\Settings\Panels\Personal\Profile::class); $this->assertNotFalse($panel); - $this->assertEquals('OC\Settings\Panels\Personal\Profile', \get_class($panel)); + $this->assertEquals(\OC\Settings\Panels\Personal\Profile::class, \get_class($panel)); } public function testGetPanelsList() { - $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user = $this->getMockBuilder('\\' . \OCP\IUser::class)->getMock(); $this->userSession->expects($this->once())->method('getUser')->willReturn($user); $this->appManager->expects($this->once())->method('getEnabledAppsForUser')->with($user)->willReturn([]); $list = $this->settingsManager->getPanelsList('personal'); - $this->assertContains('OC\Settings\Panels\Personal\Profile', $list); + $this->assertContains(\OC\Settings\Panels\Personal\Profile::class, $list); } public function testFindRegisteredPanelsAdmin() { // Return a mock user - $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user = $this->getMockBuilder('\\' . \OCP\IUser::class)->getMock(); $this->userSession->expects($this->any())->method('getUser')->willReturn($user); // Return encryption as example app with $this->appManager->expects($this->exactly(1))->method('getEnabledAppsForUser')->with($user)->willReturn(['encryption']); @@ -115,7 +115,7 @@ public function testFindRegisteredPanelsAdmin() { public function testFindRegisteredPanelsPersonal() { // Return a mock user - $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user = $this->getMockBuilder('\\' . \OCP\IUser::class)->getMock(); $this->userSession->expects($this->any())->method('getUser')->willReturn($user); // Return encryption as example app with $this->appManager->expects($this->exactly(1))->method('getEnabledAppsForUser')->with($user)->willReturn(['encryption']); @@ -131,7 +131,7 @@ public function testFindRegisteredPanelsPersonal() { public function testFindRegisteredPanelsPersonalMultiple() { // Return a mock user - $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user = $this->getMockBuilder('\\' . \OCP\IUser::class)->getMock(); $this->userSession->expects($this->any())->method('getUser')->willReturn($user); // Return encryption as example app with $this->appManager->expects($this->exactly(1))->method('getEnabledAppsForUser')->with($user)->willReturn(['encryption']); @@ -145,7 +145,7 @@ public function testFindRegisteredPanelsPersonalMultiple() { } public function testLoadPersonalPanels() { - $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user = $this->getMockBuilder('\\' . \OCP\IUser::class)->getMock(); $this->userSession->expects($this->any())->method('getUser')->willReturn($user); $this->appManager->expects($this->exactly(1))->method('getEnabledAppsForUser')->with($user)->willReturn(['encryption']); $this->appManager->expects($this->exactly(1))->method('getAppInfo')->with('encryption')->willReturn([]); @@ -157,13 +157,13 @@ public function testLoadPersonalPanels() { } } $this->assertArrayHasKey('additional', $panelClasses); - $this->assertContains('OC\Settings\Panels\Personal\Legacy', $panelClasses['additional']); + $this->assertContains(\OC\Settings\Panels\Personal\Legacy::class, $panelClasses['additional']); $this->assertArrayHasKey('general', $panelClasses); - $this->assertContains('OC\Settings\Panels\Personal\Profile', $panelClasses['general']); + $this->assertContains(\OC\Settings\Panels\Personal\Profile::class, $panelClasses['general']); } public function testLoadAdminPanels() { - $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user = $this->getMockBuilder('\\' . \OCP\IUser::class)->getMock(); $this->userSession->expects($this->any())->method('getUser')->willReturn($user); $this->appManager->expects($this->exactly(1))->method('getEnabledAppsForUser')->with($user)->willReturn(['encryption']); $this->appManager->expects($this->exactly(1))->method('getAppInfo')->with('encryption')->willReturn([]); @@ -176,7 +176,7 @@ public function testLoadAdminPanels() { } $this->assertArrayHasKey('additional', $panelClasses); $this->assertArrayHasKey('general', $panelClasses); - $this->assertContains('OC\Settings\Panels\Admin\Legacy', $panelClasses['additional']); - $this->assertContains('OC\Settings\Panels\Admin\SecurityWarning', $panelClasses['general']); + $this->assertContains(\OC\Settings\Panels\Admin\Legacy::class, $panelClasses['additional']); + $this->assertContains(\OC\Settings\Panels\Admin\SecurityWarning::class, $panelClasses['general']); } } diff --git a/tests/lib/SetupTest.php b/tests/lib/SetupTest.php index 441cc50b6820..7556fb4010a1 100644 --- a/tests/lib/SetupTest.php +++ b/tests/lib/SetupTest.php @@ -14,11 +14,11 @@ class SetupTest extends \Test\TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ protected $config; /** @var \bantu\IniGetWrapper\IniGetWrapper | \PHPUnit\Framework\MockObject\MockObject */ - private $iniWrapper; + private \PHPUnit\Framework\MockObject\MockObject $iniWrapper; /** @var \OCP\IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var \OC_Defaults | \PHPUnit\Framework\MockObject\MockObject */ - private $defaults; + private \PHPUnit\Framework\MockObject\MockObject $defaults; /** @var \OC\Setup | \PHPUnit\Framework\MockObject\MockObject */ protected $setupClass; /** @var \OCP\ILogger | \PHPUnit\Framework\MockObject\MockObject */ @@ -29,13 +29,13 @@ class SetupTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock('\OCP\IConfig'); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); $this->iniWrapper = $this->createMock('\bantu\IniGetWrapper\IniGetWrapper'); - $this->l10n = $this->createMock('\OCP\IL10N'); + $this->l10n = $this->createMock('\\' . \OCP\IL10N::class); $this->defaults = $this->createMock('\OC_Defaults'); - $this->logger = $this->createMock('\OCP\ILogger'); - $this->random = $this->createMock('\OCP\Security\ISecureRandom'); - $this->setupClass = $this->getMockBuilder('\OC\Setup') + $this->logger = $this->createMock('\\' . \OCP\ILogger::class); + $this->random = $this->createMock('\\' . \OCP\Security\ISecureRandom::class); + $this->setupClass = $this->getMockBuilder('\\' . \OC\Setup::class) ->setMethods(['IsClassExisting', 'is_callable', 'getAvailableDbDriversForPdo']) ->setConstructorArgs([$this->config, $this->iniWrapper, $this->l10n, $this->defaults, $this->logger, $this->random]) ->getMock(); diff --git a/tests/lib/Share/Backend.php b/tests/lib/Share/Backend.php index ed23077e44b9..07c61024e31d 100644 --- a/tests/lib/Share/Backend.php +++ b/tests/lib/Share/Backend.php @@ -26,9 +26,9 @@ class Backend implements \OCP\Share_Backend { public const FORMAT_TARGET = 1; public const FORMAT_PERMISSIONS = 2; - private $testItem1 = 'test.txt'; - private $testItem2 = 'share.txt'; - private $testId = 1; + private string $testItem1 = 'test.txt'; + private string $testItem2 = 'share.txt'; + private int $testId = 1; public function isValidSource($itemSource, $uidOwner) { if ($itemSource == $this->testItem1 || $itemSource == $this->testItem2 || $itemSource == 1) { diff --git a/tests/lib/Share/HelperTest.php b/tests/lib/Share/HelperTest.php index 302943638525..2d2a44a24778 100644 --- a/tests/lib/Share/HelperTest.php +++ b/tests/lib/Share/HelperTest.php @@ -29,21 +29,21 @@ class HelperTest extends \Test\TestCase { public function expireDateProvider() { return [ // no default expire date, we take the users expire date - [['defaultExpireDateSet' => false], 2000000000, 2000010000, 2000010000], + [['defaultExpireDateSet' => false], 2_000_000_000, 2_000_010_000, 2_000_010_000], // no default expire date and no user defined expire date, return false - [['defaultExpireDateSet' => false], 2000000000, null, false], + [['defaultExpireDateSet' => false], 2_000_000_000, null, false], // unenforced expire data and no user defined expire date, return false (because the default is not enforced) - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, null, false], + [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2_000_000_000, null, false], // enforced expire date and no user defined expire date, take default expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, null, 2000086400], + [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2_000_000_000, null, 2_000_086_400], // unenforced expire date and user defined date > default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, 2000100000, 2000100000], + [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2_000_000_000, 2_000_100_000, 2_000_100_000], // unenforced expire date and user expire date < default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, 2000010000, 2000010000], + [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2_000_000_000, 2_000_010_000, 2_000_010_000], // enforced expire date and user expire date < default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, 2000010000, 2000010000], + [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2_000_000_000, 2_000_010_000, 2_000_010_000], // enforced expire date and users expire date > default expire date, take default expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, 2000100000, 2000086400], + [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2_000_000_000, 2_000_100_000, 2_000_086_400], ]; } @@ -94,7 +94,7 @@ public function dataTestSplitUserRemote() { * @param string $expectedUrl */ public function testSplitUserRemote($remote, $expectedUser, $expectedUrl) { - list($remoteUser, $remoteUrl) = \OC\Share\Helper::splitUserRemote($remote); + [$remoteUser, $remoteUrl] = \OC\Share\Helper::splitUserRemote($remote); $this->assertSame($expectedUser, $remoteUser); $this->assertSame($expectedUrl, $remoteUrl); } diff --git a/tests/lib/Share/MailNotificationsTest.php b/tests/lib/Share/MailNotificationsTest.php index e6f60369f346..1b5287b6f9ad 100644 --- a/tests/lib/Share/MailNotificationsTest.php +++ b/tests/lib/Share/MailNotificationsTest.php @@ -51,29 +51,28 @@ */ class MailNotificationsTest extends TestCase { /** @var IManager | MockObject */ - private $shareManager; + private \PHPUnit\Framework\MockObject\MockObject $shareManager; /** @var IL10N | MockObject */ - private $l10n; + private \PHPUnit\Framework\MockObject\MockObject $l10n; /** @var IMailer | MockObject */ - private $mailer; + private \PHPUnit\Framework\MockObject\MockObject $mailer; /** @var ILogger | MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IConfig | MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var Defaults | MockObject */ - private $defaults; + private \PHPUnit\Framework\MockObject\MockObject $defaults; /** @var IUser | MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var IURLGenerator | MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var EventDispatcherInterface | MockObject */ - private $eventDispatcher; + private \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher; /** @var \OCP\Activity\IManager | MockObject */ private $activityManager; /** @var IRootFolder | MockObject */ - private $rootFolder; - /** @var MailNotifications */ - private $mailNotifications; + private \PHPUnit\Framework\MockObject\MockObject $rootFolder; + private \OC\Share\MailNotifications $mailNotifications; public function setUp(): void { parent::setUp(); @@ -92,9 +91,7 @@ public function setUp(): void { $this->l10n->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $this->defaults ->expects($this->any()) diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php index aebfdc2b4da7..14c69f4d89e4 100644 --- a/tests/lib/Share/ShareTest.php +++ b/tests/lib/Share/ShareTest.php @@ -81,8 +81,8 @@ protected function setUp(): void { $g2->addUser($u4); $gAU->addUser($u2); $gAU->addUser($u3); - \OCP\Share::registerBackend('test', 'Test\Share\Backend'); - \OC_Hook::clear('OCP\\Share'); + \OCP\Share::registerBackend('test', \Test\Share\Backend::class); + \OC_Hook::clear(\OCP\Share::class); \OC::registerShareHooks(); $this->resharing = \OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes'); \OC::$server->getAppConfig()->setValue('core', 'shareapi_allow_resharing', 'yes'); @@ -148,9 +148,7 @@ protected function tearDown(): void { } protected function setHttpHelper($httpHelper) { - \OC::$server->registerService('HTTPHelper', function () use ($httpHelper) { - return $httpHelper; - }); + \OC::$server->registerService('HTTPHelper', fn () => $httpHelper); } public function testShareInvalidShareType() { @@ -985,7 +983,7 @@ public function dataRemoteShareUrlCalls() { */ public function testRemoteShareUrlCalls($shareWith, $urlHost, $allowFallback, $httpsSuccess, $expectedException = null) { $oldHttpHelper = \OC::$server->query('HTTPHelper'); - $httpHelperMock = $this->getMockBuilder('OC\HttpHelper') + $httpHelperMock = $this->getMockBuilder(\OC\HttpHelper::class) ->disableOriginalConstructor() ->getMock(); $this->setHttpHelper($httpHelperMock); @@ -1181,15 +1179,15 @@ public function testSetPasswordNoUser() { $this->expectException(\Exception::class); $this->expectExceptionMessage('User not logged in'); - $userSession = $this->getMockBuilder('\OCP\IUserSession') + $userSession = $this->getMockBuilder('\\' . \OCP\IUserSession::class) ->disableOriginalConstructor() ->getMock(); - $connection = $this->getMockBuilder('\OC\DB\Connection') + $connection = $this->getMockBuilder('\\' . \OC\DB\Connection::class) ->disableOriginalConstructor() ->getMock(); - $config = $this->getMockBuilder('\OCP\IConfig') + $config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); @@ -1203,7 +1201,7 @@ public function testPasswords() { $userSession = \OC::$server->getUserSession(); $connection = \OC::$server->getDatabaseConnection(); - $config = $this->getMockBuilder('\OCP\IConfig') + $config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); @@ -1246,20 +1244,20 @@ public function testPasswords() { * Test setting a password when everything is fine */ public function testSetPassword() { - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor() ->getMock(); $user->method('getUID')->willReturn('user'); - $userSession = $this->getMockBuilder('\OCP\IUserSession') + $userSession = $this->getMockBuilder('\\' . \OCP\IUserSession::class) ->disableOriginalConstructor() ->getMock(); $userSession->method('getUser')->willReturn($user); - $ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder') + $ex = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder::class) ->disableOriginalConstructor() ->getMock(); - $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder') + $qb = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\QueryBuilder::class) ->disableOriginalConstructor() ->getMock(); $qb->method('update')->will($this->returnSelf()); @@ -1271,18 +1269,18 @@ public function testSetPassword() { $qb->method('setParameter')->will($this->returnSelf()); $qb->method('expr')->willReturn($ex); - $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement') + $ret = $this->getMockBuilder('\\' . \Doctrine\DBAL\Driver\ResultStatement::class) ->disableOriginalConstructor() ->getMock(); $ret->method('fetch')->willReturn(['uid_owner' => 'user']); $qb->method('execute')->willReturn($ret); - $connection = $this->getMockBuilder('\OC\DB\Connection') + $connection = $this->getMockBuilder('\\' . \OC\DB\Connection::class) ->disableOriginalConstructor() ->getMock(); $connection->method('getQueryBuilder')->willReturn($qb); - $config = $this->getMockBuilder('\OCP\IConfig') + $config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); @@ -1307,20 +1305,20 @@ public function testSetPasswordRemove() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Cannot remove password'); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor() ->getMock(); $user->method('getUID')->willReturn('user'); - $userSession = $this->getMockBuilder('\OCP\IUserSession') + $userSession = $this->getMockBuilder('\\' . \OCP\IUserSession::class) ->disableOriginalConstructor() ->getMock(); $userSession->method('getUser')->willReturn($user); - $ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder') + $ex = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder::class) ->disableOriginalConstructor() ->getMock(); - $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder') + $qb = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\QueryBuilder::class) ->disableOriginalConstructor() ->getMock(); $qb->method('update')->will($this->returnSelf()); @@ -1332,18 +1330,18 @@ public function testSetPasswordRemove() { $qb->method('setParameter')->will($this->returnSelf()); $qb->method('expr')->willReturn($ex); - $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement') + $ret = $this->getMockBuilder('\\' . \Doctrine\DBAL\Driver\ResultStatement::class) ->disableOriginalConstructor() ->getMock(); $ret->method('fetch')->willReturn(['uid_owner' => 'user']); $qb->method('execute')->willReturn($ret); - $connection = $this->getMockBuilder('\OC\DB\Connection') + $connection = $this->getMockBuilder('\\' . \OC\DB\Connection::class) ->disableOriginalConstructor() ->getMock(); $connection->method('getQueryBuilder')->willReturn($qb); - $config = $this->getMockBuilder('\OCP\IConfig') + $config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); $config->method('getAppValue')->willReturn('yes'); @@ -1358,20 +1356,20 @@ public function testSetPasswordInvalidShare() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Share not found'); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor() ->getMock(); $user->method('getUID')->willReturn('user'); - $userSession = $this->getMockBuilder('\OCP\IUserSession') + $userSession = $this->getMockBuilder('\\' . \OCP\IUserSession::class) ->disableOriginalConstructor() ->getMock(); $userSession->method('getUser')->willReturn($user); - $ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder') + $ex = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder::class) ->disableOriginalConstructor() ->getMock(); - $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder') + $qb = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\QueryBuilder::class) ->disableOriginalConstructor() ->getMock(); $qb->method('update')->will($this->returnSelf()); @@ -1383,18 +1381,18 @@ public function testSetPasswordInvalidShare() { $qb->method('setParameter')->will($this->returnSelf()); $qb->method('expr')->willReturn($ex); - $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement') + $ret = $this->getMockBuilder('\\' . \Doctrine\DBAL\Driver\ResultStatement::class) ->disableOriginalConstructor() ->getMock(); $ret->method('fetch')->willReturn([]); $qb->method('execute')->willReturn($ret); - $connection = $this->getMockBuilder('\OC\DB\Connection') + $connection = $this->getMockBuilder('\\' . \OC\DB\Connection::class) ->disableOriginalConstructor() ->getMock(); $connection->method('getQueryBuilder')->willReturn($qb); - $config = $this->getMockBuilder('\OCP\IConfig') + $config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); @@ -1408,20 +1406,20 @@ public function testSetPasswordShareOtherUser() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Cannot update share of a different user'); - $user = $this->getMockBuilder('\OCP\IUser') + $user = $this->getMockBuilder('\\' . \OCP\IUser::class) ->disableOriginalConstructor() ->getMock(); $user->method('getUID')->willReturn('user'); - $userSession = $this->getMockBuilder('\OCP\IUserSession') + $userSession = $this->getMockBuilder('\\' . \OCP\IUserSession::class) ->disableOriginalConstructor() ->getMock(); $userSession->method('getUser')->willReturn($user); - $ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder') + $ex = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder::class) ->disableOriginalConstructor() ->getMock(); - $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder') + $qb = $this->getMockBuilder('\\' . \OC\DB\QueryBuilder\QueryBuilder::class) ->disableOriginalConstructor() ->getMock(); $qb->method('update')->will($this->returnSelf()); @@ -1433,18 +1431,18 @@ public function testSetPasswordShareOtherUser() { $qb->method('setParameter')->will($this->returnSelf()); $qb->method('expr')->willReturn($ex); - $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement') + $ret = $this->getMockBuilder('\\' . \Doctrine\DBAL\Driver\ResultStatement::class) ->disableOriginalConstructor() ->getMock(); $ret->method('fetch')->willReturn(['uid_owner' => 'user2']); $qb->method('execute')->willReturn($ret); - $connection = $this->getMockBuilder('\OC\DB\Connection') + $connection = $this->getMockBuilder('\\' . \OC\DB\Connection::class) ->disableOriginalConstructor() ->getMock(); $connection->method('getQueryBuilder')->willReturn($qb); - $config = $this->getMockBuilder('\OCP\IConfig') + $config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); @@ -1456,7 +1454,7 @@ public function testSetPasswordShareOtherUser() { */ public function testOnlyOneRemoteShare() { $oldHttpHelper = \OC::$server->query('HTTPHelper'); - $httpHelperMock = $this->getMockBuilder('OC\HttpHelper') + $httpHelperMock = $this->getMockBuilder(\OC\HttpHelper::class) ->disableOriginalConstructor() ->getMock(); $this->setHttpHelper($httpHelperMock); diff --git a/tests/lib/Share20/DefaultShareProviderTest.php b/tests/lib/Share20/DefaultShareProviderTest.php index 6ffd2ce3a2a0..7f379b2a4612 100644 --- a/tests/lib/Share20/DefaultShareProviderTest.php +++ b/tests/lib/Share20/DefaultShareProviderTest.php @@ -2421,9 +2421,7 @@ public function testUpdateUser() { } $this->userManager->method('get')->will( - $this->returnCallback(function ($userId) use ($users) { - return $users[$userId]; - }) + $this->returnCallback(fn ($userId) => $users[$userId]) ); $file1 = $this->createMock(File::class); @@ -2482,9 +2480,7 @@ public function testUpdateLink() { } $this->userManager->method('get')->will( - $this->returnCallback(function ($userId) use ($users) { - return $users[$userId]; - }) + $this->returnCallback(fn ($userId) => $users[$userId]) ); $file1 = $this->createMock(File::class); @@ -2550,9 +2546,7 @@ public function testUpdateLinkRemovePassword() { } $this->userManager->method('get')->will( - $this->returnCallback(function ($userId) use ($users) { - return $users[$userId]; - }) + $this->returnCallback(fn ($userId) => $users[$userId]) ); $file1 = $this->createMock(File::class); @@ -2609,9 +2603,7 @@ public function testUpdateGroupNoSub() { } $this->userManager->method('get')->will( - $this->returnCallback(function ($userId) use ($users) { - return $users[$userId]; - }) + $this->returnCallback(fn ($userId) => $users[$userId]) ); $groups = []; @@ -2622,9 +2614,7 @@ public function testUpdateGroupNoSub() { } $this->groupManager->method('get')->will( - $this->returnCallback(function ($groupId) use ($groups) { - return $groups[$groupId]; - }) + $this->returnCallback(fn ($groupId) => $groups[$groupId]) ); $file1 = $this->createMock(File::class); @@ -2717,9 +2707,7 @@ public function testUpdateGroupSubShares() { } $this->userManager->method('get')->will( - $this->returnCallback(function ($userId) use ($users) { - return $users[$userId]; - }) + $this->returnCallback(fn ($userId) => $users[$userId]) ); $groups = []; @@ -2730,9 +2718,7 @@ public function testUpdateGroupSubShares() { } $this->groupManager->method('get')->will( - $this->returnCallback(function ($groupId) use ($groups) { - return $groups[$groupId]; - }) + $this->returnCallback(fn ($groupId) => $groups[$groupId]) ); $file1 = $this->createMock(File::class); diff --git a/tests/lib/Share20/ManagerTest.php b/tests/lib/Share20/ManagerTest.php index e4a9971637d9..ad0d71859855 100644 --- a/tests/lib/Share20/ManagerTest.php +++ b/tests/lib/Share20/ManagerTest.php @@ -101,25 +101,23 @@ class ManagerTest extends \Test\TestCase { public function setUp(): void { parent::setUp(); - $this->logger = $this->createMock('\OCP\ILogger'); - $this->config = $this->createMock('\OCP\IConfig'); - $this->secureRandom = $this->createMock('\OCP\Security\ISecureRandom'); - $this->hasher = $this->createMock('\OCP\Security\IHasher'); - $this->mountManager = $this->createMock('\OCP\Files\Mount\IMountManager'); - $this->groupManager = $this->createMock('\OCP\IGroupManager'); - $this->userManager = $this->createMock('\OCP\IUserManager'); - $this->rootFolder = $this->createMock('\OCP\Files\IRootFolder'); + $this->logger = $this->createMock('\\' . \OCP\ILogger::class); + $this->config = $this->createMock('\\' . \OCP\IConfig::class); + $this->secureRandom = $this->createMock('\\' . \OCP\Security\ISecureRandom::class); + $this->hasher = $this->createMock('\\' . \OCP\Security\IHasher::class); + $this->mountManager = $this->createMock('\\' . \OCP\Files\Mount\IMountManager::class); + $this->groupManager = $this->createMock('\\' . \OCP\IGroupManager::class); + $this->userManager = $this->createMock('\\' . \OCP\IUserManager::class); + $this->rootFolder = $this->createMock('\\' . \OCP\Files\IRootFolder::class); $this->eventDispatcher = new EventDispatcher(); $this->view = $this->createMock(View::class); $this->connection = $this->createMock(IDBConnection::class); $this->userSession = $this->createMock(IUserSession::class); $this->activityManager = $this->createMock(IManager::class); - $this->l = $this->createMock('\OCP\IL10N'); + $this->l = $this->createMock('\\' . \OCP\IL10N::class); $this->l->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $this->factory = new DummyFactory(\OC::$server); @@ -141,7 +139,7 @@ public function setUp(): void { $this->userSession ); - $this->defaultProvider = $this->getMockBuilder('\OC\Share20\DefaultShareProvider') + $this->defaultProvider = $this->getMockBuilder('\\' . \OC\Share20\DefaultShareProvider::class) ->disableOriginalConstructor() ->getMock(); $this->defaultProvider->method('identifier')->willReturn('default'); @@ -158,7 +156,7 @@ public function tearDown(): void { * @return \PHPUnit\Framework\MockObject\MockBuilder */ private function createManagerMock() { - return $this->getMockBuilder('\OC\Share20\Manager') + return $this->getMockBuilder('\\' . \OC\Share20\Manager::class) ->setConstructorArgs([ $this->logger, $this->config, @@ -188,10 +186,10 @@ public function testDeleteNoShareId() { } public function dataTestDelete() { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->method('getUID')->willReturn('sharedWithUser'); - $group = $this->createMock('\OCP\IGroup'); + $group = $this->createMock('\\' . \OCP\IGroup::class); $group->method('getGID')->willReturn('sharedWithGroup'); return [ @@ -210,7 +208,7 @@ public function testDelete($shareType, $sharedWith) { ->setMethods(['getShareById', 'deleteChildren']) ->getMock(); - $path = $this->createMock('\OCP\Files\File'); + $path = $this->createMock('\\' . \OCP\Files\File::class); $path->method('getId')->willReturn(1); $share = $this->manager->newShare(); @@ -230,8 +228,8 @@ public function testDelete($shareType, $sharedWith) { ->with($share); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre', 'post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_unshare', $hookListner, 'pre'); - \OCP\Util::connectHook('OCP\Share', 'post_unshare', $hookListner, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'pre_unshare', $hookListner, 'pre'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_unshare', $hookListner, 'post'); $hookListnerExpectsPre = [ 'id' => 42, @@ -335,8 +333,8 @@ public function testDeleteLazyShare() { ->with($share); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre', 'post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_unshare', $hookListner, 'pre'); - \OCP\Util::connectHook('OCP\Share', 'post_unshare', $hookListner, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'pre_unshare', $hookListner, 'pre'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_unshare', $hookListner, 'post'); $hookListnerExpectsPre = [ 'id' => 42, @@ -419,7 +417,7 @@ public function testDeleteNested() { ->setMethods(['getShareById']) ->getMock(); - $path = $this->createMock('\OCP\Files\File'); + $path = $this->createMock('\\' . \OCP\Files\File::class); $path->method('getId')->willReturn(1); $share1 = $this->manager->newShare(); @@ -463,8 +461,8 @@ public function testDeleteNested() { ->withConsecutive([$share3], [$share2], [$share1]); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre', 'post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_unshare', $hookListner, 'pre'); - \OCP\Util::connectHook('OCP\Share', 'post_unshare', $hookListner, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'pre_unshare', $hookListner, 'pre'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_unshare', $hookListner, 'post'); $hookListnerExpectsPre = [ 'id' => 42, @@ -571,14 +569,14 @@ public function testDeleteChildren() { ->setMethods(['deleteShare']) ->getMock(); - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_USER); - $child1 = $this->createMock('\OCP\Share\IShare'); + $child1 = $this->createMock('\\' . \OCP\Share\IShare::class); $child1->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_USER); - $child2 = $this->createMock('\OCP\Share\IShare'); + $child2 = $this->createMock('\\' . \OCP\Share\IShare::class); $child2->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_USER); - $child3 = $this->createMock('\OCP\Share\IShare'); + $child3 = $this->createMock('\\' . \OCP\Share\IShare::class); $child3->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_USER); $shares = [ @@ -607,7 +605,7 @@ public function testDeleteChildren() { } public function testGetShareById() { - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $this->defaultProvider ->expects($this->once()) @@ -866,8 +864,8 @@ public function dataGeneralChecks() { $user1 = 'user1'; $group0 = 'group0'; - $file = $this->createMock('\OCP\Files\File'); - $node = $this->createMock('\OCP\Files\Node'); + $file = $this->createMock('\\' . \OCP\Files\File::class); + $node = $this->createMock('\\' . \OCP\Files\Node::class); $data = [ [$this->createShare(null, \OCP\Share::SHARE_TYPE_USER, $file, null, $user0, $user0, 31, null, null), 'SharedWith is not a valid user', true], @@ -896,7 +894,7 @@ public function dataGeneralChecks() { [$this->createShare(null, \OCP\Share::SHARE_TYPE_LINK, $node, null, $user0, $user0, 31, null, null), 'Path should be either a file or a folder', true], ]; - $nonShareAble = $this->createMock('\OCP\Files\Folder'); + $nonShareAble = $this->createMock('\\' . \OCP\Files\Folder::class); $nonShareAble->method('isShareable')->willReturn(false); $nonShareAble->method('getPath')->willReturn('path'); @@ -948,7 +946,7 @@ public function testGeneralChecks($share, $exceptionMessage, $exception) { ['group0', true], ])); - $userFolder = $this->createMock('\OCP\Files\Folder'); + $userFolder = $this->createMock('\\' . \OCP\Files\Folder::class); $userFolder->method('getPath')->willReturn('myrootfolder'); $this->rootFolder->method('getUserFolder')->willReturn($userFolder); @@ -979,11 +977,9 @@ public function dataShareNotEnoughPermissions(): array { // Federated reshare should just use share node permission // exception when trying to share with more permission than node has - $fileExternalStorage = $this->createMock('OCA\Files_Sharing\External\Storage'); + $fileExternalStorage = $this->createMock(\OCA\Files_Sharing\External\Storage::class); $fileExternalStorage->method('instanceOfStorage') - ->willReturnCallback(function ($storageClass) { - return ($storageClass === 'OCA\Files_Sharing\External\Storage'); - }); + ->willReturnCallback(fn ($storageClass) => $storageClass === \OCA\Files_Sharing\External\Storage::class); $fileExternal = $this->createMock(File::class); $fileExternal->method('getStorage')->willReturn($fileExternalStorage); $share = $this->createShare(null, \OCP\Share::SHARE_TYPE_USER, $file, 'user0', 'user1', 'user2', 31, null, null); @@ -993,11 +989,9 @@ public function dataShareNotEnoughPermissions(): array { // exception when trying to share with more permission than supershare has $superShare = $this->createMock(IShare::class); $superShare->method('getPermissions')->willReturn(1); - $fileReshareStorage = $this->createMock('OCA\Files_Sharing\SharedStorage'); + $fileReshareStorage = $this->createMock(\OCA\Files_Sharing\SharedStorage::class); $fileReshareStorage->method('instanceOfStorage') - ->willReturnCallback(function ($storageClass) { - return ($storageClass === 'OCA\Files_Sharing\SharedStorage'); - }); + ->willReturnCallback(fn ($storageClass) => $storageClass === \OCA\Files_Sharing\SharedStorage::class); $fileReshareStorage->method('getShare')->willReturn($superShare); $fileReshare = $this->createMock(File::class); $fileReshare->method('getStorage')->willReturn($fileReshareStorage); @@ -1012,11 +1006,9 @@ public function dataShareNotEnoughPermissions(): array { $superShare = $this->createMock(IShare::class); $superShare->method('getPermissions')->willReturn(17); $superShare->method('getAttributes')->willReturn($superShareAttributes); - $fileReshareStorage = $this->createMock('OCA\Files_Sharing\SharedStorage'); + $fileReshareStorage = $this->createMock(\OCA\Files_Sharing\SharedStorage::class); $fileReshareStorage->method('instanceOfStorage') - ->willReturnCallback(function ($storageClass) { - return ($storageClass === 'OCA\Files_Sharing\SharedStorage'); - }); + ->willReturnCallback(fn ($storageClass) => $storageClass === \OCA\Files_Sharing\SharedStorage::class); $fileReshareStorage->method('getShare')->willReturn($superShare); $fileReshare = $this->createMock(File::class); $fileReshare->method('getStorage')->willReturn($fileReshareStorage); @@ -1202,9 +1194,7 @@ public function testvalidateExpirationDateEnforceValid() { $hookListner = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock(); \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListner, 'listener'); - $hookListner->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($future) { - return $data['expirationDate'] == $future; - })); + $hookListner->expects($this->once())->method('listener')->with($this->callback(fn ($data) => $data['expirationDate'] == $future)); self::invokePrivate($this->manager, 'validateExpirationDate', [$share]); @@ -1223,9 +1213,7 @@ public function testvalidateExpirationDateNoDateNoDefaultNull() { $hookListner = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock(); \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListner, 'listener'); - $hookListner->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { - return $data['expirationDate'] == $expected && $data['passwordSet'] === false; - })); + $hookListner->expects($this->once())->method('listener')->with($this->callback(fn ($data) => $data['expirationDate'] == $expected && $data['passwordSet'] === false)); self::invokePrivate($this->manager, 'validateExpirationDate', [$share]); @@ -1235,9 +1223,7 @@ public function testvalidateExpirationDateNoDateNoDefaultNull() { public function testvalidateExpirationDateNoDateNoDefault() { $hookListner = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock(); \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListner, 'listener'); - $hookListner->expects($this->once())->method('listener')->with($this->callback(function ($data) { - return $data['expirationDate'] === null && $data['passwordSet'] === true; - })); + $hookListner->expects($this->once())->method('listener')->with($this->callback(fn ($data) => $data['expirationDate'] === null && $data['passwordSet'] === true)); $share = $this->manager->newShare(); $share->setPassword('password'); @@ -1265,9 +1251,7 @@ public function testvalidateExpirationDateNoDateDefault() { $hookListner = $this->getMockBuilder('Dummy')->setMethods(['listener'])->getMock(); \OCP\Util::connectHook('\OC\Share', 'verifyExpirationDate', $hookListner, 'listener'); - $hookListner->expects($this->once())->method('listener')->with($this->callback(function ($data) use ($expected) { - return $data['expirationDate'] == $expected; - })); + $hookListner->expects($this->once())->method('listener')->with($this->callback(fn ($data) => $data['expirationDate'] == $expected)); self::invokePrivate($this->manager, 'validateExpirationDate', [$share]); @@ -1343,8 +1327,8 @@ public function testUserCreateChecksShareWithGroupMembersOnlyDifferentGroups() { $share = $this->manager->newShare(); - $sharedBy = $this->createMock('\OCP\IUser'); - $sharedWith = $this->createMock('\OCP\IUser'); + $sharedBy = $this->createMock('\\' . \OCP\IUser::class); + $sharedWith = $this->createMock('\\' . \OCP\IUser::class); $share->setSharedBy('sharedBy')->setSharedWith('sharedWith'); $this->groupManager @@ -1373,11 +1357,11 @@ public function testUserCreateChecksShareWithGroupMembersOnlyDifferentGroups() { public function testUserCreateChecksShareWithGroupMembersOnlySharedGroup() { $share = $this->manager->newShare(); - $sharedBy = $this->createMock('\OCP\IUser'); - $sharedWith = $this->createMock('\OCP\IUser'); + $sharedBy = $this->createMock('\\' . \OCP\IUser::class); + $sharedWith = $this->createMock('\\' . \OCP\IUser::class); $share->setSharedBy('sharedBy')->setSharedWith('sharedWith'); - $path = $this->createMock('\OCP\Files\Node'); + $path = $this->createMock('\\' . \OCP\Files\Node::class); $share->setNode($path); $this->groupManager @@ -1419,7 +1403,7 @@ public function testUserCreateChecksIdenticalShareExists() { $share = $this->manager->newShare(); $share2 = $this->manager->newShare(); - $path = $this->createMock('\OCP\Files\Node'); + $path = $this->createMock('\\' . \OCP\Files\Node::class); $share->setSharedWith('sharedWith')->setNode($path) ->setProviderId('foo')->setId('bar') @@ -1445,12 +1429,12 @@ public function testUserCreateChecksIdenticalPathSharedViaGroup() { $share = $this->manager->newShare(); - $sharedWith = $this->createMock('\OCP\IUser'); + $sharedWith = $this->createMock('\\' . \OCP\IUser::class); $sharedWith->method('getUID')->willReturn('sharedWith'); $this->userManager->method('get')->with('sharedWith')->willReturn($sharedWith); - $path = $this->createMock('\OCP\Files\Node'); + $path = $this->createMock('\\' . \OCP\Files\Node::class); $share->setSharedWith('sharedWith') ->setNode($path) @@ -1465,7 +1449,7 @@ public function testUserCreateChecksIdenticalPathSharedViaGroup() { ->setId('baz') ->setSharedWith('group'); - $group = $this->createMock('\OCP\IGroup'); + $group = $this->createMock('\\' . \OCP\IGroup::class); $group->method('inGroup') ->with($sharedWith) ->willReturn(true); @@ -1515,8 +1499,8 @@ public function testUserCreateChecksIdenticalPathSharedViaDeletedGroup() { public function testUserCreateChecksIdenticalPathNotSharedWithUser() { $share = $this->manager->newShare(); - $sharedWith = $this->createMock('\OCP\IUser'); - $path = $this->createMock('\OCP\Files\Node'); + $sharedWith = $this->createMock('\\' . \OCP\IUser::class); + $path = $this->createMock('\\' . \OCP\Files\Node::class); $share->setSharedWith('sharedWith') ->setNode($path) ->setShareOwner('shareOwner') @@ -1531,7 +1515,7 @@ public function testUserCreateChecksIdenticalPathNotSharedWithUser() { ->setProviderId('foo') ->setId('baz'); - $group = $this->createMock('\OCP\IGroup'); + $group = $this->createMock('\\' . \OCP\IGroup::class); $group->method('inGroup') ->with($sharedWith) ->willReturn(false); @@ -1575,8 +1559,8 @@ public function testGroupCreateChecksShareWithGroupMembersOnlyNotInGroup() { $share = $this->manager->newShare(); - $user = $this->createMock('\OCP\IUser'); - $group = $this->createMock('\OCP\IGroup'); + $user = $this->createMock('\\' . \OCP\IUser::class); + $group = $this->createMock('\\' . \OCP\IGroup::class); $share->setSharedBy('user')->setSharedWith('group'); $group->method('inGroup')->with($user)->willReturn(false); @@ -1602,7 +1586,7 @@ public function testGroupCreateChecksShareWithGroupMembersOnlyNullGroup() { $share = $this->manager->newShare(); - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $share->setSharedBy('user')->setSharedWith('group'); $this->groupManager->method('get')->with('group')->willReturn(null); @@ -1621,8 +1605,8 @@ public function testGroupCreateChecksShareWithGroupMembersOnlyNullGroup() { public function testGroupCreateChecksShareWithGroupMembersOnlyInGroup() { $share = $this->manager->newShare(); - $user = $this->createMock('\OCP\IUser'); - $group = $this->createMock('\OCP\IGroup'); + $user = $this->createMock('\\' . \OCP\IUser::class); + $group = $this->createMock('\\' . \OCP\IGroup::class); $share->setSharedBy('user')->setSharedWith('group'); $this->userManager->method('get')->with('user')->willReturn($user); @@ -1630,7 +1614,7 @@ public function testGroupCreateChecksShareWithGroupMembersOnlyInGroup() { $group->method('inGroup')->with($user)->willReturn(true); - $path = $this->createMock('\OCP\Files\Node'); + $path = $this->createMock('\\' . \OCP\Files\Node::class); $share->setNode($path); $this->defaultProvider->method('getSharesByPath') @@ -1657,7 +1641,7 @@ public function testGroupCreateChecksPathAlreadySharedWithSameGroup() { $share = $this->manager->newShare(); - $path = $this->createMock('\OCP\Files\Node'); + $path = $this->createMock('\\' . \OCP\Files\Node::class); $share->setSharedWith('sharedWith') ->setShareType(\OCP\Share::SHARE_TYPE_GROUP) ->setNode($path) @@ -1688,7 +1672,7 @@ public function testGroupCreateChecksPathAlreadySharedWithDifferentGroup() { $share->setSharedWith('sharedWith'); - $path = $this->createMock('\OCP\Files\Node'); + $path = $this->createMock('\\' . \OCP\Files\Node::class); $share->setNode($path); $share2 = $this->manager->newShare(); @@ -1805,13 +1789,13 @@ public function testPathCreateChecksContainsSharedMount() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Path contains files shared with you'); - $path = $this->createMock('\OCP\Files\Folder'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); $path->method('getPath')->willReturn('path'); - $mount = $this->createMock('\OCP\Files\Mount\IMountPoint'); - $storage = $this->createMock('\OCP\Files\Storage'); + $mount = $this->createMock('\\' . \OCP\Files\Mount\IMountPoint::class); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); $mount->method('getStorage')->willReturn($storage); - $storage->method('instanceOfStorage')->with('\OCA\Files_Sharing\ISharedStorage')->willReturn(true); + $storage->method('instanceOfStorage')->with('\\' . \OCA\Files_Sharing\ISharedStorage::class)->willReturn(true); $this->mountManager->method('findIn')->with('path')->willReturn([$mount]); @@ -1819,13 +1803,13 @@ public function testPathCreateChecksContainsSharedMount() { } public function testPathCreateChecksContainsNoSharedMount() { - $path = $this->createMock('\OCP\Files\Folder'); + $path = $this->createMock('\\' . \OCP\Files\Folder::class); $path->method('getPath')->willReturn('path'); - $mount = $this->createMock('\OCP\Files\Mount\IMountPoint'); - $storage = $this->createMock('\OCP\Files\Storage'); + $mount = $this->createMock('\\' . \OCP\Files\Mount\IMountPoint::class); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); $mount->method('getStorage')->willReturn($storage); - $storage->method('instanceOfStorage')->with('\OCA\Files_Sharing\ISharedStorage')->willReturn(false); + $storage->method('instanceOfStorage')->with('\\' . \OCA\Files_Sharing\ISharedStorage::class)->willReturn(false); $this->mountManager->method('findIn')->with('path')->willReturn([$mount]); @@ -1835,7 +1819,7 @@ public function testPathCreateChecksContainsNoSharedMount() { } public function testPathCreateChecksContainsNoFolder() { - $path = $this->createMock('\OCP\Files\File'); + $path = $this->createMock('\\' . \OCP\Files\File::class); $this->assertNull( self::invokePrivate($this->manager, 'pathCreateChecks', [$path]) @@ -1892,7 +1876,7 @@ public function dataIsSharingDisabledForUser() { * @param bool $expected */ public function testIsSharingDisabledForUser($excludeGroups, $groupList, $setList, $groupIds, $expected) { - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $this->config->method('getAppValue') ->will($this->returnValueMap([ @@ -2052,8 +2036,8 @@ public function testTransferShare($sharetype) { ->with($share); $hookListnerUnshare = $this->getMockBuilder('Dummy')->setMethods(['pre', 'post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_unshare', $hookListnerUnshare, 'pre'); - \OCP\Util::connectHook('OCP\Share', 'post_unshare', $hookListnerUnshare, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'pre_unshare', $hookListnerUnshare, 'pre'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_unshare', $hookListnerUnshare, 'post'); $mountPoint = $this->createMock(IMountPoint::class); $this->mountManager->expects($this->once()) @@ -2073,7 +2057,7 @@ public function testTransferShare($sharetype) { $share->setSharedWith('differentUser@server.com'); } - $shareOwner = $this->createMock('\OCP\IUser'); + $shareOwner = $this->createMock('\\' . \OCP\IUser::class); $shareOwner->method('getUID')->willReturn('user1'); $this->defaultProvider @@ -2355,11 +2339,11 @@ public function testCreateShareUser() { ->setMethods(['canShare', 'generalChecks', 'userCreateChecks', 'pathCreateChecks']) ->getMock(); - $shareOwner = $this->createMock('\OCP\IUser'); + $shareOwner = $this->createMock('\\' . \OCP\IUser::class); $shareOwner->method('getUID')->willReturn('shareOwner'); - $storage = $this->createMock('\OCP\Files\Storage'); - $path = $this->createMock('\OCP\Files\File'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); + $path = $this->createMock('\\' . \OCP\Files\File::class); $path->method('getOwner')->willReturn($shareOwner); $path->method('getName')->willReturn('target'); $path->method('getStorage')->willReturn($storage); @@ -2437,11 +2421,11 @@ public function testCreateShareGroup() { ->setMethods(['canShare', 'generalChecks', 'groupCreateChecks', 'pathCreateChecks']) ->getMock(); - $shareOwner = $this->createMock('\OCP\IUser'); + $shareOwner = $this->createMock('\\' . \OCP\IUser::class); $shareOwner->method('getUID')->willReturn('shareOwner'); - $storage = $this->createMock('\OCP\Files\Storage'); - $path = $this->createMock('\OCP\Files\File'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); + $path = $this->createMock('\\' . \OCP\Files\File::class); $path->method('getOwner')->willReturn($shareOwner); $path->method('getName')->willReturn('target'); $path->method('getStorage')->willReturn($storage); @@ -2522,8 +2506,8 @@ public function testCreateReShareGroupToSelf() { $user0 = $this->createMock(IUser::class); $user0->method('getUID')->willReturn('user0'); - $storage = $this->createMock('\OCP\Files\Storage'); - $path = $this->createMock('\OCP\Files\File'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); + $path = $this->createMock('\\' . \OCP\Files\File::class); $path->method('getOwner')->willReturn($user0); $path->method('getName')->willReturn('target'); $path->method('getStorage')->willReturn($storage); @@ -2644,11 +2628,11 @@ public function testCreateShareLink($shouldHashPassword) { ]) ->getMock(); - $shareOwner = $this->createMock('\OCP\IUser'); + $shareOwner = $this->createMock('\\' . \OCP\IUser::class); $shareOwner->method('getUID')->willReturn('shareOwner'); - $storage = $this->createMock('\OCP\Files\Storage'); - $path = $this->createMock('\OCP\Files\File'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); + $path = $this->createMock('\\' . \OCP\Files\File::class); $path->method('getOwner')->willReturn($shareOwner); $path->method('getName')->willReturn('target'); $path->method('getId')->willReturn(1); @@ -2709,13 +2693,11 @@ public function testCreateShareLink($shouldHashPassword) { ->expects($this->once()) ->method('create') ->with($share) - ->will($this->returnCallback(function (Share $share) { - return $share->setId(42); - })); + ->will($this->returnCallback(fn (Share $share) => $share->setId(42))); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre', 'post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'pre'); - \OCP\Util::connectHook('OCP\Share', 'post_shared', $hookListner, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'pre_shared', $hookListner, 'pre'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_shared', $hookListner, 'post'); $hookListnerExpectsPre = [ 'itemType' => 'file', @@ -2812,11 +2794,11 @@ public function testCreateShareHookError() { ]) ->getMock(); - $shareOwner = $this->createMock('\OCP\IUser'); + $shareOwner = $this->createMock('\\' . \OCP\IUser::class); $shareOwner->method('getUID')->willReturn('shareOwner'); - $storage = $this->createMock('\OCP\Files\Storage'); - $path = $this->createMock('\OCP\Files\File'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); + $path = $this->createMock('\\' . \OCP\Files\File::class); $path->method('getOwner')->willReturn($shareOwner); $path->method('getName')->willReturn('target'); $path->method('getStorage')->willReturn($storage); @@ -2855,7 +2837,7 @@ public function testCreateShareHookError() { ->with('/target'); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'pre'); + \OCP\Util::connectHook(\OCP\Share::class, 'pre_shared', $hookListner, 'pre'); $hookListner->expects($this->once()) ->method('pre') ->will($this->returnCallback(function (array $data) { @@ -2871,28 +2853,28 @@ public function testCreateShareOfIncomingFederatedShare() { ->setMethods(['canShare', 'generalChecks', 'userCreateChecks', 'pathCreateChecks']) ->getMock(); - $shareOwner = $this->createMock('\OCP\IUser'); + $shareOwner = $this->createMock('\\' . \OCP\IUser::class); $shareOwner->method('getUID')->willReturn('shareOwner'); - $storage = $this->createMock('\OCP\Files\Storage'); + $storage = $this->createMock('\\' . \OCP\Files\Storage::class); $storage->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(true); - $storage2 = $this->createMock('\OCP\Files\Storage'); + $storage2 = $this->createMock('\\' . \OCP\Files\Storage::class); $storage2->method('instanceOfStorage') - ->with('OCA\Files_Sharing\External\Storage') + ->with(\OCA\Files_Sharing\External\Storage::class) ->willReturn(false); - $path = $this->createMock('\OCP\Files\File'); + $path = $this->createMock('\\' . \OCP\Files\File::class); $path->expects($this->never())->method('getOwner'); $path->method('getName')->willReturn('target'); $path->method('getStorage')->willReturn($storage); - $parent = $this->createMock('\OCP\Files\Folder'); + $parent = $this->createMock('\\' . \OCP\Files\Folder::class); $parent->method('getStorage')->willReturn($storage); - $parentParent = $this->createMock('\OCP\Files\Folder'); + $parentParent = $this->createMock('\\' . \OCP\Files\Folder::class); $parentParent->method('getStorage')->willReturn($storage2); $parentParent->method('getOwner')->willReturn($shareOwner); @@ -2970,7 +2952,7 @@ function (GenericEvent $event) use (&$calledAfterShareCreate) { public function testGetAllSharesBy() { $share = $this->manager->newShare(); - $node = $this->createMock('OCP\Files\Folder'); + $node = $this->createMock(\OCP\Files\Folder::class); $node->expects($this->any()) ->method('getId') ->will($this->returnValue(0)); @@ -2978,7 +2960,7 @@ public function testGetAllSharesBy() { $nodes = [$node->getId()]; for ($i = 1; $i <= 201; $i++) { - $node = $this->createMock('OCP\Files\File'); + $node = $this->createMock(\OCP\Files\File::class); $node->expects($this->any()) ->method('getId') ->will($this->returnValue($i)); @@ -3016,7 +2998,7 @@ public function testGetAllSharesByExpiration() { $yesterday = new \DateTime("yesterday"); $shareExpired->method('getExpirationDate')->willReturn($yesterday); - $node = $this->createMock('OCP\Files\Folder'); + $node = $this->createMock(\OCP\Files\Folder::class); $node->expects($this->any()) ->method('getId') ->will($this->returnValue(0)); @@ -3024,7 +3006,7 @@ public function testGetAllSharesByExpiration() { $nodes = [$node->getId()]; for ($i = 1; $i <= 201; $i++) { - $node = $this->createMock('OCP\Files\File'); + $node = $this->createMock(\OCP\Files\File::class); $node->expects($this->any()) ->method('getId') ->will($this->returnValue($i)); @@ -3069,7 +3051,7 @@ public function testGetAllSharesByException() { public function testGetSharesBy() { $share = $this->manager->newShare(); - $node = $this->createMock('OCP\Files\Folder'); + $node = $this->createMock(\OCP\Files\Folder::class); $this->defaultProvider->expects($this->once()) ->method('getSharesBy') @@ -3130,7 +3112,7 @@ public function testGetSharesByExpiredLinkShares() { $shares2[] = clone $shares[$i]; } - $node = $this->createMock('OCP\Files\File'); + $node = $this->createMock(\OCP\Files\File::class); /* * Simulate the getSharesBy call. @@ -3170,7 +3152,7 @@ public function testGetSharesByExpiredLinkShares() { } public function testGetShareByToken() { - $factory = $this->createMock('\OCP\Share\IProviderFactory'); + $factory = $this->createMock('\\' . \OCP\Share\IProviderFactory::class); $manager = new Manager( $this->logger, @@ -3189,7 +3171,7 @@ public function testGetShareByToken() { $this->activityManager ); - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $factory->expects($this->once()) ->method('getProviderForType') @@ -3206,7 +3188,7 @@ public function testGetShareByToken() { } public function testGetShareByTokenWithException() { - $factory = $this->createMock('\OCP\Share\IProviderFactory'); + $factory = $this->createMock('\\' . \OCP\Share\IProviderFactory::class); $manager = new Manager( $this->logger, @@ -3225,7 +3207,7 @@ public function testGetShareByTokenWithException() { $this->activityManager ); - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $factory ->expects($this->exactly(2)) @@ -3318,7 +3300,7 @@ public function testGetShareByTokenPublicSharingDisabled() { } public function testGetSharesByPath() { - $factory = $this->createMock('\OCP\Share\IProviderFactory'); + $factory = $this->createMock('\\' . \OCP\Share\IProviderFactory::class); $manager = new Manager( $this->logger, @@ -3337,11 +3319,11 @@ public function testGetSharesByPath() { $this->activityManager ); - $provider1 = $this->getMockBuilder('\OC\Share20\DefaultShareProvider') + $provider1 = $this->getMockBuilder('\\' . \OC\Share20\DefaultShareProvider::class) ->disableOriginalConstructor() ->getMock(); $provider1->method('identifier')->willReturn('provider1'); - $provider2 = $this->getMockBuilder('\OC\Share20\DefaultShareProvider') + $provider2 = $this->getMockBuilder('\\' . \OC\Share20\DefaultShareProvider::class) ->disableOriginalConstructor() ->getMock(); $provider2->method('identifier')->willReturn('provider2'); @@ -3363,7 +3345,7 @@ public function testGetSharesByPath() { $share3 = $this->manager->newShare(); $share3->setId(44); - $node = $this->createMock('\OCP\Files\Folder'); + $node = $this->createMock('\\' . \OCP\Files\Folder::class); $provider1->expects($this->once()) ->method('getSharesByPath') @@ -3377,13 +3359,13 @@ public function testGetSharesByPath() { } public function testCheckPasswordNoLinkShare() { - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_USER); $this->assertFalse($this->manager->checkPassword($share, 'password')); } public function testCheckPasswordNoPassword() { - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); $this->assertFalse($this->manager->checkPassword($share, 'password')); @@ -3392,7 +3374,7 @@ public function testCheckPasswordNoPassword() { } public function testCheckPasswordInvalidPassword() { - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); $share->method('getPassword')->willReturn('password'); @@ -3422,7 +3404,7 @@ function (GenericEvent $event) use (&$calledFailEvent) { } public function testCheckPasswordValidPassword() { - $share = $this->createMock('\OCP\Share\IShare'); + $share = $this->createMock('\\' . \OCP\Share\IShare::class); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); $share->method('getPassword')->willReturn('passwordHash'); @@ -3466,9 +3448,7 @@ public function testCheckPasswordUpdateShare() { $this->defaultProvider->expects($this->once()) ->method('update') - ->with($this->callback(function (\OCP\Share\IShare $share) { - return $share->getPassword() === 'newHash'; - })); + ->with($this->callback(fn (\OCP\Share\IShare $share) => $share->getPassword() === 'newHash')); $this->assertTrue($this->manager->checkPassword($share, 'password')); } @@ -3577,7 +3557,7 @@ public function testUpdateShareUser() { ->setSharedWith('origUser') ->setPermissions(1); - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock('\\' . \OCP\Files\File::class); $node->method('getId')->willReturn(100); $node->method('getPath')->willReturn('/newUser/files/myPath'); @@ -3603,14 +3583,14 @@ public function testUpdateShareUser() { ->willReturn($share); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListner, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListner, 'post'); $hookListner->expects($this->never())->method('post'); $this->rootFolder->method('getUserFolder')->with('newUser')->will($this->returnSelf()); $this->rootFolder->method('getRelativePath')->with('/newUser/files/myPath')->willReturn('/myPath'); $hookListner2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListner2, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListner2, 'post'); $hookListner2->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3662,7 +3642,7 @@ public function testUpdateShareGroup() { $manager->expects($this->once())->method('canShare')->willReturn(true); $manager->expects($this->once())->method('getShareById')->with('foo:42')->willReturn($originalShare); - $node = $this->createMock('\OCP\Files\File'); + $node = $this->createMock('\\' . \OCP\Files\File::class); $share = $this->manager->newShare(); $share->setProviderId('foo') @@ -3679,11 +3659,11 @@ public function testUpdateShareGroup() { ->willReturn($share); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListner, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListner, 'post'); $hookListner->expects($this->never())->method('post'); $hookListner2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListner2, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListner2, 'post'); $hookListner2->expects($this->never())->method('post'); $manager->updateShare($share); @@ -3713,7 +3693,7 @@ public function testUpdateShareLink($shouldHashPassword) { $tomorrow->setTime(0, 0, 0); $tomorrow->add(new \DateInterval('P1D')); - $file = $this->createMock('OCP\Files\File', [], [], 'File'); + $file = $this->createMock(\OCP\Files\File::class); $file->method('getId')->willReturn(100); $share = $this->manager->newShare(); @@ -3747,7 +3727,7 @@ public function testUpdateShareLink($shouldHashPassword) { ->willReturn($share); $hookListner = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_set_expiration_date', $hookListner, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_set_expiration_date', $hookListner, 'post'); $hookListner->expects($this->once())->method('post')->with([ 'itemType' => 'file', 'itemSource' => 100, @@ -3756,7 +3736,7 @@ public function testUpdateShareLink($shouldHashPassword) { ]); $hookListner2 = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock(); - \OCP\Util::connectHook('OCP\Share', 'post_update_permissions', $hookListner2, 'post'); + \OCP\Util::connectHook(\OCP\Share::class, 'post_update_permissions', $hookListner2, 'post'); $hookListner2->expects($this->never())->method('post'); $calledAfterUpdate = []; diff --git a/tests/lib/Share20/ShareTest.php b/tests/lib/Share20/ShareTest.php index 57be79d79d09..87145a322ac9 100644 --- a/tests/lib/Share20/ShareTest.php +++ b/tests/lib/Share20/ShareTest.php @@ -43,8 +43,8 @@ class ShareTest extends TestCase { protected $share; public function setUp(): void { - $this->rootFolder = $this->createMock('\OCP\Files\IRootFolder'); - $this->userManager = $this->createMock('OCP\IUserManager'); + $this->rootFolder = $this->createMock('\\' . \OCP\Files\IRootFolder::class); + $this->userManager = $this->createMock(\OCP\IUserManager::class); $this->share = new Share($this->rootFolder, $this->userManager); } diff --git a/tests/lib/SubAdminTest.php b/tests/lib/SubAdminTest.php index bdd2bf400539..e9caec96ccab 100644 --- a/tests/lib/SubAdminTest.php +++ b/tests/lib/SubAdminTest.php @@ -350,13 +350,13 @@ public function testHooks() { $g = $this->groups[0]; $count = 0; - $subAdmin->listen('\OC\SubAdmin', 'postCreateSubAdmin', function ($user, $group) use ($test, $u, $g, &$count) { + $subAdmin->listen('\\' . \OC\SubAdmin::class, 'postCreateSubAdmin', function ($user, $group) use ($test, $u, $g, &$count) { $test->assertEquals($u->getUID(), $user->getUID()); $test->assertEquals($g->getGID(), $group->getGID()); $count++; }); - $subAdmin->listen('\OC\SubAdmin', 'postDeleteSubAdmin', function ($user, $group) use ($test, $u, $g, &$count) { + $subAdmin->listen('\\' . \OC\SubAdmin::class, 'postDeleteSubAdmin', function ($user, $group) use ($test, $u, $g, &$count) { $test->assertEquals($u->getUID(), $user->getUID()); $test->assertEquals($g->getGID(), $group->getGID()); $count++; diff --git a/tests/lib/SystemConfigTest.php b/tests/lib/SystemConfigTest.php index 47620f6986d4..1565278ffd32 100644 --- a/tests/lib/SystemConfigTest.php +++ b/tests/lib/SystemConfigTest.php @@ -34,9 +34,8 @@ */ class SystemConfigTest extends TestCase { /** @var \OC\Config */ - private $config; - /** @var SystemConfig */ - private $systemConfig; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OC\SystemConfig $systemConfig; protected function setUp(): void { parent::setUp(); @@ -46,7 +45,7 @@ protected function setUp(): void { } public function testGetKeys() { - $keyList = ['key1', \rand(0, 40), 45, 'another']; + $keyList = ['key1', random_int(0, 40), 45, 'another']; $this->config->expects($this->once()) ->method('getKeys') ->willReturn($keyList); @@ -56,7 +55,7 @@ public function testGetKeys() { public function testSetValue() { $key = \str_shuffle('abcdefghijk'); - $value = \rand(); + $value = random_int(0, mt_getrandmax()); $this->config->expects($this->once()) ->method('setValue') diff --git a/tests/lib/SystemTag/SystemTagManagerTest.php b/tests/lib/SystemTag/SystemTagManagerTest.php index 58eddf00d154..1b5a0f1522d3 100644 --- a/tests/lib/SystemTag/SystemTagManagerTest.php +++ b/tests/lib/SystemTag/SystemTagManagerTest.php @@ -30,7 +30,7 @@ class SystemTagManagerTest extends TestCase { /** * @var ISystemTagManager **/ - private $tagManager; + private \OC\SystemTag\SystemTagManager $tagManager; /** * @var IDBConnection @@ -40,22 +40,22 @@ class SystemTagManagerTest extends TestCase { /** * @var IGroupManager */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** * @var EventDispatcherInterface */ - private $dispatcher; + private \PHPUnit\Framework\MockObject\MockObject $dispatcher; public function setUp(): void { parent::setUp(); $this->connection = \OC::$server->getDatabaseConnection(); - $this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface') + $this->dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class) ->getMock(); - $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager')->getMock(); + $this->groupManager = $this->getMockBuilder('\\' . \OCP\IGroupManager::class)->getMock(); $this->tagManager = new SystemTagManager( $this->connection, @@ -451,7 +451,7 @@ public function visibilityCheckProvider() { * @dataProvider visibilityCheckProvider */ public function testVisibilityCheck($userVisible, $userAssignable, $isAdmin, $expectedResult) { - $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user = $this->getMockBuilder('\\' . \OCP\IUser::class)->getMock(); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('test')); @@ -498,7 +498,7 @@ public function assignabilityCheckProvider() { * @dataProvider assignabilityCheckProvider */ public function testAssignabilityCheck($userVisible, $userAssignable, $userEditable, $isAdmin, $expectedResult, $userGroupIds = [], $tagGroupIds = []) { - $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user = $this->getMockBuilder('\\' . \OCP\IUser::class)->getMock(); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('test')); diff --git a/tests/lib/SystemTag/SystemTagObjectMapperTest.php b/tests/lib/SystemTag/SystemTagObjectMapperTest.php index 651be583dcae..c0fb3545f27f 100644 --- a/tests/lib/SystemTag/SystemTagObjectMapperTest.php +++ b/tests/lib/SystemTag/SystemTagObjectMapperTest.php @@ -31,12 +31,12 @@ class SystemTagObjectMapperTest extends TestCase { /** * @var ISystemTagManager **/ - private $tagManager; + private \PHPUnit\Framework\MockObject\MockObject $tagManager; /** * @var ISystemTagObjectMapper **/ - private $tagMapper; + private \OC\SystemTag\SystemTagObjectMapper $tagMapper; /** * @var IDBConnection @@ -46,22 +46,22 @@ class SystemTagObjectMapperTest extends TestCase { /** * @var EventDispatcherInterface */ - private $dispatcher; + private \PHPUnit\Framework\MockObject\MockObject $dispatcher; /** * @var ISystemTag */ - private $tag1; + private \OC\SystemTag\SystemTag $tag1; /** * @var ISystemTag */ - private $tag2; + private \OC\SystemTag\SystemTag $tag2; /** * @var ISystemTag */ - private $tag3; + private \OC\SystemTag\SystemTag $tag3; public function setUp(): void { parent::setUp(); @@ -69,10 +69,10 @@ public function setUp(): void { $this->connection = \OC::$server->getDatabaseConnection(); $this->pruneTagsTables(); - $this->tagManager = $this->getMockBuilder('OCP\SystemTag\ISystemTagManager') + $this->tagManager = $this->getMockBuilder(\OCP\SystemTag\ISystemTagManager::class) ->getMock(); - $this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface') + $this->dispatcher = $this->getMockBuilder(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class) ->getMock(); $this->tagMapper = new SystemTagObjectMapper( diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php index 700f7d63750f..9abe73045663 100644 --- a/tests/lib/TagsTest.php +++ b/tests/lib/TagsTest.php @@ -51,7 +51,7 @@ protected function setUp(): void { $userId = self::getUniqueID('user_'); $this->user = $this->createUser($userId, 'pass'); \OC_User::setUserId($userId); - $this->userSession = $this->createMock('\OCP\IUserSession'); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); $this->userSession ->expects($this->any()) ->method('getUser') @@ -71,7 +71,7 @@ protected function tearDown(): void { } public function testTagManagerWithoutUserReturnsNull() { - $this->userSession = $this->createMock('\OCP\IUserSession'); + $this->userSession = $this->createMock('\\' . \OCP\IUserSession::class); $this->userSession ->expects($this->any()) ->method('getUser') @@ -287,7 +287,7 @@ public function testFavorite() { public function testShareTags() { $testTag = 'TestTag'; - \OCP\Share::registerBackend('test', 'Test\Share\Backend'); + \OCP\Share::registerBackend('test', \Test\Share\Backend::class); $tagger = $this->tagMgr->load('test'); $tagger->tagAs(1, $testTag); diff --git a/tests/lib/Template/ResourceLocatorTest.php b/tests/lib/Template/ResourceLocatorTest.php index 0fc8370a9b17..f94d73d9ed3a 100644 --- a/tests/lib/Template/ResourceLocatorTest.php +++ b/tests/lib/Template/ResourceLocatorTest.php @@ -25,7 +25,7 @@ class ResourceLocatorTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->logger = $this->createMock('OCP\ILogger'); + $this->logger = $this->createMock(\OCP\ILogger::class); vfsStreamWrapper::register(); $root = vfsStream::newDirectory('resources'); @@ -45,13 +45,13 @@ protected function setUp(): void { * @return \PHPUnit\Framework\MockObject\MockObject */ public function getResourceLocator($theme, $core_map, $appsRoots) { - $themeInstance = $this->createMock('OC\Theme\Theme'); + $themeInstance = $this->createMock(\OC\Theme\Theme::class); $themeInstance->method('getName')->willReturn($theme); $appManagerInstance = $this->createMock(AppManager::class); return $this->getMockForAbstractClass( - 'OC\Template\ResourceLocator', + \OC\Template\ResourceLocator::class, [$themeInstance, $appManagerInstance, $this->logger, $core_map, $appsRoots], '', true, diff --git a/tests/lib/TemplateFunctionsTest.php b/tests/lib/TemplateFunctionsTest.php index 15c8829350e0..4f86f3c27c80 100644 --- a/tests/lib/TemplateFunctionsTest.php +++ b/tests/lib/TemplateFunctionsTest.php @@ -62,7 +62,7 @@ public function testPrintUnescapedNormalString() { // Test relative_modified_date with dates only // --------------------------------------------------------------------------- public function testRelativeDateToday() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime; $result = (string)relative_modified_date($elementTime, $currentTime, true); @@ -76,7 +76,7 @@ public function testRelativeDateToday() { } public function testRelativeDateYesterday() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 24 * 3600; $result = (string)relative_modified_date($elementTime, $currentTime, true); @@ -90,7 +90,7 @@ public function testRelativeDateYesterday() { } public function testRelativeDate2DaysAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 48 * 3600; $result = (string)relative_modified_date($elementTime, $currentTime, true); @@ -104,7 +104,7 @@ public function testRelativeDate2DaysAgo() { } public function testRelativeDateLastMonth() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 86400 * 31; $result = (string)relative_modified_date($elementTime, $currentTime, true); @@ -117,7 +117,7 @@ public function testRelativeDateLastMonth() { } public function testRelativeDateMonthsAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 86400 * 65; $result = (string)relative_modified_date($elementTime, $currentTime, true); @@ -130,7 +130,7 @@ public function testRelativeDateMonthsAgo() { } public function testRelativeDateLastYear() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 86400 * 365; $result = (string)relative_modified_date($elementTime, $currentTime, true); @@ -143,7 +143,7 @@ public function testRelativeDateLastYear() { } public function testRelativeDateYearsAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 86400 * 365.25 * 2; $result = (string)relative_modified_date($elementTime, $currentTime, true); @@ -160,7 +160,7 @@ public function testRelativeDateYearsAgo() { // --------------------------------------------------------------------------- public function testRelativeTimeSecondsAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 5; $result = (string)relative_modified_date($elementTime, $currentTime, false); @@ -168,7 +168,7 @@ public function testRelativeTimeSecondsAgo() { } public function testRelativeTimeMinutesAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 190; $result = (string)relative_modified_date($elementTime, $currentTime, false); @@ -176,7 +176,7 @@ public function testRelativeTimeMinutesAgo() { } public function testRelativeTimeHoursAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 7500; $result = (string)relative_modified_date($elementTime, $currentTime, false); @@ -184,7 +184,7 @@ public function testRelativeTimeHoursAgo() { } public function testRelativeTime2DaysAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 48 * 3600; $result = (string)relative_modified_date($elementTime, $currentTime, false); @@ -198,7 +198,7 @@ public function testRelativeTime2DaysAgo() { } public function testRelativeTimeLastMonth() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 86400 * 31; $result = (string)relative_modified_date($elementTime, $currentTime, false); @@ -211,7 +211,7 @@ public function testRelativeTimeLastMonth() { } public function testRelativeTimeMonthsAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 86400 * 65; $result = (string)relative_modified_date($elementTime, $currentTime, false); @@ -224,7 +224,7 @@ public function testRelativeTimeMonthsAgo() { } public function testRelativeTimeLastYear() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 86400 * 365; $result = (string)relative_modified_date($elementTime, $currentTime, false); @@ -237,7 +237,7 @@ public function testRelativeTimeLastYear() { } public function testRelativeTimeYearsAgo() { - $currentTime = 1380703592; + $currentTime = 1_380_703_592; $elementTime = $currentTime - 86400 * 365.25 * 2; $result = (string)relative_modified_date($elementTime, $currentTime, false); diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index d1d34258b54d..5a6949e61057 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -34,17 +34,14 @@ use PHPUnit\Util\Test as TestUtil; abstract class TestCase extends BaseTestCase { - /** @var \OC\Command\QueueBus */ - private $commandBus; + private \OC\Command\QueueBus $commandBus; /** @var IDBConnection */ protected static $realDatabase = null; - /** @var bool */ - private static $wasDatabaseAllowed = false; + private static bool $wasDatabaseAllowed = false; - /** @var string */ - private static $lastTest = ''; + private static string $lastTest = ''; /** @var array */ protected $services = []; @@ -60,9 +57,7 @@ public function overwriteService($name, $newService) { } $this->services[$name] = \OC::$server->query($name); - \OC::$server->registerService($name, function () use ($newService) { - return $newService; - }); + \OC::$server->registerService($name, fn () => $newService); return true; } @@ -74,9 +69,7 @@ public function overwriteService($name, $newService) { public function restoreService($name) { if (isset($this->services[$name])) { $oldService = $this->services[$name]; - \OC::$server->registerService($name, function () use ($oldService) { - return $oldService; - }); + \OC::$server->registerService($name, fn () => $oldService); unset($this->services[$name]); return true; @@ -95,9 +88,7 @@ protected function getTestTraits() { $traits = \array_merge(\class_uses($trait), $traits); } $traits = \array_unique($traits); - return \array_filter($traits, function ($trait) { - return \substr($trait, 0, 5) === 'Test\\'; - }); + return \array_filter($traits, fn ($trait) => \substr($trait, 0, 5) === 'Test\\'); } protected function setUp(): void { @@ -115,9 +106,7 @@ protected function setUp(): void { // overwrite the command bus with one we can run ourselves $this->commandBus = new QueueBus(); - \OC::$server->registerService('AsyncCommandBus', function () { - return $this->commandBus; - }); + \OC::$server->registerService('AsyncCommandBus', fn () => $this->commandBus); $traits = $this->getTestTraits(); foreach ($traits as $trait) { @@ -138,9 +127,7 @@ protected function tearDown(): void { // restore database connection if (!$this->IsDatabaseAccessAllowed()) { - \OC::$server->registerService('DatabaseConnection', function () { - return self::$realDatabase; - }); + \OC::$server->registerService('DatabaseConnection', fn () => self::$realDatabase); } \OC::$server->getLockingProvider()->releaseAll(); @@ -240,9 +227,7 @@ public static function tearDownAfterClass(): void { if (!self::$wasDatabaseAllowed && self::$realDatabase !== null) { // in case an error is thrown in a test, PHPUnit jumps straight to tearDownAfterClass, // so we need the database again - \OC::$server->registerService('DatabaseConnection', function () { - return self::$realDatabase; - }); + \OC::$server->registerService('DatabaseConnection', fn () => self::$realDatabase); } $dataDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data-autotest'); if (self::$wasDatabaseAllowed && \OC::$server->getDatabaseConnection()) { @@ -393,7 +378,7 @@ protected function runCommands() { // get the user for which the fs is setup $view = Filesystem::getView(); if ($view) { - list(, $user) = \explode('/', $view->getRoot()); + [, $user] = \explode('/', $view->getRoot()); } else { $user = null; } @@ -472,14 +457,12 @@ protected function assertTemplate($expectedHtml, $template, $vars = []) { $requestToken = 12345; $theme = new OC_Defaults(); /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject $l10n */ - $l10n = $this->getMockBuilder('\OCP\IL10N') + $l10n = $this->getMockBuilder('\\' . \OCP\IL10N::class) ->disableOriginalConstructor()->getMock(); $l10n ->expects($this->any()) ->method('t') - ->will($this->returnCallback(function ($text, $parameters = []) { - return \vsprintf($text, $parameters); - })); + ->will($this->returnCallback(fn ($text, $parameters = []) => \vsprintf($text, $parameters))); $t = new Base($template, $requestToken, $l10n, null, $theme); $buf = $t->fetchPage($vars); diff --git a/tests/lib/Theme/ThemeServiceTest.php b/tests/lib/Theme/ThemeServiceTest.php index 8dd9393c4be5..e1c7f5a88570 100644 --- a/tests/lib/Theme/ThemeServiceTest.php +++ b/tests/lib/Theme/ThemeServiceTest.php @@ -10,12 +10,12 @@ class ThemeServiceTest extends \PHPUnit\Framework\TestCase { /** * @var IAppManager | \PHPUnit\Framework\MockObject\MockObject */ - private $appManager; + private \PHPUnit\Framework\MockObject\MockObject $appManager; /** * @var EnvironmentHelper | \PHPUnit\Framework\MockObject\MockObject */ - private $environmentHelper; + private \PHPUnit\Framework\MockObject\MockObject $environmentHelper; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Theme/ThemeTest.php b/tests/lib/Theme/ThemeTest.php index 994755bace3c..ac71928ba7eb 100644 --- a/tests/lib/Theme/ThemeTest.php +++ b/tests/lib/Theme/ThemeTest.php @@ -5,10 +5,7 @@ use OC\Theme\Theme; class ThemeTest extends \PHPUnit\Framework\TestCase { - /** - * @var Theme - */ - private $sut; + private \OC\Theme\Theme $sut; protected function setUp(): void { $this->sut = new Theme(); diff --git a/tests/lib/Traits/MountProviderTrait.php b/tests/lib/Traits/MountProviderTrait.php index b7e2fb16e575..a35edbd82cae 100644 --- a/tests/lib/Traits/MountProviderTrait.php +++ b/tests/lib/Traits/MountProviderTrait.php @@ -41,14 +41,12 @@ protected function registerStorageWrapper($name, $wrapper) { protected function setUpMountProviderTrait() { $this->storageFactory = new StorageFactory(); - $this->mountProvider = $this->createMock('\OCP\Files\Config\IMountProvider'); + $this->mountProvider = $this->createMock('\\' . \OCP\Files\Config\IMountProvider::class); $this->mountProvider->expects($this->any()) ->method('getMountsForUser') ->will($this->returnCallback(function (IUser $user) { if (isset($this->mounts[$user->getUID()])) { - return \array_map(function ($config) { - return new MountPoint($config['storage'], $config['mountPoint'], $config['arguments'], $this->storageFactory); - }, $this->mounts[$user->getUID()]); + return \array_map(fn ($config) => new MountPoint($config['storage'], $config['mountPoint'], $config['arguments'], $this->storageFactory), $this->mounts[$user->getUID()]); } else { return []; } diff --git a/tests/lib/Updater/VersionCheckTest.php b/tests/lib/Updater/VersionCheckTest.php index e2be1444f108..5b0876130158 100644 --- a/tests/lib/Updater/VersionCheckTest.php +++ b/tests/lib/Updater/VersionCheckTest.php @@ -29,20 +29,20 @@ class VersionCheckTest extends TestCase { /** @var IConfig| \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var VersionCheck | \PHPUnit\Framework\MockObject\MockObject*/ - private $updater; + private \PHPUnit\Framework\MockObject\MockObject $updater; public function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder('\OCP\IConfig') + $this->config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); - $clientService = $this->getMockBuilder('\OCP\Http\Client\IClientService') + $clientService = $this->getMockBuilder('\\' . \OCP\Http\Client\IClientService::class) ->disableOriginalConstructor() ->getMock(); - $this->updater = $this->getMockBuilder('\OC\Updater\VersionCheck') + $this->updater = $this->getMockBuilder('\\' . \OC\Updater\VersionCheck::class) ->setMethods(['getUrlContent']) ->setConstructorArgs([$clientService, $this->config]) ->getMock(); diff --git a/tests/lib/UpdaterTest.php b/tests/lib/UpdaterTest.php index c8c5d55b99af..a967ca4f2014 100644 --- a/tests/lib/UpdaterTest.php +++ b/tests/lib/UpdaterTest.php @@ -29,13 +29,12 @@ class UpdaterTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; - /** @var Updater */ - private $updater; + private \PHPUnit\Framework\MockObject\MockObject $logger; + private \OC\Updater $updater; /** @var Checker | \PHPUnit\Framework\MockObject\MockObject */ - private $checker; + private \PHPUnit\Framework\MockObject\MockObject $checker; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/UrlGeneratorTest.php b/tests/lib/UrlGeneratorTest.php index c3456dd315d3..bbb9758e9aaf 100644 --- a/tests/lib/UrlGeneratorTest.php +++ b/tests/lib/UrlGeneratorTest.php @@ -19,12 +19,12 @@ */ class UrlGeneratorTest extends TestCase { /** @var IURLGenerator */ - private $urlGenerator; + private \OC\URLGenerator $urlGenerator; /** @var IRouter | \PHPUnit\Framework\MockObject\MockObject */ - private $router; + private \PHPUnit\Framework\MockObject\MockObject $router; /** @var EnvironmentHelper | \PHPUnit\Framework\MockObject\MockObject */ - private $environmentHelper; + private \PHPUnit\Framework\MockObject\MockObject $environmentHelper; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/User/BackendTestCase.php b/tests/lib/User/BackendTestCase.php index aa96cbe7a550..0c7627faf951 100644 --- a/tests/lib/User/BackendTestCase.php +++ b/tests/lib/User/BackendTestCase.php @@ -110,7 +110,7 @@ public function testSearch() { $this->backend->createUser($name3, 'pass3'); $result = $this->backend->getUsers($prefix); - $this->assertCount(2, $result, \json_encode($result)); + $this->assertCount(2, $result, \json_encode($result, JSON_THROW_ON_ERROR)); $result = $this->backend->getDisplayNames($prefix); $this->assertCount(2, $result); diff --git a/tests/lib/User/BasicAuthModuleTest.php b/tests/lib/User/BasicAuthModuleTest.php index 0602d6cb6502..ca6b0c61379b 100644 --- a/tests/lib/User/BasicAuthModuleTest.php +++ b/tests/lib/User/BasicAuthModuleTest.php @@ -34,19 +34,19 @@ class BasicAuthModuleTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $manager; + private \PHPUnit\Framework\MockObject\MockObject $manager; /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** @var IUser | \PHPUnit\Framework\MockObject\MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var ISession | \PHPUnit\Framework\MockObject\MockObject */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/User/DeletedUserTest.php b/tests/lib/User/DeletedUserTest.php index ade7bc6017da..e257f441cabf 100644 --- a/tests/lib/User/DeletedUserTest.php +++ b/tests/lib/User/DeletedUserTest.php @@ -34,13 +34,12 @@ */ class DeletedUserTest extends TestCase { /** @var Manager */ - private $manager; + private \PHPUnit\Framework\MockObject\MockObject $manager; /** @var IConfig */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var IURLGenerator */ - private $urlGenerator; - /** @var DeletedUser */ - private $deletedUser; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; + private \OC\User\DeletedUser $deletedUser; protected function setUp(): void { $this->manager = $this->createMock(Manager::class); diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php index f636b5dda8f6..6f0a366f0a0e 100644 --- a/tests/lib/User/ManagerTest.php +++ b/tests/lib/User/ManagerTest.php @@ -35,9 +35,9 @@ class ManagerTest extends TestCase { /** @var Manager */ private $manager; /** @var AccountMapper | \PHPUnit\Framework\MockObject\MockObject */ - private $accountMapper; + private \PHPUnit\Framework\MockObject\MockObject $accountMapper; /** @var SyncService | \PHPUnit\Framework\MockObject\MockObject */ - private $syncService; + private \PHPUnit\Framework\MockObject\MockObject $syncService; /** * @var \OCP\Util\UserSearch diff --git a/tests/lib/User/RemoteUserTest.php b/tests/lib/User/RemoteUserTest.php index 31be57a943bd..858691f7a07e 100644 --- a/tests/lib/User/RemoteUserTest.php +++ b/tests/lib/User/RemoteUserTest.php @@ -32,8 +32,7 @@ * @package Test\User */ class RemoteUserTest extends TestCase { - /** @var RemoteUser */ - private $remoteUser; + private \OC\User\RemoteUser $remoteUser; protected function setUp(): void { $user = $this->createMock(IUser::class); diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index ada984c2b99e..1be39e45a87f 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -46,24 +46,24 @@ */ class SessionTest extends TestCase { /** @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; + private \PHPUnit\Framework\MockObject\MockObject $timeFactory; /** @var DefaultTokenProvider | \PHPUnit\Framework\MockObject\MockObject */ protected $tokenProvider; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var IServiceLoader */ - private $serviceLoader; + private \PHPUnit\Framework\MockObject\MockObject $serviceLoader; /** @var \OC\User\SyncService */ protected $userSyncService; /** @var EventDispatcher */ protected $eventDispatcher; - private $rootNode; - private $userNode; + private \PHPUnit\Framework\MockObject\MockObject $rootNode; + private \PHPUnit\Framework\MockObject\MockObject $userNode; protected function setUp(): void { parent::setUp(); @@ -857,9 +857,7 @@ public function testActiveUserAfterSetSession() { $manager->expects($this->any()) ->method('get') - ->will($this->returnCallback(function ($uid) use ($users) { - return $users[$uid]; - })); + ->will($this->returnCallback(fn ($uid) => $users[$uid])); $session = new Memory(''); $session->set('user_id', 'foo'); diff --git a/tests/lib/User/Sync/BackendUsersIteratorTest.php b/tests/lib/User/Sync/BackendUsersIteratorTest.php index 9274b2dfdbd2..4b43eae523c5 100644 --- a/tests/lib/User/Sync/BackendUsersIteratorTest.php +++ b/tests/lib/User/Sync/BackendUsersIteratorTest.php @@ -35,11 +35,11 @@ class BackendUsersIteratorTest extends TestCase { /** * @var UserInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $backend; + private \PHPUnit\Framework\MockObject\MockObject $backend; /** * @var \Iterator */ - private $iterator; + private \OC\User\Sync\BackendUsersIterator $iterator; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/User/Sync/SeenUsersIteratorTest.php b/tests/lib/User/Sync/SeenUsersIteratorTest.php index 0cc5ece51a55..780609706162 100644 --- a/tests/lib/User/Sync/SeenUsersIteratorTest.php +++ b/tests/lib/User/Sync/SeenUsersIteratorTest.php @@ -35,11 +35,11 @@ class SeenUsersIteratorTest extends TestCase { /** * @var AccountMapper|\PHPUnit\Framework\MockObject\MockObject */ - private $mapper; + private \PHPUnit\Framework\MockObject\MockObject $mapper; /** * @var \Iterator */ - private $iterator; + private \OC\User\Sync\SeenUsersIterator $iterator; public const TEST_BACKEND = 'TestBackend'; diff --git a/tests/lib/User/SyncServiceTest.php b/tests/lib/User/SyncServiceTest.php index 6cc4f907f695..73c726cb106e 100644 --- a/tests/lib/User/SyncServiceTest.php +++ b/tests/lib/User/SyncServiceTest.php @@ -48,11 +48,11 @@ interface IUserInterfaceWithUserNameBackendTest extends UserInterface, IProvides class SyncServiceTest extends TestCase { /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; + private \PHPUnit\Framework\MockObject\MockObject $config; /** @var ILogger | \PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private \PHPUnit\Framework\MockObject\MockObject $logger; /** @var AccountMapper | \PHPUnit\Framework\MockObject\MockObject */ - private $mapper; + private \PHPUnit\Framework\MockObject\MockObject $mapper; protected function setUp(): void { parent::setUp(); @@ -115,9 +115,7 @@ public function testSetupNewAccount() { $account->expects($this->any())->method('getUpdatedFields')->willReturn([]); // Then we should try to setup a new account and insert - $this->mapper->expects($this->once())->method('insert')->with($this->callback(function ($arg) use ($backendUids) { - return $arg instanceof Account && $arg->getUserId() === $backendUids[0]; - })); + $this->mapper->expects($this->once())->method('insert')->with($this->callback(fn ($arg) => $arg instanceof Account && $arg->getUserId() === $backendUids[0])); // Ignore state flag @@ -189,9 +187,7 @@ public function testAnalyseExistingUsers() { $s = new SyncService($this->config, $this->logger, $this->mapper); $this->mapper->expects($this->once()) ->method('callForUsers') - ->with($this->callback(function ($param) { - return \is_callable($param); - })); + ->with($this->callback(fn ($param) => \is_callable($param))); $backend = $this->createMock(UserInterface::class); $result = $s->analyzeExistingUsers($backend, function () { }); diff --git a/tests/lib/User/TokenAuthModuleTest.php b/tests/lib/User/TokenAuthModuleTest.php index 380b56d68cb5..adffa3ce7849 100644 --- a/tests/lib/User/TokenAuthModuleTest.php +++ b/tests/lib/User/TokenAuthModuleTest.php @@ -34,15 +34,15 @@ class TokenAuthModuleTest extends TestCase { /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $manager; + private \PHPUnit\Framework\MockObject\MockObject $manager; /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; + private \PHPUnit\Framework\MockObject\MockObject $request; /** @var IUser | \PHPUnit\Framework\MockObject\MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var ISession | \PHPUnit\Framework\MockObject\MockObject */ - private $session; + private \PHPUnit\Framework\MockObject\MockObject $session; /** @var IProvider | \PHPUnit\Framework\MockObject\MockObject */ - private $tokenProvider; + private \PHPUnit\Framework\MockObject\MockObject $tokenProvider; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/User/UserExtendedAttributesEventTest.php b/tests/lib/User/UserExtendedAttributesEventTest.php index 9d06cd821cae..25596447c55a 100644 --- a/tests/lib/User/UserExtendedAttributesEventTest.php +++ b/tests/lib/User/UserExtendedAttributesEventTest.php @@ -27,10 +27,10 @@ class UserExtendedAttributesEventTest extends TestCase { /** @var IUser | \PHPUnit\Framework\MockObject\MockObject */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $user; /** @var UserExtendedAttributesEvent | \PHPUnit\Framework\MockObject\MockObject */ - private $userExtendedAttributesEvent; + private \OCP\User\UserExtendedAttributesEvent $userExtendedAttributesEvent; public function setUp(): void { parent::setUp(); diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php index a91dd3064620..309c57d8139c 100644 --- a/tests/lib/User/UserTest.php +++ b/tests/lib/User/UserTest.php @@ -37,25 +37,22 @@ */ class UserTest extends TestCase { /** @var AccountMapper | \PHPUnit\Framework\MockObject\MockObject */ - private $accountMapper; - /** @var Account */ - private $account; - /** @var User */ - private $user; + private \PHPUnit\Framework\MockObject\MockObject $accountMapper; + private \OC\User\Account $account; + private \OC\User\User $user; /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; - /** @var PublicEmitter */ - private $emitter; + private \PHPUnit\Framework\MockObject\MockObject $config; + private \OC\Hooks\PublicEmitter $emitter; /** @var EventDispatcher | \PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; + private \PHPUnit\Framework\MockObject\MockObject $eventDispatcher; /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + private \PHPUnit\Framework\MockObject\MockObject $urlGenerator; /** @var Manager | \PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; + private \PHPUnit\Framework\MockObject\MockObject $groupManager; /** @var SubAdmin | \PHPUnit\Framework\MockObject\MockObject */ - private $subAdmin; + private \PHPUnit\Framework\MockObject\MockObject $subAdmin; /** @var Session | \PHPUnit\Framework\MockObject\MockObject */ - private $sessionUser; + private \PHPUnit\Framework\MockObject\MockObject $sessionUser; public function setUp(): void { parent::setUp(); @@ -65,12 +62,12 @@ public function setUp(): void { $this->account->setUserId('foo'); $this->emitter = new PublicEmitter(); $this->eventDispatcher = $this->createMock(EventDispatcher::class); - $this->urlGenerator = $this->getMockBuilder('\OC\URLGenerator') + $this->urlGenerator = $this->getMockBuilder('\\' . \OC\URLGenerator::class) ->setMethods(['getAbsoluteURL']) ->disableOriginalConstructor() ->getMock(); - $this->groupManager = $this->createMock('\OC\Group\Manager'); - $this->subAdmin = $this->createMock('\OC\SubAdmin'); + $this->groupManager = $this->createMock('\\' . \OC\Group\Manager::class); + $this->subAdmin = $this->createMock('\\' . \OC\SubAdmin::class); $this->sessionUser = $this->createMock(Session::class); $this->user = new User($this->account, $this->accountMapper, $this->emitter, $this->config, $this->urlGenerator, $this->eventDispatcher); @@ -298,7 +295,7 @@ public function testAdminSubadminCanChangeDisplayName($isAdmin, $isSubAdmin, $ex ->with('allow_user_to_change_display_name') ->willReturn(false); - $user = $this->createMock('\OCP\IUser'); + $user = $this->createMock('\\' . \OCP\IUser::class); $user->method('getUID')->willReturn('admin'); $subAdmin = $this->createMock(SubAdmin::class); @@ -462,9 +459,7 @@ public function testSetDisplayNameNotSupported() { $backend->expects($this->any()) ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - return false; - })); + ->will($this->returnCallback(fn ($actions) => false)); $user = new User($account, $this->accountMapper, null, $this->config); $this->assertFalse($user->setDisplayName('Foo')); diff --git a/tests/lib/Utf8AnalyzerTest.php b/tests/lib/Utf8AnalyzerTest.php index accf7c107983..d4951535fb8d 100644 --- a/tests/lib/Utf8AnalyzerTest.php +++ b/tests/lib/Utf8AnalyzerTest.php @@ -24,8 +24,7 @@ use OC\Utf8Analyzer; class Utf8AnalyzerTest extends \Test\TestCase { - /** @var Utf8Analyzer */ - private $utf8Analyzer; + private \OC\Utf8Analyzer $utf8Analyzer; private $openedStream; diff --git a/tests/lib/Util/Group/Dummy.php b/tests/lib/Util/Group/Dummy.php index 27843d14ba33..ddb4c1e54f29 100644 --- a/tests/lib/Util/Group/Dummy.php +++ b/tests/lib/Util/Group/Dummy.php @@ -35,7 +35,7 @@ * dummy group backend, does not keep state, only for testing use */ class Dummy extends Backend { - private $groups= []; + private array $groups= []; /** * Try to create a new group * @param string $gid The name of the group to create diff --git a/tests/lib/Util/User/Dummy.php b/tests/lib/Util/User/Dummy.php index 6438b7633410..853296571f9a 100644 --- a/tests/lib/Util/User/Dummy.php +++ b/tests/lib/Util/User/Dummy.php @@ -33,8 +33,8 @@ * dummy user backend, does not keep state, only for testing use */ class Dummy extends Backend implements \OCP\IUserBackend { - private $users = []; - private $displayNames = []; + private array $users = []; + private array $displayNames = []; /** * Create a new user @@ -160,7 +160,7 @@ public function setDisplayName($uid, $displayName) { } public function getDisplayName($uid) { - return isset($this->displayNames[$uid])? $this->displayNames[$uid]: $uid; + return $this->displayNames[$uid] ?? $uid; } /** diff --git a/tests/lib/Util/User/MemoryAccountMapper.php b/tests/lib/Util/User/MemoryAccountMapper.php index c2f1e66c7603..e68e291764ea 100644 --- a/tests/lib/Util/User/MemoryAccountMapper.php +++ b/tests/lib/Util/User/MemoryAccountMapper.php @@ -27,8 +27,8 @@ use OCP\AppFramework\Db\Entity; class MemoryAccountMapper extends AccountMapper { - private static $accounts = []; - private static $counter = 1000; + private static array $accounts = []; + private static int $counter = 1000; public $testCaseName = ''; @@ -49,17 +49,13 @@ public function delete(Entity $entity) { } public function getByEmail($email) { - $match = \array_filter(self::$accounts, function (Account $a) use ($email) { - return $a->getEmail() === $email; - }); + $match = \array_filter(self::$accounts, fn (Account $a) => $a->getEmail() === $email); return $match; } public function getByUid($uid) { - $match = \array_filter(self::$accounts, function (Account $a) use ($uid) { - return \strtolower($a->getUserId()) === \strtolower($uid); - }); + $match = \array_filter(self::$accounts, fn (Account $a) => \strtolower($a->getUserId()) === \strtolower($uid)); if (empty($match)) { throw new DoesNotExistException(''); } @@ -75,9 +71,7 @@ public function search($fieldName, $pattern, $limit, $offset) { if ($pattern === '') { return self::$accounts; } - $match = \array_filter(self::$accounts, function (Account $a) use ($pattern) { - return \stripos($a->getUserId(), (string) $pattern); - }); + $match = \array_filter(self::$accounts, fn (Account $a) => \stripos($a->getUserId(), (string) $pattern)); return $match; } diff --git a/tests/lib/UtilCheckServerTest.php b/tests/lib/UtilCheckServerTest.php index 5cf6f5fa0938..bc0ae23d6340 100644 --- a/tests/lib/UtilCheckServerTest.php +++ b/tests/lib/UtilCheckServerTest.php @@ -22,15 +22,13 @@ class UtilCheckServerTest extends TestCase { */ protected function getConfig($systemOptions) { $systemOptions['datadirectory'] = $this->datadir; - $config = $this->getMockBuilder('\OCP\IConfig') + $config = $this->getMockBuilder('\\' . \OCP\IConfig::class) ->disableOriginalConstructor() ->getMock(); $config->expects($this->any()) ->method('getSystemValue') - ->will($this->returnCallback(function ($key, $default) use ($systemOptions) { - return isset($systemOptions[$key]) ? $systemOptions[$key] : $default; - })); + ->will($this->returnCallback(fn ($key, $default) => $systemOptions[$key] ?? $default)); return $config; } diff --git a/tests/lib/UtilTest.php b/tests/lib/UtilTest.php index 32d1c89ee3ff..97f0e7632467 100644 --- a/tests/lib/UtilTest.php +++ b/tests/lib/UtilTest.php @@ -81,11 +81,11 @@ public function testGetEditionString($licenseState, $licenseType, $expectedResul public function testFormatDate() { \date_default_timezone_set("UTC"); - $result = OC_Util::formatDate(1350129205); + $result = OC_Util::formatDate(1_350_129_205); $expected = \sprintf('October 13, 2012, 11:53:25%sAM UTC', self::narrowNoBreakSpace); $this->assertEquals($expected, $result); - $result = OC_Util::formatDate(1102831200, true); + $result = OC_Util::formatDate(1_102_831_200, true); $expected = 'December 12, 2004'; $this->assertEquals($expected, $result); } @@ -93,7 +93,7 @@ public function testFormatDate() { public function testFormatDateWithTZ() { \date_default_timezone_set("UTC"); - $result = OC_Util::formatDate(1350129205, false, 'Europe/Berlin'); + $result = OC_Util::formatDate(1_350_129_205, false, 'Europe/Berlin'); $expected = \sprintf('October 13, 2012, 1:53:25%sPM GMT+2', self::narrowNoBreakSpace); $this->assertEquals($expected, $result); } @@ -103,7 +103,7 @@ public function testFormatDateWithTZ() { public function testFormatDateWithInvalidTZ() { $this->expectException(\Exception::class); - OC_Util::formatDate(1350129205, false, 'Mordor/Barad-dûr'); + OC_Util::formatDate(1_350_129_205, false, 'Mordor/Barad-dûr'); } public function formatDateWithTZFromSessionData() { @@ -127,21 +127,19 @@ public function testFormatDateWithTZFromSession($offset, $expected, $expectedTim $oldDateTimeFormatter = \OC::$server->query('DateTimeFormatter'); \OC::$server->getSession()->set('timezone', $offset); - $selectedTimeZone = \OC::$server->getDateTimeZone()->getTimeZone(1350129205); + $selectedTimeZone = \OC::$server->getDateTimeZone()->getTimeZone(1_350_129_205); $this->assertEquals($expectedTimeZone, $selectedTimeZone->getName()); $newDateTimeFormatter = new \OC\DateTimeFormatter($selectedTimeZone, \OC::$server->getL10NFactory()->get('lib', 'en')); $this->setDateFormatter($newDateTimeFormatter); - $result = OC_Util::formatDate(1350129205, false); + $result = OC_Util::formatDate(1_350_129_205, false); $this->assertEquals($expected, $result); $this->setDateFormatter($oldDateTimeFormatter); } protected function setDateFormatter($formatter) { - \OC::$server->registerService('DateTimeFormatter', function ($c) use ($formatter) { - return $formatter; - }); + \OC::$server->registerService('DateTimeFormatter', fn ($c) => $formatter); } public function testSanitizeHTML() { @@ -306,9 +304,7 @@ public function testDefaultApps($defaultAppConfig, $expectedPath, $enabledApps) $appManager = $this->createMock(IAppManager::class); $appManager->expects($this->any()) ->method('isEnabledForUser') - ->will($this->returnCallback(function ($appId) use ($enabledApps) { - return \in_array($appId, $enabledApps, true); - })); + ->will($this->returnCallback(fn ($appId) => \in_array($appId, $enabledApps, true))); Dummy_OC_Util::$appManager = $appManager; // need to set a user id to make sure enabled apps are read from cache