From 91a54643b5a34f81da6c754129f535a39c898f1a Mon Sep 17 00:00:00 2001 From: Fabian Schmid Date: Mon, 3 Feb 2025 17:19:07 +0100 Subject: [PATCH] General Code Update --- .../ILIAS/ActiveRecord/ActiveRecord.php | 4 +- .../Cache/class.arObjectCache.php | 2 +- .../Connector/Join/class.arJoinCollection.php | 1 + .../Select/class.arSelectCollection.php | 2 +- .../Connector/class.arConnectorCache.php | 12 +- .../Exception/class.arException.php | 2 +- .../ActiveRecord/Fields/class.arField.php | 1 + .../ActiveRecord/Fields/class.arFieldList.php | 6 +- .../ILIAS/ActiveRecord/class.ActiveRecord.php | 25 +- .../ActiveRecord/class.ActiveRecordList.php | 6 +- .../ActiveRecord/class.CachedActiveRecord.php | 4 + .../ilServicesActiveRecordConnectorTest.php | 7 +- .../tests/ilServicesActiveRecordFieldTest.php | 7 +- .../AdministrativeNotification.php | 10 +- .../classes/DataRetrieval.php | 18 +- .../classes/GlobalScreen/ADNProvider.php | 36 +- .../classes/Setup/class.ilADNAgent.php | 32 +- .../classes/Table.php | 6 +- .../classes/class.ilADNAbstractGUI.php | 12 +- .../classes/class.ilADNDismiss.php | 9 +- .../classes/class.ilADNNotification.php | 23 +- .../class.ilADNNotificationUIFormGUI.php | 15 +- .../classes/class.ilADNTabHandling.php | 8 +- .../class.ilObjAdministrativeNotification.php | 2 + ...ass.ilObjAdministrativeNotificationGUI.php | 1 + ...ServicesAdministrativeNotificationTest.php | 7 +- .../ILIAS/AuthShibboleth/AuthShibboleth.php | 14 +- .../Config/class.ilShibbolethSettings.php | 28 +- .../Config/class.ilShibbolethSettingsForm.php | 10 +- .../ServerData/class.shibServerData.php | 3 +- .../classes/User/class.shibUser.php | 9 +- .../class.ilAuthProviderShibboleth.php | 4 +- .../class.ilAuthShibbolethSettingsGUI.php | 11 +- ...class.ilShibbolethAuthenticationPlugin.php | 4 +- .../class.ilShibbolethRoleAssignmentRule.php | 37 +- .../class.ilShibbolethRoleAssignmentRules.php | 2 +- ...ass.ilShibbolethRoleAssignmentTableGUI.php | 1 + .../classes/class.ilShibbolethWAYF.php | 8 +- .../AuthShibboleth/resources/shib_logout.php | 27 +- .../tests/ilServicesAuthShibbolethTest.php | 2 +- .../ILIAS/BackgroundTasks/BackgroundTasks.php | 10 +- .../src/BackgroundTaskServices.php | 5 +- .../DependencyMap/BaseDependencyMap.php | 10 +- .../DependencyMap/EmptyDependencyMap.php | 3 +- .../src/Dependencies/Injector.php | 10 +- .../src/Implementation/Bucket/BasicBucket.php | 8 +- .../Persistence/BasicPersistence.php | 26 +- .../TaskManager/AsyncTaskManager.php | 18 +- .../TaskManager/BasicTaskManager.php | 13 +- .../TaskManager/NonPersistingObserver.php | 5 +- .../TaskManager/PersistingObserver.php | 7 +- .../TaskManager/SyncTaskManager.php | 9 +- .../src/Implementation/Tasks/AbstractJob.php | 1 + .../src/Implementation/Tasks/AbstractTask.php | 8 +- .../Tasks/Aggregation/ConcatenationJob.php | 4 +- .../Implementation/Tasks/BasicTaskFactory.php | 8 +- .../Implementation/Tasks/DownloadInteger.php | 2 +- .../Tasks/NotFoundUserInteraction.php | 1 - .../UserInteraction/UserInteractionOption.php | 7 +- .../Values/AggregationValues/ListValue.php | 7 +- .../Values/ScalarValues/BooleanValue.php | 3 +- .../Values/ScalarValues/FloatValue.php | 3 +- .../Values/ScalarValues/IntegerValue.php | 2 +- .../Values/ScalarValues/ScalarValue.php | 2 +- .../Values/ScalarValues/StringValue.php | 2 +- .../src/Implementation/Values/ThunkValue.php | 1 + .../ILIAS/BackgroundTasks/src/Task/Job.php | 2 +- .../BackgroundTasks/src/Task/TaskFactory.php | 1 - .../src/Task/UserInteraction.php | 2 +- .../BackgroundTasks/src/Types/ListType.php | 4 +- .../BackgroundTasks/src/Types/SingleType.php | 6 +- .../BackgroundTasks/src/Types/TupleType.php | 2 +- .../tests/BasicPersistenceTestTBD.php | 36 +- .../Observer/BasicObserverTestTBD.php | 3 +- .../Tasks/BasicTaskFactoryTest.php | 3 +- .../BackgroundTasks/tests/TaskTestTBD.php | 42 +- .../ILIAS/BackgroundTasks/tests/ValueTest.php | 16 +- .../BackgroundTasks_/BackgroundTasks_.php | 10 +- .../classes/Jobs/class.ilCollectFilesJob.php | 21 +- .../class.ilCopyFilesToTempDirectoryJob.php | 4 +- .../classes/Jobs/class.ilZipJob.php | 8 +- ...ilBackgroundTasksConfigStoredObjective.php | 39 +- .../Setup/class.ilBackgroundTasksDB80.php | 3 - ...ckgroundTasksMetricsCollectedObjective.php | 12 +- .../class.ilBackgroundTasksSetupAgent.php | 41 +- .../class.ilBackgroundTasksSetupConfig.php | 5 +- .../classes/StateTranslator.php | 21 +- .../class.ilDownloadZipInteraction.php | 6 +- ...ss.ilSumOfFileSizesTooLargeInteraction.php | 27 +- .../classes/class.ilBTControllerGUI.php | 4 +- .../classes/class.ilBTPopOverGUI.php | 21 +- .../classes/class.ilCopyDefinition.php | 6 +- ...ss.ilSoapBackgroundTasksAdministration.php | 1 - .../ILIAS/Bibliographic/Bibliographic.php | 10 +- .../Admin/Library/class.ilBiblLibrary.php | 1 + .../Library/class.ilBiblLibraryFormGUI.php | 15 +- .../Admin/Library/class.ilBiblLibraryGUI.php | 22 +- .../class.ilBiblLibraryPresentationGUI.php | 30 +- .../Library/class.ilBiblLibraryTableGUI.php | 16 +- .../Attribute/class.ilBiblAttribute.php | 1 + .../class.ilBiblAttributeFactory.php | 4 +- .../classes/Data/class.ilBiblData.php | 4 +- .../classes/Entry/class.ilBiblEntry.php | 1 + ...class.ilBiblEntryDetailPresentationGUI.php | 7 +- .../Entry/class.ilBiblEntryFactory.php | 27 +- .../Entry/class.ilBiblEntryTableGUI.php | 6 +- .../class.ilBiblEntryTablePresentationGUI.php | 10 +- .../classes/Field/DataRetrieval.php | 6 +- .../Bibliographic/classes/Field/Table.php | 10 +- .../Field/class.ilBiblAdminFieldGUI.php | 15 +- .../classes/Field/class.ilBiblField.php | 3 +- .../Field/class.ilBiblFieldFactory.php | 22 +- .../classes/FieldFilter/DataRetrieval.php | 6 +- .../classes/FieldFilter/Table.php | 6 +- .../FieldFilter/class.ilBiblFieldFilter.php | 1 + .../class.ilBiblFieldFilterFormGUI.php | 17 +- .../class.ilBiblFieldFilterGUI.php | 17 +- ...class.ilBiblFieldFilterPresentationGUI.php | 9 +- .../BibTex/class.ilBiblTexFileReader.php | 27 +- .../Ris/class.ilBiblRisFileReaderWrapper.php | 2 - .../FileReader/class.ilBiblFileReaderBase.php | 25 +- .../class.ilBiblFileReaderFactory.php | 13 +- .../class.ilBiblOverviewModel.php | 1 + .../class.ilBiblOverviewModelFactory.php | 2 +- .../Setup/class.ilBibliographicSetupAgent.php | 28 +- .../Translation/class.ilBiblTranslation.php | 1 + .../class.ilBiblTranslationFactory.php | 10 +- .../class.ilBiblTranslationGUI.php | 15 +- .../class.ilBiblTranslationTableGUI.php | 13 +- .../classes/Types/BibTex/class.ilBibTex.php | 8 +- .../classes/Types/Ris/class.ilRis.php | 8 +- .../classes/Types/class.ilBiblTypeFactory.php | 43 +- .../classes/class.ilBibliographicDataSet.php | 7 + .../classes/class.ilBibliographicExporter.php | 1 + .../classes/class.ilObjBibliographic.php | 33 +- .../class.ilObjBibliographicAccess.php | 21 +- .../class.ilObjBibliographicAdminGUI.php | 13 +- .../classes/class.ilObjBibliographicGUI.php | 43 +- .../class.ilObjBibliographicListGUI.php | 8 +- ...ass.ilObjBibliographicUploadHandlerGUI.php | 1 + .../trait.ilBibliographicSecureString.php | 2 +- .../tests/ilBibtechParserTest.php | 2 +- .../tests/ilRisParserTestTBD.php | 2 +- components/ILIAS/Cache/Cache.php | 4 +- components/ILIAS/Cache/src/Adaptor/APCu.php | 2 +- .../ILIAS/Cache/src/Adaptor/Memcached.php | 7 +- components/ILIAS/Cache/src/Config.php | 1 - .../Cache/src/Container/ActiveContainer.php | 54 +- .../ILIAS/Cache/src/Container/Container.php | 3 - .../Cache/src/Container/VoidContainer.php | 3 - components/ILIAS/Cache/src/Services.php | 1 - components/ILIAS/Cache/tests/CacheTest.php | 20 +- components/ILIAS/Database/Database.php | 10 +- .../classes/Atom/class.ilAtomQueryBase.php | 40 +- .../classes/Atom/class.ilAtomQueryLock.php | 8 +- .../classes/Atom/class.ilTableLock.php | 6 +- .../Database/classes/Integrity/Definition.php | 7 +- .../Database/classes/Integrity/Field.php | 6 + .../Database/classes/Integrity/Ignore.php | 10 +- .../class.ilDBPdoFieldDefinition.php | 68 +- .../class.ilDBPdoMySQLFieldDefinition.php | 32 +- .../PDO/Manager/class.ilDBPdoManager.php | 35 +- .../PDO/Reverse/class.ilDBPdoReverse.php | 36 +- .../Database/classes/PDO/class.ilDBPdo.php | 167 +- .../classes/PDO/class.ilDBPdoMySQL.php | 17 +- .../classes/PDO/class.ilDBPdoMySQLGalera.php | 2 + .../classes/PDO/class.ilDBPdoMySQLInnoDB.php | 3 + .../classes/PDO/class.ilPDOStatement.php | 10 +- .../QueryUtils/class.ilMySQLQueryUtils.php | 30 +- .../classes/QueryUtils/class.ilQueryUtils.php | 5 +- .../classes/Setup/MysqlIfsnopDumper.php | 11 +- .../Setup/class.ilDBStepExecutionDB.php | 7 +- ...ass.ilDBStepExecutionDBExistsObjective.php | 16 +- .../class.ilDBStepReaderExistsObjective.php | 11 +- .../class.ilDatabaseConfigStoredObjective.php | 43 +- .../class.ilDatabaseCreatedObjective.php | 11 +- ...s.ilDatabaseDumpedToDirectoryObjective.php | 20 +- ...ss.ilDatabaseEnvironmentValidObjective.php | 36 +- .../Setup/class.ilDatabaseExistsObjective.php | 13 +- .../class.ilDatabaseInitializedObjective.php | 22 +- ...ss.ilDatabaseMetricsCollectedObjective.php | 24 +- .../Setup/class.ilDatabaseObjective.php | 9 +- .../class.ilDatabasePopulatedObjective.php | 36 +- .../class.ilDatabaseResetStepsObjective.php | 6 + ...ilDatabaseServerIsConnectableObjective.php | 11 +- .../Setup/class.ilDatabaseSetupConfig.php | 27 +- ...ilDatabaseUpdateStepsExecutedObjective.php | 11 +- ...seUpdateStepsMetricsCollectedObjective.php | 13 +- .../class.ilDatabaseUpdatedObjective.php | 44 +- .../class.ilMysqlMyIsamToInnoDbMigration.php | 1 - .../Database/classes/class.ilBenchmark.php | 5 +- .../Database/classes/class.ilDBAnalyzer.php | 38 +- .../Database/classes/class.ilDBConstants.php | 14 +- .../Database/classes/class.ilDBGenerator.php | 57 +- .../Database/classes/class.ilDBUpdate.php | 30 +- .../classes/class.ilDBWrapperFactory.php | 16 +- .../exception.ilAtomQueryException.php | 1 + .../ILIAS/Database/tests/Integrity/Suite.php | 2 +- .../tests/Setup/ilDBStepExecutionDBTest.php | 21 +- .../tests/Setup/ilDBStepReaderTest.php | 4 + ...tabaseUpdateStepsExecutedObjectiveTest.php | 6 +- components/ILIAS/File/File.php | 10 +- .../Capabilities/CapabilityCollection.php | 2 - .../classes/Capabilities/Check/ForcedInfo.php | 2 + .../classes/Icons/IconAbstractRepository.php | 6 +- .../classes/Icons/IconDatabaseRepository.php | 12 +- .../ILIAS/File/classes/Icons/IconFormUI.php | 38 +- .../File/classes/Icons/IconListingUI.php | 11 +- .../Icons/class.ilIconUploadHandlerGUI.php | 7 +- .../class.ilObjFileDefaultIconsObjective.php | 9 +- .../Icons/class.ilObjFileIconsOverviewGUI.php | 19 +- .../class.ilObjFileImplementationStorage.php | 18 +- .../File/classes/Info/class.ilObjFileInfo.php | 48 +- .../FileObjectPropertyProviders.php | 6 +- .../FirstPageToTileImageFlavourDefintion.php | 3 + .../FirstPageToTileImageFlavourMachine.php | 3 + .../class.ilFileCommonSettingsGUI.php | 42 +- .../class.ilCountPDFPagesPreProcessors.php | 2 +- .../ILIAS/File/classes/Preview/Form.php | 3 +- .../ILIAS/File/classes/Preview/Settings.php | 27 + .../ILIAS/File/classes/Settings/Form.php | 3 +- .../ILIAS/File/classes/Settings/General.php | 7 +- .../class.ilFileObjectRBACDatabase.php | 8 +- .../classes/Setup/class.ilFileObjectAgent.php | 39 +- ...s.ilFileObjectSettingsUpdatedObjective.php | 10 +- .../Versions/class.ilFileVersionFormGUI.php | 29 +- .../Versions/class.ilFileVersionsGUI.php | 25 +- .../Versions/class.ilFileVersionsTableGUI.php | 8 +- .../class.ilFileVersionsUploadHandlerGUI.php | 3 + .../File/classes/class.ilFileExporter.php | 3 +- .../classes/class.ilFileKioskModeView.php | 3 + .../ILIAS/File/classes/class.ilFileLP.php | 3 + .../classes/class.ilFileNewsRendererGUI.php | 1 + .../classes/class.ilFileStaticURLHandler.php | 1 - .../File/classes/class.ilFileXMLParser.php | 16 +- .../File/classes/class.ilFileXMLWriter.php | 2 +- .../ILIAS/File/classes/class.ilObjFile.php | 5 +- .../File/classes/class.ilObjFileAccess.php | 6 +- .../class.ilObjFileAccessSettingsGUI.php | 20 +- .../class.ilObjFileComponentBuilder.php | 3 +- .../ILIAS/File/classes/class.ilObjFileGUI.php | 24 +- .../File/classes/class.ilObjFileListGUI.php | 10 +- .../classes/class.ilObjFileStakeholder.php | 2 + .../classes/class.ilObjFileUploadDropzone.php | 12 +- .../class.ilObjFileUploadHandlerGUI.php | 11 +- .../classes/trait.ilObjFileCopyrightInput.php | 1 - .../File/classes/trait.ilObjFileMetadata.php | 2 +- .../classes/trait.ilObjFileSecureString.php | 12 +- .../classes/trait.ilObjFileTransformation.php | 4 +- .../File/classes/trait.ilObjFileUsages.php | 8 +- .../ILIAS/File/tests/ilModulesFileTest.php | 28 +- .../ILIAS/FileDelivery/FileDelivery.php | 16 +- .../ILIAS/FileDelivery/classes/Delivery.php | 41 +- .../FileDeliveryTypeFactory.php | 31 +- .../classes/FileDeliveryTypes/PHP.php | 12 +- .../classes/FileDeliveryTypes/PHPChunked.php | 12 +- .../classes/FileDeliveryTypes/XAccel.php | 17 +- .../classes/FileDeliveryTypes/XSendfile.php | 13 +- .../FileDelivery/classes/HttpServiceAware.php | 2 - .../classes/class.ilFileDelivery.php | 21 + .../classes/class.ilSecureTokenSrcBuilder.php | 3 - .../src/Delivery/BaseDelivery.php | 6 +- .../src/Delivery/LegacyDelivery.php | 1 - .../ResponseBuilder/XAccelResponseBuilder.php | 9 + .../XSendFileResponseBuilder.php | 3 + .../src/Delivery/StreamDelivery.php | 15 +- components/ILIAS/FileDelivery/src/Init.php | 41 +- .../ILIAS/FileDelivery/src/Services.php | 5 +- .../ILIAS/FileDelivery/src/Setup/Agent.php | 10 +- .../src/Setup/BaseDirObjective.php | 16 +- .../src/Setup/DeliveryMethodObjective.php | 24 +- .../src/Setup/KeyRotationObjective.php | 10 +- .../Token/Compression/DeflateCompression.php | 3 + .../FileDelivery/src/Token/DataSigner.php | 6 +- .../ILIAS/FileDelivery/src/Token/Request.php | 1 - .../src/Token/Signer/HMACSigner.php | 7 +- .../Token/Signer/Payload/ShortFilePayload.php | 5 +- .../src/Token/Signer/Salt/Factory.php | 4 +- .../src/Token/SigningSerializer.php | 6 +- .../src/artifacts/delivery_method.php | 7 +- .../FileDeliveryTypeFactoryTest.php | 35 +- .../tests/FileDeliveryTypes/XAccelTest.php | 29 +- .../tests/FileDeliveryTypes/XSendfileTest.php | 21 +- .../FileDelivery/tests/Token/TokenTest.php | 8 +- .../ILIAS/FileServices/FileServices.php | 21 +- .../Setup/class.ilFileServicesSetupAgent.php | 8 +- .../class.ilFileServicesPolicy.php | 12 +- .../UploadLimits/UploadPolicyFormUI.php | 15 +- .../class.ilCtrlAwareStorageUploadHandler.php | 12 +- .../class.ilFileServicesPreProcessor.php | 11 +- .../classes/class.ilFileServicesSettings.php | 15 +- .../classes/class.ilObjFileServices.php | 2 + .../classes/class.ilObjFileServicesGUI.php | 11 +- .../tests/UploadPolicyResolverTest.php | 2 - .../tests/ilServicesFileServicesTest.php | 20 +- components/ILIAS/FileUpload/FileUpload.php | 4 +- .../src/Collection/ImmutableMapWrapper.php | 6 +- .../FileUpload/src/DTO/ProcessingStatus.php | 12 +- .../ILIAS/FileUpload/src/DTO/UploadResult.php | 6 +- .../ILIAS/FileUpload/src/FileUploadImpl.php | 45 +- .../AbstractCtrlAwareIRSSUploadHandler.php | 13 +- .../src/Handler/BasicFileInfoResult.php | 20 +- .../src/Handler/BasicHandlerResult.php | 18 +- components/ILIAS/FileUpload/src/MimeType.php | 5 +- .../AbstractRecursiveZipPreProcessor.php | 2 +- .../BlacklistExtensionPreProcessor.php | 10 +- .../BlacklistFileHeaderPreProcessor.php | 1 - .../BlacklistMimeTypePreProcessor.php | 1 - .../FilenameSanitizerPreProcessor.php | 2 +- .../InsecureFilenameSanitizerPreProcessor.php | 2 +- .../src/Processor/IsMimeTypeOrExtension.php | 8 +- .../FileUpload/src/Processor/PreProcessor.php | 1 - .../src/Processor/PreProcessorManager.php | 1 - .../src/Processor/PreProcessorManagerImpl.php | 3 +- .../Processor/SVGBlacklistPreProcessor.php | 30 +- .../Processor/SVGWhitelistPreProcessor.php | 14 +- .../WhitelistExtensionPreProcessor.php | 10 +- .../WhitelistFileHeaderPreProcessor.php | 1 - .../WhitelistMimeTypePreProcessor.php | 1 - .../ILIAS/FileUpload/src/mime_type_map.php | 1464 +++++++++-------- .../Collection/EntryLockingStringMapTest.php | 40 +- .../tests/FileUploadImplTestTBD.php | 74 +- .../BlacklistExtensionPreProcessorTest.php | 34 +- .../BlacklistFileHeaderPreProcessorTest.php | 32 +- .../BlacklistMimeTypePreProcessorTestTBD.php | 48 +- .../FilenameOverridePreProcessorTest.php | 24 +- .../PreProcessorManagerImplTestTBD.php | 53 +- .../tests/Processor/SVGPreProcessorTest.php | 12 +- .../WhitelistExtensionPreProcessorTest.php | 40 +- .../WhitelistFileHeaderPreProcessorTest.php | 32 +- .../WhitelistMimeTypePreProcessorTestTBD.php | 48 +- components/ILIAS/Filesystem/Filesystem.php | 10 +- ...eSystemClientDirectoryRenamedObjective.php | 21 +- ...ComponentDataDirectoryCreatedObjective.php | 39 +- ....ilFileSystemConfigNotChangedObjective.php | 26 +- ...lFileSystemDirectoriesCreatedObjective.php | 47 +- ...temDirectoryCopiedRecursivelyObjective.php | 32 +- ....ilFileSystemMetricsCollectedObjective.php | 11 +- .../Setup/class.ilFileSystemSetupAgent.php | 40 +- .../Setup/class.ilFileSystemSetupConfig.php | 6 +- .../ILIAS/Filesystem/classes/class.ilFile.php | 4 +- .../Filesystem/classes/class.ilFileData.php | 6 +- .../classes/class.ilFileDataImport.php | 1 + .../class.ilFileSystemAbstractionStorage.php | 27 +- .../class.ilFileSystemCleanTempDirCron.php | 6 +- .../classes/class.ilFileSystemGUI.php | 168 +- .../classes/class.ilFileSystemTableGUI.php | 79 +- .../classes/class.ilUploadFiles.php | 19 +- .../src/Definitions/SuffixDefinitions.php | 7 +- .../ILIAS/Filesystem/src/Finder/Finder.php | 54 +- .../Iterator/FileTypeFilterIterator.php | 9 +- .../Iterator/RecursiveDirectoryIterator.php | 4 +- .../Provider/Configuration/LocalConfig.php | 2 + .../FlySystem/FlySystemDirectoryAccess.php | 9 +- .../FlySystem/FlySystemFileAccess.php | 4 +- .../FlySystem/FlySystemFileStreamAccess.php | 2 - .../FlySystemLocalFilesystemFactory.php | 18 +- .../src/Provider/FlySystem/Util.php | 4 +- .../ILIAS/Filesystem/src/Stream/Stream.php | 2 +- .../Filesystem/src/Stream/StreamOptions.php | 3 + .../ILIAS/Filesystem/src/Stream/Streams.php | 8 +- .../ILIAS/Filesystem/src/Stream/ZIPStream.php | 3 +- components/ILIAS/Filesystem/src/Util.php | 20 +- .../Filesystem/src/Util/Archive/Archives.php | 1 - .../src/Util/Archive/LegacyArchives.php | 2 - .../src/Util/Archive/PathHelper.php | 23 +- .../ILIAS/Filesystem/src/Util/Archive/Zip.php | 2 +- .../src/Util/Archive/ZipDirectoryHandling.php | 4 - .../src/Util/Convert/Converters.php | 3 - .../Filesystem/src/Util/Convert/Images.php | 1 - .../src/Util/Convert/LegacyImages.php | 3 +- .../Filesystem/tests/Finder/FinderTest.php | 91 +- .../FlySystemDirectoryAccessTestTBD.php | 111 +- .../FlySystem/FlySystemFileAccessTestTBD.php | 163 +- .../FlySystemFileStreamAccessTestTBD.php | 102 +- ...FlySystemLocalFilesystemFactoryTestTBD.php | 24 +- .../Filesystem/tests/Stream/StreamTestTBD.php | 143 +- .../Util/Convert/ImageConversionTest.php | 30 +- .../Convert/LegacyImageConversionTest.php | 9 +- .../tests/Util/FilenameSanitizing.php | 5 +- .../tests/Util/LegacyPathHelperTestTBD.php | 66 +- .../Filesystem/tests/Util/LegacyZipTest.php | 26 +- .../ILIAS/Filesystem/tests/Util/UnzipTest.php | 20 +- .../ILIAS/Filesystem/tests/Util/ZipTest.php | 18 +- .../tests/ilServicesFileSystemTest.php | 3 +- components/ILIAS/GlobalCache/GlobalCache.php | 10 +- .../Setup/ilGlobalCacheSetupAgentTest.php | 3 +- .../ILIAS/GlobalCache_/GlobalCache_.php | 4 +- ...class.ilGlobalCacheAllFlushedObjective.php | 2 - ...ass.ilGlobalCacheConfigStoredObjective.php | 26 +- ...ilGlobalCacheMetricsCollectedObjective.php | 1 - .../Setup/class.ilGlobalCacheSetupAgent.php | 41 +- .../ILIAS/GlobalScreen/GlobalScreen.php | 29 +- .../GlobalScreen/resources/gs_content.php | 2 +- .../src/Client/CallbackHandler.php | 7 +- .../ILIAS/GlobalScreen/src/Client/Client.php | 6 +- .../GlobalScreen/src/Client/ItemState.php | 7 +- .../GlobalScreen/src/Client/ModeToggle.php | 6 +- .../GlobalScreen/src/Client/Notifications.php | 3 +- .../src/Collector/Map/AbstractMap.php | 6 - .../Renderer/DecoratorApplierTrait.php | 3 - .../Identification/AbstractIdentification.php | 12 +- .../AbstractIdentificationProvider.php | 12 +- .../Identification/IdentificationFactory.php | 5 +- .../src/Identification/LostIdentification.php | 5 +- .../src/Identification/NullIdentification.php | 5 +- .../NullPluginIdentification.php | 9 +- .../Identification/PluginIdentification.php | 7 +- .../PluginIdentificationProvider.php | 6 +- .../Serializer/CoreSerializer.php | 3 +- .../Serializer/PluginSerializer.php | 4 +- .../ToolIdentificationProvider.php | 2 + .../src/Provider/NullProviderFactory.php | 1 - .../src/Scope/ComponentDecoratorTrait.php | 2 - .../src/Scope/Footer/Collector/Map.php | 3 + .../Layout/Builder/DecoratedPageBuilder.php | 8 +- .../Layout/Collector/MainLayoutCollector.php | 12 +- .../Factory/AbstractLayoutModification.php | 4 +- .../Factory/BreadCrumbsModification.php | 2 + .../Layout/Factory/ContentModification.php | 2 + .../Layout/Factory/FooterModification.php | 2 + .../Layout/Factory/InvalidModification.php | 4 +- .../Scope/Layout/Factory/LogoModification.php | 2 + .../Layout/Factory/MainBarModification.php | 2 + .../Layout/Factory/MetaBarModification.php | 2 + .../Scope/Layout/Factory/NullModification.php | 2 + .../Factory/PageBuilderModification.php | 2 + .../Layout/Factory/TitleModification.php | 2 + .../src/Scope/Layout/LayoutServices.php | 1 - .../MetaContent/Media/CssCollection.php | 2 - .../Layout/MetaContent/Media/JsCollection.php | 1 + .../Layout/MetaContent/Media/OnLoadCode.php | 1 + .../src/Scope/Layout/ModificationHandler.php | 15 +- .../Provider/AbstractModificationProvider.php | 3 +- .../AbstractOriginalPagePartProvider.php | 6 +- .../PagePart/StandardPagePartProvider.php | 4 - .../Information/NullItemInformation.php | 2 +- .../Collector/Information/TypeInformation.php | 5 +- .../Collector/MainMenuMainCollector.php | 2 - .../src/Scope/MainMenu/Collector/Map/Map.php | 4 +- .../Collector/Renderer/BaseTypeRenderer.php | 1 - .../Renderer/ComplexItemRenderer.php | 3 +- .../Collector/Renderer/LinkItemRenderer.php | 2 + .../Renderer/LinkListItemRenderer.php | 4 +- .../Collector/Renderer/LostItemRenderer.php | 2 + .../Renderer/RepositoryLinkItemRenderer.php | 1 + .../Renderer/SeparatorItemRenderer.php | 4 +- .../Renderer/TopLinkItemRenderer.php | 2 + .../TopParentItemDrilldownRenderer.php | 3 +- .../Renderer/TopParentItemRenderer.php | 1 + .../MainMenu/Factory/AbstractBaseItem.php | 1 - .../MainMenu/Factory/AbstractParentItem.php | 7 +- .../src/Scope/MainMenu/Factory/Item/Link.php | 2 - .../src/Scope/MainMenu/Factory/Item/Lost.php | 2 - .../MainMenu/Factory/Item/RepositoryLink.php | 2 - .../MainMenu/Factory/TopItem/TopLinkItem.php | 2 - .../Factory/TopItem/TopParentItem.php | 2 - .../Factory/isInterchangeableItemTrait.php | 6 +- .../src/Scope/MetaBar/Collector/Map.php | 4 +- .../Collector/MetaBarMainCollector.php | 1 - .../Collector/Renderer/LinkItemRenderer.php | 3 +- .../Renderer/NotificationCenterRenderer.php | 24 +- .../Renderer/TopLegacyItemRenderer.php | 1 - .../Renderer/TopLinkItemRenderer.php | 1 - .../Renderer/TopParentItemRenderer.php | 2 - .../MetaBar/Factory/AbstractBaseItem.php | 1 - .../MetaBar/Factory/NotificationCenter.php | 1 + .../src/Scope/MetaBar/Factory/hasSymbol.php | 1 - .../Collector/MainNotificationCollector.php | 31 +- .../AbstractBaseNotificationRenderer.php | 8 +- .../AdministrativeNotificationRenderer.php | 5 +- .../StandardNotificationGroupRenderer.php | 4 +- .../Renderer/StandardNotificationRenderer.php | 7 +- .../Factory/AbstractBaseNotification.php | 10 +- .../Factory/AdministrativeNotification.php | 4 +- .../Factory/StandardNotificationGroup.php | 2 + .../Notification/NotificationServices.php | 1 - .../Renderer/StandardToastRenderer.php | 25 +- .../Renderer/StandardToastRendererFactory.php | 6 +- .../Scope/Toast/Collector/ToastCollector.php | 8 +- .../Scope/Toast/Factory/StandardToastItem.php | 34 +- .../src/Scope/Toast/Factory/ToastAction.php | 9 +- .../src/Scope/Toast/Factory/ToastFactory.php | 5 +- .../Toast/Provider/AbstractToastProvider.php | 8 +- .../src/Scope/Toast/ToastServices.php | 4 +- .../Tool/Collector/MainToolCollector.php | 27 +- .../Collector/Renderer/ToolItemRenderer.php | 2 +- .../Renderer/TreeToolItemRenderer.php | 3 +- .../src/Scope/Tool/ToolServices.php | 1 - .../GlobalScreen/src/Scope/isDecorateable.php | 1 - .../src/ScreenContext/BasicScreenContext.php | 4 +- .../src/ScreenContext/ContextRepository.php | 18 +- .../ScreenContext/Stack/CalledContexts.php | 3 +- .../ScreenContext/Stack/ContextCollection.php | 12 +- .../IdentificationFactoryTestTBD.php | 18 +- .../Identification/IdentificationTestTBD.php | 13 +- .../tests/MainMenu/CollectorTestTBD.php | 11 +- .../GlobalScreen/tests/MainMenu/MapTest.php | 12 +- .../Notification/BaseNotificationSetUpTBD.php | 9 +- .../StandardNotificationRendererTestTBD.php | 1 + .../Factory/GroupNotificationTestTBD.php | 4 +- .../Factory/StandardNotificationTestTBD.php | 12 +- .../tests/Scope/Layout/MetaDataTest.php | 17 +- .../tests/Toast/BaseToastSetUp.php | 16 +- .../Toast/Collector/ToastCollectorTest.php | 1 - .../tests/Toast/StandardToastTest.php | 20 +- .../tests/Toast/ToastServicesTest.php | 3 +- .../BasicAccessCheckClosuresSingleton.php | 6 - .../Setup/class.ilGlobalScreenSetupAgent.php | 30 +- .../Entries/class.ilFooterEntriesGUI.php | 24 + .../Footer/Groups/class.ilFooterGroupsGUI.php | 31 +- .../Translation/TranslationWorkflowForm.php | 9 + .../Translation/TranslationsRepositoryDB.php | 3 + .../class.ilFooterTranslationGUI.php | 15 + .../class.ilFooterCustomGroupsProvider.php | 1 + .../class.ilFooterStandardGroupsProvider.php | 1 + .../class.ilObjFooterAdministrationGUI.php | 12 + .../GlobalScreen_/classes/UI/Translator.php | 3 + .../GlobalScreen_/classes/UI/UIHelper.php | 1 - components/ILIAS/HTTP/HTTP.php | 4 +- .../HTTP/src/Agent/AgentDetermination.php | 50 +- .../HTTP/src/Cookies/CookieJarWrapper.php | 8 +- .../ILIAS/HTTP/src/Cookies/CookieWrapper.php | 5 +- .../HTTP/src/Duration/CallbackDuration.php | 4 +- .../ILIAS/HTTP/src/Duration/Duration.php | 4 +- .../HTTP/src/Duration/DurationFactory.php | 5 +- .../Duration/Increment/IncrementStrategy.php | 2 - .../Duration/Increment/MultiplierStrategy.php | 7 +- .../src/Duration/Increment/StaticStrategy.php | 7 +- components/ILIAS/HTTP/src/GlobalHttpState.php | 1 - components/ILIAS/HTTP/src/RawHTTPServices.php | 27 +- .../HTTP/src/Request/RequestFactoryImpl.php | 6 + .../Sender/DefaultResponseSenderStrategy.php | 30 +- components/ILIAS/HTTP/src/Services.php | 1 - .../src/Wrapper/ArrayBasedRequestWrapper.php | 6 +- .../Wrapper/SuperGlobalDropInReplacement.php | 7 +- .../ILIAS/HTTP/src/Wrapper/WrapperFactory.php | 5 +- .../tests/Cookies/CookieJarWrapperTest.php | 37 +- .../HTTP/tests/Cookies/CookieWrapperTest.php | 76 +- .../tests/Services/AbstractBaseTestCase.php | 6 +- .../tests/Services/CallbackDurationTest.php | 22 +- .../ILIAS/HTTP/tests/Services/WrapperTest.php | 1 + components/ILIAS/MainMenu/MainMenu.php | 4 +- .../class.ilMMAbstractItemGUI.php | 13 +- .../class.ilMMItemTranslationGUI.php | 17 +- .../class.ilMMItemTranslationTableGUI.php | 10 +- .../class.ilMMSubItemTableGUI.php | 74 +- .../class.ilMMSubitemFormGUI.php | 42 +- .../Administration/class.ilMMTabHandling.php | 35 +- .../class.ilMMTopItemFormGUI.php | 48 +- .../class.ilMMTopItemTableGUI.php | 9 +- .../class.ilMMUploadHandlerGUI.php | 8 +- .../Facade/class.ilMMAbstractItemFacade.php | 33 +- .../Facade/class.ilMMCustomItemFacade.php | 16 +- .../Items/Facade/class.ilMMNullItemFacade.php | 11 + .../Items/class.ilMMCustomItemStorage.php | 2 +- .../Items/class.ilMMItemInformation.php | 19 +- .../Items/class.ilMMItemRepository.php | 11 +- .../classes/Items/class.ilMMItemStorage.php | 13 +- .../class.ilMMItemTranslationStorage.php | 6 +- .../Provider/CustomMainBarProvider.php | 12 +- .../Provider/StandardTopItemsProvider.php | 14 +- ...lass.ilMMAbstractBaseTypeHandlerAction.php | 1 - .../class.ilMMTypeActionStorage.php | 5 +- .../class.ilMMTypeHandlerRepositoryLink.php | 7 +- .../class.ilMMTypeHandlerSeparator.php | 4 +- .../class.ilMMLinkItemRenderer.php | 1 + .../class.ilMMRepositoryLinkItemRenderer.php | 1 + .../class.ilMMTopLinkItemRenderer.php | 1 + .../TypeRenderer/trait.ilMMCloseOnClick.php | 7 +- .../MainMenu/classes/class.ilObjMainMenu.php | 2 + .../classes/class.ilObjMainMenuGUI.php | 1 + .../MainMenu/tests/ilServicesMainMenuTest.php | 19 +- .../ILIAS/ResourceStorage/ResourceStorage.php | 10 +- .../classes/CollectionDBRepository.php | 17 +- .../DataProvider/TableDataProvider.php | 3 +- .../Collections/View/ActionBuilder.php | 24 +- .../classes/Collections/View/EditForm.php | 12 +- .../Collections/View/PreviewDefinition.php | 1 + .../classes/Collections/View/Request.php | 45 +- .../Collections/View/RequestToDataTable.php | 8 +- .../Collections/View/RequestToDeckOfCards.php | 4 +- .../Collections/View/RequestToItems.php | 4 +- .../View/RequestToPresentationTable.php | 4 +- .../Collections/View/UploadBuilder.php | 1 - .../classes/Collections/View/ViewFactory.php | 4 +- .../class.ilResourceCollectionGUI.php | 29 +- .../DataProvider/TableDataProvider.php | 8 +- .../classes/Container/View/ActionBuilder.php | 20 +- .../View/ActionBuilder/ActionProvider.php | 4 +- .../ActionBuilder/StandardActionProvider.php | 17 +- .../classes/Container/View/Request.php | 54 +- .../Container/View/RequestToDataTable.php | 22 +- .../classes/Container/View/ViewFactory.php | 4 +- .../Container/Wrapper/ContainerWrapper.php | 14 +- .../classes/Container/Wrapper/Item.php | 3 +- .../classes/Container/Wrapper/ZipReader.php | 12 +- .../class.ilContainerResourceGUI.php | 78 +- .../classes/DBRepositoryPreloader.php | 5 +- .../classes/FlavourDBRepository.php | 5 +- .../classes/InformationDBRepository.php | 14 +- .../classes/ResourceDBRepository.php | 8 +- .../DataSource/AllResourcesDataSource.php | 21 +- .../DataSource/BaseTableDataSource.php | 3 +- .../DataSource/CollectionDataSource.php | 4 +- .../Resources/Listing/ViewDefinition.php | 4 +- .../UI/Actions/OverviewActionGenerator.php | 6 +- .../classes/Resources/UI/BaseToComponent.php | 9 +- .../Resources/UI/ResourceListingUI.php | 17 +- .../Resources/UI/ResourceToComponent.php | 12 +- .../Resources/UI/RevisionListingUI.php | 33 +- .../Resources/UI/RevisionToComponent.php | 16 +- .../classes/Resources/UI/ToComponent.php | 4 +- .../Resources/class.ilResourceOverviewGUI.php | 26 +- .../classes/RevisionDBRepository.php | 24 +- ...class.ilResourceStorageFlavourArtifact.php | 4 +- .../Setup/DB/class.ilResourceStorageDB80.php | 2 +- .../Setup/DB/class.ilResourceStorageDB90.php | 6 +- ...class.ilResourceStorageMigrationHelper.php | 11 +- .../class.ilResourceStorageSetupAgent.php | 7 +- ...s.ilStorageContainersExistingObjective.php | 21 +- .../classes/StakeholderDBRepository.php | 5 +- .../class.ilResourceStorageInfoGUI.php | 7 +- .../class.ilWACSignedResourceStorage.php | 3 +- .../ILIAS/ResourceStorage/src/Artifacts.php | 7 +- .../src/Collection/CollectionBuilder.php | 19 +- .../src/Collection/Collections.php | 14 +- .../Repository/CollectionRepository.php | 1 - .../src/Collection/ResourceCollection.php | 13 +- .../Collection/Sorter/AbstractBaseSorter.php | 7 +- .../src/Collection/Sorter/Sorter.php | 15 +- .../src/Consumer/BaseConsumer.php | 14 +- .../BaseHTTPResponseBasedConsumer.php | 42 +- .../src/Consumer/ConsumerFactory.php | 11 +- .../src/Consumer/Consumers.php | 17 +- .../src/Consumer/ContainerConsumer.php | 5 - .../src/Consumer/ContainerURIConsumer.php | 5 +- .../Consumer/ContainerZIPAccessConsumer.php | 11 +- .../src/Consumer/DownloadMultipleConsumer.php | 22 +- .../src/Consumer/FileStreamConsumer.php | 6 +- .../src/Consumer/FlavourURLs.php | 7 +- .../src/Consumer/SrcConsumer.php | 10 +- .../Consumer/StreamAccess/StreamAccess.php | 8 +- .../Consumer/StreamAccess/StreamResolver.php | 3 - .../ResourceStorage/src/Events/Subject.php | 2 +- .../Flavour/Definition/CropToRectangle.php | 1 + .../src/Flavour/Definition/PagesToExtract.php | 22 +- .../src/Flavour/Definition/ToGreyScale.php | 2 +- .../src/Flavour/Engine/Factory.php | 2 +- .../ImagickEngineWithOptionalFFMpeg.php | 1 + .../ResourceStorage/src/Flavour/Flavour.php | 10 +- .../src/Flavour/FlavourBuilder.php | 2 +- .../ResourceStorage/src/Flavour/Flavours.php | 11 +- .../Machine/DefaultMachines/CropRectangle.php | 2 +- .../Machine/DefaultMachines/CropSquare.php | 4 +- .../DefaultMachines/Extract/Extractor.php | 1 - .../Machine/DefaultMachines/Extract/PDF.php | 2 + .../Machine/DefaultMachines/Extract/SVG.php | 3 +- .../Machine/DefaultMachines/Extract/Video.php | 9 +- .../Machine/DefaultMachines/FitSquare.php | 6 +- .../DefaultMachines/GdImageToStreamTrait.php | 2 +- .../Machine/DefaultMachines/MakeGreyScale.php | 3 +- .../src/Flavour/Machine/Factory.php | 9 +- .../Flavour/Machine/NonStoreableResult.php | 11 +- .../src/Flavour/Machine/Result.php | 17 +- .../src/Flavour/StorableFlavourDecorator.php | 9 +- .../Identification/AbstractIdentification.php | 7 +- .../src/Identification/UUIDStringTrait.php | 2 +- .../src/Lock/LockHandlerResultilDB.php | 5 +- .../src/Lock/LockHandlerilDB.php | 5 +- .../src/Manager/BaseManager.php | 19 +- .../ResourceStorage/src/Manager/Manager.php | 7 - .../WhiteAndBlacklistedFileNamePolicy.php | 13 +- .../src/Preloader/SecureString.php | 2 +- .../Preloader/StandardRepositoryPreloader.php | 12 +- .../ResourceStorage/src/Repositories.php | 23 +- .../src/Resource/AbstractStorableResource.php | 8 +- .../InfoResolver/AbstractInfoResolver.php | 9 +- .../ClonedRevisionInfoResolver.php | 11 +- .../InfoResolver/StreamInfoResolver.php | 4 +- .../InfoResolver/UploadInfoResolver.php | 8 +- .../src/Resource/ResourceBuilder.php | 52 +- .../src/Resource/ResourceType.php | 5 - .../Resource/StorableContainerResource.php | 5 - .../src/Resource/StorableFileResource.php | 5 - .../src/Revision/BaseRevision.php | 6 +- .../src/Revision/CloneRevision.php | 8 +- .../src/Revision/FileRevision.php | 5 +- .../src/Revision/FileStreamRevision.php | 9 +- .../ResourceStorage/src/Revision/Revision.php | 2 - .../src/Revision/RevisionCollection.php | 26 +- .../src/Revision/RevisionStatus.php | 2 - .../Revision/StreamReplacementRevision.php | 8 +- .../src/Revision/UploadedFileRevision.php | 13 +- .../ILIAS/ResourceStorage/src/Services.php | 12 +- .../AbstractFileSystemStorageHandler.php | 32 +- .../src/StorageHandler/Migrator.php | 22 +- .../PathGenerator/MaxNestingPathGenerator.php | 25 +- .../StorageHandler/StorageHandlerFactory.php | 9 +- .../AbstractBaseResourceBuilderTestCase.php | 53 +- .../tests/AbstractTestBase.php | 10 +- .../Collection/CollectionBuilderTest.php | 3 +- .../Collection/CollectionRepositoryTest.php | 14 +- .../Collection/CollectionSortingTest.php | 1 + .../tests/Collection/CollectionTest.php | 9 +- .../tests/DummyIDGenerator.php | 5 +- .../tests/Flavours/DummyDefinition.php | 9 +- .../tests/Flavours/DummyMachine.php | 1 - .../tests/Flavours/FlavourMachineTest.php | 25 +- .../tests/Flavours/FlavourTest.php | 16 +- .../tests/Flavours/SVGDummyMachine.php | 3 +- .../tests/Policy/FileNamePolicyTest.php | 8 +- .../tests/Revision/RevisionRepositoryTest.php | 9 +- .../StakeholderRepositoryTests.php | 7 +- .../StorageHandler/DirectoryNestingTest.php | 33 +- .../StorageHandler/PathGeneratorTest.php | 6 +- components/ILIAS/StaticURL/StaticURL.php | 19 +- .../ILIAS/StaticURL/src/ArtifactObjective.php | 16 +- components/ILIAS/StaticURL/src/Context.php | 3 +- .../src/Handler/LegacyGotoHandler.php | 10 +- components/ILIAS/StaticURL/src/Init.php | 34 +- .../src/Request/BundledRequestBuilder.php | 5 +- .../src/Request/LegacyRequestBuilder.php | 5 +- .../StaticURL/src/Request/RequestBuilder.php | 3 +- .../src/Request/StaticURLRequestBuilder.php | 12 +- components/ILIAS/StaticURL/src/SetupAgent.php | 4 +- components/ILIAS/StaticURL/tests/Base.php | 4 +- .../StaticURL/tests/LegacyGotoHandlerTest.php | 25 +- .../ILIAS/StaticURL/tests/URIBuilderTest.php | 9 +- components/ILIAS/WOPI/WOPI.php | 21 +- .../class.ilWOPIAdministrationGUI.php | 20 +- .../class.ilWOPISettingsForm.php | 30 +- .../classes/Discovery/ActionDBRepository.php | 3 + .../ILIAS/WOPI/classes/Discovery/Crawler.php | 5 +- .../classes/Embed/EmbeddedApplication.php | 25 +- .../Embed/EmbeddedApplicationGSProvider.php | 6 + .../ILIAS/WOPI/classes/Embed/Renderer.php | 7 +- .../class.ilWOPIEmbeddedApplicationGUI.php | 1 - .../WOPI/classes/Handler/RequestHandler.php | 42 +- .../Handler/WOPIStakeholderWrapper.php | 6 + .../classes/Setup/class.ilWOPISetupAgent.php | 2 - components/ILIAS/WOPI/resources/index.php | 4 +- .../WebAccessChecker/WebAccessChecker.php | 10 +- .../class.ilSecurePathDefinitionProcessor.php | 6 +- .../classes/class.ilWACPath.php | 7 +- .../classes/class.ilWACSignedPath.php | 43 +- .../classes/class.ilWACToken.php | 23 +- .../classes/class.ilWebAccessChecker.php | 2 - .../class.ilWebAccessCheckerDelivery.php | 5 +- .../ILIAS/WebAccessChecker/resources/wac.php | 26 +- .../ilWACCheckingInstanceTest.php | 19 +- .../tests/Token/ilWACTokenTestTBD.php | 36 +- components/ILIAS/WebDAV/WebDAV.php | 14 +- .../class.ilWebDAVSabreBrowserPlugin.php | 5 +- .../WebDAV/classes/class.ilObjWebDAV.php | 7 +- .../classes/class.ilObjWebDAVAccess.php | 2 - .../WebDAV/classes/class.ilObjWebDAVGUI.php | 3 + .../WebDAV/classes/class.ilWebDAVDIC.php | 2 +- .../class.ilWebDAVRepositoryHelper.php | 19 +- .../classes/class.ilWebDAVRequestHandler.php | 5 +- .../classes/dav/class.ilDAVClientNode.php | 21 +- .../classes/dav/class.ilDAVContainer.php | 26 +- .../WebDAV/classes/dav/class.ilDAVFile.php | 25 +- .../classes/dav/class.ilDAVMountPoint.php | 23 +- .../dav/class.ilDAVProblemInfoFile.php | 36 +- .../classes/dav/class.ilWebDAVObjFactory.php | 28 +- .../classes/lock/class.ilWebDAVLockObject.php | 29 +- .../class.ilWebDAVLockUriPathResolver.php | 15 +- .../lock/class.ilWebDAVLocksBackend.php | 40 +- .../lock/class.ilWebDAVLocksRepository.php | 30 +- .../class.ilWebDAVBaseMountInstructions.php | 17 +- ...VMounInstructionsDocumentProcessorBase.php | 6 +- ...lass.ilWebDAVMountInstructionsDocument.php | 35 +- ...WebDAVMountInstructionsDocumentFormGUI.php | 46 +- ...ebDAVMountInstructionsDocumentTableGUI.php | 35 +- ...ructionsDocumentsContainsHtmlValidator.php | 9 +- ...class.ilWebDAVMountInstructionsFactory.php | 18 +- .../class.ilWebDAVMountInstructionsGUI.php | 20 +- ...MountInstructionsHtmlDocumentProcessor.php | 5 +- ...lass.ilWebDAVMountInstructionsModalGUI.php | 17 +- ...lWebDAVMountInstructionsRepositoryImpl.php | 67 +- ...bDAVMountInstructionsTableDataProvider.php | 9 +- ...ass.ilWebDAVMountInstructionsUploadGUI.php | 57 +- .../class.ilWebDAVObjectMountInstructions.php | 5 +- .../class.ilWebDAVUriBuilder.php | 18 +- .../ilWebDAVAccessChildrenFunctionsTrait.php | 10 +- .../traits/ilWebDAVCheckValidTitleTrait.php | 8 +- .../WebDAV/tests/dav/ilDAVContainerTest.php | 50 +- .../lock/ilWebDAVLockUriPathResolverTest.php | 16 +- ...tInstructionsDocumentProcessorBaseTest.php | 57 +- .../ILIAS/WebDAV/tests/webdav_overrides.php | 1 + 791 files changed, 5635 insertions(+), 6522 deletions(-) diff --git a/components/ILIAS/ActiveRecord/ActiveRecord.php b/components/ILIAS/ActiveRecord/ActiveRecord.php index 4cb05bce1f52..26bb59b8d704 100644 --- a/components/ILIAS/ActiveRecord/ActiveRecord.php +++ b/components/ILIAS/ActiveRecord/ActiveRecord.php @@ -20,7 +20,9 @@ namespace ILIAS; -class ActiveRecord implements Component\Component +use ILIAS\Component\Component; + +class ActiveRecord implements Component { public function init( array | \ArrayAccess &$define, diff --git a/components/ILIAS/ActiveRecord/Cache/class.arObjectCache.php b/components/ILIAS/ActiveRecord/Cache/class.arObjectCache.php index d8c9d70dacf0..02ab54fe5057 100755 --- a/components/ILIAS/ActiveRecord/Cache/class.arObjectCache.php +++ b/components/ILIAS/ActiveRecord/Cache/class.arObjectCache.php @@ -68,7 +68,7 @@ public static function printStats(): void * @param $id * @throws arException */ - public static function get($class, $id): \ActiveRecord + public static function get(string $class, string $id): \ActiveRecord { new $class(); if (!self::isCached($class, $id)) { diff --git a/components/ILIAS/ActiveRecord/Connector/Join/class.arJoinCollection.php b/components/ILIAS/ActiveRecord/Connector/Join/class.arJoinCollection.php index a360f6d9a162..a971f47987a6 100755 --- a/components/ILIAS/ActiveRecord/Connector/Join/class.arJoinCollection.php +++ b/components/ILIAS/ActiveRecord/Connector/Join/class.arJoinCollection.php @@ -42,6 +42,7 @@ public function getSaveTableName(arStatement $arStatement): string return $tableName; } + #[\Override] public function add(arStatement $arStatement): void { $arStatement->setTableNameAs($this->getSaveTableName($arStatement)); diff --git a/components/ILIAS/ActiveRecord/Connector/Select/class.arSelectCollection.php b/components/ILIAS/ActiveRecord/Connector/Select/class.arSelectCollection.php index 198a66655791..ede3a8f78377 100755 --- a/components/ILIAS/ActiveRecord/Connector/Select/class.arSelectCollection.php +++ b/components/ILIAS/ActiveRecord/Connector/Select/class.arSelectCollection.php @@ -28,7 +28,7 @@ public function asSQLStatement(): string $return = 'SELECT '; if ($this->hasStatements()) { $activeRecord = $this->getAr(); - $selectSQLs = array_map(fn ($select) => $select->asSQLStatement($activeRecord), $this->getSelects()); + $selectSQLs = array_map(fn($select): string => $select->asSQLStatement($activeRecord), $this->getSelects()); $return .= implode(', ', $selectSQLs); } diff --git a/components/ILIAS/ActiveRecord/Connector/class.arConnectorCache.php b/components/ILIAS/ActiveRecord/Connector/class.arConnectorCache.php index 7a8e9b964b60..a6472e83e6a2 100755 --- a/components/ILIAS/ActiveRecord/Connector/class.arConnectorCache.php +++ b/components/ILIAS/ActiveRecord/Connector/class.arConnectorCache.php @@ -121,14 +121,10 @@ public function read(ActiveRecord $activeRecord): array if ($this->cache_container->has($key)) { $cached_value = $this->cache_container->get( $key, - new Transformation(function ($value): ?array { - return is_array($value) ? $value : null; - }) + new Transformation(fn($value): ?array => is_array($value) ? $value : null) ); if (is_array($cached_value)) { - return array_map(function ($result): \stdClass { - return (object) $result; - }, $cached_value); + return array_map(fn($result): \stdClass => (object) $result, $cached_value); } } @@ -136,9 +132,7 @@ public function read(ActiveRecord $activeRecord): array $this->cache_container->set( $key, - array_map(function ($result): array { - return (array) $result; - }, $results) + array_map(fn($result): array => (array) $result, $results) ); return $results; diff --git a/components/ILIAS/ActiveRecord/Exception/class.arException.php b/components/ILIAS/ActiveRecord/Exception/class.arException.php index 0eb731d4533e..76180d10ae28 100755 --- a/components/ILIAS/ActiveRecord/Exception/class.arException.php +++ b/components/ILIAS/ActiveRecord/Exception/class.arException.php @@ -69,6 +69,6 @@ protected function assignMessageToCode(): void public function __toString(): string { - return implode('
', [$this::class, $this->message]); + return implode('
', [static::class, $this->message]); } } diff --git a/components/ILIAS/ActiveRecord/Fields/class.arField.php b/components/ILIAS/ActiveRecord/Fields/class.arField.php index 7548329724f4..593ef234c523 100755 --- a/components/ILIAS/ActiveRecord/Fields/class.arField.php +++ b/components/ILIAS/ActiveRecord/Fields/class.arField.php @@ -23,6 +23,7 @@ */ class arField { + public $not_null; protected bool $is_unique = false; public const FIELD_TYPE_TEXT = 'text'; // MySQL varchar, char public const FIELD_TYPE_INTEGER = 'integer'; // MySQL tinyint, smallint, mediumint, int, bigint diff --git a/components/ILIAS/ActiveRecord/Fields/class.arFieldList.php b/components/ILIAS/ActiveRecord/Fields/class.arFieldList.php index 8c7bd263e5d4..5adbb2aa996b 100755 --- a/components/ILIAS/ActiveRecord/Fields/class.arFieldList.php +++ b/components/ILIAS/ActiveRecord/Fields/class.arFieldList.php @@ -58,11 +58,7 @@ public function __construct(protected ActiveRecord $activeRecord) public static function mapKey(string $key): string { - if (isset(self::$key_maps[$key])) { - return self::$key_maps[$key]; - } - - return $key; + return self::$key_maps[$key] ?? $key; } /** diff --git a/components/ILIAS/ActiveRecord/class.ActiveRecord.php b/components/ILIAS/ActiveRecord/class.ActiveRecord.php index 8725c7c2a0d8..a1d07cf0f0a2 100755 --- a/components/ILIAS/ActiveRecord/class.ActiveRecord.php +++ b/components/ILIAS/ActiveRecord/class.ActiveRecord.php @@ -144,7 +144,7 @@ public function asArray(): array public function buildFromArray(array $array): static { - $class = $this::class; + $class = static::class; $primary = $this->getArFieldList()->getPrimaryFieldName(); $primary_value = $array[$primary]; if ($primary_value && arObjectCache::isCached($class, $primary_value)) { @@ -165,7 +165,7 @@ public function buildFromArray(array $array): static * @return string|mixed * @noinspection NullPointerExceptionInspection */ - public function fixDateField($field_name, $value) + public function fixDateField($field_name, string $value) { if ($this->getArFieldList()->getFieldByName($field_name)->isDateField()) { return $this->getArConnector()->fixDate($value); @@ -521,7 +521,7 @@ public static function where($where, $operator = null): \ActiveRecordList public static function innerjoinAR( ActiveRecord $activeRecord, $on_this, - $on_external, + string $on_external, array $fields = ['*'], string $operator = '=', bool $both_external = false @@ -543,9 +543,9 @@ public static function innerjoinAR( * @return $this */ public static function innerjoin( - $tablename, + string $tablename, $on_this, - $on_external, + string $on_external, array $fields = ['*'], string $operator = '=', bool $both_external = false @@ -562,9 +562,9 @@ public static function innerjoin( * @return $this */ public static function leftjoin( - $tablename, + string $tablename, $on_this, - $on_external, + string $on_external, array $fields = ['*'], string $operator = '=', bool $both_external = false @@ -682,7 +682,7 @@ public static function raw(bool $set_raw = true): \ActiveRecordList * @param null $values * @return mixed[]|mixed[][]|int[]|string[]|null[] */ - public static function getArray(?string $key = null, $values = null): array + public static function getArray(?string $key = null, string|array|null $values = null): array { $activeRecordList = new ActiveRecordList(self::getCalledClass()); @@ -701,19 +701,20 @@ public static function getArray(?string $key = null, $values = null): array public function __call($name, $arguments) { // Getter - if (preg_match("/get([a-zA-Z]*)/u", $name, $matches) && (is_countable($arguments) ? count( + if (preg_match("/get([a-zA-Z]*)/u", (string) $name, $matches) && (is_countable($arguments) ? count( $arguments ) : 0) === 0) { return $this->{self::fromCamelCase($matches[1])}; } // Setter - if (!preg_match("/set([a-zA-Z]*)/u", $name, $matches)) { - return; + if (!preg_match("/set([a-zA-Z]*)/u", (string) $name, $matches)) { + return null; } if (count($arguments) !== 1) { - return; + return null; } $this->{self::fromCamelCase($matches[1])} = $arguments[0]; + return null; } public static function _toCamelCase(string $str, bool $capitalise_first_char = false): ?string diff --git a/components/ILIAS/ActiveRecord/class.ActiveRecordList.php b/components/ILIAS/ActiveRecord/class.ActiveRecordList.php index 25c245680d64..88205b3148ca 100755 --- a/components/ILIAS/ActiveRecord/class.ActiveRecordList.php +++ b/components/ILIAS/ActiveRecord/class.ActiveRecordList.php @@ -163,7 +163,7 @@ public function limit(int $start, int $end): self public function innerjoinAR( ActiveRecord $activeRecord, $on_this, - $on_external, + string $on_external, array $fields = ['*'], string $operator = '=', bool $both_external = false @@ -497,8 +497,8 @@ protected function load(): void $arField = $obj->getArFieldList()->getFieldByName($key); if ($arField !== null && ($arField->isDateField() && $this->getDateFormat())) { $res_awake[$key . '_unformatted'] = $value; - $res_awake[$key . '_unix'] = strtotime($value); - $value = date($this->getDateFormat(), strtotime($value)); + $res_awake[$key . '_unix'] = strtotime((string) $value); + $value = date($this->getDateFormat(), strtotime((string) $value)); } $waked = $this->getAR()->wakeUp($key, $value); $res_awake[$key] = $waked ?? $value; diff --git a/components/ILIAS/ActiveRecord/class.CachedActiveRecord.php b/components/ILIAS/ActiveRecord/class.CachedActiveRecord.php index 0066a3687a84..40998d8409e5 100755 --- a/components/ILIAS/ActiveRecord/class.CachedActiveRecord.php +++ b/components/ILIAS/ActiveRecord/class.CachedActiveRecord.php @@ -68,17 +68,20 @@ private function buildHash(): string return md5(serialize($hashing)); } + #[\Override] public function create(): void { parent::create(); } + #[\Override] public function read(): void { parent::read(); $this->_hash = $this->buildHash(); } + #[\Override] public function update(): void { if ($this->buildHash() !== $this->_hash) { @@ -86,6 +89,7 @@ public function update(): void } } + #[\Override] public function delete(): void { parent::delete(); // TODO: Change the autogenerated stub diff --git a/components/ILIAS/ActiveRecord/tests/ilServicesActiveRecordConnectorTest.php b/components/ILIAS/ActiveRecord/tests/ilServicesActiveRecordConnectorTest.php index 2123951293e6..8b009da5c342 100755 --- a/components/ILIAS/ActiveRecord/tests/ilServicesActiveRecordConnectorTest.php +++ b/components/ILIAS/ActiveRecord/tests/ilServicesActiveRecordConnectorTest.php @@ -18,16 +18,17 @@ declare(strict_types=1); +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use ILIAS\DI\Container; class ilServicesActiveRecordConnectorTest extends TestCase { - private ?\ILIAS\DI\Container $dic_backup = null; + private ?Container $dic_backup = null; /** - * @var ilDBInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ilDBInterface|MockObject */ - protected $db_mock; + protected ?MockObject $db_mock = null; protected function setUp(): void { diff --git a/components/ILIAS/ActiveRecord/tests/ilServicesActiveRecordFieldTest.php b/components/ILIAS/ActiveRecord/tests/ilServicesActiveRecordFieldTest.php index 08f04f636144..ec8a77a049a3 100755 --- a/components/ILIAS/ActiveRecord/tests/ilServicesActiveRecordFieldTest.php +++ b/components/ILIAS/ActiveRecord/tests/ilServicesActiveRecordFieldTest.php @@ -18,16 +18,17 @@ declare(strict_types=1); +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use ILIAS\DI\Container; class ilServicesActiveRecordFieldTest extends TestCase { - private ?\ILIAS\DI\Container $dic_backup = null; + private ?Container $dic_backup = null; /** - * @var ilDBInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ilDBInterface|MockObject */ - protected $db_mock; + protected ?MockObject $db_mock = null; protected function setUp(): void { diff --git a/components/ILIAS/AdministrativeNotification/AdministrativeNotification.php b/components/ILIAS/AdministrativeNotification/AdministrativeNotification.php index a8179763aca2..94242dd59b49 100644 --- a/components/ILIAS/AdministrativeNotification/AdministrativeNotification.php +++ b/components/ILIAS/AdministrativeNotification/AdministrativeNotification.php @@ -20,7 +20,11 @@ namespace ILIAS; -class AdministrativeNotification implements Component\Component +use ILIAS\Component\Component; +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Factory; + +class AdministrativeNotification implements Component { public function init( array | \ArrayAccess &$define, @@ -32,9 +36,9 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $contribute[\ILIAS\Setup\Agent::class] = static fn() => + $contribute[Agent::class] = static fn(): \ilADNAgent => new \ilADNAgent( - $pull[\ILIAS\Refinery\Factory::class] + $pull[Factory::class] ); } } diff --git a/components/ILIAS/AdministrativeNotification/classes/DataRetrieval.php b/components/ILIAS/AdministrativeNotification/classes/DataRetrieval.php index d051d4a2a7eb..eeaa9f61ac99 100755 --- a/components/ILIAS/AdministrativeNotification/classes/DataRetrieval.php +++ b/components/ILIAS/AdministrativeNotification/classes/DataRetrieval.php @@ -60,7 +60,7 @@ protected function getRecords(Order $order): array $records = ilADNNotification::getArray(); // populate with additional data - array_walk($records, function (&$record) { + array_walk($records, function (array &$record): void { $record['languages'] = $this->getLanguagesTextForNotification($record); $record['type'] = $this->lng->txt("msg_type_" . $record['type']); $record['event_start'] = $this->formatDate($record['event_start']); @@ -68,18 +68,14 @@ protected function getRecords(Order $order): array $record['display_start'] = $this->formatDate($record['display_start']); $record['display_end'] = $this->formatDate($record['display_end']); - if (!$record['permanent']) { - $record['type_during_event'] = $this->lng->txt("msg_type_" . $record['type_during_event']); - } else { - $record['type_during_event'] = ''; - } + $record['type_during_event'] = $record['permanent'] ? '' : $this->lng->txt("msg_type_" . $record['type_during_event']); }); // sort - [$order_field, $order_direction] = $order->join([], fn($ret, $key, $value) => [$key, $value]); - usort($records, fn($a, $b) => $a[$order_field] <=> $b[$order_field]); + [$order_field, $order_direction] = $order->join([], fn($ret, $key, $value): array => [$key, $value]); + usort($records, fn($a, $b): int => $a[$order_field] <=> $b[$order_field]); if ($order_direction === 'DESC') { - $records = array_reverse($records); + return array_reverse($records); } return $records; @@ -113,9 +109,7 @@ protected function getLanguagesTextForNotification(array $record): string $languages_text = implode( ', ', array_map( - function (string $lng_code): string { - return $this->lng->txt("meta_l_" . $lng_code); - }, + fn(string $lng_code): string => $this->lng->txt("meta_l_" . $lng_code), $limited_to_languages ) ); diff --git a/components/ILIAS/AdministrativeNotification/classes/GlobalScreen/ADNProvider.php b/components/ILIAS/AdministrativeNotification/classes/GlobalScreen/ADNProvider.php index e5bd4ac3dab8..c1458fb6d198 100755 --- a/components/ILIAS/AdministrativeNotification/classes/GlobalScreen/ADNProvider.php +++ b/components/ILIAS/AdministrativeNotification/classes/GlobalScreen/ADNProvider.php @@ -20,12 +20,13 @@ namespace ILIAS\AdministrativeNotification\GlobalScreen; +use ILIAS\Refinery\String\MarkdownFormattingToHTML; +use ILIAS\GlobalScreen\Helper\BasicAccessCheckClosures; use ilADNNotification; use ILIAS\GlobalScreen\Helper\BasicAccessCheckClosuresSingleton; use ILIAS\GlobalScreen\Identification\IdentificationInterface; use ILIAS\GlobalScreen\Scope\Notification\Factory\AdministrativeNotification; use ILIAS\GlobalScreen\Scope\Notification\Provider\AbstractNotificationProvider; -use ILIAS\GlobalScreen\Scope\Notification\Provider\NotificationProvider; use Closure; use ILIAS\DI\Container; @@ -34,8 +35,8 @@ */ class ADNProvider extends AbstractNotificationProvider { - protected \ILIAS\Refinery\String\MarkdownFormattingToHTML $markdown; - protected \ILIAS\GlobalScreen\Helper\BasicAccessCheckClosures $access; + protected MarkdownFormattingToHTML $markdown; + protected BasicAccessCheckClosures $access; public function __construct(Container $dic) { @@ -62,11 +63,12 @@ public function getNotifications(): array /** * @inheritDoc */ + #[\Override] public function getAdministrativeNotifications(): array { $adns = []; - $i = fn (string $id): IdentificationInterface => $this->if->identifier($id); + $i = fn(string $id): IdentificationInterface => $this->if->identifier($id); /** * @var $item ilADNNotification * @var $adn AdministrativeNotification @@ -77,11 +79,11 @@ public function getAdministrativeNotifications(): array ); $adn = $this->handleDenotation($item, $adn); - $is_visible = static fn (): bool => true; + $is_visible = static fn(): bool => true; // is limited to roles if ($item->isLimitToRoles()) { - $is_visible = $this->combineClosure($is_visible, fn () => $this->dic->rbac()->review()->isAssignedToAtLeastOneGivenRole( + $is_visible = $this->combineClosure($is_visible, fn(): bool => $this->dic->rbac()->review()->isAssignedToAtLeastOneGivenRole( $this->dic->user()->getId(), $item->getLimitedToRoleIds() )); @@ -92,10 +94,10 @@ public function getAdministrativeNotifications(): array $adn = $adn->withClosedCallable(function () use ($item): void { $item->dismiss($this->dic->user()); }); - $is_visible = $this->combineClosure($is_visible, fn (): bool => !\ilADNDismiss::hasDimissed($this->dic->user(), $item)); + $is_visible = $this->combineClosure($is_visible, fn(): bool => !\ilADNDismiss::hasDimissed($this->dic->user(), $item)); } - $is_visible = $this->combineClosure($is_visible, fn (): bool => $item->isVisibleForUser($this->dic->user())); + $is_visible = $this->combineClosure($is_visible, fn(): bool => $item->isVisibleForUser($this->dic->user())); $adns[] = $adn->withVisibilityCallable($is_visible); } @@ -106,17 +108,11 @@ private function handleDenotation( ilADNNotification $item, AdministrativeNotification $adn ): AdministrativeNotification { - $settype = static function (int $type, AdministrativeNotification $adn): AdministrativeNotification { - switch ($type) { - case ilADNNotification::TYPE_ERROR: - return $adn->withBreakingDenotation(); - case ilADNNotification::TYPE_WARNING: - return $adn->withImportantDenotation(); - case ilADNNotification::TYPE_INFO: - default: - return $adn->withNeutralDenotation(); - } - }; + $settype = (static fn(int $type, AdministrativeNotification $adn): AdministrativeNotification => match ($type) { + ilADNNotification::TYPE_ERROR => $adn->withBreakingDenotation(), + ilADNNotification::TYPE_WARNING => $adn->withImportantDenotation(), + default => $adn->withNeutralDenotation(), + }); // denotation during event if (!$item->isPermanent() && $item->isDuringEvent()) { @@ -128,7 +124,7 @@ private function handleDenotation( private function combineClosure(Closure $closure, ?Closure $additional = null): Closure { if ($additional instanceof Closure) { - return static fn (): bool => $additional() && $closure(); + return static fn(): bool => $additional() && $closure(); } return $closure; diff --git a/components/ILIAS/AdministrativeNotification/classes/Setup/class.ilADNAgent.php b/components/ILIAS/AdministrativeNotification/classes/Setup/class.ilADNAgent.php index 3e1599a2f890..11b485e7aaae 100755 --- a/components/ILIAS/AdministrativeNotification/classes/Setup/class.ilADNAgent.php +++ b/components/ILIAS/AdministrativeNotification/classes/Setup/class.ilADNAgent.php @@ -18,23 +18,23 @@ declare(strict_types=1); -use ILIAS\Setup\ObjectiveConstructor; +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Transformation; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Objective\NullObjective; +use ILIAS\Setup\ObjectiveCollection; +use ILIAS\Setup\Metrics\Storage; use ILIAS\Setup\Config; use ILIAS\Refinery\Factory; -use ILIAS\Refinery; -use ILIAS\Setup; /** * @author Lukas Zehnder * @noinspection AutoloadingIssuesInspection */ -class ilADNAgent implements Setup\Agent +class ilADNAgent implements Agent { - protected Factory $refinery; - - public function __construct(Factory $refinery) + public function __construct(protected Factory $refinery) { - $this->refinery = $refinery; } @@ -44,21 +44,21 @@ public function hasConfig(): bool } - public function getArrayToConfigTransformation(): Refinery\Transformation + public function getArrayToConfigTransformation(): Transformation { throw new \LogicException("Agent has no config."); } - public function getInstallObjective(?Config $config = null): Setup\Objective + public function getInstallObjective(?Config $config = null): Objective { - return new Setup\Objective\NullObjective(); + return new NullObjective(); } - public function getUpdateObjective(?Config $config = null): Setup\Objective + public function getUpdateObjective(?Config $config = null): Objective { - return new Setup\ObjectiveCollection( + return new ObjectiveCollection( "", true, new ilDatabaseUpdateStepsExecutedObjective( @@ -68,13 +68,13 @@ public function getUpdateObjective(?Config $config = null): Setup\Objective } - public function getBuildObjective(): Setup\Objective + public function getBuildObjective(): Objective { - return new Setup\Objective\NullObjective(); + return new NullObjective(); } - public function getStatusObjective(Setup\Metrics\Storage $storage): Setup\Objective + public function getStatusObjective(Storage $storage): Objective { return new ilDatabaseUpdateStepsMetricsCollectedObjective($storage, new ilADNDatabaseObjective()); } diff --git a/components/ILIAS/AdministrativeNotification/classes/Table.php b/components/ILIAS/AdministrativeNotification/classes/Table.php index 3bd1cdb29e75..a37b71505374 100755 --- a/components/ILIAS/AdministrativeNotification/classes/Table.php +++ b/components/ILIAS/AdministrativeNotification/classes/Table.php @@ -18,6 +18,8 @@ namespace ILIAS\AdministrativeNotification; +use ILIAS\UI\Factory; +use ILIAS\UI\Renderer; use ilADNAbstractGUI; use ILIAS\UI\URLBuilder; use ILIAS\Data\URI; @@ -28,8 +30,8 @@ */ class Table { - private \ILIAS\UI\Factory $ui_factory; - private \ILIAS\UI\Renderer $ui_renderer; + private Factory $ui_factory; + private Renderer $ui_renderer; private \ilCtrlInterface $ctrl; private \ilLanguage $lng; private URLBuilder $url_builder; diff --git a/components/ILIAS/AdministrativeNotification/classes/class.ilADNAbstractGUI.php b/components/ILIAS/AdministrativeNotification/classes/class.ilADNAbstractGUI.php index 8138e15228b0..16bc7583e73e 100755 --- a/components/ILIAS/AdministrativeNotification/classes/class.ilADNAbstractGUI.php +++ b/components/ILIAS/AdministrativeNotification/classes/class.ilADNAbstractGUI.php @@ -16,6 +16,9 @@ * *********************************************************************/ +use ILIAS\DI\UIServices; +use ILIAS\HTTP\Services; + /** * Class ilADNAbstractGUI * @author Fabian Schmid @@ -24,12 +27,11 @@ abstract class ilADNAbstractGUI { public const IDENTIFIER = 'identifier'; - protected \ILIAS\DI\UIServices $ui; + protected UIServices $ui; - protected \ILIAS\HTTP\Services $http; + protected Services $http; protected ilToolbarGUI $toolbar; - protected \ilADNTabHandling $tab_handling; protected ilTabsGUI $tabs; @@ -45,11 +47,9 @@ abstract class ilADNAbstractGUI /** * ilADNAbstractGUI constructor. */ - public function __construct(ilADNTabHandling $tab_handling) + public function __construct(protected \ilADNTabHandling $tab_handling) { global $DIC; - - $this->tab_handling = $tab_handling; $this->tabs = $DIC['ilTabs']; $this->lng = $DIC->language(); $this->ctrl = $DIC['ilCtrl']; diff --git a/components/ILIAS/AdministrativeNotification/classes/class.ilADNDismiss.php b/components/ILIAS/AdministrativeNotification/classes/class.ilADNDismiss.php index f9731793a3cd..04e065245123 100755 --- a/components/ILIAS/AdministrativeNotification/classes/class.ilADNDismiss.php +++ b/components/ILIAS/AdministrativeNotification/classes/class.ilADNDismiss.php @@ -25,6 +25,7 @@ class ilADNDismiss extends ActiveRecord { public const TABLE_NAME = 'il_adn_dismiss'; + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; @@ -38,17 +39,17 @@ public static function returnDbTableName(): string return self::TABLE_NAME; } - protected static array $request_cache = array(); + protected static array $request_cache = []; public static function hasDimissed(ilObjUser $ilObjUser, ilADNNotification $ilADNNotification): bool { $not_id = $ilADNNotification->getId(); $usr_id = $ilObjUser->getId(); if (!isset(self::$request_cache[$usr_id][$not_id])) { - self::$request_cache[$usr_id][$not_id] = self::where(array( + self::$request_cache[$usr_id][$not_id] = self::where([ 'usr_id' => $usr_id, 'notification_id' => $not_id, - ))->hasSets(); + ])->hasSets(); } return (bool) self::$request_cache[$usr_id][$not_id]; @@ -69,7 +70,7 @@ public static function reactivateAll(ilADNNotification $ilADNNotification): void /** * @var ilADNDismiss $dismiss */ - foreach (self::where(array('notification_id' => $ilADNNotification->getId())) as $dismiss) { + foreach (self::where(['notification_id' => $ilADNNotification->getId()]) as $dismiss) { $dismiss->delete(); } } diff --git a/components/ILIAS/AdministrativeNotification/classes/class.ilADNNotification.php b/components/ILIAS/AdministrativeNotification/classes/class.ilADNNotification.php index 46df8786d317..4c7f9d664b03 100755 --- a/components/ILIAS/AdministrativeNotification/classes/class.ilADNNotification.php +++ b/components/ILIAS/AdministrativeNotification/classes/class.ilADNNotification.php @@ -36,8 +36,9 @@ class ilADNNotification extends ActiveRecord public const LINK_TYPE_NONE = 0; public const LINK_TYPE_REF_ID = 1; public const LINK_TYPE_URL = 2; - protected static array $allowed_user_ids = array(0, 13, 6); + protected static array $allowed_user_ids = [0, 13, 6]; + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; @@ -69,7 +70,7 @@ protected function hasUserDismissed(ilObjUser $ilObjUser): bool public function resetForAllUsers(): void { - foreach (ilADNDismiss::where(array('notification_id' => $this->getId()))->get() as $not) { + foreach (ilADNDismiss::where(['notification_id' => $this->getId()])->get() as $not) { $not->delete(); } } @@ -85,12 +86,11 @@ public function getFullTimeFormated(): string $this->getEventStart() ) . " - " . date(self::TIME_FORMAT, $this->getEventEnd()); - } else { - return date(self::DATE_TIME_FORMAT, $this->getEventStart()) . ' - ' . date( - self::DATE_TIME_FORMAT, - $this->getEventEnd() - ); } + return date(self::DATE_TIME_FORMAT, $this->getEventStart()) . ' - ' . date( + self::DATE_TIME_FORMAT, + $this->getEventEnd() + ); } public function isUserAllowedToDismiss(ilObjUser $user): bool @@ -242,7 +242,7 @@ protected function isVisibleRoleUserRoles(ilObjUser $ilObjUser): bool * @con_fieldtype text * @con_length 256 */ - protected array $allowed_users = array(0, 6, 13); + protected array $allowed_users = [0, 6, 13]; /** * @con_has_field true * @con_fieldtype integer @@ -348,7 +348,7 @@ public function wakeUp($field_name, $field_value) if ($field_value === null) { $array_unique = self::$allowed_user_ids; } else { - $json_decode = json_decode($field_value, true); + $json_decode = json_decode((string) $field_value, true); if (!is_array($json_decode)) { $json_decode = self::$allowed_user_ids; } @@ -360,8 +360,9 @@ public function wakeUp($field_name, $field_value) return $array_unique; case 'limited_to_languages': case 'limited_to_role_ids': - return json_decode($field_value, true); + return json_decode((string) $field_value, true); } + return null; } /** @@ -393,8 +394,10 @@ public function sleep($field_name) case 'limited_to_role_ids': return json_encode($this->{$field_name}, JSON_THROW_ON_ERROR); } + return null; } + #[\Override] public function create(): void { global $DIC; diff --git a/components/ILIAS/AdministrativeNotification/classes/class.ilADNNotificationUIFormGUI.php b/components/ILIAS/AdministrativeNotification/classes/class.ilADNNotificationUIFormGUI.php index 647f446e951b..58c5df07b63b 100755 --- a/components/ILIAS/AdministrativeNotification/classes/class.ilADNNotificationUIFormGUI.php +++ b/components/ILIAS/AdministrativeNotification/classes/class.ilADNNotificationUIFormGUI.php @@ -16,7 +16,8 @@ * *********************************************************************/ -use ILIAS\DI\Container; +use ILIAS\UI\Renderer; +use ILIAS\UI\Component\Input\Container\Form\Standard; use ILIAS\Refinery\Factory; use ILIAS\HTTP\Services; use ILIAS\Refinery\Transformation; @@ -53,8 +54,8 @@ class ilADNNotificationUIFormGUI public const F_PRESENTATION = 'presentation'; protected ilCtrlInterface $ctrl; protected \ILIAS\UI\Factory $ui; - protected \ILIAS\UI\Renderer $renderer; - protected ?\ILIAS\UI\Component\Input\Container\Form\Standard $form = null; + protected Renderer $renderer; + protected ?Standard $form = null; protected Factory $refinery; protected ilLanguage $lng; protected ilRbacReview $rbac_review; @@ -332,18 +333,14 @@ public function initForm(): void self::F_HAS_LANGUAGE_LIMITATION => $languages, self::F_LIMIT_TO_ROLES => $roles, ], $this->txt('form_title'))->withAdditionalTransformation( - $custom_trafo(function ($v): ilADNNotification { - return $this->notification; - }) + $custom_trafo(fn($v): ilADNNotification => $this->notification) ); $this->form = $this->ui->input()->container()->form()->standard( $this->action, [$section] )->withAdditionalTransformation( - $this->refinery->custom()->transformation(function ($v) { - return array_shift($v); - }) + $this->refinery->custom()->transformation(fn($v) => array_shift($v)) ); } diff --git a/components/ILIAS/AdministrativeNotification/classes/class.ilADNTabHandling.php b/components/ILIAS/AdministrativeNotification/classes/class.ilADNTabHandling.php index 1a52d7347841..2a7c3c38f934 100755 --- a/components/ILIAS/AdministrativeNotification/classes/class.ilADNTabHandling.php +++ b/components/ILIAS/AdministrativeNotification/classes/class.ilADNTabHandling.php @@ -22,8 +22,6 @@ */ class ilADNTabHandling { - private int $ref_id; - private ilRbacSystem $rbacsystem; private ilTabsGUI $tabs; @@ -37,11 +35,9 @@ class ilADNTabHandling /** * ilMMTabHandling constructor. */ - public function __construct(int $ref_id) + public function __construct(private int $ref_id) { global $DIC; - - $this->ref_id = $ref_id; $this->tabs = $DIC['ilTabs']; $this->lng = $DIC->language(); $this->lng->loadLanguageModule('adn'); @@ -92,7 +88,7 @@ public function initTabs(string $tab, ?string $subtab = null, bool $backtab = fa $this->tabs->addTab( 'perm_settings', $this->lng->txt('perm_settings'), - $this->ctrl->getLinkTargetByClass(array(ilObjAdministrativeNotificationGUI::class, ilPermissionGUI::class), 'perm') + $this->ctrl->getLinkTargetByClass([ilObjAdministrativeNotificationGUI::class, ilPermissionGUI::class], 'perm') ); } if ($backtab) { diff --git a/components/ILIAS/AdministrativeNotification/classes/class.ilObjAdministrativeNotification.php b/components/ILIAS/AdministrativeNotification/classes/class.ilObjAdministrativeNotification.php index 16276a8e14a2..01bd3e497c4f 100755 --- a/components/ILIAS/AdministrativeNotification/classes/class.ilObjAdministrativeNotification.php +++ b/components/ILIAS/AdministrativeNotification/classes/class.ilObjAdministrativeNotification.php @@ -32,6 +32,7 @@ public function __construct(int $id = 0, bool $call_by_reference = true) /** * @inheritDoc */ + #[\Override] public function getPresentationTitle(): string { return $this->lng->txt("obj_adn"); @@ -40,6 +41,7 @@ public function getPresentationTitle(): string /** * @inheritDoc */ + #[\Override] public function getLongDescription(): string { return $this->lng->txt("administrative_notification_description"); diff --git a/components/ILIAS/AdministrativeNotification/classes/class.ilObjAdministrativeNotificationGUI.php b/components/ILIAS/AdministrativeNotification/classes/class.ilObjAdministrativeNotificationGUI.php index 37e6746abb21..a8e516fb564b 100755 --- a/components/ILIAS/AdministrativeNotification/classes/class.ilObjAdministrativeNotificationGUI.php +++ b/components/ILIAS/AdministrativeNotification/classes/class.ilObjAdministrativeNotificationGUI.php @@ -50,6 +50,7 @@ public function __construct() $this->assignObject(); } + #[\Override] public function executeCommand(): void { $this->admin_notification_access->checkAccessAndThrowException("visible,read"); diff --git a/components/ILIAS/AdministrativeNotification/tests/ilServicesAdministrativeNotificationTest.php b/components/ILIAS/AdministrativeNotification/tests/ilServicesAdministrativeNotificationTest.php index 91c3518f1114..84ca543f7580 100755 --- a/components/ILIAS/AdministrativeNotification/tests/ilServicesAdministrativeNotificationTest.php +++ b/components/ILIAS/AdministrativeNotification/tests/ilServicesAdministrativeNotificationTest.php @@ -18,16 +18,17 @@ declare(strict_types=1); +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use ILIAS\DI\Container; class ilServicesAdministrativeNotificationTest extends TestCase { - private ?\ILIAS\DI\Container $dic_backup; + private ?Container $dic_backup; /** - * @var ilRbacReview|\PHPUnit\Framework\MockObject\MockObject + * @var ilRbacReview|MockObject */ - protected $rbacreview_mock; + protected MockObject $rbacreview_mock; protected function setUp(): void { diff --git a/components/ILIAS/AuthShibboleth/AuthShibboleth.php b/components/ILIAS/AuthShibboleth/AuthShibboleth.php index 7556f42c7976..4e99a137b868 100644 --- a/components/ILIAS/AuthShibboleth/AuthShibboleth.php +++ b/components/ILIAS/AuthShibboleth/AuthShibboleth.php @@ -20,7 +20,11 @@ namespace ILIAS; -class AuthShibboleth implements Component\Component +use ILIAS\Component\Component; +use ILIAS\Component\Resource\PublicAsset; +use ILIAS\Component\Resource\Endpoint; + +class AuthShibboleth implements Component { public function init( array | \ArrayAccess &$define, @@ -32,10 +36,10 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $contribute[Component\Resource\PublicAsset::class] = fn() => - new Component\Resource\Endpoint($this, "shib_login.php"); + $contribute[PublicAsset::class] = fn(): Endpoint => + new Endpoint($this, "shib_login.php"); - $contribute[Component\Resource\PublicAsset::class] = fn() => - new Component\Resource\Endpoint($this, "shib_logout.php"); + $contribute[PublicAsset::class] = fn(): Endpoint => + new Endpoint($this, "shib_logout.php"); } } diff --git a/components/ILIAS/AuthShibboleth/classes/Config/class.ilShibbolethSettings.php b/components/ILIAS/AuthShibboleth/classes/Config/class.ilShibbolethSettings.php index d6851a84beb3..e856e48577fb 100755 --- a/components/ILIAS/AuthShibboleth/classes/Config/class.ilShibbolethSettings.php +++ b/components/ILIAS/AuthShibboleth/classes/Config/class.ilShibbolethSettings.php @@ -1,21 +1,5 @@ action = $action; $this->ctrl = $DIC->ctrl(); $this->lng = $DIC->language(); $this->rbac_review = $DIC->rbac()->review(); $this->refinery = $DIC->refinery(); $this->renderer = $DIC->ui()->renderer(); $this->request = $DIC->http()->request(); - $this->settings = $settings; $this->ui = $DIC->ui()->factory(); $this->initForm(); @@ -75,7 +71,7 @@ public function getHTML(): string public function initForm(): void { $field = $this->ui->input()->field(); - $custom_trafo = fn(callable $c) => $this->refinery->custom()->transformation($c); + $custom_trafo = fn(callable $c): Transformation => $this->refinery->custom()->transformation($c); /** @noRector */ $active = $field->checkbox($this->txt('shib_active'), $this->lng->txt("auth_shib_instructions")) ->withValue($this->settings->isActive()) diff --git a/components/ILIAS/AuthShibboleth/classes/ServerData/class.shibServerData.php b/components/ILIAS/AuthShibboleth/classes/ServerData/class.shibServerData.php index 760e3cea307a..afa1e6c1c4c1 100755 --- a/components/ILIAS/AuthShibboleth/classes/ServerData/class.shibServerData.php +++ b/components/ILIAS/AuthShibboleth/classes/ServerData/class.shibServerData.php @@ -22,7 +22,7 @@ */ class shibServerData extends shibConfig { - protected static ?shibServerData $server_cache; + protected static ?shibServerData $server_cache = null; /** * @noinspection MagicMethodsValidityInspection @@ -39,6 +39,7 @@ protected function __construct(array $data) } } + #[\Override] public static function getInstance(): shibServerData { if (!isset(self::$server_cache)) { diff --git a/components/ILIAS/AuthShibboleth/classes/User/class.shibUser.php b/components/ILIAS/AuthShibboleth/classes/User/class.shibUser.php index d649c5bd0946..f768713ee5b4 100755 --- a/components/ILIAS/AuthShibboleth/classes/User/class.shibUser.php +++ b/components/ILIAS/AuthShibboleth/classes/User/class.shibUser.php @@ -109,7 +109,7 @@ public function createFields(): void $this->setLastname($this->shibServerData->getLastname()); $this->setLogin($this->returnNewLoginName()); $array = ilSecuritySettingsChecker::generatePasswords(1); - $this->setPasswd(md5(end($array)), ilObjUser::PASSWD_CRYPTED); + $this->setPasswd(md5((string) end($array)), ilObjUser::PASSWD_CRYPTED); $this->setGender($this->shibServerData->getGender()); $this->setExternalAccount($this->shibServerData->getLogin()); $this->setTitle($this->shibServerData->getTitle()); @@ -138,19 +138,18 @@ public function createFields(): void /** * @throws ilUserException */ + #[\Override] public function create(): int { $c = shibConfig::getInstance(); $registration_settings = new ilRegistrationSettings(); - $recipients = array_filter($registration_settings->getApproveRecipients(), static function ($v) { - return is_int($v); - }); + $recipients = array_filter($registration_settings->getApproveRecipients(), static fn($v): bool => is_int($v)); if ($recipients !== [] && $c->isActivateNew()) { $this->setActive(false); $mail = new ilRegistrationMailNotification(); $mail->setType(ilRegistrationMailNotification::TYPE_NOTIFICATION_CONFIRMATION); $mail->setRecipients($registration_settings->getApproveRecipients()); - $mail->setAdditionalInformation(array('usr' => $this)); + $mail->setAdditionalInformation(['usr' => $this]); $mail->send(); } diff --git a/components/ILIAS/AuthShibboleth/classes/class.ilAuthProviderShibboleth.php b/components/ILIAS/AuthShibboleth/classes/class.ilAuthProviderShibboleth.php index 6bb2d8473089..b6fa638bef75 100755 --- a/components/ILIAS/AuthShibboleth/classes/class.ilAuthProviderShibboleth.php +++ b/components/ILIAS/AuthShibboleth/classes/class.ilAuthProviderShibboleth.php @@ -66,7 +66,7 @@ public function doAuthentication(ilAuthStatus $status): bool $shib_user->update(); $shib_user = ilShibbolethPluginWrapper::getInstance()->afterUpdateUser($shib_user); ilShibbolethRoleAssignmentRules::updateAssignments($shib_user->getId(), $_SERVER); - } elseif (!($account_creation === ilShibbolethSettings::ACCOUNT_CREATION_DISABLED)) { + } elseif ($account_creation !== ilShibbolethSettings::ACCOUNT_CREATION_DISABLED) { $shib_user->createFields(); $shib_user->setPref('hits_per_page', $this->settings->get('hits_per_page')); @@ -93,7 +93,7 @@ public function doAuthentication(ilAuthStatus $status): bool ilShibbolethRoleAssignmentRules::doAssignments($shib_user->getId(), $_SERVER); } - if(!$new_user || $account_creation === ilShibbolethSettings::ACCOUNT_CREATION_ENABLED) { + if (!$new_user || $account_creation === ilShibbolethSettings::ACCOUNT_CREATION_ENABLED) { $status->setStatus(ilAuthStatus::STATUS_AUTHENTICATED); $status->setAuthenticatedUserId(ilObjUser::_lookupId($shib_user->getLogin())); } elseif ($account_creation === ilShibbolethSettings::ACCOUNT_CREATION_WITH_APPROVAL) { diff --git a/components/ILIAS/AuthShibboleth/classes/class.ilAuthShibbolethSettingsGUI.php b/components/ILIAS/AuthShibboleth/classes/class.ilAuthShibbolethSettingsGUI.php index 2598dc8b3f78..fe2dc4cde05b 100755 --- a/components/ILIAS/AuthShibboleth/classes/class.ilAuthShibbolethSettingsGUI.php +++ b/components/ILIAS/AuthShibboleth/classes/class.ilAuthShibbolethSettingsGUI.php @@ -30,6 +30,9 @@ */ class ilAuthShibbolethSettingsGUI { + /** + * @var string + */ private const PARAM_RULE_ID = 'rule_id'; private ilAccessHandler $access; @@ -41,7 +44,6 @@ class ilAuthShibbolethSettingsGUI private ilLanguage $lng; private RBACServices $rbac; private ilRbacReview $rbac_review; - private int $ref_id; private Refinery $refinery; private ?ilShibbolethRoleAssignmentRule $rule = null; private ilShibbolethSettings $shib_settings; @@ -50,7 +52,7 @@ class ilAuthShibbolethSettingsGUI private WrapperFactory $wrapper; - public function __construct(int $a_auth_ref_id) + public function __construct(private int $ref_id) { global $DIC; @@ -62,7 +64,6 @@ public function __construct(int $a_auth_ref_id) $this->lng->loadLanguageModule('shib'); $this->rbac = $DIC->rbac(); $this->rbac_review = $DIC->rbac()->review(); - $this->ref_id = $a_auth_ref_id; $this->refinery = $DIC->refinery(); $this->shib_settings = new ilShibbolethSettings(); $this->tabs_gui = $DIC->tabs(); @@ -405,7 +406,7 @@ private function loadRule(int $a_rule_id = 0): ilShibbolethRoleAssignmentRule $parser->setCombination(ilQueryParser::QP_COMBINATION_AND); $parser->parse(); $object_search = new ilLikeObjectSearch($parser); - $object_search->setFilter(array('role')); + $object_search->setFilter(['role']); $res = $object_search->performSearch(); $entries = $res->getEntries(); if (count($entries) === 1) { @@ -453,7 +454,7 @@ private function getRuleValues(): void $this->form->setValuesByArray($values); } - private function checkInput($a_rule_id = 0): string + private function checkInput(int $a_rule_id = 0): string { $this->loadRule($a_rule_id); diff --git a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethAuthenticationPlugin.php b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethAuthenticationPlugin.php index 0cf049727181..a1c1c7dc8a57 100755 --- a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethAuthenticationPlugin.php +++ b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethAuthenticationPlugin.php @@ -36,14 +36,14 @@ protected function checkValue(array $a_user_data, string $a_keyword, string $a_v } if (is_array($a_user_data[$a_keyword])) { foreach ($a_user_data[$a_keyword] as $values) { - if (strcasecmp(trim($values), $a_value) === 0) { + if (strcasecmp(trim((string) $values), $a_value) === 0) { return true; } } return false; } - return strcasecmp(trim($a_user_data[$a_keyword]), trim($a_value)) === 0; + return strcasecmp(trim((string) $a_user_data[$a_keyword]), trim($a_value)) === 0; } diff --git a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentRule.php b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentRule.php index 8e87c24f7dfd..9b31789eb411 100755 --- a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentRule.php +++ b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentRule.php @@ -1,20 +1,4 @@ db = $DIC->database(); - $this->rule_id = $a_rule_id; $this->read(); } @@ -257,7 +254,7 @@ public function doesMatch(array $a_data): bool $pattern = str_replace('*', '.*?', $this->getValue()); - return (bool) preg_match('/^' . $pattern . '$/us', $values); + return (bool) preg_match('/^' . $pattern . '$/us', (string) $values); } private function read(): void diff --git a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentRules.php b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentRules.php index dcee0ae6aca8..fa0f8e208a6f 100755 --- a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentRules.php +++ b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentRules.php @@ -34,7 +34,7 @@ public static function getAllRules(): array { global $DIC; $db = $DIC->database(); - $rules = array(); + $rules = []; /** * @var $db ilDBInterface */ diff --git a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentTableGUI.php b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentTableGUI.php index 802b3a29bf17..4a5603e5396b 100755 --- a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentTableGUI.php +++ b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethRoleAssignmentTableGUI.php @@ -50,6 +50,7 @@ public function __construct(ilAuthShibbolethSettingsGUI $a_parent_obj, string $a /** * @throws ilCtrlException */ + #[\Override] protected function fillRow(array $a_set): void { $this->tpl->setVariable('VAL_ID', $a_set['id']); diff --git a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethWAYF.php b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethWAYF.php index 4b8b0d5c590e..ec59944d567c 100755 --- a/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethWAYF.php +++ b/components/ILIAS/AuthShibboleth/classes/class.ilShibbolethWAYF.php @@ -148,7 +148,7 @@ public function setSAMLCookie(): void $_saml_idp = $this->wrapper->cookie()->retrieve(self::COOKIE_NAME_SAML_IDP, $this->refinery->kindlyTo()->string()); $arr_idps = $_saml_idp ? $this->generateCookieArray($_saml_idp) : []; $arr_idps = $this->appendCookieValue($this->selected_idp, $arr_idps); - setcookie(self::COOKIE_NAME_SAML_IDP, $this->generateCookieValue($arr_idps), time() + (100 * 24 * 3600), '/'); + setcookie(self::COOKIE_NAME_SAML_IDP, $this->generateCookieValue($arr_idps), ['expires' => time() + (100 * 24 * 3600), 'path' => '/']); } /** @@ -170,13 +170,13 @@ public function showNotice(): string public function getIdplist(): array { $idp_list = []; - $idp_raw_list = explode("\n", $this->settings->get("shib_idp_list")); + $idp_raw_list = explode("\n", (string) $this->settings->get("shib_idp_list")); foreach ($idp_raw_list as $idp_line) { $idp_data = explode(',', $idp_line); if (isset($idp_data[2])) { - $idp_list[trim($idp_data[0])] = array(trim($idp_data[1]), trim($idp_data[2])); + $idp_list[trim($idp_data[0])] = [trim($idp_data[1]), trim($idp_data[2])]; } elseif (isset($idp_data[1])) { - $idp_list[trim($idp_data[0])] = array(trim($idp_data[1])); + $idp_list[trim($idp_data[0])] = [trim($idp_data[1])]; } } diff --git a/components/ILIAS/AuthShibboleth/resources/shib_logout.php b/components/ILIAS/AuthShibboleth/resources/shib_logout.php index 4e2eec33315c..4d721747838a 100644 --- a/components/ILIAS/AuthShibboleth/resources/shib_logout.php +++ b/components/ILIAS/AuthShibboleth/resources/shib_logout.php @@ -126,7 +126,7 @@ /******************************************************************************/ /// This function does the actual logout -function LogoutNotification($SessionID) +function LogoutNotification($SessionID): ?\SoapFault { // Delete session of user using $SessionID to locate the user's session file // on the file system or in the database @@ -145,29 +145,30 @@ function LogoutNotification($SessionID) // Look for session with matching Shibboleth session id // and then delete this ilias session foreach ($user_session as $user_session_entry) { - if (is_array($user_session_entry) - && array_key_exists('shibboleth_session_id', $user_session_entry) - && $user_session_entry['shibboleth_session_id'] == $SessionID + // Delete this session entry + if (is_array($user_session_entry) && array_key_exists('shibboleth_session_id', $user_session_entry) && $user_session_entry['shibboleth_session_id'] == $SessionID && !ilSession::_destroy($session_entry['session_id']) ) { - // Delete this session entry - if (ilSession::_destroy($session_entry['session_id']) !== true) { - return new SoapFault('LogoutError', 'Could not delete session entry in database.'); - } + return new SoapFault('LogoutError', 'Could not delete session entry in database.'); } } } // If no SoapFault is returned, all is fine + return null; } /******************************************************************************/ // Deserializes session data and returns it in a hash array of arrays -function unserializesession($serialized_string) +/** + * @return mixed[] + */ +function unserializesession($serialized_string): array { - $variables = array(); - $a = preg_split("/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); - for ($i = 0; $i < count($a); $i = $i + 2) { + $variables = []; + $a = preg_split("/(\w+)\|/", (string) $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); + $counter = count($a); + for ($i = 0; $i < $counter; $i += 2) { $variables[$a[$i]] = unserialize($a[$i + 1]); } return ($variables); -} \ No newline at end of file +} diff --git a/components/ILIAS/AuthShibboleth/tests/ilServicesAuthShibbolethTest.php b/components/ILIAS/AuthShibboleth/tests/ilServicesAuthShibbolethTest.php index 58c52fab648d..9ef8391f920e 100755 --- a/components/ILIAS/AuthShibboleth/tests/ilServicesAuthShibbolethTest.php +++ b/components/ILIAS/AuthShibboleth/tests/ilServicesAuthShibbolethTest.php @@ -23,7 +23,7 @@ class ilServicesAuthShibbolethTest extends TestCase { - private ?\ILIAS\DI\Container $dic_backup; + private ?Container $dic_backup; protected function setUp(): void { diff --git a/components/ILIAS/BackgroundTasks/BackgroundTasks.php b/components/ILIAS/BackgroundTasks/BackgroundTasks.php index bdf965561f0e..7785d9d378dd 100644 --- a/components/ILIAS/BackgroundTasks/BackgroundTasks.php +++ b/components/ILIAS/BackgroundTasks/BackgroundTasks.php @@ -20,7 +20,11 @@ namespace ILIAS; -class BackgroundTasks implements Component\Component +use ILIAS\Component\Component; +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Factory; + +class BackgroundTasks implements Component { public function init( array | \ArrayAccess &$define, @@ -32,9 +36,9 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $contribute[\ILIAS\Setup\Agent::class] = static fn() => + $contribute[Agent::class] = static fn(): \ilBackgroundTasksSetupAgent => new \ilBackgroundTasksSetupAgent( - $pull[\ILIAS\Refinery\Factory::class] + $pull[Factory::class] ); } } diff --git a/components/ILIAS/BackgroundTasks/src/BackgroundTaskServices.php b/components/ILIAS/BackgroundTasks/src/BackgroundTaskServices.php index 22db711d0460..18f7e30b120b 100755 --- a/components/ILIAS/BackgroundTasks/src/BackgroundTaskServices.php +++ b/components/ILIAS/BackgroundTasks/src/BackgroundTaskServices.php @@ -31,11 +31,8 @@ */ class BackgroundTaskServices { - protected Container $container; - - public function __construct(Container $container) + public function __construct(protected Container $container) { - $this->container = $container; } public function taskFactory(): TaskFactory diff --git a/components/ILIAS/BackgroundTasks/src/Dependencies/DependencyMap/BaseDependencyMap.php b/components/ILIAS/BackgroundTasks/src/Dependencies/DependencyMap/BaseDependencyMap.php index f1d8fcdd9636..2bf7e028d3f2 100755 --- a/components/ILIAS/BackgroundTasks/src/Dependencies/DependencyMap/BaseDependencyMap.php +++ b/components/ILIAS/BackgroundTasks/src/Dependencies/DependencyMap/BaseDependencyMap.php @@ -18,6 +18,8 @@ namespace ILIAS\BackgroundTasks\Dependencies\DependencyMap; +use ILIAS\UI\Factory; +use ILIAS\UI\Renderer; use ILIAS\BackgroundTasks\Dependencies\Injector; use ILIAS\BackgroundTasks\Persistence; use ILIAS\BackgroundTasks\Task\TaskFactory; @@ -34,9 +36,7 @@ class BaseDependencyMap extends EmptyDependencyMap public function __construct() { - $this->maps = [function (\ILIAS\DI\Container $DIC, $fullyQualifiedDomainName, $for) { - return $this->resolveBaseDependencies($DIC, $fullyQualifiedDomainName, $for); - }]; + $this->maps = [fn(Container $DIC, $fullyQualifiedDomainName, $for) => $this->resolveBaseDependencies($DIC, $fullyQualifiedDomainName, $for)]; } protected function resolveBaseDependencies(Container $DIC, $fullyQualifiedDomainName, $for) @@ -74,9 +74,9 @@ protected function resolveBaseDependencies(Container $DIC, $fullyQualifiedDomain return $DIC->backgroundTasks()->injector(); case \ilSetting::class: return $DIC->settings(); - case \ILIAS\UI\Factory::class: + case Factory::class: return $DIC->ui()->factory(); - case \ILIAS\UI\Renderer::class: + case Renderer::class: return $DIC->ui()->renderer(); case \ilTemplate::class: return $DIC->ui()->mainTemplate(); diff --git a/components/ILIAS/BackgroundTasks/src/Dependencies/DependencyMap/EmptyDependencyMap.php b/components/ILIAS/BackgroundTasks/src/Dependencies/DependencyMap/EmptyDependencyMap.php index 74c836bfa20f..21c625eaffcf 100755 --- a/components/ILIAS/BackgroundTasks/src/Dependencies/DependencyMap/EmptyDependencyMap.php +++ b/components/ILIAS/BackgroundTasks/src/Dependencies/DependencyMap/EmptyDependencyMap.php @@ -38,9 +38,8 @@ public function getDependencyWith(Container $DIC, string $fullyQualifiedDomainNa $result = $map($DIC, $fullyQualifiedDomainName, $for); if ($result) { return $result; - } else { - return $this->getDependency($DIC, $fullyQualifiedDomainName, $for); } + return $this->getDependency($DIC, $fullyQualifiedDomainName, $for); } /** diff --git a/components/ILIAS/BackgroundTasks/src/Dependencies/Injector.php b/components/ILIAS/BackgroundTasks/src/Dependencies/Injector.php index 4e6a078f5273..1bddd9ccd1e3 100755 --- a/components/ILIAS/BackgroundTasks/src/Dependencies/Injector.php +++ b/components/ILIAS/BackgroundTasks/src/Dependencies/Injector.php @@ -31,17 +31,12 @@ */ class Injector { - protected \ILIAS\DI\Container $dic; - protected \ILIAS\BackgroundTasks\Dependencies\DependencyMap\DependencyMap $dependencyMap; - /** * Factory constructor. * @param $dic Container */ - public function __construct(Container $dic, DependencyMap $dependencyMap) + public function __construct(protected Container $dic, protected DependencyMap $dependencyMap) { - $this->dic = $dic; - $this->dependencyMap = $dependencyMap; } /** @@ -114,8 +109,7 @@ protected function getDependency( if ($with) { return $this->dependencyMap->getDependencyWith($this->dic, $type, $fullyQualifiedClassName, $with); - } else { - return $this->dependencyMap->getDependency($this->dic, $type, $fullyQualifiedClassName); } + return $this->dependencyMap->getDependency($this->dic, $type, $fullyQualifiedClassName); } } diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Bucket/BasicBucket.php b/components/ILIAS/BackgroundTasks/src/Implementation/Bucket/BasicBucket.php index 19a32ea4dea7..07352a4c671b 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Bucket/BasicBucket.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Bucket/BasicBucket.php @@ -18,6 +18,8 @@ namespace ILIAS\BackgroundTasks\Implementation\Bucket; +use ILIAS\BackgroundTasks\Task\Job; +use ILIAS\BackgroundTasks\Task\UserInteraction; use ILIAS\BackgroundTasks\Bucket; use ILIAS\BackgroundTasks\Exceptions\Exception; use ILIAS\BackgroundTasks\Implementation\Values\ThunkValue; @@ -88,7 +90,7 @@ public function calculateOverallPercentage(): void * @var $task Task\UserInteraction\ */ foreach ($this->tasks as $task) { - if ($task instanceof Task\Job) { + if ($task instanceof Job) { $countable_tasks++; } } @@ -130,7 +132,7 @@ public function checkIntegrity(): bool { if ($this->getUserId() === 0) { foreach ($this->getTask()->unfoldTask() as $task) { - if ($task instanceof Task\UserInteraction) { + if ($task instanceof UserInteraction) { throw new Exception("Your task contains user interactions and thus needs a user that observes the task."); } } @@ -149,7 +151,7 @@ public function userInteraction(Option $option): void if ($this->getState() != State::USER_INTERACTION) { throw new Exception("Cannot continue a task that is not in the state 'user interaction'"); } - if (!$currentTask instanceof Task\UserInteraction) { + if (!$currentTask instanceof UserInteraction) { // TODO: Maybe cleanup task? throw new Exception("Observer is in an invalid state! state: userInteraction but current task is not a user interaction!"); } diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Persistence/BasicPersistence.php b/components/ILIAS/BackgroundTasks/src/Implementation/Persistence/BasicPersistence.php index a794980a1093..001788e94a50 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Persistence/BasicPersistence.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Persistence/BasicPersistence.php @@ -33,7 +33,6 @@ class BasicPersistence implements Persistence { protected static BasicPersistence $instance; protected static array $buckets = []; - protected \ilDBInterface $db; protected \SplObjectStorage $bucketHashToObserverContainerId; protected \SplObjectStorage $taskHashToTaskContainerId; protected \SplObjectStorage $valueHashToValueContainerId; @@ -49,9 +48,8 @@ public static function instance(\ilDBInterface $db): \ILIAS\BackgroundTasks\Impl return self::$instance; } - public function __construct(\ilDBInterface $db) + public function __construct(protected \ilDBInterface $db) { - $this->db = $db; $this->valueHashToValueContainerId = new \SplObjectStorage(); $this->bucketHashToObserverContainerId = new \SplObjectStorage(); $this->taskHashToTaskContainerId = new \SplObjectStorage(); @@ -124,7 +122,7 @@ public function getBucketMetaOfUser(int $user_id): array { $buckets = BucketContainer::where(['user_id' => $user_id])->get(); - return array_map(function (BucketContainer $bucketContainer): \ILIAS\BackgroundTasks\Implementation\Bucket\BasicBucketMeta { + return array_map(function (BucketContainer $bucketContainer): BasicBucketMeta { $bucketMeta = new BasicBucketMeta(); $bucketMeta->setUserId($bucketContainer->getUserId()); @@ -144,7 +142,7 @@ public function getBucketIdsByState(int $state): array { $buckets = BucketContainer::where(['state' => $state])->get(); - return array_map(fn (BucketContainer $bucket_container): int => $bucket_container->getId(), $buckets); + return array_map(fn(BucketContainer $bucket_container): int => $bucket_container->getId(), $buckets); } /** @@ -204,8 +202,8 @@ protected function saveTask(Task $task, int $bucketId): void // The basic information about the task. $taskContainer->setType($task->getType()); $taskContainer->setBucketId($bucketId); - $reflection = new \ReflectionClass(get_class($task)); - $taskContainer->setClassName(get_class($task)); + $reflection = new \ReflectionClass($task::class); + $taskContainer->setClassName($task::class); // Recursivly save the inputs and link them to this task. foreach ($task->getInput() as $k => $input) { @@ -263,7 +261,7 @@ protected function saveValue(Value $value, int $bucketId, int $position): void } else { $valueContainer = new ValueContainer(0, $this->connector); } - $valueContainer->setClassName(get_class($value)); + $valueContainer->setClassName($value::class); // bugfix mantis 23503 // $absolute_class_path = $reflection->getFileName(); // $relative_class_path = str_replace(ILIAS_ABSOLUTE_PATH,".",$absolute_class_path); @@ -323,11 +321,11 @@ protected function getValueContainerId(Value $value): int . print_r($value, true)); } - return (int )$this->valueHashToValueContainerId[$value]; + return (int) $this->valueHashToValueContainerId[$value]; } /** - * @throws \ILIAS\BackgroundTasks\Exceptions\BucketNotFoundException + * @throws BucketNotFoundException */ public function loadBucket(int $bucket_container_id): Bucket { @@ -362,7 +360,7 @@ public function loadBucket(int $bucket_container_id): Bucket * @param BucketContainer $bucketContainer Needed because we need the current tasks container * id for correct linking. */ - private function loadTask(int $taskContainerId, Bucket $bucket, BucketContainer $bucketContainer): \ILIAS\BackgroundTasks\Task + private function loadTask(int $taskContainerId, Bucket $bucket, BucketContainer $bucketContainer): Task { global $DIC; $factory = $DIC->backgroundTasks()->taskFactory(); @@ -393,7 +391,7 @@ private function loadTask(int $taskContainerId, Bucket $bucket, BucketContainer return $task; } - private function loadValue($valueContainerId, Bucket $bucket, BucketContainer $bucketContainer): \ILIAS\BackgroundTasks\Value + private function loadValue($valueContainerId, Bucket $bucket, BucketContainer $bucketContainer): Value { global $DIC; $factory = $DIC->backgroundTasks()->injector(); @@ -452,7 +450,7 @@ public function deleteBucket(Bucket $bucket): void } /** - * @return \ILIAS\BackgroundTasks\Bucket[] + * @return Bucket[] */ public function loadBuckets(array $bucket_container_ids): array { @@ -460,7 +458,7 @@ public function loadBuckets(array $bucket_container_ids): array foreach ($bucket_container_ids as $bucket_id) { try { $buckets[] = $this->loadBucket($bucket_id); - } catch (\Throwable $t) { + } catch (\Throwable) { // there seem to be a problem with this container, we must delete it $this->deleteBucketById($bucket_id); } diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/AsyncTaskManager.php b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/AsyncTaskManager.php index 25a1e466e02a..ed280dad25a7 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/AsyncTaskManager.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/AsyncTaskManager.php @@ -22,8 +22,6 @@ use ILIAS\BackgroundTasks\Implementation\Bucket\State; use ILIAS\BackgroundTasks\Implementation\Tasks\UserInteraction\UserInteractionRequiredException; use ILIAS\BackgroundTasks\Implementation\Tasks\UserInteraction\UserInteractionSkippedException; -use ILIAS\BackgroundTasks\Task\UserInteraction; -use ILIAS\Export\ImportStatus\Exception\ilException; class AsyncTaskManager extends BasicTaskManager { @@ -68,9 +66,9 @@ public function run(Bucket $bucket): void ); try { - $soap_client->call(self::CMD_START_WORKER, array( + $soap_client->call(self::CMD_START_WORKER, [ $session_id . '::' . $client_id, - )); + ]); } catch (\Throwable $t) { $DIC->logger()->bgtk()->warning($t->getMessage()); $DIC->logger()->bgtk()->warning("Calling webserver failed, fallback to sync version"); @@ -82,14 +80,14 @@ public function run(Bucket $bucket): void } /** - * @return void|bool + * @return bool|null */ - public function runAsync() + public function runAsync(): ?bool { global $DIC, $ilIliasIniFile; $n_of_tasks = $ilIliasIniFile->readVariable("background_tasks", "number_of_concurrent_tasks"); - $n_of_tasks = $n_of_tasks ? $n_of_tasks : 5; + $n_of_tasks = $n_of_tasks ?: 5; $DIC->logger()->bgtk()->info("Starting background job."); $persistence = $DIC->backgroundTasks()->persistence(); @@ -99,7 +97,7 @@ public function runAsync() if (count($persistence->getBucketIdsByState(State::RUNNING)) >= $MAX_PARALLEL_JOBS) { $DIC->logger()->bgtk()->info("Too many running jobs, worker going down."); - return; + return null; } while (true) { @@ -116,10 +114,10 @@ public function runAsync() $this->executeTask($task, $observer); $bucket->setState(State::FINISHED); $this->persistence->updateBucket($bucket); - } catch (UserInteractionSkippedException $e) { + } catch (UserInteractionSkippedException) { $bucket->setState(State::FINISHED); $this->persistence->deleteBucket($bucket); - } catch (UserInteractionRequiredException $e) { + } catch (UserInteractionRequiredException) { // We're okay! $this->persistence->saveBucketAndItsTasks($bucket); } catch (\Exception $e) { diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/BasicTaskManager.php b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/BasicTaskManager.php index 842e4d6a4ee4..452182cfbd3d 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/BasicTaskManager.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/BasicTaskManager.php @@ -18,6 +18,8 @@ namespace ILIAS\BackgroundTasks\Implementation\TaskManager; +use ILIAS\BackgroundTasks\Task\Job; +use ILIAS\BackgroundTasks\Task\UserInteraction; use ILIAS\BackgroundTasks\Bucket; use ILIAS\BackgroundTasks\Exceptions\Exception; use ILIAS\BackgroundTasks\Implementation\Bucket\State; @@ -44,11 +46,8 @@ */ abstract class BasicTaskManager implements TaskManager { - protected Persistence $persistence; - - public function __construct(Persistence $persistence) + public function __construct(protected Persistence $persistence) { - $this->persistence = $persistence; } /** @@ -62,7 +61,7 @@ public function executeTask(Task $task, Observer $observer): Value $final_values = []; $replace_thunk_values = false; foreach ($values as $value) { - if (is_a($value, ThunkValue::class)) { + if ($value instanceof ThunkValue) { $value = $this->executeTask($value->getParentTask(), $observer); $replace_thunk_values = true; } @@ -73,7 +72,7 @@ public function executeTask(Task $task, Observer $observer): Value $task->setInput($final_values); } - if (is_a($task, Task\Job::class)) { + if ($task instanceof Job) { /** @var Task\Job $job */ $job = $task; $observer->notifyCurrentTask($job); @@ -89,7 +88,7 @@ public function executeTask(Task $task, Observer $observer): Value return $value; } - if (is_a($task, Task\UserInteraction::class)) { + if ($task instanceof UserInteraction) { /** @var Task\UserInteraction $user_interaction */ $user_interaction = $task; diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/NonPersistingObserver.php b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/NonPersistingObserver.php index 235f267a4ac1..fca0e7636b4d 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/NonPersistingObserver.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/NonPersistingObserver.php @@ -29,11 +29,8 @@ */ class NonPersistingObserver implements Observer { - protected \ILIAS\BackgroundTasks\Bucket $bucket; - - public function __construct(Bucket $bucket) + public function __construct(protected Bucket $bucket) { - $this->bucket = $bucket; } /** diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/PersistingObserver.php b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/PersistingObserver.php index 81fe49d27a13..f575da03708b 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/PersistingObserver.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/PersistingObserver.php @@ -30,13 +30,8 @@ */ class PersistingObserver implements Observer { - protected \ILIAS\BackgroundTasks\Bucket $bucket; - protected \ILIAS\BackgroundTasks\Persistence $persistence; - - public function __construct(Bucket $bucket, Persistence $persistence) + public function __construct(protected Bucket $bucket, protected Persistence $persistence) { - $this->bucket = $bucket; - $this->persistence = $persistence; } /** diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/SyncTaskManager.php b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/SyncTaskManager.php index 013f4af72b6d..784597f8c797 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/SyncTaskManager.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/TaskManager/SyncTaskManager.php @@ -38,11 +38,8 @@ */ class SyncTaskManager extends BasicTaskManager { - protected Persistence $persistence; - - public function __construct(Persistence $persistence) + public function __construct(protected Persistence $persistence) { - $this->persistence = $persistence; } /** @@ -61,9 +58,9 @@ public function run(Bucket $bucket): void throw new UserInteractionSkippedException('can be skipped'); } $bucket->setState(State::FINISHED); - } catch (UserInteractionSkippedException $e) { + } catch (UserInteractionSkippedException) { $bucket->setState(State::FINISHED); - } catch (UserInteractionRequiredException $e) { + } catch (UserInteractionRequiredException) { // We're okay! $this->persistence->saveBucketAndItsTasks($bucket); } diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/AbstractJob.php b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/AbstractJob.php index de0e0a650d0f..5b4e7eec102a 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/AbstractJob.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/AbstractJob.php @@ -30,6 +30,7 @@ abstract class AbstractJob extends AbstractTask implements Job /** * @inheritdoc */ + #[\Override] public function getInput(): array { return $this->input; diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/AbstractTask.php b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/AbstractTask.php index b6d0f15fd63d..e463e28e2b2d 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/AbstractTask.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/AbstractTask.php @@ -42,7 +42,7 @@ abstract class AbstractTask implements Task * @var Value[] */ protected array $input = []; - protected \ILIAS\BackgroundTasks\Value $output; + protected Value $output; /** * @param Value[]|Task[] $values @@ -53,7 +53,7 @@ public function setInput(array $values): void $this->checkTypes($this->input); } - protected function checkTypes($values) + protected function checkTypes(array $values) { $expectedTypes = $this->getInputTypes(); @@ -99,7 +99,7 @@ public function getOutput(): Value * @param $values (Value|Task)[] * @return Value[] */ - private function getValues($values): array + private function getValues(array $values): array { $inputs = []; @@ -138,7 +138,7 @@ public function unfoldTask(): array { $list = [$this]; foreach ($this->getInput() as $input) { - if (is_a($input, ThunkValue::class)) { + if ($input instanceof ThunkValue) { $list = array_merge($list, $input->getParentTask()->unfoldTask()); } } diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/Aggregation/ConcatenationJob.php b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/Aggregation/ConcatenationJob.php index d1d099ba0ab7..4bc3c35885bf 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/Aggregation/ConcatenationJob.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/Aggregation/ConcatenationJob.php @@ -30,7 +30,7 @@ class ConcatenationJob extends AbstractJob { /** - * @param \ILIAS\BackgroundTasks\Value[] $input + * @param Value[] $input * @param Observer $observer Notify the bucket about your progress! */ public function run(array $input, Observer $observer): Value @@ -39,7 +39,7 @@ public function run(array $input, Observer $observer): Value $list = $input[0]->getList(); /** @var ScalarValue[] $values */ $values = array_map( - fn ($a) => $a->getValue(), + fn($a) => $a->getValue(), $list ); diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/BasicTaskFactory.php b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/BasicTaskFactory.php index b29e143d1de5..17fac97198cd 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/BasicTaskFactory.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/BasicTaskFactory.php @@ -19,7 +19,6 @@ namespace ILIAS\BackgroundTasks\Implementation\Tasks; use ILIAS\BackgroundTasks\Dependencies\Injector; -use ILIAS\BackgroundTasks\Exceptions\InvalidArgumentException; use ILIAS\BackgroundTasks\Implementation\Values\ScalarValues\BasicScalarValueFactory; use ILIAS\BackgroundTasks\Task; use ILIAS\BackgroundTasks\Task\TaskFactory; @@ -29,11 +28,8 @@ class BasicTaskFactory implements TaskFactory { use BasicScalarValueFactory; - protected \ILIAS\BackgroundTasks\Dependencies\Injector $injector; - - public function __construct(Injector $injector) + public function __construct(protected Injector $injector) { - $this->injector = $injector; } /** @@ -47,7 +43,7 @@ public function createTask(string $class_name, ?array $input = null): Task /** @var Task $task */ $task = $this->injector->createInstance($class_name); if ($input) { - $wrappedInput = array_map(function ($i): \ILIAS\BackgroundTasks\Value { + $wrappedInput = array_map(function ($i): Value { if ($i instanceof Task) { return $i->getOutput(); } diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/DownloadInteger.php b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/DownloadInteger.php index c554d1517a68..7b2340c1727c 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/DownloadInteger.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/DownloadInteger.php @@ -55,7 +55,7 @@ public function interaction(array $input, Option $user_selected_option, Bucket $ $integerValue = $input[0]; global $DIC; - if ($user_selected_option->getValue() == "download") { + if ($user_selected_option->getValue() === "download") { $outputter = new \ilPHPOutputDelivery(); $outputter->start("IntegerFile"); echo $integerValue->getValue(); diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/NotFoundUserInteraction.php b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/NotFoundUserInteraction.php index 046d50c8dd02..e695a74e239c 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/NotFoundUserInteraction.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/NotFoundUserInteraction.php @@ -20,7 +20,6 @@ use ILIAS\BackgroundTasks\Bucket; use ILIAS\BackgroundTasks\Implementation\Values\ScalarValues\BooleanValue; -use ILIAS\BackgroundTasks\Implementation\Values\ThunkValue; use ILIAS\BackgroundTasks\Task\UserInteraction\Option; use ILIAS\BackgroundTasks\Types\SingleType; use ILIAS\BackgroundTasks\Types\Type; diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/UserInteraction/UserInteractionOption.php b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/UserInteraction/UserInteractionOption.php index 903e4b939954..4c1a9fff4730 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/UserInteraction/UserInteractionOption.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Tasks/UserInteraction/UserInteractionOption.php @@ -22,16 +22,11 @@ class UserInteractionOption implements Option { - protected string $lang_var; - protected string $value; - /** * UserInteractionOption constructor. */ - public function __construct(string $lang_var, string $value) + public function __construct(protected string $lang_var, protected string $value) { - $this->lang_var = $lang_var; - $this->value = $value; } diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Values/AggregationValues/ListValue.php b/components/ILIAS/BackgroundTasks/src/Implementation/Values/AggregationValues/ListValue.php index 2fca1993ec3b..184b27c847e1 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Values/AggregationValues/ListValue.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Values/AggregationValues/ListValue.php @@ -104,7 +104,7 @@ protected function sameClassOnLevel(array $ancestorsList, int $i): bool } /** - * @return \ILIAS\BackgroundTasks\Types\Type[] + * @return Type[] */ protected function getTypes(array $list): array { @@ -138,7 +138,7 @@ public function serialize() * @return void * @since 5.1.0 */ - public function unserialize($serialized) + public function unserialize($serialized): void { $this->list = unserialize($serialized); $this->type = $this->deriveType($this->list); @@ -205,7 +205,7 @@ protected function getClassHierarchy($object): array } $hierarchy = []; - $class = get_class($object); + $class = $object::class; do { $hierarchy[] = $class; @@ -214,6 +214,7 @@ protected function getClassHierarchy($object): array return $hierarchy; } + #[\Override] public function getType(): Type { return $this->type; diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/BooleanValue.php b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/BooleanValue.php index 1dba59668833..12e9def61a7e 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/BooleanValue.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/BooleanValue.php @@ -18,10 +18,9 @@ namespace ILIAS\BackgroundTasks\Implementation\Values\ScalarValues; -use ILIAS\BackgroundTasks\Value; - class BooleanValue extends ScalarValue { + #[\Override] public function setValue($value): void { if (!is_bool($value)) { diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/FloatValue.php b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/FloatValue.php index aba57a2847fb..246e97dc9f32 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/FloatValue.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/FloatValue.php @@ -18,10 +18,9 @@ namespace ILIAS\BackgroundTasks\Implementation\Values\ScalarValues; -use ILIAS\BackgroundTasks\Value; - class FloatValue extends ScalarValue { + #[\Override] public function setValue($value): void { if (!is_float($value)) { diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/IntegerValue.php b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/IntegerValue.php index 59ebc32327d6..bbe796ea3738 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/IntegerValue.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/IntegerValue.php @@ -19,10 +19,10 @@ namespace ILIAS\BackgroundTasks\Implementation\Values\ScalarValues; use ILIAS\BackgroundTasks\Exceptions\InvalidArgumentException; -use ILIAS\BackgroundTasks\Value; class IntegerValue extends ScalarValue { + #[\Override] public function setValue($value): void { if (!is_int($value)) { diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/ScalarValue.php b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/ScalarValue.php index f050644a8127..6947bfd881db 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/ScalarValue.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/ScalarValue.php @@ -49,7 +49,7 @@ public function serialize() * @return void * @since 5.1.0 */ - public function unserialize($serialized) + public function unserialize($serialized): void { $this->value = unserialize($serialized); } diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/StringValue.php b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/StringValue.php index 56be5abaeabd..7bcd178db56b 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/StringValue.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ScalarValues/StringValue.php @@ -19,10 +19,10 @@ namespace ILIAS\BackgroundTasks\Implementation\Values\ScalarValues; use ILIAS\BackgroundTasks\Exceptions\InvalidArgumentException; -use ILIAS\BackgroundTasks\Value; class StringValue extends ScalarValue { + #[\Override] public function setValue($value): void { if (!is_string($value)) { diff --git a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ThunkValue.php b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ThunkValue.php index 9ff8f925d596..1e4646814a32 100755 --- a/components/ILIAS/BackgroundTasks/src/Implementation/Values/ThunkValue.php +++ b/components/ILIAS/BackgroundTasks/src/Implementation/Values/ThunkValue.php @@ -32,6 +32,7 @@ class ThunkValue extends AbstractValue { protected Type $type; + #[\Override] public function getType(): Type { return $this->parentTask->getOutputType(); diff --git a/components/ILIAS/BackgroundTasks/src/Task/Job.php b/components/ILIAS/BackgroundTasks/src/Task/Job.php index 81d9f71d8a80..eaae37de8837 100755 --- a/components/ILIAS/BackgroundTasks/src/Task/Job.php +++ b/components/ILIAS/BackgroundTasks/src/Task/Job.php @@ -31,7 +31,7 @@ interface Job extends Task { /** - * @param \ILIAS\BackgroundTasks\Value[] $input This will be a list of Values hinted by + * @param Value[] $input This will be a list of Values hinted by * getInputTypes. * @param Observer $observer Notify the bucket about your progress! * @return Value The returned Value must be of the type hinted by diff --git a/components/ILIAS/BackgroundTasks/src/Task/TaskFactory.php b/components/ILIAS/BackgroundTasks/src/Task/TaskFactory.php index 609a2c03d2a3..3bb12a0067ea 100755 --- a/components/ILIAS/BackgroundTasks/src/Task/TaskFactory.php +++ b/components/ILIAS/BackgroundTasks/src/Task/TaskFactory.php @@ -19,7 +19,6 @@ namespace ILIAS\BackgroundTasks\Task; use ILIAS\BackgroundTasks\Task; -use ILIAS\BackgroundTasks\Value; interface TaskFactory { diff --git a/components/ILIAS/BackgroundTasks/src/Task/UserInteraction.php b/components/ILIAS/BackgroundTasks/src/Task/UserInteraction.php index 6729cb886aca..fc17ce88384b 100755 --- a/components/ILIAS/BackgroundTasks/src/Task/UserInteraction.php +++ b/components/ILIAS/BackgroundTasks/src/Task/UserInteraction.php @@ -57,7 +57,7 @@ public function getSkippedValue(array $input): Value; public function isFinal(): bool; /** - * @param \ILIAS\BackgroundTasks\Value[] $input The input value of this task. + * @param Value[] $input The input value of this task. * @param Option $user_selected_option The Option the user chose. * @param Bucket $bucket Notify the bucket about your * progress! diff --git a/components/ILIAS/BackgroundTasks/src/Types/ListType.php b/components/ILIAS/BackgroundTasks/src/Types/ListType.php index b7ee2dcccce4..57bf0b65ad5b 100755 --- a/components/ILIAS/BackgroundTasks/src/Types/ListType.php +++ b/components/ILIAS/BackgroundTasks/src/Types/ListType.php @@ -30,7 +30,7 @@ */ class ListType implements Type, Ancestors { - protected \ILIAS\BackgroundTasks\Types\Type $type; + protected Type $type; /** * SingleType constructor. @@ -71,7 +71,7 @@ public function isExtensionOf(Type $type): bool return $this->type->isExtensionOf($type->getContainedType()); } - public function getContainedType(): \ILIAS\BackgroundTasks\Types\Type + public function getContainedType(): Type { return $this->type; } diff --git a/components/ILIAS/BackgroundTasks/src/Types/SingleType.php b/components/ILIAS/BackgroundTasks/src/Types/SingleType.php index 04f05feb6185..ceae51da6611 100755 --- a/components/ILIAS/BackgroundTasks/src/Types/SingleType.php +++ b/components/ILIAS/BackgroundTasks/src/Types/SingleType.php @@ -47,8 +47,10 @@ public function isExtensionOf(Type $type): bool if (!$type instanceof SingleType) { return false; } - - return $this->type->isSubclassOf($type->__toString()) || $this->__toString() === $type->__toString(); + if ($this->type->isSubclassOf($type->__toString())) { + return true; + } + return $this->__toString() === $type->__toString(); } /** diff --git a/components/ILIAS/BackgroundTasks/src/Types/TupleType.php b/components/ILIAS/BackgroundTasks/src/Types/TupleType.php index 9a9674e57ae2..bee74e3fbc77 100755 --- a/components/ILIAS/BackgroundTasks/src/Types/TupleType.php +++ b/components/ILIAS/BackgroundTasks/src/Types/TupleType.php @@ -68,7 +68,7 @@ public function isExtensionOf(Type $type): bool } /** - * @return \ILIAS\BackgroundTasks\Types\Type[] + * @return Type[] */ public function getTypes(): array { diff --git a/components/ILIAS/BackgroundTasks/tests/BasicPersistenceTestTBD.php b/components/ILIAS/BackgroundTasks/tests/BasicPersistenceTestTBD.php index 0998497ea169..93bddeab5822 100644 --- a/components/ILIAS/BackgroundTasks/tests/BasicPersistenceTestTBD.php +++ b/components/ILIAS/BackgroundTasks/tests/BasicPersistenceTestTBD.php @@ -18,6 +18,10 @@ namespace ILIAS\BackgroundTasks\Implementation\Persistence; +use PHPUnit\Framework\Attributes\BackupGlobals; +use PHPUnit\Framework\Attributes\BackupStaticProperties; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration; use ILIAS\BackgroundTasks\Exceptions\SerializationException; use ILIAS\BackgroundTasks\Implementation\Bucket\BasicBucket; use ILIAS\BackgroundTasks\Implementation\Bucket\State; @@ -44,15 +48,15 @@ /** * Class BackgroundTaskTest * - * @preserveGlobalState disabled - * @backupGlobals disabled - * @backupStaticAttributes disabled * * @author Oskar Truffer */ +#[BackupGlobals(false)] +#[BackupStaticProperties(false)] +#[PreserveGlobalState(false)] class BasicPersistenceTest extends TestCase { - use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration; + use MockeryPHPUnitIntegration; /** @var Bucket */ protected $bucket; @@ -63,9 +67,7 @@ class BasicPersistenceTest extends TestCase public function setUp(): void { $dic = new Container(); - $dic[Bucket::class] = function ($c) { - return new BasicBucket(); - }; + $dic[Bucket::class] = (fn($c): BasicBucket => new BasicBucket()); $factory = new Injector($dic, new BaseDependencyMap()); $this->persistence = BasicPersistence::instance($this->createMock(\ilDBInterface::class)); @@ -97,7 +99,7 @@ public function setUp(): void /** * */ - public function testSave() + public function testSave(): void { /** @var \arConnector $bucketConnector */ $bucketConnector = Mockery::namedMock("bucketConnectorMock", \arConnector::class); @@ -147,7 +149,7 @@ public function testSave() $this->persistence->saveBucketAndItsTasks($this->bucket); } - public function testCannotUpdateUnknownBucket() + public function testCannotUpdateUnknownBucket(): void { // We have an unknown observer, we can't update it. $this->expectException(SerializationException::class); @@ -155,7 +157,7 @@ public function testCannotUpdateUnknownBucket() $this->persistence->updateBucket($this->bucket); } - public function testUpdateObserver() + public function testUpdateObserver(): void { // We do the whole save part. $this->testSave(); @@ -172,7 +174,7 @@ public function testUpdateObserver() $this->persistence->updateBucket($this->bucket); } - public function testGetObserverIdsOfUser() + public function testGetObserverIdsOfUser(): void { /** @var \arConnector $observerConnector */ $observerConnector = Mockery::namedMock("observerConnectorMock", \arConnector::class); @@ -185,7 +187,7 @@ public function testGetObserverIdsOfUser() $this->assertEquals($observer_ids, [0 => 2, 1 => 3]); } - public function testGetObserverIdsByState() + public function testGetObserverIdsByState(): void { /** @var \arConnector $observerConnector */ $observerConnector = Mockery::namedMock("observerConnectorMock", \arConnector::class); @@ -199,7 +201,7 @@ public function testGetObserverIdsByState() } - public function testUserInteraction() + public function testUserInteraction(): void { $this->expectException(UserInteractionRequiredException::class); /** @var IntegerValue $finalValue */ @@ -208,14 +210,14 @@ public function testUserInteraction() $taskManager->executeTask($this->bucket->getTask(), new MockObserver()); } - public function testContinueUserInteraction() + public function testContinueUserInteraction(): void { /** @var IntegerValue $finalValue */ $taskManager = new SyncTaskManager(Mockery::mock(Persistence::class)); try { /** @var IntegerValue $finalValue */ $taskManager->executeTask($this->bucket->getTask(), new NonPersistingObserver($this->bucket)); - } catch (UserInteractionRequiredException $e) { + } catch (UserInteractionRequiredException) { } $download_integer = new DownloadInteger(); @@ -233,7 +235,7 @@ public function testContinueUserInteraction() self::assertEquals($this->bucket->getState(), State::FINISHED); } - public function testContinueUserInteraction2() + public function testContinueUserInteraction2(): void { $dic = new Container(); @@ -253,7 +255,7 @@ public function testContinueUserInteraction2() try { /** @var IntegerValue $finalValue */ $taskManager->executeTask($this->bucket->getTask(), new NonPersistingObserver($this->bucket)); - } catch (UserInteractionRequiredException $e) { + } catch (UserInteractionRequiredException) { } $download_integer = new DownloadInteger(); diff --git a/components/ILIAS/BackgroundTasks/tests/Implementation/Observer/BasicObserverTestTBD.php b/components/ILIAS/BackgroundTasks/tests/Implementation/Observer/BasicObserverTestTBD.php index b72823e023bd..76eb129e14e6 100644 --- a/components/ILIAS/BackgroundTasks/tests/Implementation/Observer/BasicObserverTestTBD.php +++ b/components/ILIAS/BackgroundTasks/tests/Implementation/Observer/BasicObserverTestTBD.php @@ -22,6 +22,7 @@ * Date: 20.04.17 * Time: 16:50 */ + namespace BackgroundTasks\Implementation\Observer; use ILIAS\BackgroundTasks\Exceptions\Exception; @@ -34,7 +35,7 @@ class BasicObserverTest extends MockeryTestCase { - public function testCheckIntegrity() + public function testCheckIntegrity(): void { $this->expectException(Exception::class); diff --git a/components/ILIAS/BackgroundTasks/tests/Implementation/Tasks/BasicTaskFactoryTest.php b/components/ILIAS/BackgroundTasks/tests/Implementation/Tasks/BasicTaskFactoryTest.php index 17a8721781df..b8c8d41ffcf0 100755 --- a/components/ILIAS/BackgroundTasks/tests/Implementation/Tasks/BasicTaskFactoryTest.php +++ b/components/ILIAS/BackgroundTasks/tests/Implementation/Tasks/BasicTaskFactoryTest.php @@ -21,6 +21,7 @@ * Date: 12.05.17 * Time: 10:05 */ + namespace BackgroundTasks\Implementation\Tasks; use ILIAS\BackgroundTasks\Implementation\Tasks\BasicTaskFactory; @@ -33,7 +34,7 @@ class BasicTaskFactoryTest extends TestCase { - public function testBasicFactory() + public function testBasicFactory(): void { $dic = new Container(); $injector = new Injector($dic, new BaseDependencyMap()); diff --git a/components/ILIAS/BackgroundTasks/tests/TaskTestTBD.php b/components/ILIAS/BackgroundTasks/tests/TaskTestTBD.php index d1b1ead39069..e056648b3b07 100644 --- a/components/ILIAS/BackgroundTasks/tests/TaskTestTBD.php +++ b/components/ILIAS/BackgroundTasks/tests/TaskTestTBD.php @@ -16,10 +16,14 @@ * *********************************************************************/ +use PHPUnit\Framework\Attributes\BackupGlobals; +use PHPUnit\Framework\Attributes\BackupStaticProperties; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses; +use ILIAS\BackgroundTasks\Implementation\TaskManager\SyncTaskManager; use ILIAS\BackgroundTasks\Exceptions\InvalidArgumentException; use ILIAS\BackgroundTasks\Implementation\Bucket\BasicBucket; use ILIAS\BackgroundTasks\Implementation\Bucket\BucketMock; -use ILIAS\BackgroundTasks\Implementation\TaskManager\BasicTaskManager; use ILIAS\BackgroundTasks\Implementation\TaskManager\MockObserver; use ILIAS\BackgroundTasks\Implementation\Tasks\Aggregation\ConcatenationJob; use ILIAS\BackgroundTasks\Implementation\Tasks\PlusJob; @@ -39,16 +43,16 @@ /** * Class BackgroundTaskTest * - * @runTestsInSeparateProcesses - * @preserveGlobalState disabled - * @backupGlobals disabled - * @backupStaticAttributes disabled * * @author Oskar Truffer */ +#[BackupGlobals(false)] +#[BackupStaticProperties(false)] +#[PreserveGlobalState(false)] +#[RunTestsInSeparateProcesses] class TaskTest extends TestCase { - public function testPlusTask() + public function testPlusTask(): void { $dic = new Container(); @@ -71,37 +75,33 @@ public function testPlusTask() $this->assertTrue($t2->getOutputType()->equals(new SingleType(IntegerValue::class))); - $taskManager = new \ILIAS\BackgroundTasks\Implementation\TaskManager\SyncTaskManager(Mockery::mock(Persistence::class)); + $taskManager = new SyncTaskManager(Mockery::mock(Persistence::class)); /** @var IntegerValue $finalValue */ $finalValue = $taskManager->executeTask($t2, new MockObserver()); $this->assertEquals($finalValue->getValue(), 6); } - public function testValueWrapper() + public function testValueWrapper(): void { $dic = new Container(); - $dic[Bucket::class] = function ($c) { - return new BucketMock(); - }; + $dic[Bucket::class] = (fn($c): BucketMock => new BucketMock()); $factory = new Injector($dic, new BaseDependencyMap()); $t = $factory->createInstance(PlusJob::class); $t->setInput([1, 4]); - $taskManager = new \ILIAS\BackgroundTasks\Implementation\TaskManager\SyncTaskManager(Mockery::mock(Persistence::class)); + $taskManager = new SyncTaskManager(Mockery::mock(Persistence::class)); /** @var IntegerValue $finalValue */ $finalValue = $taskManager->executeTask($t, new MockObserver()); $this->assertEquals($finalValue->getValue(), 5); } - public function testTypeCheck() + public function testTypeCheck(): void { $this->expectException(InvalidArgumentException::class); $dic = new Container(); - $dic[Bucket::class] = function ($c) { - return new BucketMock(); - }; + $dic[Bucket::class] = (fn($c): BucketMock => new BucketMock()); $factory = new Injector($dic, new BaseDependencyMap()); $a = new IntegerValue(1); @@ -112,7 +112,7 @@ public function testTypeCheck() $t1->setInput([$a, $b]); } - public function testAggregation() + public function testAggregation(): void { $dic = new Container(); $factory = new Injector($dic, new BaseDependencyMap()); @@ -128,12 +128,10 @@ public function testAggregation() $this->assertEquals($output->getValue(), "1, hello, 3"); } - public function testUnfoldTask() + public function testUnfoldTask(): void { $dic = new Container(); - $dic[Bucket::class] = function ($c) { - return new BasicBucket(); - }; + $dic[Bucket::class] = (fn($c): BasicBucket => new BasicBucket()); $factory = new Injector($dic, new BaseDependencyMap()); @@ -161,7 +159,7 @@ public function testUnfoldTask() $this->assertEquals($list, [$t2, $t1, $t0, $t25]); /** @var IntegerValue $finalValue */ - $taskManager = new \ILIAS\BackgroundTasks\Implementation\TaskManager\SyncTaskManager(Mockery::mock(Persistence::class)); + $taskManager = new SyncTaskManager(Mockery::mock(Persistence::class)); /** @var IntegerValue $finalValue */ $finalValue = $taskManager->executeTask($t2, new MockObserver()); $this->assertEquals($finalValue->getValue(), 8); diff --git a/components/ILIAS/BackgroundTasks/tests/ValueTest.php b/components/ILIAS/BackgroundTasks/tests/ValueTest.php index b58298449318..6375f29eeb01 100755 --- a/components/ILIAS/BackgroundTasks/tests/ValueTest.php +++ b/components/ILIAS/BackgroundTasks/tests/ValueTest.php @@ -16,6 +16,10 @@ * *********************************************************************/ +use PHPUnit\Framework\Attributes\BackupGlobals; +use PHPUnit\Framework\Attributes\BackupStaticProperties; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses; use ILIAS\BackgroundTasks\Implementation\Values\AggregationValues\ListValue; use ILIAS\BackgroundTasks\Implementation\Values\ScalarValues\IntegerValue; use ILIAS\BackgroundTasks\Implementation\Values\ScalarValues\StringValue; @@ -29,16 +33,16 @@ /** * Class BackgroundTaskTest * - * @runTestsInSeparateProcesses - * @preserveGlobalState disabled - * @backupGlobals disabled - * @backupStaticAttributes disabled * * @author Oskar Truffer */ +#[BackupGlobals(false)] +#[BackupStaticProperties(false)] +#[PreserveGlobalState(false)] +#[RunTestsInSeparateProcesses] class ValueTest extends TestCase { - public function testIntegerValue() + public function testIntegerValue(): void { $integer = new IntegerValue(); $integer->setValue(3); @@ -56,7 +60,7 @@ public function testIntegerValue() $this->assertTrue($integer->getType()->equals(new SingleType(IntegerValue::class))); } - public function testListValue() + public function testListValue(): void { $list = new ListValue(); $list->setValue([1, 2, 3]); diff --git a/components/ILIAS/BackgroundTasks_/BackgroundTasks_.php b/components/ILIAS/BackgroundTasks_/BackgroundTasks_.php index 30f7ba592d82..150aa951659a 100644 --- a/components/ILIAS/BackgroundTasks_/BackgroundTasks_.php +++ b/components/ILIAS/BackgroundTasks_/BackgroundTasks_.php @@ -20,7 +20,11 @@ namespace ILIAS; -class BackgroundTasks_ implements Component\Component +use ILIAS\Component\Component; +use ILIAS\Component\Resource\PublicAsset; +use ILIAS\Component\Resource\ComponentJS; + +class BackgroundTasks_ implements Component { public function init( array | \ArrayAccess &$define, @@ -32,7 +36,7 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $contribute[Component\Resource\PublicAsset::class] = fn() => - new Component\Resource\ComponentJS($this, "background_task_refresh.js"); + $contribute[PublicAsset::class] = fn(): ComponentJS => + new ComponentJS($this, "background_task_refresh.js"); } } diff --git a/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilCollectFilesJob.php b/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilCollectFilesJob.php index ee1dbf2fd36b..3dae62a64972 100755 --- a/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilCollectFilesJob.php +++ b/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilCollectFilesJob.php @@ -16,6 +16,7 @@ * *********************************************************************/ +use ILIAS\BackgroundTasks\Observer; use ILIAS\BackgroundTasks\Implementation\Tasks\AbstractJob; use ILIAS\BackgroundTasks\Implementation\Values\ScalarValues\BooleanValue; use ILIAS\BackgroundTasks\Types\SingleType; @@ -85,14 +86,14 @@ public function isStateless(): bool * @inheritDoc * @todo use filsystem service */ - public function run(array $input, \ILIAS\BackgroundTasks\Observer $observer): Value + public function run(array $input, Observer $observer): Value { $this->logger->debug('Start collecting files!'); $this->logger->dump($input); $definition = $input[0]; $initiated_by_folder_action = $input[1]->getValue(); $object_ref_ids = $definition->getObjectRefIds(); - $files = array(); + $files = []; foreach ($object_ref_ids as $object_ref_id) { $object = ilObjectFactory::getInstanceByRefId($object_ref_id); @@ -121,7 +122,7 @@ public function run(array $input, \ILIAS\BackgroundTasks\Observer $observer): Va $this->logger->debug('Added new copy definition: ' . $file['source_dir'] . ' -> ' . $file['target_dir']); // count files only (without empty directories) - $is_empty_folder = preg_match_all("/\/$/", $file['target_dir']); + $is_empty_folder = preg_match_all("/\/$/", (string) $file['target_dir']); if (!$is_empty_folder) { $num_files++; } @@ -139,7 +140,7 @@ public function run(array $input, \ILIAS\BackgroundTasks\Observer $observer): Va * duplicate entries. DO NOT call this method e.g. in an if condition and * then again in its body. */ - private function getFileDirs($a_ref_id, $a_file_name, $a_temp_dir) + private function getFileDirs($a_ref_id, string $a_file_name, string $a_temp_dir): false|array { global $DIC; @@ -186,14 +187,14 @@ private function getFileDirs($a_ref_id, $a_file_name, $a_temp_dir) * * @return mixed[] */ - private function recurseFolder($a_ref_id, $a_folder_name, $a_temp_dir, $a_num_recursions, $a_initiated_by_folder_action): array + private function recurseFolder($a_ref_id, string $a_folder_name, string $a_temp_dir, int|float $a_num_recursions, $a_initiated_by_folder_action): array { global $DIC; $num_recursions = $a_num_recursions + 1; $tree = $DIC->repositoryTree(); $ilAccess = $DIC->access(); - $files = array(); + $files = []; // Avoid the duplication of the uppermost folder when the download is initiated via a folder's action drop-down // by not including said folders name in the temp_dir path. @@ -203,7 +204,7 @@ private function recurseFolder($a_ref_id, $a_folder_name, $a_temp_dir, $a_num_re $temp_dir = $a_temp_dir . '/' . ilFileUtils::getASCIIFilename($a_folder_name); } - $subtree = $tree->getChildsByTypeFilter($a_ref_id, array("fold", "file")); + $subtree = $tree->getChildsByTypeFilter($a_ref_id, ["fold", "file"]); foreach ($subtree as $child) { if (!$ilAccess->checkAccess("read", "", $child["ref_id"])) { @@ -215,10 +216,8 @@ private function recurseFolder($a_ref_id, $a_folder_name, $a_temp_dir, $a_num_re if ($child["type"] == "fold") { $files_from_folder = $this->recurseFolder($child["ref_id"], $child['title'], $temp_dir, $num_recursions, $a_initiated_by_folder_action); $files = array_merge($files, $files_from_folder); - } else { - if (($child["type"] === "file") && (($dirs = $this->getFileDirs($child["ref_id"], $child['title'], $temp_dir)) !== false)) { - $files[] = $dirs; - } + } elseif (($child["type"] === "file") && (($dirs = $this->getFileDirs($child["ref_id"], $child['title'], $temp_dir)) !== false)) { + $files[] = $dirs; } } // ensure that empty folders are also contained in the downloaded zip diff --git a/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilCopyFilesToTempDirectoryJob.php b/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilCopyFilesToTempDirectoryJob.php index 690f1be001a6..d2b22fca2c0e 100755 --- a/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilCopyFilesToTempDirectoryJob.php +++ b/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilCopyFilesToTempDirectoryJob.php @@ -46,7 +46,7 @@ public function __construct() /** - * @return \ILIAS\BackgroundTasks\Types\SingleType[] + * @return SingleType[] */ public function getInputTypes(): array { @@ -119,7 +119,7 @@ protected function createUniqueTempDirectory(): string } - protected function createTargetDirectory($a_tmpdir): string + protected function createTargetDirectory(string $a_tmpdir): string { $final_dir = $a_tmpdir . "/" . $this->target_directory; ilFileUtils::makeDirParents($final_dir); diff --git a/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilZipJob.php b/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilZipJob.php index 86d5693a0d71..f39fbd5b3294 100755 --- a/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilZipJob.php +++ b/components/ILIAS/BackgroundTasks_/classes/Jobs/class.ilZipJob.php @@ -15,6 +15,8 @@ * *********************************************************************/ +use ILIAS\Filesystem\Util\Archive\Archives; +use ILIAS\BackgroundTasks\Observer; use ILIAS\BackgroundTasks\Implementation\Tasks\AbstractJob; use ILIAS\BackgroundTasks\Implementation\Values\ScalarValues\StringValue; use ILIAS\BackgroundTasks\Types\SingleType; @@ -30,7 +32,7 @@ class ilZipJob extends AbstractJob { private ?ilLogger $logger; - private \ILIAS\Filesystem\Util\Archive\Archives $archives; + private Archives $archives; /** * Construct @@ -77,12 +79,12 @@ public function isStateless(): bool * @inheritDoc * @todo use filsystem service */ - public function run(array $input, \ILIAS\BackgroundTasks\Observer $observer): Value + public function run(array $input, Observer $observer): Value { $this->logger->debug('Start zipping input dir!'); $this->logger->dump($input); $string = $input[0]->getValue(); - $tmpdir = rtrim($string, "/"); + $tmpdir = rtrim((string) $string, "/"); $this->logger->debug('Zipping directory:' . $tmpdir); $zip_name = $tmpdir . '.zip'; diff --git a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksConfigStoredObjective.php b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksConfigStoredObjective.php index 95be9f05c605..48bdb9f33e6a 100755 --- a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksConfigStoredObjective.php +++ b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksConfigStoredObjective.php @@ -16,16 +16,14 @@ * *********************************************************************/ -use ILIAS\Setup; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Environment; +use ILIAS\Setup\UnachievableException; -class ilBackgroundTasksConfigStoredObjective implements Setup\Objective +class ilBackgroundTasksConfigStoredObjective implements Objective { - protected ilBackgroundTasksSetupConfig $config; - - public function __construct( - \ilBackgroundTasksSetupConfig $config - ) { - $this->config = $config; + public function __construct(protected ilBackgroundTasksSetupConfig $config) + { } public function getHash(): string @@ -46,16 +44,16 @@ public function isNotable(): bool /** * @return \ilIniFilesLoadedObjective[] */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { return [ new ilIniFilesLoadedObjective() ]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { - $ini = $environment->getResource(Setup\Environment::RESOURCE_ILIAS_INI); + $ini = $environment->getResource(Environment::RESOURCE_ILIAS_INI); if (!$ini->groupExists("background_tasks")) { $ini->addGroup("background_tasks"); @@ -65,7 +63,7 @@ public function achieve(Setup\Environment $environment): Setup\Environment $ini->setVariable("background_tasks", "number_of_concurrent_tasks", $this->config->getMaxCurrentTasks()); if (!$ini->write()) { - throw new Setup\UnachievableException("Could not write ilias.ini.php"); + throw new UnachievableException("Could not write ilias.ini.php"); } return $environment; @@ -74,14 +72,15 @@ public function achieve(Setup\Environment $environment): Setup\Environment /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { - $ini = $environment->getResource(Setup\Environment::RESOURCE_ILIAS_INI); - - return - !$ini->groupExists("background_tasks") || - $ini->readVariable("background_tasks", "concurrency") !== $this->config->getType() || - $ini->readVariable("background_tasks", "number_of_concurrent_tasks") !== $this->config->getMaxCurrentTasks() - ; + $ini = $environment->getResource(Environment::RESOURCE_ILIAS_INI); + if (!$ini->groupExists("background_tasks")) { + return true; + } + if ($ini->readVariable("background_tasks", "concurrency") !== $this->config->getType()) { + return true; + } + return $ini->readVariable("background_tasks", "number_of_concurrent_tasks") !== $this->config->getMaxCurrentTasks(); } } diff --git a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksDB80.php b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksDB80.php index cf586b968fe2..d4d2f0888bf8 100755 --- a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksDB80.php +++ b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksDB80.php @@ -16,9 +16,6 @@ * *********************************************************************/ -use ILIAS\Setup; -use ILIAS\Data\Password; - class ilBackgroundTasksDB80 implements ilDatabaseUpdateSteps { protected ilDBInterface $db; diff --git a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksMetricsCollectedObjective.php b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksMetricsCollectedObjective.php index 41f87b17fab1..0236691d7251 100755 --- a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksMetricsCollectedObjective.php +++ b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksMetricsCollectedObjective.php @@ -16,23 +16,25 @@ * *********************************************************************/ -use ILIAS\Setup; +use ILIAS\Setup\Metrics\CollectedObjective; +use ILIAS\Setup\Environment; +use ILIAS\Setup\Metrics\Storage; -class ilBackgroundTasksMetricsCollectedObjective extends Setup\Metrics\CollectedObjective +class ilBackgroundTasksMetricsCollectedObjective extends CollectedObjective { /** * @return \ilIniFilesLoadedObjective[] */ - public function getTentativePreconditions(Setup\Environment $environment): array + public function getTentativePreconditions(Environment $environment): array { return [ new ilIniFilesLoadedObjective() ]; } - public function collectFrom(Setup\Environment $environment, Setup\Metrics\Storage $storage): void + public function collectFrom(Environment $environment, Storage $storage): void { - $ini = $environment->getResource(Setup\Environment::RESOURCE_ILIAS_INI); + $ini = $environment->getResource(Environment::RESOURCE_ILIAS_INI); if (!$ini) { return; } diff --git a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksSetupAgent.php b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksSetupAgent.php index eb1d416ecc1c..01ef973c2a51 100755 --- a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksSetupAgent.php +++ b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksSetupAgent.php @@ -16,21 +16,22 @@ * *********************************************************************/ -use ILIAS\Setup; -use ILIAS\Refinery; -use ILIAS\Data; -use ILIAS\UI; +use ILIAS\Setup\Agent; +use ILIAS\Setup\Agent\HasNoNamedObjective; +use ILIAS\Refinery\Factory; +use ILIAS\Refinery\Transformation; +use ILIAS\Setup\Config; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Objective\NullObjective; +use ILIAS\Setup\Metrics\Storage; +use ILIAS\Setup\ObjectiveCollection; -class ilBackgroundTasksSetupAgent implements Setup\Agent +class ilBackgroundTasksSetupAgent implements Agent { - use Setup\Agent\HasNoNamedObjective; + use HasNoNamedObjective; - protected Refinery\Factory $refinery; - - public function __construct( - Refinery\Factory $refinery - ) { - $this->refinery = $refinery; + public function __construct(protected Factory $refinery) + { } /** @@ -44,7 +45,7 @@ public function hasConfig(): bool /** * @inheritdoc */ - public function getArrayToConfigTransformation(): Refinery\Transformation + public function getArrayToConfigTransformation(): Transformation { return $this->refinery->custom()->transformation(fn($data): \ilBackgroundTasksSetupConfig => new \ilBackgroundTasksSetupConfig( $data["type"] ?? \ilBackgroundTasksSetupConfig::TYPE_SYNCHRONOUS, @@ -55,7 +56,7 @@ public function getArrayToConfigTransformation(): Refinery\Transformation /** * @inheritdoc */ - public function getInstallObjective(?Setup\Config $config = null): Setup\Objective + public function getInstallObjective(?Config $config = null): Objective { /** @noinspection PhpParamsInspection */ return new ilBackgroundTasksConfigStoredObjective($config); @@ -64,29 +65,29 @@ public function getInstallObjective(?Setup\Config $config = null): Setup\Objecti /** * @inheritdoc */ - public function getUpdateObjective(?Setup\Config $config = null): Setup\Objective + public function getUpdateObjective(?Config $config = null): Objective { if ($config !== null) { /** @noinspection PhpParamsInspection */ return new ilBackgroundTasksConfigStoredObjective($config); } - return new Setup\Objective\NullObjective(); + return new NullObjective(); } /** * @inheritdoc */ - public function getBuildObjective(): Setup\Objective + public function getBuildObjective(): Objective { - return new Setup\Objective\NullObjective(); + return new NullObjective(); } /** * @inheritdoc */ - public function getStatusObjective(Setup\Metrics\Storage $storage): Setup\Objective + public function getStatusObjective(Storage $storage): Objective { - return new Setup\ObjectiveCollection( + return new ObjectiveCollection( 'Component BackgroundTasks', true, new ilBackgroundTasksMetricsCollectedObjective($storage), diff --git a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksSetupConfig.php b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksSetupConfig.php index 7aedf5e5cb9f..4f2c7003399c 100755 --- a/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksSetupConfig.php +++ b/components/ILIAS/BackgroundTasks_/classes/Setup/class.ilBackgroundTasksSetupConfig.php @@ -16,10 +16,9 @@ * *********************************************************************/ -use ILIAS\Setup; -use ILIAS\Data\Password; +use ILIAS\Setup\Config; -class ilBackgroundTasksSetupConfig implements Setup\Config +class ilBackgroundTasksSetupConfig implements Config { public const TYPE_SYNCHRONOUS = "sync"; public const TYPE_ASYNCHRONOUS = "async"; diff --git a/components/ILIAS/BackgroundTasks_/classes/StateTranslator.php b/components/ILIAS/BackgroundTasks_/classes/StateTranslator.php index 6b79b806cdbf..17960f8a3d0e 100755 --- a/components/ILIAS/BackgroundTasks_/classes/StateTranslator.php +++ b/components/ILIAS/BackgroundTasks_/classes/StateTranslator.php @@ -29,18 +29,13 @@ trait StateTranslator { public function translateState(int $state, \ilLanguage $lng): string { - switch ($state) { - case State::SCHEDULED: - return $lng->txt("observer_state_scheduled"); - case State::RUNNING: - return $lng->txt("observer_state_running"); - case State::USER_INTERACTION: - return $lng->txt("observer_state_user_interaction"); - case State::FINISHED: - return $lng->txt("observer_state_finished"); - case State::ERROR: - return $lng->txt("observer_state_error"); - } - return ''; + return match ($state) { + State::SCHEDULED => $lng->txt("observer_state_scheduled"), + State::RUNNING => $lng->txt("observer_state_running"), + State::USER_INTERACTION => $lng->txt("observer_state_user_interaction"), + State::FINISHED => $lng->txt("observer_state_finished"), + State::ERROR => $lng->txt("observer_state_error"), + default => '', + }; } } diff --git a/components/ILIAS/BackgroundTasks_/classes/UserInteractions/class.ilDownloadZipInteraction.php b/components/ILIAS/BackgroundTasks_/classes/UserInteractions/class.ilDownloadZipInteraction.php index 43a1205ae1d8..2f7114cf5af5 100755 --- a/components/ILIAS/BackgroundTasks_/classes/UserInteractions/class.ilDownloadZipInteraction.php +++ b/components/ILIAS/BackgroundTasks_/classes/UserInteractions/class.ilDownloadZipInteraction.php @@ -61,6 +61,7 @@ public function getInputTypes(): array /** * @inheritDoc */ + #[\Override] public function getRemoveOption(): Option { return new UserInteractionOption('remove', self::OPTION_CANCEL); @@ -99,14 +100,14 @@ public function interaction(array $input, Option $user_selected_option, Bucket $ $this->logger->debug('User interaction download zip ' . $input[0]->getValue() . ' as ' . $input[1]->getValue()); - if ($user_selected_option->getValue() != self::OPTION_DOWNLOAD) { + if ($user_selected_option->getValue() !== self::OPTION_DOWNLOAD) { $this->logger->info('Download canceled'); // delete zip file $filesystem = $DIC->filesystem()->temp(); try { $path = LegacyPathHelper::createRelativePath($zip_name->getValue()); - } catch (InvalidArgumentException $e) { + } catch (InvalidArgumentException) { $path = null; } if (!is_null($path) && $filesystem->has($path)) { @@ -123,6 +124,7 @@ public function interaction(array $input, Option $user_selected_option, Bucket $ return new ThunkValue(); } + #[\Override] public function canBeSkipped(array $input): bool { return false; diff --git a/components/ILIAS/BackgroundTasks_/classes/UserInteractions/class.ilSumOfFileSizesTooLargeInteraction.php b/components/ILIAS/BackgroundTasks_/classes/UserInteractions/class.ilSumOfFileSizesTooLargeInteraction.php index 4adbb63a07c9..5ceb63d8a038 100755 --- a/components/ILIAS/BackgroundTasks_/classes/UserInteractions/class.ilSumOfFileSizesTooLargeInteraction.php +++ b/components/ILIAS/BackgroundTasks_/classes/UserInteractions/class.ilSumOfFileSizesTooLargeInteraction.php @@ -31,6 +31,9 @@ */ class ilSumOfFileSizesTooLargeInteraction extends AbstractUserInteraction { + /** + * @var string + */ private const OPTION_OK = 'ok'; protected ilLanguage $lng; @@ -43,7 +46,7 @@ public function __construct() } /** - * @return \ILIAS\BackgroundTasks\Types\SingleType[] + * @return SingleType[] */ public function getInputTypes(): array { @@ -57,6 +60,7 @@ public function getOutputType(): Type return new SingleType(ilCopyDefinition::class); } + #[\Override] public function getRemoveOption(): Option { return new UserInteractionOption('ok', self::OPTION_OK); @@ -64,7 +68,7 @@ public function getRemoveOption(): Option public function interaction(array $input, Option $user_selected_option, Bucket $bucket): Value { - if ($user_selected_option->getValue() == self::OPTION_OK) { + if ($user_selected_option->getValue() === self::OPTION_OK) { // Set state to finished to stop the BackgroundTask and remove it from the popover. $bucket->setState(3); } @@ -77,33 +81,32 @@ public function interaction(array $input, Option $user_selected_option, Bucket $ */ public function getOptions(array $input): array { - return array(); + return []; } + #[\Override] public function getMessage(array $input): string { return $this->lng->txt('ui_msg_files_violate_maxsize'); } + #[\Override] public function canBeSkipped(array $input): bool { $copy_definition = $input[0]; - if ($copy_definition->getAdheresToLimit()->getValue()) { - // skip the user interaction if the adherence to the global limit for the sum of file sizes - // hasn't been violated (as this interaction is used as an error message and mustn't be - // shown when everything is fine)) - - return true; - } else { - return false; - } + // skip the user interaction if the adherence to the global limit for the sum of file sizes + // hasn't been violated (as this interaction is used as an error message and mustn't be + // shown when everything is fine)) + return (bool) $copy_definition->getAdheresToLimit()->getValue(); } + #[\Override] public function getSkippedValue(array $input): Value { return $input[0]; } + #[\Override] public function isFinal(): bool { return false; diff --git a/components/ILIAS/BackgroundTasks_/classes/class.ilBTControllerGUI.php b/components/ILIAS/BackgroundTasks_/classes/class.ilBTControllerGUI.php index 1e90ba1ac6b3..d9e7f7186a78 100755 --- a/components/ILIAS/BackgroundTasks_/classes/class.ilBTControllerGUI.php +++ b/components/ILIAS/BackgroundTasks_/classes/class.ilBTControllerGUI.php @@ -120,7 +120,7 @@ protected function getFromURL(): string */ public static function hash($url): string { - return base64_encode($url); + return base64_encode((string) $url); } @@ -129,6 +129,6 @@ public static function hash($url): string */ public static function unhash($url): string { - return base64_decode($url); + return base64_decode((string) $url); } } diff --git a/components/ILIAS/BackgroundTasks_/classes/class.ilBTPopOverGUI.php b/components/ILIAS/BackgroundTasks_/classes/class.ilBTPopOverGUI.php index 714e9559a40d..9f57763d2e63 100755 --- a/components/ILIAS/BackgroundTasks_/classes/class.ilBTPopOverGUI.php +++ b/components/ILIAS/BackgroundTasks_/classes/class.ilBTPopOverGUI.php @@ -16,6 +16,9 @@ * *********************************************************************/ +use ILIAS\DI\Container; +use ILIAS\UI\Component\Item\Notification; +use ILIAS\BackgroundTasks\Task\UserInteraction\Option; use ILIAS\BackgroundTasks\Bucket; use ILIAS\BackgroundTasks\Implementation\Bucket\State; use ILIAS\BackgroundTasks\Implementation\Tasks\AbstractTask; @@ -34,19 +37,17 @@ class ilBTPopOverGUI { use StateTranslator; - protected \ILIAS\DI\Container $dic; - public function __construct(\ILIAS\DI\Container $dic) + public function __construct(protected Container $dic) { - $this->dic = $dic; } /** * Get the Notification Items. DOES NOT DO ANY PERMISSION CHECKS. */ - public function getNotificationItem(int $nr_buckets): ILIAS\UI\Component\Item\Notification + public function getNotificationItem(int $nr_buckets): Notification { $ui_factory = $this->dic->ui()->factory(); @@ -62,7 +63,7 @@ public function getNotificationItem(int $nr_buckets): ILIAS\UI\Component\Item\No /** - * @return ILIAS\UI\Component\Item\Notification[] + * @return Notification[] */ protected function getAggregateItems(): array { @@ -77,7 +78,7 @@ protected function getAggregateItems(): array } - public function getItemForObserver(Bucket $observer): ILIAS\UI\Component\Item\Notification + public function getItemForObserver(Bucket $observer): Notification { $redirect_uri = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; @@ -123,7 +124,7 @@ public function getItemForObserver(Bucket $observer): ILIAS\UI\Component\Item\No if ($state === State::RUNNING) { $url = $this->getRefreshUrl($observer); //Running Items probably need to refresh themselves, right? - $item = $item->withAdditionalOnLoadCode(fn($id) => "var notification_item = il.UI.item.notification.getNotificationItemObject($('#$id')); + $item = $item->withAdditionalOnLoadCode(fn($id): string => "var notification_item = il.UI.item.notification.getNotificationItemObject($('#$id')); il.BGTask.refreshItem(notification_item,'$url');"); $expected = $current_task->getExpectedTimeOfTaskInSeconds(); @@ -147,7 +148,7 @@ private function getDefaultCardContent(Bucket $observer): Content /** - * @return \ILIAS\UI\Component\Legacy\Content[]|\ILIAS\UI\Component\Button\Shy[] + * @return Content[]|Shy[] */ public function getUserInteractionContent(Bucket $observer, string $redirect_uri): array { @@ -164,7 +165,7 @@ public function getUserInteractionContent(Bucket $observer, string $redirect_uri $options = $userInteraction->getOptions($userInteraction->getInput()); return array_map( - function (UserInteraction\Option $option) use ($ctrl, $factory, $observer, $persistence, $redirect_uri, $language): \ILIAS\UI\Component\Button\Shy { + function (Option $option) use ($ctrl, $factory, $observer, $persistence, $redirect_uri, $language): Shy { $ctrl->setParameterByClass( ilBTControllerGUI::class, ilBTControllerGUI::FROM_URL, @@ -221,7 +222,7 @@ private function getProgressbar(Bucket $observer): Content } - private function getCloseButtonAction(UserInteraction\Option $option, string $redirect_uri, Bucket $observer): string + private function getCloseButtonAction(Option $option, string $redirect_uri, Bucket $observer): string { $ctrl = $this->dic->ctrl(); $persistence = $this->dic->backgroundTasks()->persistence(); diff --git a/components/ILIAS/BackgroundTasks_/classes/class.ilCopyDefinition.php b/components/ILIAS/BackgroundTasks_/classes/class.ilCopyDefinition.php index e8c5b58ff012..832ec09e79d5 100755 --- a/components/ILIAS/BackgroundTasks_/classes/class.ilCopyDefinition.php +++ b/components/ILIAS/BackgroundTasks_/classes/class.ilCopyDefinition.php @@ -56,7 +56,7 @@ class ilCopyDefinition extends AbstractValue /** * States if the sum of all file sizes adheres to the global limit. */ - private ?BooleanValue $adheres_to_limit; + private ?BooleanValue $adheres_to_limit = null; /** * Get copy definitions @@ -197,13 +197,13 @@ public function setValue($value): void * Unserialize definitions * @param string $serialized */ - public function unserialize($serialized) + public function unserialize($serialized): void { $elements = unserialize($serialized); $this->setCopyDefinitions($elements["copy_definition"]); $this->setTempDir($elements['temp_dir']); - $this->setObjectRefIds(explode(",", $elements["object_ref_ids"])); + $this->setObjectRefIds(explode(",", (string) $elements["object_ref_ids"])); $this->setNumFiles($elements["num_files"]); $this->setSumFileSizes($elements["sum_file_sizes"]); $this->setAdheresToLimit($elements["adheres_to_limit"]); diff --git a/components/ILIAS/BackgroundTasks_/classes/class.ilSoapBackgroundTasksAdministration.php b/components/ILIAS/BackgroundTasks_/classes/class.ilSoapBackgroundTasksAdministration.php index a96ae9e732f7..93202a85b98d 100755 --- a/components/ILIAS/BackgroundTasks_/classes/class.ilSoapBackgroundTasksAdministration.php +++ b/components/ILIAS/BackgroundTasks_/classes/class.ilSoapBackgroundTasksAdministration.php @@ -20,7 +20,6 @@ require_once __DIR__ . "/../../../../vendor/composer/vendor/autoload.php"; use ILIAS\BackgroundTasks\Implementation\TaskManager\AsyncTaskManager; -use ILIAS\BackgroundTasks\Persistence; class ilSoapBackgroundTasksAdministration extends ilSoapAdministration { diff --git a/components/ILIAS/Bibliographic/Bibliographic.php b/components/ILIAS/Bibliographic/Bibliographic.php index ec5d25f51336..325ca12795a1 100644 --- a/components/ILIAS/Bibliographic/Bibliographic.php +++ b/components/ILIAS/Bibliographic/Bibliographic.php @@ -20,7 +20,11 @@ namespace ILIAS; -class Bibliographic implements Component\Component +use ILIAS\Component\Component; +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Factory; + +class Bibliographic implements Component { public function init( array | \ArrayAccess &$define, @@ -32,9 +36,9 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $contribute[\ILIAS\Setup\Agent::class] = static fn() => + $contribute[Agent::class] = static fn(): \ilBibliographicSetupAgent => new \ilBibliographicSetupAgent( - $pull[\ILIAS\Refinery\Factory::class] + $pull[Factory::class] ); } } diff --git a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibrary.php b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibrary.php index 92a3144753fb..48ee8e8fe85c 100755 --- a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibrary.php +++ b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibrary.php @@ -32,6 +32,7 @@ public static function returnDbTableName(): string } + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; diff --git a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryFormGUI.php b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryFormGUI.php index a075b89bd1aa..d6ce6a5e0978 100755 --- a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryFormGUI.php +++ b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryFormGUI.php @@ -1,4 +1,5 @@ object = $library; - $this->ctrl()->setParameterByClass(ilBiblLibraryGUI::class, ilBiblLibraryGUI::F_LIB_ID, $library->getId()); + $this->ctrl()->setParameterByClass(ilBiblLibraryGUI::class, ilBiblLibraryGUI::F_LIB_ID, $this->object->getId()); $this->initForm(); if ($this->object->getId()) { @@ -82,12 +83,12 @@ private function initForm(): void private function fillForm(): void { - $this->setValuesByArray(array( + $this->setValuesByArray([ 'name' => $this->object->getName(), 'url' => $this->object->getUrl(), 'img' => $this->object->getImg(), 'show_in_list' => $this->object->isShownInList(), - )); + ]); } diff --git a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryGUI.php b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryGUI.php index 634a99031fce..488367ad7259 100755 --- a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryGUI.php +++ b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryGUI.php @@ -16,6 +16,10 @@ * *********************************************************************/ +use ILIAS\components\OrgUnit\ARHelper\DIC; +use ILIAS\Refinery\Factory; +use ILIAS\HTTP\Wrapper\WrapperFactory; + /** * Class ilBiblLibraryGUI * @@ -23,26 +27,24 @@ */ class ilBiblLibraryGUI { - use \ILIAS\components\OrgUnit\ARHelper\DIC; + use DIC; public const F_LIB_ID = 'lib_id'; public const F_LIB_IDS = 'lib_ids'; public const CMD_DELETE = 'delete'; public const CMD_EDIT = 'edit'; public const CMD_INDEX = 'index'; public const CMD_ADD = 'add'; - protected \ilBiblAdminLibraryFacadeInterface $facade; private \ilGlobalTemplateInterface $main_tpl; - protected \ILIAS\Refinery\Factory $refinery; - protected \ILIAS\HTTP\Wrapper\WrapperFactory $wrapper; + protected Factory $refinery; + protected WrapperFactory $wrapper; /** * ilBiblLibraryGUI constructor. */ - public function __construct(ilBiblAdminLibraryFacadeInterface $facade) + public function __construct(protected \ilBiblAdminLibraryFacadeInterface $facade) { global $DIC; $this->main_tpl = $DIC->ui()->mainTemplate(); - $this->facade = $facade; $this->wrapper = $DIC->http()->wrapper(); $this->refinery = $DIC->refinery(); } @@ -56,11 +58,9 @@ public function __construct(ilBiblAdminLibraryFacadeInterface $facade) */ public function executeCommand(): void { - switch ($this->ctrl()->getNextClass()) { - case null: - $cmd = $this->ctrl()->getCmd(self::CMD_INDEX); - $this->{$cmd}(); - break; + if ($this->ctrl()->getNextClass() === null) { + $cmd = $this->ctrl()->getCmd(self::CMD_INDEX); + $this->{$cmd}(); } } diff --git a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryPresentationGUI.php b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryPresentationGUI.php index 7ac2ff9a8ddb..2e9e552e3789 100755 --- a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryPresentationGUI.php +++ b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryPresentationGUI.php @@ -16,6 +16,8 @@ * *********************************************************************/ +use ILIAS\DI\UIServices; + /** * Class ilBiblLibraryPresentationGUI * @author Fabian Schmid @@ -30,7 +32,7 @@ public function __construct( protected \ilBiblFactoryFacade $facade, protected \ilCtrlInterface $ctrl, protected \ilLanguage $lng, - protected \ILIAS\DI\UIServices $ui + protected UIServices $ui ) { } @@ -47,25 +49,25 @@ public function generateLibraryLink(ilBiblEntry $entry, string $type): string case ilBiblTypeFactoryInterface::DATA_TYPE_BIBTEX: $prefix = "bib_default_"; if (!empty($attributes[$prefix . "isbn"])) { - $attr = array("isbn"); + $attr = ["isbn"]; } elseif (!empty($attributes[$prefix . "pmid"])) { - $attr = array("pmid"); + $attr = ["pmid"]; } elseif (!empty($attributes[$prefix . "doi"])) { - $attr = array("doi"); + $attr = ["doi"]; } elseif (!empty($attributes[$prefix . "issn"])) { - $attr = array("issn"); + $attr = ["issn"]; } else { - $attr = array("title", "author", "year", "number", "volume"); + $attr = ["title", "author", "year", "number", "volume"]; } break; case ilBiblTypeFactoryInterface::DATA_TYPE_RIS: $prefix = "ris_" . strtolower($entry->getType()) . "_"; if (!empty($attributes[$prefix . "sn"])) { - $attr = array("sn"); + $attr = ["sn"]; } elseif (!empty($attributes[$prefix . "do"])) { - $attr = array("do"); + $attr = ["do"]; } else { - $attr = array("ti", "t1", "au", "py", "is", "vl"); + $attr = ["ti", "t1", "au", "py", "is", "vl"]; } break; } @@ -80,7 +82,7 @@ public function generateLibraryLink(ilBiblEntry $entry, string $type): string . "i%3A" . $attributes[$prefix . $attr[0]]; } else { $url_params .= $this->formatAttribute($attr[0], $type, $attributes, $prefix) . "=" - . urlencode($attributes[$prefix . $attr[0]]); + . urlencode((string) $attributes[$prefix . $attr[0]]); } } else { foreach ($attr as $a) { @@ -89,7 +91,7 @@ public function generateLibraryLink(ilBiblEntry $entry, string $type): string $url_params .= "&"; } $url_params .= $this->formatAttribute($a, $type, $attributes, $prefix) . "=" - . urlencode($attributes[$prefix . $a]); + . urlencode((string) $attributes[$prefix . $a]); } } } @@ -135,11 +137,7 @@ public function formatAttribute(string $a, ilBiblTypeInterface $type, array $att $a = "author"; break; case 'sn': - if (strlen($attributes[$prefix . "sn"]) <= 9) { - $a = "issn"; - } else { - $a = "isbn"; - } + $a = strlen((string) $attributes[$prefix . "sn"]) <= 9 ? "issn" : "isbn"; break; case 'py': $a = "date"; diff --git a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryTableGUI.php b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryTableGUI.php index bebf8eeccead..f0a497640b38 100755 --- a/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryTableGUI.php +++ b/components/ILIAS/Bibliographic/classes/Admin/Library/class.ilBiblLibraryTableGUI.php @@ -20,12 +20,12 @@ use ILIAS\UI\Component\Table\DataRowBuilder; use ILIAS\Data\Range; use ILIAS\Data\Order; -use Psr\Http\Message\ServerRequestInterface AS HttpRequest; +use Psr\Http\Message\ServerRequestInterface as HttpRequest; use ILIAS\UI\Factory as UIFactory; -use ILIAS\UI\Renderer AS UIRenderer; +use ILIAS\UI\Renderer as UIRenderer; use ILIAS\Data\Factory as DataFactory; use ILIAS\UI\URLBuilder; -use ILIAS\UI\Component\Table\Data AS DataTable; +use ILIAS\UI\Component\Table\Data as DataTable; use ILIAS\UI\URLBuilderToken; class ilBiblLibraryTableGUI implements DataRetrieval @@ -185,15 +185,15 @@ private function getRecords(?Range $range = null, ?Order $order = null): array ]; } - if ($order) { - [$order_field, $order_direction] = $order->join([], fn($ret, $key, $value) => [$key, $value]); - usort($records, static fn($a, $b) => $a[$order_field] <=> $b[$order_field]); + if ($order !== null) { + [$order_field, $order_direction] = $order->join([], fn($ret, $key, $value): array => [$key, $value]); + usort($records, static fn($a, $b): int => $a[$order_field] <=> $b[$order_field]); if ($order_direction === 'DESC') { $records = array_reverse($records); } } - if ($range) { - $records = array_slice($records, $range->getStart(), $range->getLength()); + if ($range !== null) { + return array_slice($records, $range->getStart(), $range->getLength()); } return $records; diff --git a/components/ILIAS/Bibliographic/classes/Attribute/class.ilBiblAttribute.php b/components/ILIAS/Bibliographic/classes/Attribute/class.ilBiblAttribute.php index a4df2e35b76f..b9c770522855 100755 --- a/components/ILIAS/Bibliographic/classes/Attribute/class.ilBiblAttribute.php +++ b/components/ILIAS/Bibliographic/classes/Attribute/class.ilBiblAttribute.php @@ -28,6 +28,7 @@ public static function returnDbTableName(): string } + #[\Override] public function getConnectorContainerName(): string { return 'il_bibl_attribute'; diff --git a/components/ILIAS/Bibliographic/classes/Attribute/class.ilBiblAttributeFactory.php b/components/ILIAS/Bibliographic/classes/Attribute/class.ilBiblAttributeFactory.php index 8d84fff73676..3c99168793f8 100755 --- a/components/ILIAS/Bibliographic/classes/Attribute/class.ilBiblAttributeFactory.php +++ b/components/ILIAS/Bibliographic/classes/Attribute/class.ilBiblAttributeFactory.php @@ -21,13 +21,11 @@ */ class ilBiblAttributeFactory implements ilBiblAttributeFactoryInterface { - protected \ilBiblFieldFactoryInterface $field_factory; protected ilDBInterface $db; - public function __construct(ilBiblFieldFactoryInterface $field_factory) + public function __construct(protected \ilBiblFieldFactoryInterface $field_factory) { global $DIC; - $this->field_factory = $field_factory; $this->db = $DIC->database(); } diff --git a/components/ILIAS/Bibliographic/classes/Data/class.ilBiblData.php b/components/ILIAS/Bibliographic/classes/Data/class.ilBiblData.php index 26322f116677..53580cefa94c 100755 --- a/components/ILIAS/Bibliographic/classes/Data/class.ilBiblData.php +++ b/components/ILIAS/Bibliographic/classes/Data/class.ilBiblData.php @@ -16,14 +16,11 @@ * *********************************************************************/ -use ILIAS\ResourceStorage\Identification\ResourceIdentification; - /** * Class ilBiblData * * @author: Benjamin Seglias */ - class ilBiblData extends ActiveRecord implements ilBiblDataInterface { public const TABLE_NAME = 'il_bibl_data'; @@ -35,6 +32,7 @@ public static function returnDbTableName(): string } + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; diff --git a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntry.php b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntry.php index 39d8678c2363..4417d993e924 100755 --- a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntry.php +++ b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntry.php @@ -29,6 +29,7 @@ public static function returnDbTableName(): string return self::TABLE_NAME; } + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; diff --git a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryDetailPresentationGUI.php b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryDetailPresentationGUI.php index ce129a8651fb..b702055766a4 100755 --- a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryDetailPresentationGUI.php +++ b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryDetailPresentationGUI.php @@ -16,8 +16,7 @@ * *********************************************************************/ -use ILIAS\UI\Component\Deck\Deck; -use ILIAS\UI\Component\Panel\Standard; +use ILIAS\DI\UIServices; use ILIAS\UI\Component\Panel\Sub; /** @@ -39,7 +38,7 @@ public function __construct( protected ilLanguage $lng, protected ilGlobalTemplateInterface $main_tpl, protected ilTabsGUI $tabs, - protected \ILIAS\DI\UIServices $ui + protected UIServices $ui ) { $this->initHelp(); $this->initTabs(); @@ -90,7 +89,7 @@ public function getHTML(): string private function getLibrariesDeck(): ?Sub { $settings = $this->facade->libraryFactory()->getAll(); - if (count($settings) === 0) { + if ($settings === []) { return null; } diff --git a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryFactory.php b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryFactory.php index 0ca9f01cfdb5..0c52baa00e23 100755 --- a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryFactory.php +++ b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryFactory.php @@ -27,22 +27,16 @@ class ilBiblEntryFactory implements ilBiblEntryFactoryInterface protected int $entry_id; protected string $type; protected array $attributes; - protected \ilBiblTypeInterface $file_type; - protected \ilBiblFieldFactoryInterface $field_factory; - protected \ilBiblOverviewModelFactoryInterface $overview_factory; protected ilDBInterface $db; /** * ilBiblEntryFactory constructor. */ - public function __construct(ilBiblFieldFactoryInterface $field_factory, \ilBiblTypeInterface $file_type, ilBiblOverviewModelFactoryInterface $overview_factory) + public function __construct(protected \ilBiblFieldFactoryInterface $field_factory, protected \ilBiblTypeInterface $file_type, protected \ilBiblOverviewModelFactoryInterface $overview_factory) { global $DIC; $this->db = $DIC->database(); - $this->file_type = $file_type; - $this->field_factory = $field_factory; - $this->overview_factory = $overview_factory; } /** @@ -50,16 +44,11 @@ public function __construct(ilBiblFieldFactoryInterface $field_factory, \ilBiblT */ public function loadParsedAttributesByEntryId(int $entry_id): array { - $ilBiblEntry = ilBiblEntry::where(array('id' => $entry_id))->first(); + $ilBiblEntry = ilBiblEntry::where(['id' => $entry_id])->first(); $attributes = $this->getAllAttributesByEntryId($entry_id); - if ($this->file_type->getId() == ilBiblTypeFactoryInterface::DATA_TYPE_RIS) { - //for RIS-Files also add the type; - $type = $ilBiblEntry->getType(); - } else { - $type = 'default'; - } - $parsed_attributes = array(); + $type = $this->file_type->getId() == ilBiblTypeFactoryInterface::DATA_TYPE_RIS ? $ilBiblEntry->getType() : 'default'; + $parsed_attributes = []; foreach ($attributes as $attribute) { $value = $this->secure($attribute->getValue()); // surround links with @@ -83,7 +72,7 @@ public function loadParsedAttributesByEntryId(int $entry_id): array public function findByIdAndTypeString(int $id, string $type_string): ilBiblEntryInterface { /** @noinspection PhpIncompatibleReturnTypeInspection */ - return ilBiblEntry::where(array('id' => $id))->first(); + return ilBiblEntry::where(['id' => $id])->first(); } /** @@ -92,7 +81,7 @@ public function findByIdAndTypeString(int $id, string $type_string): ilBiblEntry public function findOrCreateEntry(int $id, int $bibliographic_obj_id, string $entry_type): \ilBiblEntryInterface { $inst = $this->getARInstance($id); - if (!$inst) { + if ($inst === null) { $inst = $this->createEntry($bibliographic_obj_id, $entry_type); } $inst->setDataId($bibliographic_obj_id); @@ -188,7 +177,7 @@ public function filterEntryIdsForTableAsArray(int $object_id, ?ilBiblTableQueryI public function deleteEntryById(int $id): void { - $entry = ilBiblEntry::where(array('id' => $id))->first(); + $entry = ilBiblEntry::where(['id' => $id])->first(); if ($entry instanceof ilBiblEntry) { $entry->delete(); } @@ -204,7 +193,7 @@ public function deleteEntriesById(int $object_id): void */ public function getAllAttributesByEntryId(int $id): array { - return ilBiblAttribute::where(array('entry_id' => $id))->get(); + return ilBiblAttribute::where(['entry_id' => $id])->get(); } public function getFileType(): \ilBiblTypeInterface diff --git a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryTableGUI.php b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryTableGUI.php index fe2871bafdf6..16c855f16293 100755 --- a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryTableGUI.php +++ b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryTableGUI.php @@ -121,7 +121,7 @@ private function renderLibraryButtons(int $entry_id): array $entry = $this->facade->entryFactory()->findByIdAndTypeString($entry_id, $this->facade->type()->getStringRepresentation()); $settings = $this->facade->libraryFactory()->getAll(); - if (count($settings) === 0) { + if ($settings === []) { return []; } @@ -171,8 +171,8 @@ function ( $record['year'] = empty($record['year']) ? null : $record['year']; $author = $record['autor'] = $record['author'] ?? $record['AU'] ?? ''; - $title = $record['title'] = $record['title'] ?? $record['TI'] ?? ''; - $year = $record['year'] = $record['year'] ?? $record['PY'] ?? ''; + $title = ($record['title'] ??= $record['TI'] ?? ''); + $year = ($record['year'] ??= $record['PY'] ?? ''); $entry_id = $record['entry_id']; unset($record['author'], $record['title'], $record['AU'], $record['TI'], $record['entry_id']); diff --git a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryTablePresentationGUI.php b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryTablePresentationGUI.php index fea9f9b72a1d..0ad64ff2423c 100755 --- a/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryTablePresentationGUI.php +++ b/components/ILIAS/Bibliographic/classes/Entry/class.ilBiblEntryTablePresentationGUI.php @@ -23,17 +23,13 @@ */ class ilBiblEntryTablePresentationGUI { - protected \ilBiblEntry $entry; protected string $html = ''; - protected \ilBiblFactoryFacadeInterface $facade; /** * ilBiblEntryTablePresentationGUI constructor. */ - public function __construct(ilBiblEntry $entry, ilBiblFactoryFacadeInterface $facade) + public function __construct(protected \ilBiblEntry $entry, protected \ilBiblFactoryFacadeInterface $facade) { - $this->entry = $entry; - $this->facade = $facade; $this->render(); } @@ -71,9 +67,9 @@ protected function render(): void . $cuts[2], $single_entry); // replace the tags with a span, in order to make text italic by css do { - $first_sign_after_begin_emph_tag = strpos(strtolower($single_entry), '') + $first_sign_after_begin_emph_tag = stripos($single_entry, '') + 6; - $last_sign_after_end_emph_tag = strpos(strtolower($single_entry), ''); + $last_sign_after_end_emph_tag = stripos($single_entry, ''); $italic_text_length = $last_sign_after_end_emph_tag - $first_sign_after_begin_emph_tag; //would not be true if there is no tag left diff --git a/components/ILIAS/Bibliographic/classes/Field/DataRetrieval.php b/components/ILIAS/Bibliographic/classes/Field/DataRetrieval.php index 646ffb7f8d24..c235c65de029 100755 --- a/components/ILIAS/Bibliographic/classes/Field/DataRetrieval.php +++ b/components/ILIAS/Bibliographic/classes/Field/DataRetrieval.php @@ -73,10 +73,10 @@ public function getRows22( protected function getRecords(Order $order): array { $records = $this->facade->fieldFactory()->filterAllFieldsForTypeAsArray($this->facade->type()); - [$order_field, $order_direction] = $order->join([], fn($ret, $key, $value) => [$key, $value]); - usort($records, fn($a, $b) => $a[$order_field] <=> $b[$order_field]); + [$order_field, $order_direction] = $order->join([], fn($ret, $key, $value): array => [$key, $value]); + usort($records, fn($a, $b): int => $a[$order_field] <=> $b[$order_field]); if ($order_direction === 'DESC') { - $records = array_reverse($records); + return array_reverse($records); } return $records; } diff --git a/components/ILIAS/Bibliographic/classes/Field/Table.php b/components/ILIAS/Bibliographic/classes/Field/Table.php index 8632702dd901..dcf032074136 100755 --- a/components/ILIAS/Bibliographic/classes/Field/Table.php +++ b/components/ILIAS/Bibliographic/classes/Field/Table.php @@ -18,8 +18,10 @@ namespace ILIAS\Bibliographic\Field; +use ILIAS\UI\Factory; +use ILIAS\UI\Renderer; +use ILIAS\UI\Component\Table\Ordering; use ilBiblAdminFieldGUI; -use ilBiblAdminRisFieldGUI; use ilBiblTranslationGUI; use ILIAS\Bibliographic\Field\DataRetrieval; use ILIAS\Data\URI; @@ -32,13 +34,13 @@ */ class Table { - private \ILIAS\UI\Factory $ui_factory; - private \ILIAS\UI\Renderer $ui_renderer; + private Factory $ui_factory; + private Renderer $ui_renderer; private \ilCtrlInterface $ctrl; private \ilLanguage $lng; private URLBuilder $url_builder; private URLBuilderToken $id_token; - private \ILIAS\UI\Component\Table\Ordering $table; + private Ordering $table; protected array $components = []; diff --git a/components/ILIAS/Bibliographic/classes/Field/class.ilBiblAdminFieldGUI.php b/components/ILIAS/Bibliographic/classes/Field/class.ilBiblAdminFieldGUI.php index e6ac36bb888c..3d0cc4788942 100755 --- a/components/ILIAS/Bibliographic/classes/Field/class.ilBiblAdminFieldGUI.php +++ b/components/ILIAS/Bibliographic/classes/Field/class.ilBiblAdminFieldGUI.php @@ -16,6 +16,7 @@ * *********************************************************************/ +use ILIAS\HTTP\Services; use ILIAS\Bibliographic\Field\Table; /** @@ -37,23 +38,21 @@ abstract class ilBiblAdminFieldGUI public const CMD_APPLY_FILTER = 'applyFilter'; public const CMD_RESET_FILTER = 'resetFilter'; public const CMD_SAVE = 'save'; - private \ILIAS\HTTP\Services $http; + private Services $http; private ilCtrl $ctrl; private ilTabsGUI $tabs; private ilLanguage $lng; private ilAccessHandler $access; - protected \ilBiblAdminFactoryFacadeInterface $facade; protected Table $table; private \ilGlobalTemplateInterface $main_tpl; /** * ilBiblAdminFieldGUI constructor. */ - public function __construct(ilBiblAdminFactoryFacadeInterface $facade) + public function __construct(protected \ilBiblAdminFactoryFacadeInterface $facade) { global $DIC; $this->main_tpl = $DIC->ui()->mainTemplate(); - $this->facade = $facade; $this->table = new Table( $this, $this->facade @@ -159,10 +158,10 @@ protected function setSubTabs(): void self::SUBTAB_RIS, $this->lng->txt('ris'), $this->ctrl->getLinkTargetByClass( - array( + [ ilObjBibliographicAdminGUI::class, ilBiblAdminRisFieldGUI::class, - ), + ], ilBiblAdminRisFieldGUI::CMD_STANDARD ) ); @@ -172,10 +171,10 @@ protected function setSubTabs(): void self::SUBTAB_BIBTEX, $this->lng->txt('bibtex'), $this->ctrl->getLinkTargetByClass( - array( + [ ilObjBibliographicAdminGUI::class, ilBiblAdminBibtexFieldGUI::class, - ), + ], ilBiblAdminBibtexFieldGUI::CMD_STANDARD ) ); diff --git a/components/ILIAS/Bibliographic/classes/Field/class.ilBiblField.php b/components/ILIAS/Bibliographic/classes/Field/class.ilBiblField.php index 5ddbba5f0f1a..a8bb3c8a284a 100755 --- a/components/ILIAS/Bibliographic/classes/Field/class.ilBiblField.php +++ b/components/ILIAS/Bibliographic/classes/Field/class.ilBiblField.php @@ -28,6 +28,7 @@ public static function returnDbTableName(): string return self::TABLE_NAME; } + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; @@ -83,7 +84,7 @@ public function setId(int $id): void public function getIdentifier(): string { - return trim($this->identifier); + return trim((string) $this->identifier); } public function setIdentifier(string $identifier): void diff --git a/components/ILIAS/Bibliographic/classes/Field/class.ilBiblFieldFactory.php b/components/ILIAS/Bibliographic/classes/Field/class.ilBiblFieldFactory.php index 6220d04505c2..54bd163943c9 100755 --- a/components/ILIAS/Bibliographic/classes/Field/class.ilBiblFieldFactory.php +++ b/components/ILIAS/Bibliographic/classes/Field/class.ilBiblFieldFactory.php @@ -23,15 +23,11 @@ */ class ilBiblFieldFactory implements ilBiblFieldFactoryInterface { - protected \ilBiblTypeInterface $type; - - /** * ilBiblFieldFactory constructor. */ - public function __construct(\ilBiblTypeInterface $type) + public function __construct(protected \ilBiblTypeInterface $type) { - $this->type = $type; } @@ -68,7 +64,7 @@ public function findById(int $id): ilBiblFieldInterface public function getFieldByTypeAndIdentifier(int $type, string $identifier): ilBiblFieldInterface { $inst = $this->getARInstance($type, $identifier); - if (!$inst) { + if ($inst === null) { throw new ilException("bibliografic identifier {$identifier} not found"); } @@ -220,11 +216,11 @@ private function getCollectionForFilter(ilBiblTypeInterface $type, ?ilBiblTableQ { $collection = ilBiblField::getCollection(); - $collection->where(array('data_type' => $type->getId())); + $collection->where(['data_type' => $type->getId()]); - if ($queryInfo) { - $sorting_column = $queryInfo->getSortingColumn() ? $queryInfo->getSortingColumn() : null; - $offset = $queryInfo->getOffset() ? $queryInfo->getOffset() : 0; + if ($queryInfo !== null) { + $sorting_column = $queryInfo->getSortingColumn() !== '' && $queryInfo->getSortingColumn() !== '0' ? $queryInfo->getSortingColumn() : null; + $offset = $queryInfo->getOffset(); $sorting_direction = $queryInfo->getSortingDirection(); $limit = $queryInfo->getLimit(); if ($sorting_column) { @@ -233,11 +229,7 @@ private function getCollectionForFilter(ilBiblTypeInterface $type, ?ilBiblTableQ $collection->limit($offset, $limit); foreach ($queryInfo->getFilters() as $queryFilter) { - switch ($queryFilter->getFieldName()) { - default: - $collection->where(array($queryFilter->getFieldName() => $queryFilter->getFieldValue()), $queryFilter->getOperator()); - break; - } + $collection->where([$queryFilter->getFieldName() => $queryFilter->getFieldValue()], $queryFilter->getOperator()); } } diff --git a/components/ILIAS/Bibliographic/classes/FieldFilter/DataRetrieval.php b/components/ILIAS/Bibliographic/classes/FieldFilter/DataRetrieval.php index 2dec9f65cf2e..43b976a39773 100755 --- a/components/ILIAS/Bibliographic/classes/FieldFilter/DataRetrieval.php +++ b/components/ILIAS/Bibliographic/classes/FieldFilter/DataRetrieval.php @@ -61,10 +61,10 @@ protected function getRecords(Order $order): array $this->info->setSortingColumn('id'); $records = $this->facade->filterFactory()->filterItemsForTable($this->facade->iliasObjId(), $this->info); - [$order_field, $order_direction] = $order->join([], fn($ret, $key, $value) => [$key, $value]); - usort($records, fn($a, $b) => $a[$order_field] <=> $b[$order_field]); + [$order_field, $order_direction] = $order->join([], fn($ret, $key, $value): array => [$key, $value]); + usort($records, fn($a, $b): int => $a[$order_field] <=> $b[$order_field]); if ($order_direction === 'DESC') { - $records = array_reverse($records); + return array_reverse($records); } return $records; } diff --git a/components/ILIAS/Bibliographic/classes/FieldFilter/Table.php b/components/ILIAS/Bibliographic/classes/FieldFilter/Table.php index 30667d58479b..63ec7618d90b 100755 --- a/components/ILIAS/Bibliographic/classes/FieldFilter/Table.php +++ b/components/ILIAS/Bibliographic/classes/FieldFilter/Table.php @@ -18,6 +18,8 @@ namespace ILIAS\Bibliographic\FieldFilter; +use ILIAS\UI\Factory; +use ILIAS\UI\Renderer; use ILIAS\UI\URLBuilder; use ILIAS\Data\URI; use ILIAS\UI\URLBuilderToken; @@ -27,8 +29,8 @@ */ class Table { - private \ILIAS\UI\Factory $ui_factory; - private \ILIAS\UI\Renderer $ui_renderer; + private Factory $ui_factory; + private Renderer $ui_renderer; private \ilCtrlInterface $ctrl; private \ilLanguage $lng; private URLBuilder $url_builder; diff --git a/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilter.php b/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilter.php index dbc7d89f2810..a8c9cf7e63e3 100755 --- a/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilter.php +++ b/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilter.php @@ -28,6 +28,7 @@ public static function returnDbTableName(): string return self::TABLE_NAME; } + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; diff --git a/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterFormGUI.php b/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterFormGUI.php index 5024d90984e5..9655ea5fe920 100755 --- a/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterFormGUI.php +++ b/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterFormGUI.php @@ -1,4 +1,5 @@ facade = $facade; - $this->filter = $field_filter; - $this->parent_gui = $parent_gui; $this->filter_id = $this->filter->getId(); $this->lng()->loadLanguageModule('bibl'); @@ -71,7 +68,7 @@ public function initForm(): void array_unshift($options, $available_field); continue; } - if(!in_array($available_field->getId(), $existing_field_ids, false)) { + if (!in_array($available_field->getId(), $existing_field_ids, false)) { $options[] = $available_field; } } @@ -115,7 +112,7 @@ public function initForm(): void public function fillForm(): void { - $array = array(self::F_FIELD_ID => $this->filter->getFieldId(), self::F_FILTER_TYPE => $this->filter->getFilterType(),); + $array = [self::F_FIELD_ID => $this->filter->getFieldId(), self::F_FILTER_TYPE => $this->filter->getFilterType(),]; $this->setValuesByArray($array); } diff --git a/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterGUI.php b/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterGUI.php index af39bffbd268..978f232c5338 100755 --- a/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterGUI.php +++ b/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterGUI.php @@ -16,6 +16,8 @@ * *********************************************************************/ +use ILIAS\components\OrgUnit\ARHelper\DIC; +use ILIAS\HTTP\Services; use ILIAS\Bibliographic\FieldFilter\Table; /** @@ -26,7 +28,7 @@ */ class ilBiblFieldFilterGUI { - use \ILIAS\components\OrgUnit\ARHelper\DIC; + use DIC; public const FILTER_ID = 'filter_id'; public const CMD_STANDARD = 'index'; @@ -39,23 +41,21 @@ class ilBiblFieldFilterGUI public const CMD_RENDER_INTERRUPTIVE = 'renderInterruptiveModal'; public const CMD_APPLY_FILTER = 'applyFilter'; public const CMD_RESET_FILTER = 'resetFilter'; - private \ILIAS\HTTP\Services $http; + private Services $http; private ilCtrl $ctrl; private ilLanguage $lng; private ilTabsGUI $tabs; private ilAccessHandler $access; - protected \ilBiblFactoryFacade $facade; protected Table $table; protected \ilGlobalTemplateInterface $main_tpl; /** * ilBiblFieldFilterGUI constructor. */ - public function __construct(ilBiblFactoryFacade $facade) + public function __construct(protected \ilBiblFactoryFacade $facade) { global $DIC; $this->main_tpl = $DIC->ui()->mainTemplate(); - $this->facade = $facade; $this->table = new Table( $this, $this->facade @@ -99,11 +99,8 @@ public function executeCommand(): void { $this->saveFieldIdsInRequest(); $next_class = $this->ctrl->getNextClass(); - switch ($next_class) { - default: - $this->tabs->activateTab(ilObjBibliographicGUI::TAB_SETTINGS); - $this->performCommand(); - } + $this->tabs->activateTab(ilObjBibliographicGUI::TAB_SETTINGS); + $this->performCommand(); } protected function performCommand(): void diff --git a/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterPresentationGUI.php b/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterPresentationGUI.php index 7298c8041f5c..884b3b66bbdb 100755 --- a/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterPresentationGUI.php +++ b/components/ILIAS/Bibliographic/classes/FieldFilter/class.ilBiblFieldFilterPresentationGUI.php @@ -16,6 +16,7 @@ * *********************************************************************/ +use ILIAS\components\OrgUnit\ARHelper\DIC; use ILIAS\UI\Component\Input\Field\MultiSelect; use ILIAS\UI\Component\Input\Field\Select; use ILIAS\UI\Component\Input\Field\Text; @@ -27,18 +28,14 @@ */ class ilBiblFieldFilterPresentationGUI { - use \ILIAS\components\OrgUnit\ARHelper\DIC; - protected ilBiblFactoryFacadeInterface $facade; - protected ilBiblFieldFilterInterface $filter; + use DIC; /** * ilBiblFieldFilterPresentationGUI constructor. */ - public function __construct(ilBiblFieldFilterInterface $filter, ilBiblFactoryFacadeInterface $facade) + public function __construct(protected ilBiblFieldFilterInterface $filter, protected ilBiblFactoryFacadeInterface $facade) { - $this->facade = $facade; - $this->filter = $filter; $this->lng()->loadLanguageModule('bibl'); } diff --git a/components/ILIAS/Bibliographic/classes/FileReader/BibTex/class.ilBiblTexFileReader.php b/components/ILIAS/Bibliographic/classes/FileReader/BibTex/class.ilBiblTexFileReader.php index 84a496060484..a583c4b02ca7 100755 --- a/components/ILIAS/Bibliographic/classes/FileReader/BibTex/class.ilBiblTexFileReader.php +++ b/components/ILIAS/Bibliographic/classes/FileReader/BibTex/class.ilBiblTexFileReader.php @@ -22,7 +22,7 @@ */ class ilBiblTexFileReader extends ilBiblFileReaderBase implements ilBiblFileReaderInterface { - protected static array $ignored_keywords = array('Preamble'); + protected static array $ignored_keywords = ['Preamble']; /** * @inheritdoc @@ -41,7 +41,7 @@ public function parseContent(): array $objects = array_splice($objects, 2); } // some files lead to a empty first entry in the array with the fist bib-entry, we have to trow them away... - if (strlen($objects[0]) <= 3) { + if (strlen((string) $objects[0]) <= 3) { $objects = array_splice($objects, 1); } @@ -49,10 +49,10 @@ public function parseContent(): array foreach ($objects as $key => $object) { if ((int) $key % 2 == 0 || (int) $key == 0) { $entry = []; - $entry['entryType'] = strtolower($object); + $entry['entryType'] = strtolower((string) $object); } else { // Citation - preg_match("/^{(?.*),\\n/um", $object, $cite_matches); + preg_match("/^{(?.*),\\n/um", (string) $object, $cite_matches); if ($cite_matches['cite'] ?? false) { $entry['cite'] = $cite_matches['cite']; } @@ -60,7 +60,7 @@ public function parseContent(): array // Edit at regex101.com: (?[\w]*)\s*=\s*[{"]*(?(.*?))\s*[}"]*?\s*[,]*?\s*\n $re = "/(?[\\w]*)\\s*=\\s*[{\"]*(?(.*?))\\s*[}\"]*?\\s*[,]*?\\s*\\n/"; - preg_match_all($re, $object, $matches, PREG_SET_ORDER); + preg_match_all($re, (string) $object, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $clean = $match['content']; @@ -85,21 +85,21 @@ protected function normalizeContent(): void // remove emty newlines $result = preg_replace("/^\n/um", "", $result); // Remove lines with only whitespaces - $result = preg_replace("/^[\\s]*$/um", "\n", $result); - $result = preg_replace("/\\n\\n\\n/um", "\n\n", $result); + $result = preg_replace("/^[\\s]*$/um", "\n", (string) $result); + $result = preg_replace("/\\n\\n\\n/um", "\n\n", (string) $result); // remove comments - $result = preg_replace("/^%.*\\n/um", "", $result); + $result = preg_replace("/^%.*\\n/um", "", (string) $result); // Intend attributes with a tab - $result = preg_replace("/^[ ]+/um", "\t", $result); - $result = preg_replace("/^([\\w])/um", "\t$1", $result); + $result = preg_replace("/^[ ]+/um", "\t", (string) $result); + $result = preg_replace("/^([\\w])/um", "\t$1", (string) $result); // replace newline-braktes with brakets - $result = preg_replace('/\\n}/uimx', '}', $result); + $result = preg_replace('/\\n}/uimx', '}', (string) $result); // move last bracket on newline - $result = preg_replace("/}[\\s]*$/um", "\n}", $result); + $result = preg_replace("/}[\\s]*$/um", "\n}", (string) $result); // Support long lines (not working at the moment) // $re = "/(\"[^\"\\n]*)\\r?\\n(?!(([^\"]*\"){2})*[^\"]*$)/"; @@ -178,8 +178,7 @@ protected function removeBomUtf8(string $s): string { if (substr($s, 0, 3) === chr(hexdec('EF')) . chr(hexdec('BB')) . chr(hexdec('BF'))) { return substr($s, 3); - } else { - return $s; } + return $s; } } diff --git a/components/ILIAS/Bibliographic/classes/FileReader/Ris/class.ilBiblRisFileReaderWrapper.php b/components/ILIAS/Bibliographic/classes/FileReader/Ris/class.ilBiblRisFileReaderWrapper.php index 35adf94f7c8a..c01ab0135f97 100755 --- a/components/ILIAS/Bibliographic/classes/FileReader/Ris/class.ilBiblRisFileReaderWrapper.php +++ b/components/ILIAS/Bibliographic/classes/FileReader/Ris/class.ilBiblRisFileReaderWrapper.php @@ -16,8 +16,6 @@ * *********************************************************************/ -use LibRIS\RISReader; - /** * Class ilBiblRisFileReaderWrapper * @author Fabian Schmid diff --git a/components/ILIAS/Bibliographic/classes/FileReader/class.ilBiblFileReaderBase.php b/components/ILIAS/Bibliographic/classes/FileReader/class.ilBiblFileReaderBase.php index 36090c9909b0..fbc07d206cd5 100755 --- a/components/ILIAS/Bibliographic/classes/FileReader/class.ilBiblFileReaderBase.php +++ b/components/ILIAS/Bibliographic/classes/FileReader/class.ilBiblFileReaderBase.php @@ -16,6 +16,8 @@ * *********************************************************************/ +use ILIAS\Refinery\Factory; +use ILIAS\ResourceStorage\Services; use ILIAS\ResourceStorage\Identification\ResourceIdentification; /** @@ -35,28 +37,21 @@ abstract class ilBiblFileReaderBase implements ilBiblFileReaderInterface public const ENCODING_ISO_8859_1 = 'ISO-8859-1'; protected string $file_content = ''; protected string $path_to_file = ''; - private \ILIAS\Refinery\Factory $refinery; - protected \ilBiblEntryFactoryInterface $entry_factory; - protected \ilBiblFieldFactoryInterface $field_factory; - protected \ilBiblAttributeFactoryInterface $attribute_factory; + private Factory $refinery; - protected \ILIAS\ResourceStorage\Services $storage; + protected Services $storage; /** * ilBiblFileReaderBase constructor. */ public function __construct( - ilBiblEntryFactoryInterface $entry_factory, - ilBiblFieldFactoryInterface $field_factory, - ilBiblAttributeFactoryInterface $attribute_factory + protected \ilBiblEntryFactoryInterface $entry_factory, + protected \ilBiblFieldFactoryInterface $field_factory, + protected \ilBiblAttributeFactoryInterface $attribute_factory ) { global $DIC; - - $this->entry_factory = $entry_factory; $this->refinery = $DIC->refinery(); - $this->field_factory = $field_factory; - $this->attribute_factory = $attribute_factory; $this->storage = $DIC["resource_storage"]; } @@ -103,7 +98,7 @@ public function parseContentToEntries(ilObjBibliographic $bib): array foreach ($entries_from_file as $file_entry) { $type = null; $x = 0; - $parsed_entry = array(); + $parsed_entry = []; foreach ($file_entry as $key => $attribute) { $key = $this->secure($key); if (is_string($attribute)) { @@ -111,9 +106,7 @@ public function parseContentToEntries(ilObjBibliographic $bib): array } // if the attribute is an array, make a comma separated string out of it if (is_array($attribute)) { - $attribute = array_map(function (string $a): string { - return $this->secure($a); - }, $attribute); + $attribute = array_map(fn(string $a): string => $this->secure($a), $attribute); $attribute = implode(", ", $attribute); } // reduce the attribute strings to a maximum of 4000 (ATTRIBUTE_VALUE_MAXIMAL_TEXT_LENGTH) characters, in order to fit in the database diff --git a/components/ILIAS/Bibliographic/classes/FileReader/class.ilBiblFileReaderFactory.php b/components/ILIAS/Bibliographic/classes/FileReader/class.ilBiblFileReaderFactory.php index 668f0997fce4..149fb7690c8e 100755 --- a/components/ILIAS/Bibliographic/classes/FileReader/class.ilBiblFileReaderFactory.php +++ b/components/ILIAS/Bibliographic/classes/FileReader/class.ilBiblFileReaderFactory.php @@ -28,13 +28,10 @@ public function getByType( ilBiblFieldFactoryInterface $field_factory, ilBiblAttributeFactoryInterface $attribute_factory ): ilBiblFileReaderInterface { - switch ($type) { - case ilBiblTypeFactoryInterface::DATA_TYPE_BIBTEX: - return new ilBiblTexFileReader($entry_factory, $field_factory, $attribute_factory); - case ilBiblTypeFactoryInterface::DATA_TYPE_RIS: - return new ilBiblRisFileReader($entry_factory, $field_factory, $attribute_factory); - default: - throw new ilException("bibliografic type not found"); - } + return match ($type) { + ilBiblTypeFactoryInterface::DATA_TYPE_BIBTEX => new ilBiblTexFileReader($entry_factory, $field_factory, $attribute_factory), + ilBiblTypeFactoryInterface::DATA_TYPE_RIS => new ilBiblRisFileReader($entry_factory, $field_factory, $attribute_factory), + default => throw new ilException("bibliografic type not found"), + }; } } diff --git a/components/ILIAS/Bibliographic/classes/OverviewModel/class.ilBiblOverviewModel.php b/components/ILIAS/Bibliographic/classes/OverviewModel/class.ilBiblOverviewModel.php index 7250e7b17507..c58e82b6058c 100755 --- a/components/ILIAS/Bibliographic/classes/OverviewModel/class.ilBiblOverviewModel.php +++ b/components/ILIAS/Bibliographic/classes/OverviewModel/class.ilBiblOverviewModel.php @@ -28,6 +28,7 @@ public static function returnDbTableName(): string return self::TABLE_NAME; } + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; diff --git a/components/ILIAS/Bibliographic/classes/OverviewModel/class.ilBiblOverviewModelFactory.php b/components/ILIAS/Bibliographic/classes/OverviewModel/class.ilBiblOverviewModelFactory.php index 14b7ee52ea47..97d3545609fd 100755 --- a/components/ILIAS/Bibliographic/classes/OverviewModel/class.ilBiblOverviewModelFactory.php +++ b/components/ILIAS/Bibliographic/classes/OverviewModel/class.ilBiblOverviewModelFactory.php @@ -38,7 +38,7 @@ private function getAllOverviewModels(): array * @var ilBiblOverviewModel[] $overviewModels */ $overviewModels = ilBiblOverviewModel::get(); - $overviewModelsArray = array(); + $overviewModelsArray = []; foreach ($overviewModels as $model) { if ($model->getLiteratureType()) { $overviewModelsArray[$model->getFileTypeId()][$model->getLiteratureType()] = $model->getPattern(); diff --git a/components/ILIAS/Bibliographic/classes/Setup/class.ilBibliographicSetupAgent.php b/components/ILIAS/Bibliographic/classes/Setup/class.ilBibliographicSetupAgent.php index 310d9b3ab9ff..d4d66dac670f 100755 --- a/components/ILIAS/Bibliographic/classes/Setup/class.ilBibliographicSetupAgent.php +++ b/components/ILIAS/Bibliographic/classes/Setup/class.ilBibliographicSetupAgent.php @@ -16,16 +16,22 @@ * *********************************************************************/ -use ILIAS\Refinery; -use ILIAS\Setup; +use ILIAS\Setup\Agent; +use ILIAS\Setup\Agent\HasNoNamedObjective; +use ILIAS\Refinery\Transformation; +use ILIAS\Setup\Config; +use ILIAS\Setup\Objective; +use ILIAS\Setup\ObjectiveCollection; +use ILIAS\Setup\Objective\NullObjective; +use ILIAS\Setup\Metrics\Storage; /** * Class ilBibliographicSetupAgent * @author Thibeau Fuhrer */ -final class ilBibliographicSetupAgent implements Setup\Agent +final class ilBibliographicSetupAgent implements Agent { - use Setup\Agent\HasNoNamedObjective; + use HasNoNamedObjective; /** * @var string component dir within ilias's data dir @@ -43,7 +49,7 @@ public function hasConfig(): bool /** * @inheritdoc */ - public function getArrayToConfigTransformation(): Refinery\Transformation + public function getArrayToConfigTransformation(): Transformation { throw new LogicException("ilBibliographicSetupAgent has no config."); } @@ -51,7 +57,7 @@ public function getArrayToConfigTransformation(): Refinery\Transformation /** * @inheritdoc */ - public function getInstallObjective(?Setup\Config $config = null): Setup\Objective + public function getInstallObjective(?Config $config = null): Objective { return new ilFileSystemComponentDataDirectoryCreatedObjective( self::COMPONENT_DIR, @@ -62,9 +68,9 @@ public function getInstallObjective(?Setup\Config $config = null): Setup\Objecti /** * @inheritdoc */ - public function getUpdateObjective(?Setup\Config $config = null): Setup\Objective + public function getUpdateObjective(?Config $config = null): Objective { - return new Setup\ObjectiveCollection('Setup Bibliografic directories and database', true, ...[ + return new ObjectiveCollection('Setup Bibliografic directories and database', true, ...[ new ilDatabaseUpdateStepsExecutedObjective( new ilBibliograficDB80() ) @@ -74,15 +80,15 @@ public function getUpdateObjective(?Setup\Config $config = null): Setup\Objectiv /** * @inheritdoc */ - public function getBuildObjective(): Setup\Objective + public function getBuildObjective(): Objective { - return new Setup\Objective\NullObjective(); + return new NullObjective(); } /** * @inheritdoc */ - public function getStatusObjective(Setup\Metrics\Storage $storage): Setup\Objective + public function getStatusObjective(Storage $storage): Objective { return new ilDatabaseUpdateStepsMetricsCollectedObjective($storage, new ilBibliograficDB80()); } diff --git a/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslation.php b/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslation.php index db1ddbf01b70..1f9070d5e9b0 100755 --- a/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslation.php +++ b/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslation.php @@ -29,6 +29,7 @@ public static function returnDbTableName(): string return self::TABLE_NAME; } + #[\Override] public function getConnectorContainerName(): string { return self::TABLE_NAME; diff --git a/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationFactory.php b/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationFactory.php index 9a355c7cad6e..16d0b6330601 100755 --- a/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationFactory.php +++ b/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationFactory.php @@ -16,23 +16,23 @@ * *********************************************************************/ +use ILIAS\DI\Container; + /** * Class ilBiblTranslationFactory * @author Fabian Schmid */ class ilBiblTranslationFactory implements ilBiblTranslationFactoryInterface { - protected \ILIAS\DI\Container $dic; - protected \ilBiblFieldFactoryInterface $field_factory; + protected Container $dic; /** * ilBiblTranslationFactory constructor. */ - public function __construct(ilBiblFieldFactoryInterface $field_factory) + public function __construct(protected \ilBiblFieldFactoryInterface $field_factory) { global $DIC; $this->dic = $DIC; - $this->field_factory = $field_factory; } public function translate(ilBiblFieldInterface $field): string @@ -45,7 +45,7 @@ public function translate(ilBiblFieldInterface $field): string } $core_translation = $this->translateInCore($field); - if (strpos($core_translation, "-") !== 0) { + if (!str_starts_with($core_translation, "-")) { return $core_translation; } diff --git a/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationGUI.php b/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationGUI.php index f2aeed8ddb7c..2fc4918fc588 100755 --- a/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationGUI.php +++ b/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationGUI.php @@ -36,8 +36,6 @@ class ilBiblTranslationGUI public const CMD_DELETE_TRANSLATIONS = "deleteTranslations"; public const CMD_DEFAULT = 'index'; private ilCtrlInterface $ctrl; - protected \ilBiblAdminFactoryFacadeInterface $facade; - protected \ilBiblFieldInterface $field; private \ilGlobalTemplateInterface $main_tpl; private LOMServices $lom_services; @@ -45,13 +43,11 @@ class ilBiblTranslationGUI /** * ilBiblTranslationGUI constructor. */ - public function __construct(ilBiblAdminFactoryFacadeInterface $facade, \ilBiblFieldInterface $field) + public function __construct(protected \ilBiblAdminFactoryFacadeInterface $facade, protected \ilBiblFieldInterface $field) { global $DIC; $DIC->language()->loadLanguageModule('obj'); $this->main_tpl = $DIC->ui()->mainTemplate(); - $this->facade = $facade; - $this->field = $field; $this->ctrl = $DIC['ilCtrl']; $this->lom_services = $DIC->learningObjectMetadata(); } @@ -59,11 +55,8 @@ public function __construct(ilBiblAdminFactoryFacadeInterface $facade, \ilBiblFi public function executeCommand(): void { - switch ($this->ctrl->getNextClass()) { - default: - $cmd = $this->ctrl->getCmd(self::CMD_DEFAULT); - $this->{$cmd}(); - } + $cmd = $this->ctrl->getCmd(self::CMD_DEFAULT); + $this->{$cmd}(); } @@ -154,7 +147,7 @@ protected function getLanguagesForm(): \ilPropertyFormGUI foreach ($this->lom_services->dataHelper()->getAllLanguages() as $language) { $options[$language->value()] = $language->presentableLabel(); } - $options = array("" => $this->lng()->txt("please_select")) + $options; + $options = ["" => $this->lng()->txt("please_select")] + $options; $si = new ilSelectInputGUI($this->lng()->txt("obj_additional_langs"), "additional_langs"); $si->setOptions($options); $si->setMulti(true); diff --git a/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationTableGUI.php b/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationTableGUI.php index bc8dec1ee893..6e61344ea3ac 100755 --- a/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationTableGUI.php +++ b/components/ILIAS/Bibliographic/classes/Translation/class.ilBiblTranslationTableGUI.php @@ -16,6 +16,8 @@ * *********************************************************************/ +use ILIAS\components\OrgUnit\ARHelper\DIC; + /** * Class ilBiblTranslationTableGUI * @@ -23,19 +25,15 @@ */ class ilBiblTranslationTableGUI extends ilTable2GUI { - use \ILIAS\components\OrgUnit\ARHelper\DIC; - protected \ilBiblFieldInterface $field; - protected \ilBiblTranslationFactoryInterface $translation_facory; + use DIC; /** * @inheritDoc */ - public function __construct(?object $a_parent_obj, ilBiblFieldInterface $bibl_field, ilBiblTranslationFactoryInterface $translation_factory) + public function __construct(?object $a_parent_obj, protected \ilBiblFieldInterface $field, protected \ilBiblTranslationFactoryInterface $translation_facory) { - $this->translation_facory = $translation_factory; - $this->field = $bibl_field; - $table_id = 'bibl_trans_field_' . $bibl_field->getId(); + $table_id = 'bibl_trans_field_' . $this->field->getId(); $this->setId($table_id); $this->setPrefix($table_id); $this->setFormName($table_id); @@ -78,6 +76,7 @@ protected function parseData(): void /** * @inheritDoc */ + #[\Override] protected function fillRow(array $a_set): void { $translation = $this->translation_facory->findById($a_set['id']); diff --git a/components/ILIAS/Bibliographic/classes/Types/BibTex/class.ilBibTex.php b/components/ILIAS/Bibliographic/classes/Types/BibTex/class.ilBibTex.php index a54ec877d9bb..9bb297950e3e 100755 --- a/components/ILIAS/Bibliographic/classes/Types/BibTex/class.ilBibTex.php +++ b/components/ILIAS/Bibliographic/classes/Types/BibTex/class.ilBibTex.php @@ -53,7 +53,7 @@ public function getStandardFieldIdentifiers(): array protected static array $standard_fields - = array( + = [ 'address', 'annote', 'author', @@ -80,9 +80,9 @@ public function getStandardFieldIdentifiers(): array 'url', 'volume', 'year', - ); + ]; protected static array $entry_types - = array( + = [ 'article', 'book', 'booklet', @@ -97,7 +97,7 @@ public function getStandardFieldIdentifiers(): array 'proceedings', 'techreport', 'unpublished', - ); + ]; /** diff --git a/components/ILIAS/Bibliographic/classes/Types/Ris/class.ilRis.php b/components/ILIAS/Bibliographic/classes/Types/Ris/class.ilRis.php index a8168be55410..84a8078b9857 100755 --- a/components/ILIAS/Bibliographic/classes/Types/Ris/class.ilRis.php +++ b/components/ILIAS/Bibliographic/classes/Types/Ris/class.ilRis.php @@ -55,7 +55,7 @@ public function getStandardFieldIdentifiers(): array * @source https://en.wikipedia.org/wiki/RIS_(file_format) */ protected static array $standard_fields - = array( + = [ 'A1', // First Author 'A2', @@ -212,9 +212,9 @@ public function getStandardFieldIdentifiers(): array // Primary Date 'Y2', // Access Date - ); + ]; protected static array $entry_types - = array( + = [ 'ABST', 'ADVS', 'ART', @@ -250,7 +250,7 @@ public function getStandardFieldIdentifiers(): array 'UNBILl', 'UNPB', 'VIDEO', - ); + ]; public function isStandardField(string $field_name): bool diff --git a/components/ILIAS/Bibliographic/classes/Types/class.ilBiblTypeFactory.php b/components/ILIAS/Bibliographic/classes/Types/class.ilBiblTypeFactory.php index 837274fc8ec7..96e49f86623c 100755 --- a/components/ILIAS/Bibliographic/classes/Types/class.ilBiblTypeFactory.php +++ b/components/ILIAS/Bibliographic/classes/Types/class.ilBiblTypeFactory.php @@ -29,14 +29,11 @@ class ilBiblTypeFactory implements ilBiblTypeFactoryInterface public function getInstanceForType(int $type): ilBiblTypeInterface { assert(is_int($type)); - switch ($type) { - case ilBiblTypeFactoryInterface::DATA_TYPE_BIBTEX: - return new ilBibTex(); - case ilBiblTypeFactoryInterface::DATA_TYPE_RIS: - return new ilRis(); - default: - throw new ilException("bibliografic type not found"); - } + return match ($type) { + ilBiblTypeFactoryInterface::DATA_TYPE_BIBTEX => new ilBibTex(), + ilBiblTypeFactoryInterface::DATA_TYPE_RIS => new ilRis(), + default => throw new ilException("bibliografic type not found"), + }; } @@ -46,8 +43,8 @@ public function getInstanceForType(int $type): ilBiblTypeInterface public function getInstanceForFileName(string $filename): ilBiblTypeInterface { //return bib for filetype .bibtex: - if (strtolower(substr($filename, -6)) == "bibtex" - || strtolower(substr($filename, -3)) == "bib" + if (strtolower(substr($filename, -6)) === "bibtex" + || strtolower(substr($filename, -3)) === "bib" ) { return $this->getInstanceForType(ilBiblTypeFactoryInterface::DATA_TYPE_BIBTEX); } @@ -62,14 +59,11 @@ public function getInstanceForFileName(string $filename): ilBiblTypeInterface */ public function getInstanceForString(string $string): ilBiblTypeInterface { - switch ($string) { - case "bib": - return new ilBibTex(); - case "ris": - return new ilRis(); - default: - throw new ilException("bibliografic type not found"); - } + return match ($string) { + "bib" => new ilBibTex(), + "ris" => new ilRis(), + default => throw new ilException("bibliografic type not found"), + }; } @@ -78,14 +72,11 @@ public function getInstanceForString(string $string): ilBiblTypeInterface */ public function convertFileEndingToDataType(string $file_ending): int { - switch ($file_ending) { - case "ris": - return ilBiblTypeFactoryInterface::DATA_TYPE_RIS; - case "bib": - return ilBiblTypeFactoryInterface::DATA_TYPE_BIBTEX; - default: - throw new ilException("no data type found for this file ending"); - } + return match ($file_ending) { + "ris" => ilBiblTypeFactoryInterface::DATA_TYPE_RIS, + "bib" => ilBiblTypeFactoryInterface::DATA_TYPE_BIBTEX, + default => throw new ilException("no data type found for this file ending"), + }; } diff --git a/components/ILIAS/Bibliographic/classes/class.ilBibliographicDataSet.php b/components/ILIAS/Bibliographic/classes/class.ilBibliographicDataSet.php index 46ea940ae180..290ea92b1bec 100755 --- a/components/ILIAS/Bibliographic/classes/class.ilBibliographicDataSet.php +++ b/components/ILIAS/Bibliographic/classes/class.ilBibliographicDataSet.php @@ -26,7 +26,13 @@ */ class ilBibliographicDataSet extends ilDataSet { + /** + * @var string + */ private const EXP_DIRECTORY = "/Modules/Bibliographic/set_1/expDir_1/"; + /** + * @var string + */ private const EXP_DIRECTORY_NEW = "/components/ILIAS/Bibliographic/set_1/expDir_1/"; /** * @var Services @@ -121,6 +127,7 @@ protected function getTypes(string $a_entity, string $a_version): array * Return dependencies form entities to other entities (in our case these are all the DB * relations) */ + #[\Override] protected function getDependencies( string $a_entity, string $a_version, diff --git a/components/ILIAS/Bibliographic/classes/class.ilBibliographicExporter.php b/components/ILIAS/Bibliographic/classes/class.ilBibliographicExporter.php index 1d0c8832dfc2..fb9d05a85b5f 100755 --- a/components/ILIAS/Bibliographic/classes/class.ilBibliographicExporter.php +++ b/components/ILIAS/Bibliographic/classes/class.ilBibliographicExporter.php @@ -59,6 +59,7 @@ public function getXmlRepresentation(string $a_entity, string $a_schema_version, return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, [$a_id], '', true, true); } + #[\Override] public function getXmlExportTailDependencies( string $a_entity, string $a_target_release, diff --git a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographic.php b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographic.php index 1bd4869e8e9b..4318f2abe96b 100755 --- a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographic.php +++ b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographic.php @@ -16,10 +16,12 @@ * *********************************************************************/ +use ILIAS\Filesystem\Filesystem; +use ILIAS\Filesystem\Exception\IOException; +use ILIAS\FileUpload\Exception\IllegalStateException; use ILIAS\ResourceStorage\Services; use ILIAS\FileUpload\FileUpload; use ILIAS\ResourceStorage\Identification\ResourceIdentification; -use ILIAS\DI\Container; /** * Class ilObjBibliographic @@ -30,7 +32,7 @@ */ class ilObjBibliographic extends ilObject2 { - protected \ILIAS\Filesystem\Filesystem $filesystem; + protected Filesystem $filesystem; protected FileUpload $upload_service; protected \ilBiblFileReaderFactory $bib_filereader_factory; protected \ilBiblTypeFactory $bib_type_factory; @@ -44,7 +46,7 @@ class ilObjBibliographic extends ilObject2 protected ?string $filename = null; protected array $entries = []; protected int $file_type = 0; - protected ?\ILIAS\ResourceStorage\Identification\ResourceIdentification $resource_id = null; + protected ?ResourceIdentification $resource_id = null; protected bool $is_migrated = false; protected function initType(): void @@ -65,7 +67,7 @@ public function __construct(int $existant_bibl_id = 0) $this->stakeholder = new ilObjBibliographicStakeholder(); $this->filesystem = $DIC->filesystem()->storage(); - if ($existant_bibl_id) { + if ($existant_bibl_id !== 0) { $this->setId($existant_bibl_id); $this->doRead(); } @@ -85,9 +87,9 @@ public function __construct(int $existant_bibl_id = 0) /** * handles a FileUpload and returns an IRSS identification string. - * @throws \ILIAS\FileUpload\Exception\IllegalStateException + * @throws IllegalStateException */ - private function handleUpload(): ?\ILIAS\ResourceStorage\Identification\ResourceIdentification + private function handleUpload(): ?ResourceIdentification { if (!$this->upload_service->hasBeenProcessed()) { $this->upload_service->process(); @@ -98,7 +100,7 @@ private function handleUpload(): ?\ILIAS\ResourceStorage\Identification\Resource return null; } - if ($this->getResourceId()) { + if ($this->getResourceId() !== null) { $this->storage->manage()->appendNewRevision( $this->getResourceId(), $result, @@ -131,7 +133,7 @@ protected function doCreate(bool $clone_mode = false): void "file_type" => ["integer", $this->getFilename() ? $this->determineFileTypeByFileName($this->getFilename()) : "" ], - "rid" => ["string", ($rid = $this->getResourceId()) ? $rid->serialize() : ''], + "rid" => ["string", (($rid = $this->getResourceId()) !== null) ? $rid->serialize() : ''], ] ); $this->parseFileToDatabase(); @@ -141,7 +143,7 @@ protected function doCreate(bool $clone_mode = false): void protected function doRead(): void { /** @var ilBiblData $bibl_data */ - $bibl_data = ilBiblData::where(array('id' => $this->getId()))->first(); + $bibl_data = ilBiblData::where(['id' => $this->getId()])->first(); if (!$this->getFilename() && $bibl_data->getFilename() !== null) { $this->setFilename($bibl_data->getFilename()); } @@ -177,7 +179,7 @@ protected function doUpdate(): void [ "filename" => ["text", $this->getFilename()], "file_type" => ["integer", $this->getFileType()], - "rid" => ["string", ($rid = $this->getResourceId()) ? $rid->serialize() : ''], + "rid" => ["string", (($rid = $this->getResourceId()) !== null) ? $rid->serialize() : ''], ], ["id" => ["integer", $this->getId()]] ); @@ -231,7 +233,7 @@ protected function deleteFile(): bool $path = $this->getFileDirectory(); try { $this->filesystem->deleteDir($path); - } catch (\ILIAS\Filesystem\Exception\IOException $e) { + } catch (IOException) { return false; } @@ -241,15 +243,14 @@ protected function deleteFile(): bool /** * @return string|void */ - public function getFilePath(bool $without_filename = false) + public function getFilePath(bool $without_filename = false): ?string { $file_name = $this->getFilename(); if ($without_filename) { - return substr($file_name, 0, strrpos($file_name, DIRECTORY_SEPARATOR)); - } else { - return $file_name; + return substr((string) $file_name, 0, strrpos((string) $file_name, DIRECTORY_SEPARATOR)); } + return $file_name; } public function setFilename(string $filename): void @@ -259,7 +260,7 @@ public function setFilename(string $filename): void public function getFilename(): ?string { - if ($this->getResourceId()) { + if ($this->getResourceId() !== null) { return $this->filename = $this->storage->manage() ->getCurrentRevision($this->getResourceId()) ->getInformation() diff --git a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicAccess.php b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicAccess.php index 3990c8ed6b7f..dead43c26bd7 100755 --- a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicAccess.php +++ b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicAccess.php @@ -38,27 +38,29 @@ class ilObjBibliographicAccess extends ilObjectAccess * ); * @return array>|array> */ + #[\Override] public static function _getCommands(): array { - return array( - array( + return [ + [ "permission" => "read", "cmd" => "render", "lang_var" => "show", "default" => true, - ), - array("permission" => "write", "cmd" => "view", "lang_var" => "edit_content"), - array("permission" => "write", "cmd" => "settings", "lang_var" => "settings"), - ); + ], + ["permission" => "write", "cmd" => "view", "lang_var" => "edit_content"], + ["permission" => "write", "cmd" => "settings", "lang_var" => "settings"], + ]; } + #[\Override] public static function _checkGoto(string $target): bool { global $DIC; $ilAccess = $DIC['ilAccess']; $t_arr = explode('_', $target); - if ($t_arr[0] != 'bibl' || ((int) $t_arr[1]) <= 0) { + if ($t_arr[0] !== 'bibl' || ((int) $t_arr[1]) <= 0) { return false; } return (bool) $ilAccess->checkAccess('read', '', $t_arr[1]); @@ -69,6 +71,7 @@ public static function _checkGoto(string $target): bool * checks whether a user may invoke a command or not * (this method is called by ilAccessHandler::checkAccess) */ + #[\Override] public function _checkAccess(string $cmd, string $permission, int $ref_id, int $obj_id, ?int $user_id = null): bool { global $DIC; @@ -85,7 +88,7 @@ public function _checkAccess(string $cmd, string $permission, int $ref_id, int $ ilObjBibliographicGUI::P_ENTRY_ID, $DIC->refinery()->kindlyTo()->int() ); - if (!self::checkEntryIdMatch($obj_id, $entry_id)) { + if (!$this->checkEntryIdMatch($obj_id, $entry_id)) { return false; } } @@ -126,7 +129,7 @@ public function _checkAccess(string $cmd, string $permission, int $ref_id, int $ } - private static function checkEntryIdMatch(int $obj_id, int $entry_id): bool + private function checkEntryIdMatch(int $obj_id, int $entry_id): bool { /** * @var ilBiblEntry $ilBiblEntry diff --git a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicAdminGUI.php b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicAdminGUI.php index 770bf0e7f8a5..9ab280840c48 100755 --- a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicAdminGUI.php +++ b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicAdminGUI.php @@ -48,7 +48,6 @@ class ilObjBibliographicAdminGUI extends ilObjectGUI public function __construct($a_data, int $a_id, bool $a_call_by_reference = true, bool $a_prepare_output = true) { parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - $this->type = 'bibs'; $this->lng->loadLanguageModule('bibl'); // Check Permissions globally for all SubGUIs. We check read-permission first $this->checkPermission('read'); @@ -58,6 +57,7 @@ public function __construct($a_data, int $a_id, bool $a_call_by_reference = true /** * @throws ilCtrlException */ + #[\Override] public function executeCommand(): void { $next_class = $this->ctrl->getNextClass($this); @@ -98,6 +98,7 @@ protected function view(): void } + #[\Override] public function getAdminTabs(): void { global $DIC; @@ -106,20 +107,20 @@ public function getAdminTabs(): void * @var $rbacsystem ilRbacSystem */ if ($rbacsystem->checkAccess('write', $this->object->getRefId())) { - $this->tabs_gui->addTab('fields', $this->lng->txt('fields'), $this->ctrl->getLinkTargetByClass(array( + $this->tabs_gui->addTab('fields', $this->lng->txt('fields'), $this->ctrl->getLinkTargetByClass([ ilObjBibliographicAdminGUI::class, ilBiblAdminRisFieldGUI::class, - ), ilBiblAdminRisFieldGUI::CMD_STANDARD)); + ], ilBiblAdminRisFieldGUI::CMD_STANDARD)); } if ($rbacsystem->checkAccess('visible,read', $this->object->getRefId())) { - $this->tabs_gui->addTab(self::TAB_SETTINGS, $this->lng->txt('settings'), $this->ctrl->getLinkTargetByClass(array( + $this->tabs_gui->addTab(self::TAB_SETTINGS, $this->lng->txt('settings'), $this->ctrl->getLinkTargetByClass([ ilObjBibliographicAdminGUI::class, ilBiblLibraryGUI::class, - ), ilBiblLibraryGUI::CMD_INDEX)); + ], ilBiblLibraryGUI::CMD_INDEX)); } if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { - $this->tabs_gui->addTarget('perm_settings', $this->ctrl->getLinkTargetByClass('ilpermissiongui', 'perm'), array(), 'ilpermissiongui'); + $this->tabs_gui->addTarget('perm_settings', $this->ctrl->getLinkTargetByClass('ilpermissiongui', 'perm'), [], 'ilpermissiongui'); } } diff --git a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicGUI.php b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicGUI.php index 564a63ee2a6c..59675fa80d1c 100755 --- a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicGUI.php +++ b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicGUI.php @@ -16,10 +16,11 @@ * *********************************************************************/ +use ILIAS\components\OrgUnit\ARHelper\DIC; +use ILIAS\UI\Factory; +use ILIAS\Refinery\Constraint; use ILIAS\ResourceStorage\Services; -use ILIAS\DI\Container; use ILIAS\UI\Component\Input\Container\Form\Standard; -use ILIAS\UI\Implementation\Component\Input\UploadLimitResolver; /** * Class ilObjBibliographicGUI @@ -38,7 +39,7 @@ */ class ilObjBibliographicGUI extends ilObject2GUI implements ilDesktopItemHandling { - use \ILIAS\components\OrgUnit\ARHelper\DIC; + use DIC; public const P_ENTRY_ID = 'entry_id'; public const CMD_SHOW_CONTENT = 'showContent'; @@ -66,7 +67,6 @@ class ilObjBibliographicGUI extends ilObject2GUI implements ilDesktopItemHandlin public const PROP_ONLINE_STATUS = 'online_status'; public const SECTION_PRESENTATION = 'section_presentation'; public const PROP_TILE_IMAGE = 'tile_image'; - private UploadLimitResolver $upload_limit; public ?ilObject $object = null; protected ?\ilBiblFactoryFacade $facade = null; @@ -79,7 +79,7 @@ class ilObjBibliographicGUI extends ilObject2GUI implements ilDesktopItemHandlin protected Services $storage; protected \ilObjBibliographicStakeholder $stakeholder; protected \ILIAS\HTTP\Services $http; - protected \ILIAS\UI\Factory $ui_factory; + protected Factory $ui_factory; protected \ILIAS\Refinery\Factory $refinery; protected ?string $cmd = self::CMD_SHOW_CONTENT; @@ -93,7 +93,6 @@ public function __construct(int $a_id = 0, int $a_id_type = self::REPOSITORY_NOD $this->http = $DIC->http(); $this->ui_factory = $DIC->ui()->factory(); $this->refinery = $DIC->refinery(); - $this->upload_limit = $DIC["ui.upload_limit_resolver"]; parent::__construct($a_id, $a_id_type, $a_parent_node_id); $DIC->language()->loadLanguageModule('bibl'); @@ -128,6 +127,7 @@ public function getType(): string /** * executeCommand */ + #[\Override] public function executeCommand(): void { global $DIC; @@ -177,7 +177,7 @@ public function executeCommand(): void $this->prepareOutput(); $this->dic()->tabs()->setTabActive(self::TAB_EXPORT); $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); + $exp_gui->addFormat(); $this->ctrl->forwardCommand($exp_gui); break; case strtolower(ilBiblFieldFilterGUI::class): @@ -281,18 +281,18 @@ public static function _goto(string $a_target): void $DIC->ctrl() ->setParameterByClass(ilObjBibliographicGUI::class, ilObjBibliographicGUI::P_ENTRY_ID, $id[1]); $DIC->ctrl()->redirectByClass( - array( + [ ilRepositoryGUI::class, ilObjBibliographicGUI::class, - ), + ], self::CMD_SHOW_DETAILS ); } else { $DIC->ctrl()->redirectByClass( - array( + [ ilRepositoryGUI::class, ilObjBibliographicGUI::class, - ), + ], self::CMD_VIEW ); } @@ -301,6 +301,7 @@ public static function _goto(string $a_target): void /** * @return mixed[] */ + #[\Override] protected function initCreateForm(string $new_type): ilPropertyFormGUI { $form = new ilPropertyFormGUI(); @@ -333,6 +334,7 @@ protected function initCreateForm(string $new_type): ilPropertyFormGUI return $form; } + #[\Override] public function save(): void { $form = $this->initCreateForm($this->getType()); @@ -344,6 +346,7 @@ public function save(): void } } + #[\Override] public function saveObject(): void { // create permission is already checked in createObject. This check here is done to prevent hacking attempts @@ -367,7 +370,7 @@ public function saveObject(): void $this->putObjectInTree($newObj); $dtpl = $this->getDidacticTemplateVar('dtpl'); - if ($dtpl) { + if ($dtpl !== 0) { $newObj->applyDidacticTemplate($dtpl); } @@ -378,6 +381,7 @@ public function saveObject(): void $this->tpl->setContent($form->getHTML()); } + #[\Override] public function updateObject(): void { $form = $this->getSettingsForm(); @@ -407,6 +411,7 @@ public function updateObject(): void } } + #[\Override] protected function afterSave(ilObject $a_new_object): void { $this->addNews($a_new_object->getId(), 'created'); @@ -485,10 +490,6 @@ protected function getReplaceBibliographicFileForm(): Standard $rid = $bibl_obj->getResourceId() ? $bibl_obj->getResourceId()->serialize() : ""; $bibl_upload_handler = new ilObjBibliographicUploadHandlerGUI($rid); - $max_filesize_bytes = $this->upload_limit->getPhpUploadLimitInBytes(); - $max_filesize_mb = round($max_filesize_bytes / 1024 / 1024, 1); - $info_file_limitations = $this->lng->txt('file_notice') . " " . number_format($max_filesize_mb, 1) . " MB
" - . $this->lng->txt('file_allowed_suffixes') . " .bib, .bibtex, .ris"; $section_replace_bibliographic_file = $this->ui_factory ->input() ->field() @@ -499,10 +500,8 @@ protected function getReplaceBibliographicFileForm(): Standard ->field() ->file( $bibl_upload_handler, - $this->lng->txt('bibliography_file'), - $info_file_limitations + $this->lng->txt('bibliography_file') ) - ->withMaxFileSize($max_filesize_bytes) ->withRequired(true) ->withAdditionalTransformation( $this->getValidBiblFileSuffixConstraint() @@ -519,7 +518,7 @@ protected function getReplaceBibliographicFileForm(): Standard ); } - protected function getValidBiblFileSuffixConstraint(): \ILIAS\Refinery\Constraint + protected function getValidBiblFileSuffixConstraint(): Constraint { return $this->refinery->custom()->constraint( function ($bibl_file_input): bool { @@ -544,6 +543,7 @@ function ($bibl_file_input): bool { * create tabs (repository/workspace switch) * this had to be moved here because of the context-specific permission tab */ + #[\Override] public function setTabs(): void { global $DIC; @@ -623,6 +623,7 @@ protected function initSubTabs(): void * edit object * @access public */ + #[\Override] public function editObject(): void { if (!$this->checkPermissionBool("write")) { @@ -808,6 +809,7 @@ public function showDetails(): void } } + #[\Override] public function view(): void { $this->showContent(); @@ -876,6 +878,7 @@ public function removeFromDesk(): void $this->removeFromDeskObject(); } + #[\Override] protected function afterImport(ilObject $a_new_object): void { /** diff --git a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicListGUI.php b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicListGUI.php index 490cac15c56f..88818d01a709 100755 --- a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicListGUI.php +++ b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicListGUI.php @@ -27,6 +27,7 @@ class ilObjBibliographicListGUI extends ilObjectListGUI /** * initialisation */ + #[\Override] public function init(): void { $this->lng->loadLanguageModule('bibl'); @@ -50,12 +51,13 @@ public function init(): void * "property" (string) => property name * "value" (string) => property value */ + #[\Override] public function getProperties(): array { global $DIC; $lng = $DIC['lng']; - $props = array(); + $props = []; $obj = new ilObjBibliographic($this->obj_id); if (!$obj->isMigrated()) { $props[] = [ @@ -66,12 +68,12 @@ public function getProperties(): array ]; } if (!ilObjBibliographicAccess::_lookupOnline($this->obj_id)) { - $props[] = array( + $props[] = [ "alert" => true, "property" => $lng->txt("status"), "value" => $lng->txt("offline"), "newline" => true - ); + ]; } return $props; diff --git a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicUploadHandlerGUI.php b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicUploadHandlerGUI.php index 70d6e11852e2..4cc415bdc419 100755 --- a/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicUploadHandlerGUI.php +++ b/components/ILIAS/Bibliographic/classes/class.ilObjBibliographicUploadHandlerGUI.php @@ -33,6 +33,7 @@ public function __construct(private string $rid = "") parent::__construct(new ilObjBibliographicStakeholder()); } + #[\Override] protected function getUploadResult(): HandlerResult { $this->upload->process(); diff --git a/components/ILIAS/Bibliographic/classes/trait.ilBibliographicSecureString.php b/components/ILIAS/Bibliographic/classes/trait.ilBibliographicSecureString.php index 4e6dc26b775a..60c9d3ae6428 100755 --- a/components/ILIAS/Bibliographic/classes/trait.ilBibliographicSecureString.php +++ b/components/ILIAS/Bibliographic/classes/trait.ilBibliographicSecureString.php @@ -24,7 +24,7 @@ protected function secure(string $string): string { return htmlspecialchars( strip_tags( - preg_replace('#\p{C}+#u', '', $string) + (string) preg_replace('#\p{C}+#u', '', $string) ), ENT_QUOTES, 'UTF-8', diff --git a/components/ILIAS/Bibliographic/tests/ilBibtechParserTest.php b/components/ILIAS/Bibliographic/tests/ilBibtechParserTest.php index 07f5ceeada00..79854afbb7c0 100755 --- a/components/ILIAS/Bibliographic/tests/ilBibtechParserTest.php +++ b/components/ILIAS/Bibliographic/tests/ilBibtechParserTest.php @@ -25,7 +25,7 @@ class ilBibtechParserTest extends TestCase { - private ?\ILIAS\DI\Container $dic_backup = null; + private ?Container $dic_backup = null; protected function setUp(): void { diff --git a/components/ILIAS/Bibliographic/tests/ilRisParserTestTBD.php b/components/ILIAS/Bibliographic/tests/ilRisParserTestTBD.php index 52f7165da83a..8c3311086b5e 100644 --- a/components/ILIAS/Bibliographic/tests/ilRisParserTestTBD.php +++ b/components/ILIAS/Bibliographic/tests/ilRisParserTestTBD.php @@ -25,7 +25,7 @@ class ilRisParserTest extends TestCase { - private ?\ILIAS\DI\Container $dic_backup = null; + private ?Container $dic_backup = null; protected function setUp(): void { diff --git a/components/ILIAS/Cache/Cache.php b/components/ILIAS/Cache/Cache.php index 4ff99324e857..15467a6cf844 100644 --- a/components/ILIAS/Cache/Cache.php +++ b/components/ILIAS/Cache/Cache.php @@ -20,7 +20,9 @@ namespace ILIAS; -class Cache implements Component\Component +use ILIAS\Component\Component; + +class Cache implements Component { public function init( array | \ArrayAccess &$define, diff --git a/components/ILIAS/Cache/src/Adaptor/APCu.php b/components/ILIAS/Cache/src/Adaptor/APCu.php index 6a3796c39425..106325c774f5 100755 --- a/components/ILIAS/Cache/src/Adaptor/APCu.php +++ b/components/ILIAS/Cache/src/Adaptor/APCu.php @@ -32,7 +32,7 @@ public function isAvailable(): bool public function has(string $container, string $key): bool { - return apcu_exists($this->buildKey($container, $key)) === true; + return apcu_exists($this->buildKey($container, $key)); } public function get(string $container, string $key): ?string diff --git a/components/ILIAS/Cache/src/Adaptor/Memcached.php b/components/ILIAS/Cache/src/Adaptor/Memcached.php index 992f87035e33..53007ed39d0f 100755 --- a/components/ILIAS/Cache/src/Adaptor/Memcached.php +++ b/components/ILIAS/Cache/src/Adaptor/Memcached.php @@ -27,6 +27,9 @@ */ class Memcached extends BaseAdaptor implements Adaptor { + /** + * @var string + */ private const PERSISTENT_ID = 'ilias_cache'; private ?\Memcached $server = null; @@ -72,12 +75,12 @@ public function flushContainer(string $container): void { $prefix = $this->buildContainerPrefix($container); foreach ($this->server->getAllKeys() as $key) { - if (str_starts_with($key, $prefix)) { + if (str_starts_with((string) $key, $prefix)) { $this->server->set($key, false, 0); } } foreach ($this->server->getAllKeys() as $key) { - if (str_starts_with($key, $prefix)) { + if (str_starts_with((string) $key, $prefix)) { $this->server->get( $key ); // invalidates the key, see https://www.php.net/manual/en/memcached.expiration.php diff --git a/components/ILIAS/Cache/src/Config.php b/components/ILIAS/Cache/src/Config.php index 5747ecd1a8c6..e5d5566bcbe0 100755 --- a/components/ILIAS/Cache/src/Config.php +++ b/components/ILIAS/Cache/src/Config.php @@ -20,7 +20,6 @@ namespace ILIAS\Cache; -use org\bovigo\vfs\Issue104TestCase; use ILIAS\Cache\Nodes\NodeRepository; use ILIAS\Cache\Nodes\NullNodeRepository; diff --git a/components/ILIAS/Cache/src/Container/ActiveContainer.php b/components/ILIAS/Cache/src/Container/ActiveContainer.php index 03ece729c6bb..dec6b565ddf8 100755 --- a/components/ILIAS/Cache/src/Container/ActiveContainer.php +++ b/components/ILIAS/Cache/src/Container/ActiveContainer.php @@ -20,29 +20,55 @@ namespace ILIAS\Cache\Container; +use ILIAS\Data\Factory; use ILIAS\Cache\Adaptor\Adaptor; use ILIAS\Cache\Config; use ILIAS\Refinery\Transformation; -use ILIAS\Refinery\Factory; use ILIAS\Refinery\ByTrying; -use ILIAS\Refinery\To\Transformation\FloatTransformation; /** * @author Fabian Schmid */ final class ActiveContainer implements Container { + /** + * @var string + */ private const LOCK_UNTIL = '_lock_until'; + /** + * @var string + */ private const GLUE = '|||||'; + /** + * @var string + */ private const STRING_PREFIX = 'string'; + /** + * @var string + */ private const ARRAY_PREFIX = 'array'; + /** + * @var string + */ private const INT_PREFIX = 'int'; + /** + * @var string + */ private const BOOL_PREFIX = 'bool'; + /** + * @var string + */ private const NULL_PREFIX = 'null'; + /** + * @var string + */ private const TRUE = 'true'; + /** + * @var string + */ private const FALSE = 'false'; - private \ILIAS\Data\Factory $data_factory; + private Factory $data_factory; private $null_trafo; private string $prefix_pattern; @@ -51,11 +77,9 @@ public function __construct( private Adaptor $adaptor, private Config $config ) { - $this->data_factory = new \ILIAS\Data\Factory(); + $this->data_factory = new Factory(); // see comment in buildFinalTransformation why this is not a good solution. - $this->null_trafo = new \ILIAS\Refinery\Custom\Transformation(function ($value) { - return null; - }); + $this->null_trafo = new \ILIAS\Refinery\Custom\Transformation(fn($value): null => null); $this->prefix_pattern = '(' . implode('|', [ preg_quote(self::STRING_PREFIX, '/'), preg_quote(self::ARRAY_PREFIX, '/'), @@ -93,11 +117,7 @@ private function pack(mixed $value): string private function packRecursive(array $value): array { array_walk($value, function (&$item): void { - if (is_array($item)) { - $item = $this->packRecursive($item); - } else { - $item = $this->pack($item); - } + $item = is_array($item) ? $this->packRecursive($item) : $this->pack($item); }); return $value; } @@ -131,7 +151,7 @@ private function unpack(?string $value): string|int|array|bool|null case self::BOOL_PREFIX: return $unprefixed_value === self::TRUE; case self::ARRAY_PREFIX: - $unprefixed_value = json_decode($unprefixed_value, true, 512); + $unprefixed_value = json_decode((string) $unprefixed_value, true, 512); if (!is_array($unprefixed_value)) { return null; } @@ -149,16 +169,12 @@ private function unpack(?string $value): string|int|array|bool|null private function unpackRecursive(array $value): array { array_walk($value, function (&$item): void { - if (is_array($item)) { - $item = $this->unpackRecursive($item); - } else { - $item = $this->unpack($item); - } + $item = is_array($item) ? $this->unpackRecursive($item) : $this->unpack($item); }); return $value; } - protected function buildFinalTransformation(Transformation $transformation): \ILIAS\Refinery\ByTrying + protected function buildFinalTransformation(Transformation $transformation): ByTrying { // This is a workaround for the fact that the ByTrying transformation cannot be created by // $DIC->refinery()->byTrying() since we are in a hell of dependencies. E.g. we cant instantiate the diff --git a/components/ILIAS/Cache/src/Container/Container.php b/components/ILIAS/Cache/src/Container/Container.php index 7b4c58f0f6b9..75ad5b393fae 100755 --- a/components/ILIAS/Cache/src/Container/Container.php +++ b/components/ILIAS/Cache/src/Container/Container.php @@ -20,10 +20,7 @@ namespace ILIAS\Cache\Container; -use ILIAS\Cache\Adaptor\Adaptor; -use ILIAS\Cache\Config; use ILIAS\Refinery\Transformation; -use ILIAS\Refinery\ByTrying; /** * @author Fabian Schmid diff --git a/components/ILIAS/Cache/src/Container/VoidContainer.php b/components/ILIAS/Cache/src/Container/VoidContainer.php index 14d00e8e7b49..559d81ba78dc 100755 --- a/components/ILIAS/Cache/src/Container/VoidContainer.php +++ b/components/ILIAS/Cache/src/Container/VoidContainer.php @@ -20,10 +20,7 @@ namespace ILIAS\Cache\Container; -use ILIAS\Cache\Adaptor\Adaptor; -use ILIAS\Cache\Config; use ILIAS\Refinery\Transformation; -use ILIAS\Refinery\ByTrying; /** * @author Fabian Schmid diff --git a/components/ILIAS/Cache/src/Services.php b/components/ILIAS/Cache/src/Services.php index 20882246a17b..afcb1609b180 100755 --- a/components/ILIAS/Cache/src/Services.php +++ b/components/ILIAS/Cache/src/Services.php @@ -21,7 +21,6 @@ namespace ILIAS\Cache; use ILIAS\Cache\Adaptor\Adaptor; -use ILIAS\Cache\Adaptor\AvailableAdaptors; use ILIAS\Cache\Adaptor\Factory; use ILIAS\Cache\Container\ActiveContainer; use ILIAS\Cache\Container\Request; diff --git a/components/ILIAS/Cache/tests/CacheTest.php b/components/ILIAS/Cache/tests/CacheTest.php index a297806ba325..b16d23d925ff 100755 --- a/components/ILIAS/Cache/tests/CacheTest.php +++ b/components/ILIAS/Cache/tests/CacheTest.php @@ -18,6 +18,8 @@ namespace ILIAS\Cache; +use ILIAS\Refinery\Factory; +use PHPUnit\Framework\Attributes\DataProvider; use ILIAS\Cache\Adaptor\APCu; use ILIAS\Cache\Adaptor\Memcached; use ILIAS\Cache\Config; @@ -29,7 +31,6 @@ use ILIAS\Cache\Container\VoidContainer; use ILIAS\Cache\Adaptor\PHPStatic; use ILIAS\Cache\Container\BaseRequest; -use ILIAS\Cache\Nodes\NodeRepository; use ILIAS\Cache\Nodes\NullNodeRepository; require_once(__DIR__ . '/../../../../vendor/composer/vendor/autoload.php'); @@ -41,15 +42,15 @@ class CacheTest extends TestCase { public const TEST_CONTAINER = 'test_container'; /** - * @var \ilLanguage|(\ilLanguage&\PHPUnit\Framework\MockObject\MockObject)|\PHPUnit\Framework\MockObject\MockObject + * @var \ilLanguage|\ilLanguage&MockObject|MockObject */ private \ilLanguage $language_mock; - private \ILIAS\Refinery\Factory $refinery; + private Factory $refinery; protected function setUp(): void { $this->language_mock = $this->createMock(\ilLanguage::class); - $this->refinery = new \ILIAS\Refinery\Factory( + $this->refinery = new Factory( new \ILIAS\Data\Factory(), $this->language_mock ); @@ -181,9 +182,7 @@ public static function getInvalidLockTimes(): array ]; } - /** - * @dataProvider getInvalidLockTimes - */ + #[DataProvider('getInvalidLockTimes')] public function testInvalidLockTimes(float|int $time): void { $services = new Services($this->getConfig()); @@ -401,12 +400,7 @@ public function testTypes(): void $trafo = $this->refinery->to()->dictOf( $this->refinery->custom()->transformation( - function ($value) { - return $value; - }, - function ($value) { - return $value; - } + fn($value) => $value ) ); diff --git a/components/ILIAS/Database/Database.php b/components/ILIAS/Database/Database.php index 2521bb3c6970..4ff651bcd6b7 100644 --- a/components/ILIAS/Database/Database.php +++ b/components/ILIAS/Database/Database.php @@ -20,7 +20,11 @@ namespace ILIAS; -class Database implements Component\Component +use ILIAS\Component\Component; +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Factory; + +class Database implements Component { public function init( array | \ArrayAccess &$define, @@ -32,9 +36,9 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $contribute[\ILIAS\Setup\Agent::class] = static fn() => + $contribute[Agent::class] = static fn(): \ilDatabaseSetupAgent => new \ilDatabaseSetupAgent( - $pull[\ILIAS\Refinery\Factory::class] + $pull[Factory::class] ); } } diff --git a/components/ILIAS/Database/classes/Atom/class.ilAtomQueryBase.php b/components/ILIAS/Database/classes/Atom/class.ilAtomQueryBase.php index ba39ca9c1c8f..e1be3cdc6854 100755 --- a/components/ILIAS/Database/classes/Atom/class.ilAtomQueryBase.php +++ b/components/ILIAS/Database/classes/Atom/class.ilAtomQueryBase.php @@ -30,59 +30,57 @@ abstract class ilAtomQueryBase /** * @var int[] */ - protected static array $available_isolations_levels = array( + protected static array $available_isolations_levels = [ ilAtomQuery::ISOLATION_READ_UNCOMMITED, ilAtomQuery::ISOLATION_READ_COMMITED, ilAtomQuery::ISOLATION_REPEATED_READ, ilAtomQuery::ISOLATION_SERIALIZABLE, - ); + ]; /** * @var int[] */ - protected static array $possible_anomalies = array( + protected static array $possible_anomalies = [ ilAtomQuery::ANO_LOST_UPDATES, ilAtomQuery::ANO_DIRTY_READ, ilAtomQuery::ANO_NON_REPEATED_READ, ilAtomQuery::ANO_PHANTOM, - ); + ]; /** * @var int[][] */ - protected static array $anomalies_map = array( - ilAtomQuery::ISOLATION_READ_UNCOMMITED => array( + protected static array $anomalies_map = [ + ilAtomQuery::ISOLATION_READ_UNCOMMITED => [ ilAtomQuery::ANO_LOST_UPDATES, ilAtomQuery::ANO_DIRTY_READ, ilAtomQuery::ANO_NON_REPEATED_READ, ilAtomQuery::ANO_PHANTOM, - ), - ilAtomQuery::ISOLATION_READ_COMMITED => array( + ], + ilAtomQuery::ISOLATION_READ_COMMITED => [ ilAtomQuery::ANO_NON_REPEATED_READ, ilAtomQuery::ANO_PHANTOM, - ), - ilAtomQuery::ISOLATION_REPEATED_READ => array( + ], + ilAtomQuery::ISOLATION_REPEATED_READ => [ ilAtomQuery::ANO_PHANTOM, - ), - ilAtomQuery::ISOLATION_SERIALIZABLE => array(), - ); + ], + ilAtomQuery::ISOLATION_SERIALIZABLE => [], + ]; protected int $isolation_level = ilAtomQuery::ISOLATION_SERIALIZABLE; /** * @var ilTableLock[] */ - protected array $tables = array(); + protected array $tables = []; /** * @var callable */ protected $query; - protected \ilDBInterface $ilDBInstance; /** * ilAtomQuery constructor. * @param int $isolation_level currently only ISOLATION_SERIALIZABLE is available */ - public function __construct(ilDBInterface $ilDBInstance, int $isolation_level = ilAtomQuery::ISOLATION_SERIALIZABLE) + public function __construct(protected \ilDBInterface $ilDBInstance, int $isolation_level = ilAtomQuery::ISOLATION_SERIALIZABLE) { static::checkIsolationLevel($isolation_level); - $this->ilDBInstance = $ilDBInstance; $this->isolation_level = $isolation_level; } @@ -192,11 +190,11 @@ public static function getPossibleAnomalies(int $isolation_level): array public static function checkIsolationLevel(int $isolation_level): void { // The following Isolations are currently not supported - if (in_array($isolation_level, array( + if (in_array($isolation_level, [ ilAtomQuery::ISOLATION_READ_UNCOMMITED, ilAtomQuery::ISOLATION_READ_COMMITED, ilAtomQuery::ISOLATION_REPEATED_READ, - ))) { + ])) { throw new ilAtomQueryException('Level: ' . $isolation_level, ilAtomQueryException::DB_ATOM_ISO_WRONG_LEVEL); } // Check if a available Isolation level is selected @@ -220,7 +218,7 @@ public static function checkAnomaly(int $anomaly): void */ protected function checkQueries(): void { - if (!($this->query instanceof \Traversable) && (is_array($this->query) && 0 === count($this->query))) { + if (!($this->query instanceof \Traversable) && (is_array($this->query) && [] === $this->query)) { throw new ilAtomQueryException('', ilAtomQueryException::DB_ATOM_CLOSURE_NONE); } @@ -299,7 +297,7 @@ protected function checkBeforeRun(): void throw new ilAtomQueryException('', ilAtomQueryException::DB_ATOM_LOCK_WRONG_LEVEL); } - if (count($this->tables) === 0) { + if ($this->tables === []) { throw new ilAtomQueryException('', ilAtomQueryException::DB_ATOM_LOCK_NO_TABLE); } } diff --git a/components/ILIAS/Database/classes/Atom/class.ilAtomQueryLock.php b/components/ILIAS/Database/classes/Atom/class.ilAtomQueryLock.php index 8b9d4ef9fc60..9ecafabf13bd 100755 --- a/components/ILIAS/Database/classes/Atom/class.ilAtomQueryLock.php +++ b/components/ILIAS/Database/classes/Atom/class.ilAtomQueryLock.php @@ -71,7 +71,7 @@ protected function runWithLocks(): void */ protected function getLocksForDBInstance(): array { - $locks = array(); + $locks = []; foreach ($this->tables as $table) { $full_name = $table->getTableName() . $table->getAlias(); if (in_array($full_name, $this->locked_table_full_names, true)) { @@ -80,14 +80,14 @@ protected function getLocksForDBInstance(): array $this->locked_table_full_names[] = $full_name; if (!in_array($table->getTableName(), $this->locked_table_names, true)) { - $locks[] = array( 'name' => $table->getTableName(), 'type' => $table->getLockLevel() ); + $locks[] = [ 'name' => $table->getTableName(), 'type' => $table->getLockLevel() ]; $this->locked_table_names[] = $table->getTableName(); if ($table->isLockSequence() && $this->ilDBInstance->sequenceExists($table->getTableName())) { - $locks[] = array( 'name' => $table->getTableName(), 'type' => $table->getLockLevel(), 'sequence' => true ); + $locks[] = [ 'name' => $table->getTableName(), 'type' => $table->getLockLevel(), 'sequence' => true ]; } } if ($table->getAlias() !== '') { - $locks[] = array( 'name' => $table->getTableName(), 'type' => $table->getLockLevel(), 'alias' => $table->getAlias() ); + $locks[] = [ 'name' => $table->getTableName(), 'type' => $table->getLockLevel(), 'alias' => $table->getAlias() ]; } } diff --git a/components/ILIAS/Database/classes/Atom/class.ilTableLock.php b/components/ILIAS/Database/classes/Atom/class.ilTableLock.php index d3db223a36d0..da2ecbb94350 100755 --- a/components/ILIAS/Database/classes/Atom/class.ilTableLock.php +++ b/components/ILIAS/Database/classes/Atom/class.ilTableLock.php @@ -24,20 +24,16 @@ */ class ilTableLock implements ilTableLockInterface { - protected string $table_name = ''; protected bool $lock_sequence = false; protected string $alias = ''; protected int $lock_level = ilAtomQuery::LOCK_WRITE; protected bool $checked = false; - protected \ilDBInterface $ilDBInstance; /** * ilTableLock constructor. */ - public function __construct(string $table_name, ilDBInterface $ilDBInterface) + public function __construct(protected string $table_name, protected \ilDBInterface $ilDBInstance) { - $this->table_name = $table_name; - $this->ilDBInstance = $ilDBInterface; } /** diff --git a/components/ILIAS/Database/classes/Integrity/Definition.php b/components/ILIAS/Database/classes/Integrity/Definition.php index c4272037fdef..e52b65915015 100755 --- a/components/ILIAS/Database/classes/Integrity/Definition.php +++ b/components/ILIAS/Database/classes/Integrity/Definition.php @@ -24,14 +24,11 @@ class Definition { - private Ignore $ignore; - /** - * @param \ILIAS\components\Database\Integrity\Association[] $associations + * @param Association[] $associations */ - public function __construct(private array $associations, ?Ignore $ignore = null) + public function __construct(private array $associations, private Ignore $ignore = new Ignore()) { - $this->ignore = $ignore ?? new Ignore(); $this->validate(); } diff --git a/components/ILIAS/Database/classes/Integrity/Field.php b/components/ILIAS/Database/classes/Integrity/Field.php index 0d86667e2f6c..12c8ba4afbc0 100755 --- a/components/ILIAS/Database/classes/Integrity/Field.php +++ b/components/ILIAS/Database/classes/Integrity/Field.php @@ -22,7 +22,13 @@ class Field { + /** + * @var string + */ private const _AS = 'as'; + /** + * @var string + */ private const COMBINE_TABLE_AND_FIELD = '.'; private string $original_table_name; private string $converted_table_name; diff --git a/components/ILIAS/Database/classes/Integrity/Ignore.php b/components/ILIAS/Database/classes/Integrity/Ignore.php index ea91e51e20bb..4259764cfebd 100755 --- a/components/ILIAS/Database/classes/Integrity/Ignore.php +++ b/components/ILIAS/Database/classes/Integrity/Ignore.php @@ -22,7 +22,13 @@ class Ignore { + /** + * @var string + */ private const IS_NOT_NULL = 'IS NOT NULL'; + /** + * @var string + */ private const NOT_EQUALS = '!='; /** @@ -32,9 +38,7 @@ class Ignore public function __construct(?string ...$values_to_ignore) { - $this->values_to_ignore = array_map(static function (?string $value_to_ignore): string { - return null === $value_to_ignore ? self::IS_NOT_NULL : self::NOT_EQUALS . ' ' . $value_to_ignore; - }, $values_to_ignore); + $this->values_to_ignore = array_map(static fn(?string $value_to_ignore): string => null === $value_to_ignore ? self::IS_NOT_NULL : self::NOT_EQUALS . ' ' . $value_to_ignore, $values_to_ignore); } /** diff --git a/components/ILIAS/Database/classes/PDO/FieldDefinition/class.ilDBPdoFieldDefinition.php b/components/ILIAS/Database/classes/PDO/FieldDefinition/class.ilDBPdoFieldDefinition.php index 9a81f26e7af7..6b1e832fdfc4 100755 --- a/components/ILIAS/Database/classes/PDO/FieldDefinition/class.ilDBPdoFieldDefinition.php +++ b/components/ILIAS/Database/classes/PDO/FieldDefinition/class.ilDBPdoFieldDefinition.php @@ -68,7 +68,6 @@ abstract class ilDBPdoFieldDefinition "clob" => ["length", "notnull", "default"], "blob" => ["length", "notnull", "default"], ]; - protected \ilDBInterface $db_instance; protected array $max_length = [ self::T_INTEGER => [1, 2, 3, 4, 8], self::T_TEXT => 4000, @@ -719,7 +718,7 @@ abstract class ilDBPdoFieldDefinition /** * @var string[] */ - protected array $reserved_postgres = array( + protected array $reserved_postgres = [ "ALL", "ANALYSE", "ANALYZE", @@ -815,7 +814,7 @@ abstract class ilDBPdoFieldDefinition "WHEN", "WHERE", "WITH", - ); + ]; /** * @var */ @@ -824,9 +823,8 @@ abstract class ilDBPdoFieldDefinition /** * ilDBPdoFieldDefinition constructor. */ - public function __construct(\ilDBInterface $ilDBInterface) + public function __construct(protected \ilDBInterface $db_instance) { - $this->db_instance = $ilDBInterface; } protected function getQueryUtils(): \ilMySQLQueryUtils @@ -1067,10 +1065,10 @@ public function getValidTypes(): array if (array_key_exists($mapped_type, $types)) { $types[$type] = $types[$mapped_type]; } elseif (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type, 'mapped_type' => $mapped_type); + $parameter = ['type' => $type, 'mapped_type' => $mapped_type]; $default = call_user_func_array( $db->options['datatype_map_callback'][$type], - array(&$db, __FUNCTION__, $parameter) + [&$db, __FUNCTION__, $parameter] ); $types[$type] = $default; } @@ -1086,18 +1084,18 @@ public function getValidTypes(): array * @return mixed * @throws \ilDatabaseException */ - public function getDeclaration(string $type, string $name, $field) + public function getDeclaration(string $type, string $name, array $field) { $db = $this->getDBInstance(); if (!empty($db->options['datatype_map'][$type])) { $type = $db->options['datatype_map'][$type]; if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type, 'name' => $name, 'field' => $field); + $parameter = ['type' => $type, 'name' => $name, 'field' => $field]; return call_user_func_array( $db->options['datatype_map_callback'][$type], - array(&$db, __FUNCTION__, $parameter) + [&$db, __FUNCTION__, $parameter] ); } $field['type'] = $type; @@ -1287,11 +1285,11 @@ public function compareDefinition(array $current, array $previous): array $db = $this->getDBInstance(); if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('current' => $current, 'previous' => $previous); + $parameter = ['current' => $current, 'previous' => $previous]; return call_user_func_array( $db->options['datatype_map_callback'][$type], - array(&$db, __FUNCTION__, $parameter) + [&$db, __FUNCTION__, $parameter] ); } @@ -1333,7 +1331,7 @@ public function compareDefinition(array $current, array $previous): array */ protected function compareIntegerDefinition(array $current, array $previous): array { - $change = array(); + $change = []; $previous_unsigned = empty($previous['unsigned']) ? false : $previous['unsigned']; $unsigned = empty($current['unsigned']) ? false : $current['unsigned']; if ($previous_unsigned != $unsigned) { @@ -1353,7 +1351,7 @@ protected function compareIntegerDefinition(array $current, array $previous): ar */ protected function compareTextDefinition(array $current, array $previous): array { - $change = array(); + $change = []; $previous_length = empty($previous['length']) ? 0 : $previous['length']; $length = empty($current['length']) ? 0 : $current['length']; if ($previous_length != $length) { @@ -1386,32 +1384,32 @@ protected function compareBLOBDefinition(array $current, array $previous): array protected function compareDateDefinition(array $current, array $previous): array { - return array(); + return []; } protected function compareTimeDefinition(array $current, array $previous): array { - return array(); + return []; } protected function compareTimestampDefinition(array $current, array $previous): array { - return array(); + return []; } protected function compareBooleanDefinition(array $current, array $previous): array { - return array(); + return []; } protected function compareFloatDefinition(array $current, array $previous): array { - return array(); + return []; } protected function compareDecimalDefinition(array $current, array $previous): array { - return array(); + return []; } /** @@ -1534,28 +1532,26 @@ protected function quoteFloat(string $value, bool $quote, bool $escape_wildcards $decimal = $this->quoteDecimal($matches[1], $quote, $escape_wildcards); $sign = $matches[2]; $exponent = str_pad($matches[3], 2, '0', STR_PAD_LEFT); - $value = $decimal . 'E' . $sign . $exponent; - } else { - $value = $this->quoteDecimal($value, $quote, $escape_wildcards); + return $decimal . 'E' . $sign . $exponent; } - return $value; + return $this->quoteDecimal($value, $quote, $escape_wildcards); } protected function quoteDecimal(string $value, bool $quote, bool $escape_wildcards): ?string { $value = preg_replace('/[^\d\.,\-+eE]/', '', $value); - if (preg_match('/[^.0-9]/', $value) && strpos($value, ',')) { + if (preg_match('/[^.0-9]/', (string) $value) && strpos((string) $value, ',')) { // 1000,00 - if (!strpos($value, '.')) { + if (!strpos((string) $value, '.')) { // convert the last "," to a "." - $value = strrev(str_replace(',', '.', strrev($value))); - // 1.000,00 - } elseif (strpos($value, '.') && strpos($value, '.') < strpos($value, ',')) { + $value = strrev(str_replace(',', '.', strrev((string) $value))); + // 1.000,00 + } elseif (strpos((string) $value, '.') && strpos((string) $value, '.') < strpos((string) $value, ',')) { $value = str_replace('.', '', $value); // convert the last "," to a "." $value = strrev(str_replace(',', '.', strrev($value))); - // 1,000.00 + // 1,000.00 } else { $value = str_replace(',', '', $value); } @@ -1604,7 +1600,7 @@ protected function retrieveLOB(array &$lob): bool protected function readLOB(array $lob, int $length): string { - return substr($lob['value'], $lob['position'], $length); + return substr((string) $lob['value'], $lob['position'], $length); } /** @@ -1640,7 +1636,7 @@ public function matchPattern(array $pattern, $operator = null, $field = null): s $match = ''; if (!is_null($operator)) { - $operator = strtoupper($operator); + $operator = strtoupper((string) $operator); switch ($operator) { // case insensitive case 'ILIKE': @@ -1664,7 +1660,7 @@ public function matchPattern(array $pattern, $operator = null, $field = null): s $match .= $value; } else { if ($operator === 'ILIKE') { - $value = strtolower($value); + $value = strtolower((string) $value); } $escaped = $db->escape($value); $match .= $db->escapePattern($escaped); @@ -1689,7 +1685,7 @@ public function mapNativeDatatype(array $field) $db = $this->getDBInstance(); $db_type = strtok($field['type'], '(), '); if (!empty($db->options['nativetype_map_callback'][$db_type])) { - return call_user_func_array($db->options['nativetype_map_callback'][$db_type], array($db, $field)); + return call_user_func_array($db->options['nativetype_map_callback'][$db_type], [$db, $field]); } return $this->mapNativeDatatypeInternal($field); @@ -1710,11 +1706,11 @@ public function mapPrepareDatatype(string $type) if (!empty($db->options['datatype_map'][$type])) { $type = $db->options['datatype_map'][$type]; if (!empty($db->options['datatype_map_callback'][$type])) { - $parameter = array('type' => $type); + $parameter = ['type' => $type]; return call_user_func_array( $db->options['datatype_map_callback'][$type], - array(&$db, __FUNCTION__, $parameter) + [&$db, __FUNCTION__, $parameter] ); } } diff --git a/components/ILIAS/Database/classes/PDO/FieldDefinition/class.ilDBPdoMySQLFieldDefinition.php b/components/ILIAS/Database/classes/PDO/FieldDefinition/class.ilDBPdoMySQLFieldDefinition.php index c04458e8b639..e4b28387574c 100755 --- a/components/ILIAS/Database/classes/PDO/FieldDefinition/class.ilDBPdoMySQLFieldDefinition.php +++ b/components/ILIAS/Database/classes/PDO/FieldDefinition/class.ilDBPdoMySQLFieldDefinition.php @@ -25,6 +25,7 @@ */ class ilDBPdoMySQLFieldDefinition extends ilDBPdoFieldDefinition { + #[\Override] public function getTypeDeclaration(array $field): string { $db = $this->getDBInstance(); @@ -124,6 +125,7 @@ public function getTypeDeclaration(array $field): string /** * @throws \ilDatabaseException */ + #[\Override] protected function getIntegerDeclaration(string $name, array $field): string { $db = $this->getDBInstance(); @@ -153,7 +155,7 @@ protected function getIntegerDeclaration(string $name, array $field): string */ protected function mapNativeDatatypeInternal(array $field): array { - $db_type = strtolower($field['type']); + $db_type = strtolower((string) $field['type']); $db_type = strtok($db_type, '(), '); if ($db_type === 'national') { $db_type = strtok('(), '); @@ -165,37 +167,37 @@ protected function mapNativeDatatypeInternal(array $field): array $length = strtok('(), '); $decimal = strtok('(), '); } - $type = array(); + $type = []; $unsigned = $fixed = null; switch ($db_type) { case 'tinyint': $type[] = 'integer'; $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { + if (preg_match('/^(is|has)/', (string) $field['name'])) { $type = array_reverse($type); } - $unsigned = preg_match('/ unsigned/i', $field['type']); + $unsigned = preg_match('/ unsigned/i', (string) $field['type']); $length = 1; break; case 'smallint': $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); + $unsigned = preg_match('/ unsigned/i', (string) $field['type']); $length = 2; break; case 'mediumint': $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); + $unsigned = preg_match('/ unsigned/i', (string) $field['type']); $length = 3; break; case 'int': case 'integer': $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); + $unsigned = preg_match('/ unsigned/i', (string) $field['type']); $length = 4; break; case 'bigint': $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); + $unsigned = preg_match('/ unsigned/i', (string) $field['type']); $length = 8; break; case 'tinytext': @@ -210,10 +212,10 @@ protected function mapNativeDatatypeInternal(array $field): array $type[] = 'text'; if ($length == '1') { $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { + if (preg_match('/^(is|has)/', (string) $field['name'])) { $type = array_reverse($type); } - } elseif (strpos($db_type, 'text') !== false) { + } elseif (str_contains($db_type, 'text')) { $type[] = 'clob'; if ($decimal === 'binary') { $type[] = 'blob'; @@ -225,7 +227,7 @@ protected function mapNativeDatatypeInternal(array $field): array break; case 'enum': $type[] = 'text'; - preg_match_all('/\'.+\'/U', $field['type'], $matches); + preg_match_all('/\'.+\'/U', (string) $field['type'], $matches); $length = 0; $fixed = false; if (is_array($matches)) { @@ -234,7 +236,7 @@ protected function mapNativeDatatypeInternal(array $field): array } if ($length == '1' && count($matches[0]) === 2) { $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { + if (preg_match('/^(is|has)/', (string) $field['name'])) { $type = array_reverse($type); } } @@ -263,13 +265,13 @@ protected function mapNativeDatatypeInternal(array $field): array case 'double': case 'real': $type[] = 'float'; - $unsigned = preg_match('/ unsigned/i', $field['type']); + $unsigned = preg_match('/ unsigned/i', (string) $field['type']); break; case 'unknown': case 'decimal': case 'numeric': $type[] = 'decimal'; - $unsigned = preg_match('/ unsigned/i', $field['type']); + $unsigned = preg_match('/ unsigned/i', (string) $field['type']); if ($decimal !== false) { $length = $length . ',' . $decimal; } @@ -298,6 +300,6 @@ protected function mapNativeDatatypeInternal(array $field): array $length = null; } - return array( $type, $length, $unsigned, $fixed ); + return [ $type, $length, $unsigned, $fixed ]; } } diff --git a/components/ILIAS/Database/classes/PDO/Manager/class.ilDBPdoManager.php b/components/ILIAS/Database/classes/PDO/Manager/class.ilDBPdoManager.php index 0646f79143b2..9e4332e224ba 100755 --- a/components/ILIAS/Database/classes/PDO/Manager/class.ilDBPdoManager.php +++ b/components/ILIAS/Database/classes/PDO/Manager/class.ilDBPdoManager.php @@ -24,17 +24,13 @@ */ class ilDBPdoManager implements ilDBManager, ilDBPdoManagerInterface { - protected \PDO $pdo; - protected \ilDBPdo $db_instance; protected ?\ilQueryUtils $query_utils = null; /** * ilDBPdoManager constructor. */ - public function __construct(\PDO $pdo, ilDBPdo $db_instance) + public function __construct(protected \PDO $pdo, protected \ilDBPdo $db_instance) { - $this->pdo = $pdo; - $this->db_instance = $db_instance; } public function getQueryUtils(): \ilQueryUtils @@ -93,14 +89,15 @@ public function listSequences(?string $database = null): array $res = $this->db_instance->query($query); - $result = array(); + $result = []; while ($table_name = $this->db_instance->fetchAssoc($res)) { - if ($sqn = $this->fixSequenceName(reset($table_name), true)) { + $sqn = $this->fixSequenceName(reset($table_name), true); + if ($sqn !== '' && $sqn !== '0') { $result[] = $sqn; } } if ($this->db_instance->options['portability'] ?? null) { - $result = array_map( + return array_map( ($this->db_instance->options['field_case'] === CASE_LOWER ? 'strtolower' : 'strtoupper'), $result ); @@ -124,7 +121,7 @@ public function createConstraint(string $table, string $name, array $definition) } elseif (!empty($definition['unique'])) { $query .= ' UNIQUE'; } - $fields = array(); + $fields = []; foreach (array_keys($definition['fields']) as $field) { $fields[] = $db->quoteIdentifier($field, true); } @@ -138,7 +135,7 @@ public function createSequence(string $seq_name, int $start = 1, array $options $sequence_name = $this->db_instance->quoteIdentifier($this->db_instance->getSequenceName($seq_name)); $seqcol_name = $this->db_instance->quoteIdentifier(ilDBConstants::SEQUENCE_COLUMNS_NAME); - $options_strings = array(); + $options_strings = []; if (!empty($options['comment'])) { $options_strings['comment'] = 'COMMENT = ' . $this->db_instance->quote($options['comment'], 'text'); @@ -228,7 +225,7 @@ public function alterTable(string $name, array $changes, bool $check): bool } } - $rename = array(); + $rename = []; if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $field_name => $field) { $rename[$field['name']] = $field_name; @@ -289,7 +286,7 @@ public function alterTable(string $name, array $changes, bool $check): bool return (bool) $this->pdo->exec($statement); } - public function createTable(string $name, array $fields, array $options = array()): bool + public function createTable(string $name, array $fields, array $options = []): bool { $options['type'] = $this->db_instance->getStorageEngine(); @@ -311,7 +308,7 @@ public function listTableFields(string $table): array $table = $this->db_instance->quoteIdentifier($table); $query = "SHOW COLUMNS FROM $table"; $result = $this->db_instance->query($query); - $return = array(); + $return = []; while ($data = $this->db_instance->fetchObject($result)) { $return[] = $data->Field; } @@ -342,7 +339,7 @@ public function listTableConstraints(string $table): array $query = "SHOW INDEX FROM $table"; $result_set = $this->db_instance->query($query); - $result = array(); + $result = []; while ($index_data = $this->db_instance->fetchAssoc($result_set)) { if (!$index_data[$non_unique]) { $index = $index_data[$key_name] !== 'PRIMARY' ? $this->fixIndexName($index_data[$key_name]) : 'PRIMARY'; @@ -380,11 +377,11 @@ public function listTableIndexes(string $table): array $table = $this->db_instance->quoteIdentifier($table); $query = "SHOW INDEX FROM $table"; $result_set = $this->db_instance->query($query); - $indexes = array(); + $indexes = []; while ($index_data = $this->db_instance->fetchAssoc($result_set)) { $indexes[] = $index_data; } - $result = array(); + $result = []; foreach ($indexes as $index_data) { if ($index_data[$non_unique] && ($index = $this->fixIndexName($index_data[$key_name]))) { $result[$index] = true; @@ -414,7 +411,7 @@ public function createIndex(string $table, string $name, array $definition): boo $table = $this->db_instance->quoteIdentifier($table, true); $name = $this->db_instance->quoteIdentifier($this->db_instance->getIndexName($name), true); $query = "CREATE INDEX $name ON $table"; - $fields = array(); + $fields = []; foreach ($definition['fields'] as $field => $fieldinfo) { if (!empty($fieldinfo['length'])) { $fields[] = $this->db_instance->quoteIdentifier($field, true) . '(' . $fieldinfo['length'] . ')'; @@ -493,12 +490,12 @@ public function addForeignKey( $reference_field_names = $this->db_instance->quoteIdentifier($reference_field_names, true); $foreign_key_name = $this->db_instance->quoteIdentifier($foreign_key_name, true); $update = ''; - if ($on_update) { + if ($on_update !== null) { $on_update = $on_update->value; $update = "ON UPDATE $on_update"; } $delete = ''; - if ($on_delete) { + if ($on_delete !== null) { $on_delete = $on_delete->value; $delete = "ON DELETE $on_delete"; } diff --git a/components/ILIAS/Database/classes/PDO/Reverse/class.ilDBPdoReverse.php b/components/ILIAS/Database/classes/PDO/Reverse/class.ilDBPdoReverse.php index d03108d62e32..42d6c717e963 100755 --- a/components/ILIAS/Database/classes/PDO/Reverse/class.ilDBPdoReverse.php +++ b/components/ILIAS/Database/classes/PDO/Reverse/class.ilDBPdoReverse.php @@ -24,17 +24,13 @@ */ class ilDBPdoReverse implements ilDBReverse { - protected \PDO $pdo; - protected \ilDBPdo $db_instance; protected ?\ilMySQLQueryUtils $query_utils = null; /** * ilDBPdoReverse constructor. */ - public function __construct(\PDO $pdo, ilDBPdo $db_instance) + public function __construct(protected \PDO $pdo, protected \ilDBPdo $db_instance) { - $this->pdo = $pdo; - $this->db_instance = $db_instance; } public function getQueryUtils(): \ilMySQLQueryUtils @@ -54,7 +50,7 @@ public function getTableFieldDefinition(string $table_name, string $field_name): $table = $this->db_instance->quoteIdentifier($table_name); $query = "SHOW COLUMNS FROM $table LIKE " . $this->db_instance->quote($field_name); $res = $this->pdo->query($query); - $columns = array(); + $columns = []; while ($data = $res->fetch(PDO::FETCH_ASSOC)) { $columns[] = $data; } @@ -84,10 +80,10 @@ public function getTableFieldDefinition(string $table_name, string $field_name): $autoincrement = true; } - $definition[0] = array( + $definition[0] = [ 'notnull' => $notnull, - 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type']), - ); + 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', (string) $column['type']), + ]; if (!is_null($length)) { $definition[0]['length'] = $length; } @@ -138,7 +134,7 @@ public function getTableIndexDefinition(string $table, string $constraint_name): $result = $this->db_instance->query(sprintf($query, $this->db_instance->quote($constraint_name))); $colpos = 1; - $definition = array(); + $definition = []; while (is_object($row = $result->fetchObject())) { $row = array_change_key_case((array) $row, CASE_LOWER); @@ -149,9 +145,9 @@ public function getTableIndexDefinition(string $table, string $constraint_name): throw new ilDatabaseException('it was not specified an existing table index'); } $column_name = $row['column_name']; - $definition['fields'][$column_name] = array( + $definition['fields'][$column_name] = [ 'position' => $colpos++, - ); + ]; if (!empty($row['collation'])) { $definition['fields'][$column_name]['sorting'] = ($row['collation'] === 'A' ? 'ascending' : 'descending'); } @@ -189,20 +185,20 @@ public function getTableConstraintDefinition(string $table, string $index_name): $result = $this->db_instance->query(sprintf($query, $this->db_instance->quote($index_name))); $colpos = 1; - $definition = array(); + $definition = []; while (is_object($row = $result->fetchObject())) { $row = (array) $row; $row = array_change_key_case($row, CASE_LOWER); $key_name = $row['key_name']; if ($this->db_instance->options['portability'] ?? null) { - $key_name = strtolower($key_name); + $key_name = strtolower((string) $key_name); } - $key_name = strtolower($key_name); // FSX fix + $key_name = strtolower((string) $key_name); // FSX fix if ($index_name === $key_name) { if ($row['non_unique']) { throw new ilDatabaseException(' is not an existing table constraint'); } - if (strtolower($row['key_name']) === 'primary') { + if (strtolower((string) $row['key_name']) === 'primary') { $definition['primary'] = true; } else { $definition['unique'] = true; @@ -210,14 +206,14 @@ public function getTableConstraintDefinition(string $table, string $index_name): $column_name = $row['column_name']; if ($this->db_instance->options['portability'] ?? null) { if ($this->db_instance->options['field_case'] == CASE_LOWER) { - $column_name = strtolower($column_name); + $column_name = strtolower((string) $column_name); } else { - $column_name = strtoupper($column_name); + $column_name = strtoupper((string) $column_name); } } - $definition['fields'][$column_name] = array( + $definition['fields'][$column_name] = [ 'position' => $colpos++, - ); + ]; if (!empty($row['collation'])) { $definition['fields'][$column_name]['sorting'] = ($row['collation'] === 'A' ? 'ascending' : 'descending'); } diff --git a/components/ILIAS/Database/classes/PDO/class.ilDBPdo.php b/components/ILIAS/Database/classes/PDO/class.ilDBPdo.php index fb659147f9e5..ec349131da2e 100755 --- a/components/ILIAS/Database/classes/PDO/class.ilDBPdo.php +++ b/components/ILIAS/Database/classes/PDO/class.ilDBPdo.php @@ -48,10 +48,10 @@ abstract class ilDBPdo implements ilDBInterface, ilDBPdoInterface /** * @var int[] */ - protected array $attributes = array( + protected array $attributes = [ // PDO::ATTR_EMULATE_PREPARES => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - ); + ]; protected string $db_type = ''; protected int $error_code = 0; protected ?\ilDBPdoFieldDefinition $field_definition = null; @@ -96,7 +96,7 @@ protected function getAttributes(): array protected function getAdditionalAttributes(): array { - return array(); + return []; } public function getFieldDefinition(): ?\ilDBPdoFieldDefinition @@ -117,7 +117,7 @@ public function createDatabase(string $a_name, string $a_charset = "utf8", strin try { $this->query($this->manager->getQueryUtils()->createDatabase($a_name, $a_charset, $a_collation)); return true; - } catch (PDOException $e) { + } catch (PDOException) { return false; } } @@ -156,7 +156,7 @@ public function initFromIniFile(?ilIniFile $ini = null): void $this->generateDSN(); } - public function generateDSN() + public function generateDSN(): void { $port = $this->getPort() !== 0 ? ";port=" . $this->getPort() : ""; $dbname = $this->getDbname() !== '' ? ';dbname=' . $this->getDbname() : ''; @@ -198,7 +198,7 @@ public function createTable( $this->dropTable($table_name, false); } - return $this->manager->createTable($table_name, $fields, array()); + return $this->manager->createTable($table_name, $fields, []); } protected function checkTableColumns(array $a_cols): bool @@ -237,14 +237,14 @@ public function addPrimaryKey(string $table_name, array $primary_keys): bool { assert(is_array($primary_keys)); - $fields = array(); + $fields = []; foreach ($primary_keys as $f) { - $fields[$f] = array(); + $fields[$f] = []; } - $definition = array( + $definition = [ 'primary' => true, 'fields' => $fields, - ); + ]; $this->manager->createConstraint( $table_name, $this->constraintName($table_name, $this->getPrimaryKeyIdentifier()), @@ -285,7 +285,7 @@ public function createSequence(string $table_name, int $start = 1): bool public function tableExists(string $table_name): bool { $result = $this->pdo->prepare("SHOW TABLES LIKE :table_name"); - $result->execute(array('table_name' => $table_name)); + $result->execute(['table_name' => $table_name]); $return = $result->rowCount(); $result->closeCursor(); @@ -311,11 +311,11 @@ public function addTableColumn(string $table_name, string $column_name, array $a throw new ilDatabaseException("ilDB Error: addTableColumn(" . $table_name . ", " . $column_name . ")"); } - $changes = array( - "add" => array( + $changes = [ + "add" => [ $column_name => $attributes, - ), - ); + ], + ]; return $this->manager->alterTable($table_name, $changes, false); } @@ -365,7 +365,7 @@ public function query(string $query): ilDBStatement $ilBench->stopDbBench(); } } catch (PDOException $e) { - throw new ilDatabaseException($e->getMessage() . ' QUERY: ' . $query, (int) $e->getCode()); + throw new ilDatabaseException($e->getMessage() . ' QUERY: ' . $query, (int) $e->getCode(), $e); } $err = $this->pdo->errorCode(); @@ -399,11 +399,11 @@ public function dropSequence(string $table_name): bool */ public function dropTableColumn(string $table_name, string $column_name): bool { - $changes = array( - "remove" => array( - $column_name => array(), - ), - ); + $changes = [ + "remove" => [ + $column_name => [], + ], + ]; return $this->manager->alterTable($table_name, $changes, false); } @@ -429,19 +429,19 @@ public function renameTableColumn(string $table_name, string $column_old_name, s $f["definition"] = $def; $f["name"] = $column_new_name; - $changes = array( - "rename" => array( + $changes = [ + "rename" => [ $column_old_name => $f, - ), - ); + ], + ]; return $this->manager->alterTable($table_name, $changes, false); } public function insert(string $table_name, array $values): int { - $real = array(); - $fields = array(); + $real = []; + $fields = []; foreach ($values as $key => $val) { $real[] = $this->quote($val[1], $val[0]); $fields[] = $this->quoteIdentifier($key); @@ -469,14 +469,14 @@ public function fetchObject(ilDBStatement $query_result): ?stdClass public function update(string $table_name, array $columns, array $where): int { - $fields = array(); - $field_values = array(); - $placeholders = array(); - $placeholders_full = array(); - $types = array(); - $values = array(); + $fields = []; + $field_values = []; + $placeholders = []; + $placeholders_full = []; + $types = []; + $values = []; $lobs = false; - $lob = array(); + $lob = []; foreach ($columns as $k => $col) { $field_value = $col[1]; $fields[] = $k; @@ -562,7 +562,7 @@ public function manipulate(string $query): int $ilBench->stopDbBench(); } } catch (PDOException $e) { - throw new ilDatabaseException($e->getMessage() . ' QUERY: ' . $query, (int) $e->getCode()); + throw new ilDatabaseException($e->getMessage() . ' QUERY: ' . $query, (int) $e->getCode(), $e); } return (int) $num_affected_rows; @@ -639,13 +639,13 @@ public function addIndex(string $table_name, array $fields, string $index_name = assert(is_array($fields)); $this->field_definition->checkIndexName($index_name); - $definition_fields = array(); + $definition_fields = []; foreach ($fields as $f) { - $definition_fields[$f] = array(); + $definition_fields[$f] = []; } - $definition = array( + $definition = [ 'fields' => $definition_fields, - ); + ]; if (!$fulltext) { $this->manager->createIndex($table_name, $this->constraintName($table_name, $index_name), $definition); @@ -781,7 +781,7 @@ public function queryF(string $query, array $types, array $values): ilDBStatemen if (!is_array($types) || !is_array($values) || count($types) !== count($values)) { throw new ilDatabaseException("ilDB::queryF: Types and values must be arrays of same size. ($query)"); } - $quoted_values = array(); + $quoted_values = []; foreach ($types as $k => $t) { $quoted_values[] = $this->quote($values[$k], $t); } @@ -799,7 +799,7 @@ public function manipulateF(string $query, array $types, array $values): int if (!is_array($types) || !is_array($values) || count($types) !== count($values)) { throw new ilDatabaseException("ilDB::manipulateF: types and values must be arrays of same size. ($query)"); } - $quoted_values = array(); + $quoted_values = []; foreach ($types as $k => $t) { $quoted_values[] = $this->quote($values[$k], $t); } @@ -1032,16 +1032,12 @@ public function supportsTransactions(): bool public function supports(string $feature): bool { - switch ($feature) { - case self::FEATURE_TRANSACTIONS: - return $this->supportsTransactions(); - case self::FEATURE_FULLTEXT: - return $this->supportsFulltext(); - case self::FEATURE_SLAVE: - return $this->supportsSlave(); - default: - return false; - } + return match ($feature) { + self::FEATURE_TRANSACTIONS => $this->supportsTransactions(), + self::FEATURE_FULLTEXT => $this->supportsFulltext(), + self::FEATURE_SLAVE => $this->supportsSlave(), + default => false, + }; } /** @@ -1057,13 +1053,11 @@ public function listTables(): array */ public function loadModule(string $module) { - switch ($module) { - case ilDBConstants::MODULE_MANAGER: - return $this->manager; - case ilDBConstants::MODULE_REVERSE: - return $this->reverse; - } - throw new LogicException('module "' . $module . '" not available'); + return match ($module) { + ilDBConstants::MODULE_MANAGER => $this->manager, + ilDBConstants::MODULE_REVERSE => $this->reverse, + default => throw new LogicException('module "' . $module . '" not available'), + }; } /** @@ -1143,11 +1137,11 @@ public function modifyTableColumn(string $table, string $column, array $attribut $attributes["definition"] = $def; - $changes = array( - "change" => array( + $changes = [ + "change" => [ $column => $attributes, - ), - ); + ], + ]; return $this->manager->alterTable($table, $changes, false); } @@ -1166,10 +1160,7 @@ public function renameTable(string $name, string $new_name): bool try { $this->checkTableName($new_name); } catch (ilDatabaseException $e) { - throw new ilDatabaseException( - "ilDB Error: renameTable(" . $name . "," . $new_name . ")
" . $e->getMessage(), - $e->getCode() - ); + throw new ilDatabaseException("ilDB Error: renameTable(" . $name . "," . $new_name . ")
" . $e->getMessage(), $e->getCode(), $e); } $this->manager->alterTable($name, ["name" => $new_name], false); @@ -1255,17 +1246,11 @@ public function getStorageEngine(): string public function queryCol(string $query, int $type = PDO::FETCH_ASSOC, int $colnum = 0): array { - switch ($type) { - case ilDBConstants::FETCHMODE_ASSOC: - $type = PDO::FETCH_ASSOC; - break; - case ilDBConstants::FETCHMODE_OBJECT: - $type = PDO::FETCH_OBJ; - break; - default: - $type = PDO::FETCH_ASSOC; - break; - } + $type = match ($type) { + ilDBConstants::FETCHMODE_ASSOC => PDO::FETCH_ASSOC, + ilDBConstants::FETCHMODE_OBJECT => PDO::FETCH_OBJ, + default => PDO::FETCH_ASSOC, + }; return $this->pdo->query($query, PDO::FETCH_ASSOC)->fetchAll(PDO::FETCH_COLUMN, $colnum); } @@ -1275,17 +1260,11 @@ public function queryRow( ?array $types = null, int $fetchmode = ilDBConstants::FETCHMODE_DEFAULT ): array { - switch ($fetchmode) { - case ilDBConstants::FETCHMODE_ASSOC: - $type = PDO::FETCH_ASSOC; - break; - case ilDBConstants::FETCHMODE_OBJECT: - $type = PDO::FETCH_OBJ; - break; - default: - $type = PDO::FETCH_ASSOC; - break; - } + $type = match ($fetchmode) { + ilDBConstants::FETCHMODE_ASSOC => PDO::FETCH_ASSOC, + ilDBConstants::FETCHMODE_OBJECT => PDO::FETCH_OBJ, + default => PDO::FETCH_ASSOC, + }; return $this->pdo->query($query, $type)->fetch(); } @@ -1307,7 +1286,7 @@ public function escapePattern(string $text): string public function migrateAllTablesToEngine(string $engine = ilDBConstants::MYSQL_ENGINE_INNODB): array { - return array(); + return []; } /** @@ -1315,7 +1294,7 @@ public function migrateAllTablesToEngine(string $engine = ilDBConstants::MYSQL_E */ public function migrateAllTablesToCollation(string $collation = ilDBConstants::MYSQL_COLLATION_UTF8MB4): array { - return array(); + return []; } /** @@ -1356,14 +1335,14 @@ public function addUniqueConstraint(string $table, array $fields, string $name = throw new ilDatabaseException("ilDB Error: addUniqueConstraint(" . $table . "," . $name . ")"); } - $fields_corrected = array(); + $fields_corrected = []; foreach ($fields as $f) { - $fields_corrected[$f] = array(); + $fields_corrected[$f] = []; } - $definition = array( + $definition = [ 'unique' => true, 'fields' => $fields_corrected, - ); + ]; return $manager->createConstraint($table, $this->constraintName($table, $name), $definition); } diff --git a/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQL.php b/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQL.php index cfe3d3723970..23cf613d7d47 100755 --- a/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQL.php +++ b/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQL.php @@ -36,6 +36,7 @@ abstract class ilDBPdoMySQL extends ilDBPdo 'NO_ENGINE_SUBSTITUTION', ]; + #[\Override] public function supportsTransactions(): bool { return false; @@ -53,6 +54,7 @@ protected function initSQLMode(): void $this->pdo->exec("SET SESSION sql_mode = '" . implode(",", $this->modes) . "';"); } + #[\Override] public function supportsEngineMigration(): bool { return true; @@ -61,12 +63,13 @@ public function supportsEngineMigration(): bool /** * @return array */ + #[\Override] protected function getAdditionalAttributes(): array { - return array( + return [ PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, PDO::ATTR_TIMEOUT => 300 * 60, - ); + ]; } public function migrateTableToEngine(string $table_name, string $engine = ilDBConstants::MYSQL_ENGINE_INNODB): void @@ -77,13 +80,14 @@ public function migrateTableToEngine(string $table_name, string $engine = ilDBCo $this->pdo->exec("ALTER TABLE {$table_name}_seq ENGINE={$engine}"); } } catch (PDOException $e) { - throw new ilDatabaseException($e->getMessage()); + throw new ilDatabaseException($e->getMessage(), $e->getCode(), $e); } } /** * @return array */ + #[\Override] public function migrateAllTablesToEngine(string $engine = ilDBConstants::MYSQL_ENGINE_INNODB): array { $engines = $this->queryCol('SHOW ENGINES'); @@ -116,7 +120,7 @@ public function migrateTableCollation( $q = "ALTER TABLE {$this->quoteIdentifier($table_name)} CONVERT TO CHARACTER SET {$character} COLLATE {$collate};"; try { $this->pdo->exec($q); - } catch (PDOException $e) { + } catch (PDOException) { return false; } return true; @@ -125,6 +129,7 @@ public function migrateTableCollation( /** * @inheritDoc */ + #[\Override] public function migrateAllTablesToCollation(string $collation = ilDBConstants::MYSQL_COLLATION_UTF8MB4): array { $manager = $this->loadModule(ilDBConstants::MODULE_MANAGER); @@ -141,6 +146,7 @@ public function migrateAllTablesToCollation(string $collation = ilDBConstants::M /** * @inheritDoc */ + #[\Override] public function supportsCollationMigration(): bool { return true; @@ -153,7 +159,7 @@ public function nextId(string $table_name): int $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)"; try { $this->pdo->exec($query); - } catch (PDOException $e) { + } catch (PDOException) { // no such table check } @@ -171,6 +177,7 @@ public function nextId(string $table_name): int /** * @inheritDoc */ + #[\Override] public function doesCollationSupportMB4Strings(): bool { // Currently ILIAS does not support utf8mb4, after that ilDB could check like this: diff --git a/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQLGalera.php b/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQLGalera.php index cacfba978375..b31b038d165c 100755 --- a/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQLGalera.php +++ b/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQLGalera.php @@ -24,11 +24,13 @@ */ class ilDBPdoMySQLGalera extends ilDBPdoMySQLInnoDB { + #[\Override] public function supportsTransactions(): bool { return true; } + #[\Override] public function buildAtomQuery(): ilAtomQuery { return new ilAtomQueryTransaction($this); diff --git a/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQLInnoDB.php b/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQLInnoDB.php index 534f86aebc28..486029cfda82 100755 --- a/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQLInnoDB.php +++ b/components/ILIAS/Database/classes/PDO/class.ilDBPdoMySQLInnoDB.php @@ -26,18 +26,21 @@ class ilDBPdoMySQLInnoDB extends ilDBPdoMySQL { protected string $storage_engine = 'InnoDB'; + #[\Override] public function supportsFulltext(): bool { return false; } + #[\Override] public function supportsTransactions(): bool { return false; } + #[\Override] public function addFulltextIndex(string $table_name, array $fields, string $name = 'in'): bool { return false; // NOT SUPPORTED diff --git a/components/ILIAS/Database/classes/PDO/class.ilPDOStatement.php b/components/ILIAS/Database/classes/PDO/class.ilPDOStatement.php index 6f83f5408688..16be7c1ff651 100755 --- a/components/ILIAS/Database/classes/PDO/class.ilPDOStatement.php +++ b/components/ILIAS/Database/classes/PDO/class.ilPDOStatement.php @@ -26,15 +26,11 @@ */ class ilPDOStatement implements ilDBStatement { - protected \PDOStatement $pdo_statement; - - /** * @param $pdo_statement PDOStatement The PDO Statement to be wrapped. */ - public function __construct(PDOStatement $pdo_statement) + public function __construct(protected \PDOStatement $pdo_statement) { - $this->pdo_statement = $pdo_statement; } @@ -42,7 +38,7 @@ public function __construct(PDOStatement $pdo_statement) * @return mixed * @throws ilDatabaseException */ - public function fetchRow(int $fetch_mode = ilDBConstants::FETCHMODE_ASSOC) + public function fetchRow(int $fetch_mode = ilDBConstants::FETCHMODE_ASSOC): mixed { if ($fetch_mode === ilDBConstants::FETCHMODE_ASSOC) { return $this->pdo_statement->fetch(PDO::FETCH_ASSOC); @@ -59,7 +55,7 @@ public function fetchRow(int $fetch_mode = ilDBConstants::FETCHMODE_ASSOC) /** * @return mixed */ - public function fetch(int $fetch_mode = ilDBConstants::FETCHMODE_ASSOC) + public function fetch(int $fetch_mode = ilDBConstants::FETCHMODE_ASSOC): mixed { return $this->fetchRow($fetch_mode); } diff --git a/components/ILIAS/Database/classes/QueryUtils/class.ilMySQLQueryUtils.php b/components/ILIAS/Database/classes/QueryUtils/class.ilMySQLQueryUtils.php index 00d231aa6341..6774cdc61d9f 100755 --- a/components/ILIAS/Database/classes/QueryUtils/class.ilMySQLQueryUtils.php +++ b/components/ILIAS/Database/classes/QueryUtils/class.ilMySQLQueryUtils.php @@ -29,13 +29,13 @@ class ilMySQLQueryUtils extends ilQueryUtils */ public function in(string $field, array $values, bool $negate = false, string $type = ""): string { - if (!is_array($values) || count($values) === 0) { + if (!is_array($values) || $values === []) { // BEGIN fixed mantis #0014191: //return " 1=2 "; // return a false statement on empty array return $negate ? ' 1=1 ' : ' 1=2 '; // END fixed mantis #0014191: } - if ($type == "") { // untyped: used ? for prepare/execute + if ($type === "") { // untyped: used ? for prepare/execute $str = $field . (($negate) ? " NOT" : "") . " IN (?" . str_repeat(",?", count($values) - 1) . ")"; } else { // typed, use values for query/manipulate $str = $field . (($negate) ? " NOT" : "") . " IN ("; @@ -60,7 +60,7 @@ public function quote($value, ?string $type = null): string public function concat(array $values, bool $allow_null = true): string { - if (count($values) === 0) { + if ($values === []) { return ' '; } @@ -145,7 +145,7 @@ public function createTable(string $name, array $fields, array $options = []): s $query = "CREATE TABLE $name ($query_fields)"; - $options_strings = array(); + $options_strings = []; if (!empty($options['comment'])) { $options_strings['comment'] = 'COMMENT = ' . $this->quote($options['comment'], 'text'); @@ -178,11 +178,11 @@ public function createTable(string $name, array $fields, array $options = []): s */ public function like(string $column, string $type, string $value = "?", bool $case_insensitive = true): string { - if (!in_array($type, array( + if (!in_array($type, [ ilDBConstants::T_TEXT, ilDBConstants::T_CLOB, "blob", - ), true) + ], true) ) { throw new ilDatabaseException("Like: Invalid column type '" . $type . "'."); } @@ -252,25 +252,21 @@ public function unlock(): string public function createDatabase(string $name, string $charset = "utf8", string $collation = ""): string { if ($collation !== "") { - $sql = "CREATE DATABASE `" . $name . "` CHARACTER SET " . $charset . " COLLATE " . $collation; - } else { - $sql = "CREATE DATABASE `" . $name . "` CHARACTER SET " . $charset; + return "CREATE DATABASE `" . $name . "` CHARACTER SET " . $charset . " COLLATE " . $collation; } - return $sql; + return "CREATE DATABASE `" . $name . "` CHARACTER SET " . $charset; } public function groupConcat(string $field_name, string $seperator = ",", ?string $order = null): string { if ($order === null) { - $sql = "GROUP_CONCAT(" . $field_name . " SEPARATOR " . $this->quote($seperator, "text") . ")"; - } else { - $sql = "GROUP_CONCAT(" . $field_name . " ORDER BY " . $order . " SEPARATOR " . $this->quote( - $seperator, - "text" - ) . ")"; + return "GROUP_CONCAT(" . $field_name . " SEPARATOR " . $this->quote($seperator, "text") . ")"; } - return $sql; + return "GROUP_CONCAT(" . $field_name . " ORDER BY " . $order . " SEPARATOR " . $this->quote( + $seperator, + "text" + ) . ")"; } /** diff --git a/components/ILIAS/Database/classes/QueryUtils/class.ilQueryUtils.php b/components/ILIAS/Database/classes/QueryUtils/class.ilQueryUtils.php index 7a4ecdc6cbe7..55faf1a59362 100755 --- a/components/ILIAS/Database/classes/QueryUtils/class.ilQueryUtils.php +++ b/components/ILIAS/Database/classes/QueryUtils/class.ilQueryUtils.php @@ -23,14 +23,11 @@ */ abstract class ilQueryUtils implements ilQueryUtilsInterface { - protected \ilDBInterface $db_instance; - /** * ilMySQLQueryUtils constructor. */ - public function __construct(ilDBInterface $ilDBInterface) + public function __construct(protected \ilDBInterface $db_instance) { - $this->db_instance = $ilDBInterface; } /** diff --git a/components/ILIAS/Database/classes/Setup/MysqlIfsnopDumper.php b/components/ILIAS/Database/classes/Setup/MysqlIfsnopDumper.php index 293f48d15116..bb7d881a7c25 100755 --- a/components/ILIAS/Database/classes/Setup/MysqlIfsnopDumper.php +++ b/components/ILIAS/Database/classes/Setup/MysqlIfsnopDumper.php @@ -18,15 +18,14 @@ declare(strict_types=1); +use Ifsnop\Mysqldump\Mysqldump; + class MysqlIfsnopDumper implements MysqlDumper { public const FILE_NAME = "dump.sql"; - protected ?string $export_hooks_path; - - public function __construct(?string $export_hooks_path) + public function __construct(protected ?string $export_hooks_path) { - $this->export_hooks_path = $export_hooks_path; } public function createDump( @@ -42,7 +41,7 @@ public function createDump( } try { - $dumper = new Ifsnop\Mysqldump\Mysqldump( + $dumper = new Mysqldump( "mysql:host=$host;port=$port;dbname=$name", $user, $password, @@ -53,7 +52,7 @@ public function createDump( } $dumper->start($target . "/" . self::FILE_NAME); } catch (\Exception $e) { - throw new Exception("Error during sql dump: " . $e->getMessage()); + throw new Exception("Error during sql dump: " . $e->getMessage(), $e->getCode(), $e); } } } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDBStepExecutionDB.php b/components/ILIAS/Database/classes/Setup/class.ilDBStepExecutionDB.php index 7aa37b7b3288..5cfb9eb0b923 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDBStepExecutionDB.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDBStepExecutionDB.php @@ -31,17 +31,14 @@ class ilDBStepExecutionDB implements ilDatabaseUpdateStepExecutionLog public const FIELD_STEP = "step"; public const FIELD_STARTED = "started"; public const FIELD_FINISHED = "finished"; - - protected ilDBInterface $db; protected $get_now; /** * @param callable $get_now must return a DateTime object indicating the * very moment the callable was called. */ - public function __construct(ilDBInterface $db, callable $get_now) + public function __construct(protected ilDBInterface $db, callable $get_now) { - $this->db = $db; $this->get_now = $get_now; } @@ -86,7 +83,7 @@ public function finished(string $class, int $step): void $this->throwIfClassNameTooLong($class); $last_started_step = $this->getLastStartedStep($class); - if ($last_started_step != $step) { + if ($last_started_step !== $step) { throw new \RuntimeException( "The step $step for $class is supposed to be finished, but" . " $last_started_step was $step started last." diff --git a/components/ILIAS/Database/classes/Setup/class.ilDBStepExecutionDBExistsObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDBStepExecutionDBExistsObjective.php index 34179671a16e..d4bd82f8107a 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDBStepExecutionDBExistsObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDBStepExecutionDBExistsObjective.php @@ -16,10 +16,10 @@ * *********************************************************************/ -use ILIAS\Setup; -use ILIAS\DI; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Environment; -class ilDBStepExecutionDBExistsObjective implements Setup\Objective +class ilDBStepExecutionDBExistsObjective implements Objective { public function getHash(): string { @@ -36,23 +36,23 @@ public function isNotable(): bool return true; } - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { return [ new \ilDatabaseUpdatedObjective() ]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { - $db = $environment->getResource(Setup\Environment::RESOURCE_DATABASE); + $db = $environment->getResource(Environment::RESOURCE_DATABASE); return $environment ->withResource( \ilDatabaseUpdateStepExecutionLog::class, new \ilDBStepExecutionDB( $db, - fn() => new \DateTime() + fn(): \DateTime => new \DateTime() ) ); } @@ -60,7 +60,7 @@ public function achieve(Setup\Environment $environment): Setup\Environment /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { $execution_db = $environment->getResource(\ilDatabaseUpdateStepExecutionLog::class); return is_null($execution_db); diff --git a/components/ILIAS/Database/classes/Setup/class.ilDBStepReaderExistsObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDBStepReaderExistsObjective.php index c3cb5dbfca94..4d200946f9c6 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDBStepReaderExistsObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDBStepReaderExistsObjective.php @@ -16,9 +16,10 @@ * *********************************************************************/ -use ILIAS\Setup; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Environment; -class ilDBStepReaderExistsObjective implements Setup\Objective +class ilDBStepReaderExistsObjective implements Objective { public function getHash(): string { @@ -35,14 +36,14 @@ public function isNotable(): bool return true; } - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { return [ new ilDatabaseUpdatedObjective() ]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { return $environment ->withResource( @@ -54,7 +55,7 @@ public function achieve(Setup\Environment $environment): Setup\Environment /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { $execution_db = $environment->getResource(ilDBStepReader::class); return is_null($execution_db); diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseConfigStoredObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseConfigStoredObjective.php index c724a00aabc6..94e4db94c59a 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseConfigStoredObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseConfigStoredObjective.php @@ -18,7 +18,9 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Environment; +use ILIAS\Setup\NotExecutableException; +use ILIAS\Setup\UnachievableException; class ilDatabaseConfigStoredObjective extends ilDatabaseObjective { @@ -40,7 +42,7 @@ public function isNotable(): bool /** * @return array */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { return [ new ilIniFilesLoadedObjective(), @@ -48,14 +50,14 @@ public function getPreconditions(Setup\Environment $environment): array ]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { - $client_ini = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI); + $client_ini = $environment->getResource(Environment::RESOURCE_CLIENT_INI); $type = $this->config->getType(); if ($type === 'postgres' || $type === 'pdo-postgre') { - throw new Setup\NotExecutableException('ILIAS 8 no longer Supports POSTGRES'); + throw new NotExecutableException('ILIAS 8 no longer Supports POSTGRES'); } $client_ini->setVariable("db", "type", $type); @@ -67,26 +69,33 @@ public function achieve(Setup\Environment $environment): Setup\Environment $client_ini->setVariable("db", "pass", $pw !== null ? $pw->toString() : ""); if (!$client_ini->write()) { - throw new Setup\UnachievableException("Could not write client.ini.php"); + throw new UnachievableException("Could not write client.ini.php"); } return $environment; } - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { - $client_ini = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI); + $client_ini = $environment->getResource(Environment::RESOURCE_CLIENT_INI); $port = $this->config->getPort() ?? ""; $pass = $this->config->getPassword() !== null ? $this->config->getPassword()->toString() : ""; - - return - $client_ini->readVariable("db", "type") !== $this->config->getType() || - $client_ini->readVariable("db", "host") !== $this->config->getHost() || - $client_ini->readVariable("db", "name") !== $this->config->getDatabase() || - $client_ini->readVariable("db", "user") !== $this->config->getUser() || - $client_ini->readVariable("db", "port") !== $port || - $client_ini->readVariable("dv", "pass") !== $pass - ; + if ($client_ini->readVariable("db", "type") !== $this->config->getType()) { + return true; + } + if ($client_ini->readVariable("db", "host") !== $this->config->getHost()) { + return true; + } + if ($client_ini->readVariable("db", "name") !== $this->config->getDatabase()) { + return true; + } + if ($client_ini->readVariable("db", "user") !== $this->config->getUser()) { + return true; + } + if ($client_ini->readVariable("db", "port") !== $port) { + return true; + } + return $client_ini->readVariable("dv", "pass") !== $pass; } } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseCreatedObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseCreatedObjective.php index b87b012655fe..432aaecef82b 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseCreatedObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseCreatedObjective.php @@ -18,7 +18,8 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Environment; +use ILIAS\Setup\UnachievableException; class ilDatabaseCreatedObjective extends ilDatabaseObjective { @@ -45,21 +46,21 @@ public function isNotable(): bool /** * @return \ilDatabaseServerIsConnectableObjective[] */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { return [ new \ilDatabaseServerIsConnectableObjective($this->config) ]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { $c = $this->config; $db = \ilDBWrapperFactory::getWrapper($this->config->getType()); $db->initFromIniFile($c->toMockIniFile()); if (!$db->createDatabase($c->getDatabase(), "utf8", $c->getCollation())) { - throw new Setup\UnachievableException( + throw new UnachievableException( "Database cannot be created." ); } @@ -70,7 +71,7 @@ public function achieve(Setup\Environment $environment): Setup\Environment /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { $c = $this->config; $db = \ilDBWrapperFactory::getWrapper($this->config->getType()); diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseDumpedToDirectoryObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseDumpedToDirectoryObjective.php index 0c13b3653578..6821e585639b 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseDumpedToDirectoryObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseDumpedToDirectoryObjective.php @@ -18,17 +18,13 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Environment; -class ilDatabaseDumpedToDirectoryObjective implements Setup\Objective +class ilDatabaseDumpedToDirectoryObjective implements Objective { - protected string $target; - protected MysqlDumper $dumper; - - public function __construct(string $target, MysqlDumper $dumper) + public function __construct(protected string $target, protected MysqlDumper $dumper) { - $this->target = $target; - $this->dumper = $dumper; } /** @@ -58,7 +54,7 @@ public function isNotable(): bool /** * @inheritdoc */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { return [ new ilIniFilesLoadedObjective(), @@ -69,14 +65,14 @@ public function getPreconditions(Setup\Environment $environment): array /** * @inheritdoc */ - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { if (file_exists($this->target)) { $this->deleteDirRecursive($this->target); } mkdir($this->target, 0755); - $client_ini = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI); + $client_ini = $environment->getResource(Environment::RESOURCE_CLIENT_INI); $host = $client_ini->readVariable("db", "host"); $user = $client_ini->readVariable("db", "user"); $password = $client_ini->readVariable("db", "pass"); @@ -91,7 +87,7 @@ public function achieve(Setup\Environment $environment): Setup\Environment /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { return is_writable(pathinfo($this->target, PATHINFO_DIRNAME)); } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseEnvironmentValidObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseEnvironmentValidObjective.php index 0e896ec08e62..656125383f61 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseEnvironmentValidObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseEnvironmentValidObjective.php @@ -18,11 +18,19 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Environment; +use ILIAS\Setup\UnachievableException; -class ilDatabaseEnvironmentValidObjective implements Setup\Objective +class ilDatabaseEnvironmentValidObjective implements Objective { + /** + * @var string + */ private const ROW_FORMAT_DYNAMIC = "DYNAMIC"; + /** + * @var string + */ private const INNO_DB = "InnoDB"; public function getHash(): string @@ -43,19 +51,19 @@ public function isNotable(): bool /** * @return array<\ilDatabaseServerIsConnectableObjective|\ilDatabaseCreatedObjective> */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { return [ ]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { /** * @var $db ilDBInterface * @var $io Setup\CLI\IOWrapper */ - $db = $environment->getResource(Setup\Environment::RESOURCE_DATABASE); - $io = $environment->getResource(Setup\Environment::RESOURCE_ADMIN_INTERACTION); + $db = $environment->getResource(Environment::RESOURCE_DATABASE); + $io = $environment->getResource(Environment::RESOURCE_ADMIN_INTERACTION); $this->checkDBAvailable($db); $this->checkRowFormat($db); $io->inform("Default Row Format is " . self::ROW_FORMAT_DYNAMIC . "."); @@ -71,17 +79,17 @@ protected function checkDefaultEngine(ilDBInterface $db) try { $r = $db->query('SHOW ENGINES '); while ($d = $db->fetchObject($r)) { - if (strtoupper($d->Support) === 'DEFAULT') { - $default_engine = strtolower($d->Engine); + if (strtoupper((string) $d->Support) === 'DEFAULT') { + $default_engine = strtolower((string) $d->Engine); break; } } - } catch (Throwable $e) { + } catch (Throwable) { } $default_engine = strtolower($default_engine); if ($default_engine !== strtolower(self::INNO_DB)) { - throw new Setup\UnachievableException( + throw new UnachievableException( "The default database engine is not set to '" . self::INNO_DB . ", `$default_engine` given'. Please set the default database engine to '" . self::INNO_DB . " to proceed'." @@ -93,8 +101,8 @@ protected function checkRowFormat(ilDBInterface $db): void { $setting = $db->fetchObject($db->query('SELECT @@GLOBAL.innodb_default_row_format AS row_format;')); $row_format = $setting->row_format ?? null; - if ($row_format === null || strtoupper($row_format) !== self::ROW_FORMAT_DYNAMIC) { - throw new Setup\UnachievableException( + if ($row_format === null || strtoupper((string) $row_format) !== self::ROW_FORMAT_DYNAMIC) { + throw new UnachievableException( "The default row format of the database is not set to '" . self::ROW_FORMAT_DYNAMIC . "'. Please set the default row format to " . self::ROW_FORMAT_DYNAMIC . " and run an 'OPTIMIZE TABLE' for each of your database tables before you continue." ); } @@ -107,7 +115,7 @@ protected function checkRowFormat(ilDBInterface $db): void protected function checkDBAvailable(?ilDBInterface $db): void { if ($db === null) { - throw new Setup\UnachievableException( + throw new UnachievableException( "Database cannot be connected. Please check the credentials." ); } @@ -116,7 +124,7 @@ protected function checkDBAvailable(?ilDBInterface $db): void /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { return true; } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseExistsObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseExistsObjective.php index a41d08566076..8e65236aacfc 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseExistsObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseExistsObjective.php @@ -18,7 +18,8 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Environment; +use ILIAS\Setup\UnachievableException; class ilDatabaseExistsObjective extends \ilDatabaseObjective { @@ -45,7 +46,7 @@ public function isNotable(): bool /** * @return array<\ilDatabaseServerIsConnectableObjective|\ilDatabaseCreatedObjective> */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { $preconditions = [ new \ilDatabaseServerIsConnectableObjective($this->config) @@ -56,24 +57,24 @@ public function getPreconditions(Setup\Environment $environment): array return $preconditions; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { $db = \ilDBWrapperFactory::getWrapper($this->config->getType()); $db->initFromIniFile($this->config->toMockIniFile()); $connect = $db->connect(true); if (!$connect) { - throw new Setup\UnachievableException( + throw new UnachievableException( "Database cannot be connected. Please check the credentials." ); } - return $environment->withResource(Setup\Environment::RESOURCE_DATABASE, $db); + return $environment->withResource(Environment::RESOURCE_DATABASE, $db); } /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { return true; } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseInitializedObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseInitializedObjective.php index 4dbccab2ab19..c5c9d468be62 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseInitializedObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseInitializedObjective.php @@ -18,9 +18,11 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Environment; +use ILIAS\Setup\UnachievableException; -class ilDatabaseInitializedObjective implements Setup\Objective +class ilDatabaseInitializedObjective implements Objective { public function getHash(): string { @@ -40,7 +42,7 @@ public function isNotable(): bool /** * @return array<\ilIniFilesLoadedObjective>|array<\ilDatabaseConfigStoredObjective|\ilDatabasePopulatedObjective> */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { // If there is no config for the database the existing config seems // to be ok, and we can just connect. @@ -57,13 +59,13 @@ public function getPreconditions(Setup\Environment $environment): array ]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { - if ($environment->getResource(Setup\Environment::RESOURCE_DATABASE)) { + if ($environment->getResource(Environment::RESOURCE_DATABASE)) { return $environment; } - $client_ini = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI); + $client_ini = $environment->getResource(Environment::RESOURCE_CLIENT_INI); $type = $client_ini->readVariable("db", "type"); if ($type === "") { @@ -74,19 +76,19 @@ public function achieve(Setup\Environment $environment): Setup\Environment $db->initFromIniFile($client_ini); $connect = $db->connect(true); if (!$connect) { - throw new Setup\UnachievableException( + throw new UnachievableException( "Database cannot be connected." ); } - return $environment->withResource(Setup\Environment::RESOURCE_DATABASE, $db); + return $environment->withResource(Environment::RESOURCE_DATABASE, $db); } /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { - return $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI) !== null; + return $environment->getResource(Environment::RESOURCE_CLIENT_INI) !== null; } } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseMetricsCollectedObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseMetricsCollectedObjective.php index fa043f248bee..f41d129e619f 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseMetricsCollectedObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseMetricsCollectedObjective.php @@ -18,15 +18,17 @@ declare(strict_types=1); -use ILIAS\Setup; -use ILIAS\DI; +use ILIAS\Setup\Metrics\CollectedObjective; +use ILIAS\Setup\Environment; +use ILIAS\Setup\Metrics\Storage; +use ILIAS\DI\Container; -class ilDatabaseMetricsCollectedObjective extends Setup\Metrics\CollectedObjective +class ilDatabaseMetricsCollectedObjective extends CollectedObjective { /** * @return array<\ilDatabaseInitializedObjective|\ilIniFilesLoadedObjective> */ - protected function getTentativePreconditions(Setup\Environment $environment): array + protected function getTentativePreconditions(Environment $environment): array { return [ new \ilIniFilesLoadedObjective(), @@ -34,9 +36,9 @@ protected function getTentativePreconditions(Setup\Environment $environment): ar ]; } - protected function collectFrom(Setup\Environment $environment, Setup\Metrics\Storage $storage): void + protected function collectFrom(Environment $environment, Storage $storage): void { - $client_ini = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI); + $client_ini = $environment->getResource(Environment::RESOURCE_CLIENT_INI); if ($client_ini) { $storage->storeConfigText( "type", @@ -71,12 +73,12 @@ protected function collectFrom(Setup\Environment $environment, Setup\Metrics\Sto } - $db = $environment->getResource(Setup\Environment::RESOURCE_DATABASE); - $ini = $environment->getResource(Setup\Environment::RESOURCE_ILIAS_INI); + $db = $environment->getResource(Environment::RESOURCE_DATABASE); + $ini = $environment->getResource(Environment::RESOURCE_ILIAS_INI); if (!$db && !$ini) { return; } - $client_id = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_ID); + $client_id = $environment->getResource(Environment::RESOURCE_CLIENT_ID); // ATTENTION: This is a total abomination. It only exists to allow the db- // update to run. This is a memento to the fact, that dependency injection @@ -84,7 +86,7 @@ protected function collectFrom(Setup\Environment $environment, Setup\Metrics\Sto // locate the whole world via the global $DIC. $DIC = $GLOBALS["DIC"] ?? []; try { - $GLOBALS["DIC"] = new DI\Container(); + $GLOBALS["DIC"] = new Container(); $GLOBALS["DIC"]["ilDB"] = $db; $GLOBALS["DIC"]["ilBench"] = null; $GLOBALS["DIC"]["ilLog"] = new class () { @@ -134,7 +136,7 @@ public function write(): void define("SYSTEM_FOLDER_ID", (int) $client_ini->readVariable("system", "SYSTEM_FOLDER_ID")); } - $db_update = new ilDBUpdate($db); + $db_update = new ilDBUpdate($db); $storage->storeStableCounter( "custom_version", diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseObjective.php index fcfd062dfb46..af1841380d81 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseObjective.php @@ -18,14 +18,11 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Objective; -abstract class ilDatabaseObjective implements Setup\Objective +abstract class ilDatabaseObjective implements Objective { - protected \ilDatabaseSetupConfig $config; - - public function __construct(\ilDatabaseSetupConfig $config) + public function __construct(protected \ilDatabaseSetupConfig $config) { - $this->config = $config; } } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabasePopulatedObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabasePopulatedObjective.php index e3f3ea9c2625..cf0635a2ba6f 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabasePopulatedObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabasePopulatedObjective.php @@ -18,7 +18,9 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Environment; +use ILIAS\Setup\CLI\InstallCommand; +use ILIAS\Setup\UnachievableException; use ILIAS\Setup\CLI\ImportFileUnzippedFileObjective; use ILIAS\Setup\Objective\ObjectiveWithPreconditions; @@ -49,15 +51,15 @@ public function isNotable(): bool /** * @return \ilDatabaseExistsObjective[] */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { - if ($environment->hasConfigFor(Setup\CLI\InstallCommand::IMPORT)) { + if ($environment->hasConfigFor(InstallCommand::IMPORT)) { return [new ObjectiveWithPreconditions( new \ilDatabaseExistsObjective($this->config), - new ImportFileUnzippedFileObjective($environment->getConfigFor(Setup\CLI\InstallCommand::IMPORT)) + new ImportFileUnzippedFileObjective($environment->getConfigFor(InstallCommand::IMPORT)) )]; } - if ($environment->getResource(Setup\Environment::RESOURCE_DATABASE)) { + if ($environment->getResource(Environment::RESOURCE_DATABASE)) { return []; } return [ @@ -65,14 +67,14 @@ public function getPreconditions(Setup\Environment $environment): array ]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { /** * @var $db ilDBInterface * @var $io Setup\CLI\IOWrapper */ - $db = $environment->getResource(Setup\Environment::RESOURCE_DATABASE); - $io = $environment->getResource(Setup\Environment::RESOURCE_ADMIN_INTERACTION); + $db = $environment->getResource(Environment::RESOURCE_DATABASE); + $io = $environment->getResource(Environment::RESOURCE_ADMIN_INTERACTION); // $this->setDefaultEngine($db); // maybe we could set the default? $default = $this->getDefaultEngine($db); @@ -87,7 +89,7 @@ public function achieve(Setup\Environment $environment): Setup\Environment break; default: - throw new Setup\UnachievableException( + throw new UnachievableException( "Cannot determine database default engine, must be InnoDB, `$default` given." ); } @@ -98,13 +100,13 @@ public function achieve(Setup\Environment $environment): Setup\Environment /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { - if ($environment->hasConfigFor(Setup\CLI\InstallCommand::IMPORT)) { + if ($environment->hasConfigFor(InstallCommand::IMPORT)) { return true; } - $db = $environment->getResource(Setup\Environment::RESOURCE_DATABASE); + $db = $environment->getResource(Environment::RESOURCE_DATABASE); return !$this->isDatabasePopulated($db); } @@ -129,7 +131,7 @@ private function readDumpFile(ilDBInterface $db): void $path_to_db_dump = $this->config->getPathToDBDump(); if (!is_file(realpath($path_to_db_dump) ?: '') || !is_readable(realpath($path_to_db_dump) ?: '')) { - throw new Setup\UnachievableException( + throw new UnachievableException( "Cannot read database dump file: $path_to_db_dump" ); } @@ -138,7 +140,7 @@ private function readDumpFile(ilDBInterface $db): void $statement = $db->prepareManip($query); $db->execute($statement); } catch (Throwable $e) { - throw new Setup\UnachievableException( + throw new UnachievableException( "Cannot populate database with dump file: $path_to_db_dump. Query failed: $query wih message " . $e->getMessage( ) ); @@ -194,13 +196,13 @@ private function getDefaultEngine(ilDBInterface $db): string $default = ''; while ($d = $db->fetchObject($r)) { - if (strtoupper($d->Support) === 'DEFAULT') { + if (strtoupper((string) $d->Support) === 'DEFAULT') { $default = $d->Engine; break; } } - return strtolower($default); - } catch (Throwable $e) { + return strtolower((string) $default); + } catch (Throwable) { return 'unknown'; } } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseResetStepsObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseResetStepsObjective.php index f4f12c3d674d..4b683f5b9d31 100644 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseResetStepsObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseResetStepsObjective.php @@ -37,16 +37,19 @@ public function __construct() ); } + #[\Override] public function getHash(): string { return hash("sha256", self::class); } + #[\Override] public function getLabel(): string { return "failing update steps are removed."; } + #[\Override] public function isNotable(): bool { return true; @@ -55,11 +58,13 @@ public function isNotable(): bool /** * @return \ilDatabaseInitializedObjective[]|ClientIdReadObjective[]|\ilIniFilesPopulatedObjective[] */ + #[\Override] public function getPreconditions(Environment $environment): array { return [new ClientIdReadObjective(), new ilIniFilesPopulatedObjective(), new ilDatabaseInitializedObjective()]; } + #[\Override] public function achieve(Environment $environment): Environment { $environment = parent::achieve($environment); @@ -71,6 +76,7 @@ public function achieve(Environment $environment): Environment /** * @inheritDoc */ + #[\Override] public function isApplicable(Environment $environment): bool { $db = $environment->getResource(Environment::RESOURCE_DATABASE); diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseServerIsConnectableObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseServerIsConnectableObjective.php index 7d93c714266f..8f756806732c 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseServerIsConnectableObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseServerIsConnectableObjective.php @@ -18,7 +18,8 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Environment; +use ILIAS\Setup\UnachievableException; class ilDatabaseServerIsConnectableObjective extends \ilDatabaseObjective { @@ -44,12 +45,12 @@ public function isNotable(): bool return true; } - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { return []; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { $db = \ilDBWrapperFactory::getWrapper($this->config->getType()); $db->initFromIniFile($this->config->toMockIniFile()); @@ -65,7 +66,7 @@ public function achieve(Setup\Environment $environment): Setup\Environment $connect = true; } if (!$connect) { - throw new Setup\UnachievableException( + throw new UnachievableException( "Database cannot be reached. Please check the credentials." ); } @@ -76,7 +77,7 @@ public function achieve(Setup\Environment $environment): Setup\Environment /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { return true; } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseSetupConfig.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseSetupConfig.php index 34b8322cba35..06d7b651fcb2 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseSetupConfig.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseSetupConfig.php @@ -18,10 +18,10 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Config; use ILIAS\Data\Password; -class ilDatabaseSetupConfig implements Setup\Config +class ilDatabaseSetupConfig implements Config { public const DEFAULT_COLLATION = "utf8_general_ci"; public const DEFAULT_PATH_TO_DB_DUMP = "./components/ILIAS/setup_/sql/ilias3.sql"; @@ -30,18 +30,12 @@ class ilDatabaseSetupConfig implements Setup\Config protected string $host; - protected ?int $port = null; - protected string $database; - protected bool $create_database; - protected string $collation; protected string $user; - protected ?\ILIAS\Data\Password $password = null; - protected string $path_to_db_dump; public ilDatabaseSetupConfig $config; @@ -51,10 +45,10 @@ public function __construct( string $host, string $database, string $user, - ?Password $password = null, - bool $create_database = true, + protected ?Password $password = null, + protected bool $create_database = true, ?string $collation = null, - ?int $port = null, + protected ?int $port = null, ?string $path_to_db_dump = null ) { if (!in_array($type, \ilDBConstants::getInstallableTypes())) { @@ -71,10 +65,7 @@ public function __construct( $this->host = trim($host); $this->database = trim($database); $this->user = trim($user); - $this->password = $password; - $this->create_database = $create_database; $this->collation = $collation ? trim($collation) : self::DEFAULT_COLLATION; - $this->port = $port; $this->path_to_db_dump = $path_to_db_dump ?? self::DEFAULT_PATH_TO_DB_DUMP; } @@ -129,7 +120,6 @@ public function getPathToDBDump(): string public function toMockIniFile(): \ilIniFile { return new class ($this) extends \ilIniFile { - protected ilDatabaseSetupConfig $config; /** * reads a single variable from a group * @access public @@ -153,7 +143,7 @@ public function readVariable(string $a_group, string $a_var_name): string return (string) $this->config->getPort(); case "pass": $pw = $this->config->getPassword(); - return $pw ? $pw->toString() : ""; + return $pw !== null ? $pw->toString() : ""; case "name": return $this->config->getDatabase(); case "type": @@ -165,9 +155,8 @@ public function readVariable(string $a_group, string $a_var_name): string } } - public function __construct(\ilDatabaseSetupConfig $config) + public function __construct(protected ilDatabaseSetupConfig $config) { - $this->config = $config; } public function read(): bool { @@ -177,7 +166,7 @@ public function parse(): bool { throw new \LogicException("Just a mock here..."); } - public function fixIniFile(): void + public function fixIniFile(): never { throw new \LogicException("Just a mock here..."); } diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdateStepsExecutedObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdateStepsExecutedObjective.php index 526f9d9a5690..b5efbef4d771 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdateStepsExecutedObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdateStepsExecutedObjective.php @@ -16,9 +16,9 @@ * *********************************************************************/ +use ILIAS\Data\Factory; use ILIAS\Setup\Environment; use ILIAS\Setup\Objective; -use ILIAS\Data; /** * This class attempt to achieve a set of database update steps. Look into the @@ -27,14 +27,11 @@ class ilDatabaseUpdateStepsExecutedObjective implements Objective { public const STEP_METHOD_PREFIX = "step_"; - - protected ilDatabaseUpdateSteps $steps; protected string $steps_class; - public function __construct(ilDatabaseUpdateSteps $steps) + public function __construct(protected ilDatabaseUpdateSteps $steps) { - $this->steps = $steps; - $this->steps_class = get_class($this->steps); + $this->steps_class = $this->steps::class; } /** @@ -68,7 +65,7 @@ final public function isNotable(): bool public function getPreconditions(Environment $environment): array { return [ - new ilNoMajorVersionSkippedConditionObjective(new Data\Factory()), + new ilNoMajorVersionSkippedConditionObjective(new Factory()), new ilDBStepExecutionDBExistsObjective(), new ilDatabaseUpdatedObjective(), new ilDBStepReaderExistsObjective() diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdateStepsMetricsCollectedObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdateStepsMetricsCollectedObjective.php index e208d115392d..3806cbe9634c 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdateStepsMetricsCollectedObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdateStepsMetricsCollectedObjective.php @@ -18,11 +18,12 @@ declare(strict_types=1); -use ILIAS\Setup; +use ILIAS\Setup\Metrics\CollectedObjective; +use ILIAS\Setup\Environment; use ILIAS\Setup\Metrics\Metric; use ILIAS\Setup\Metrics\Storage; -class ilDatabaseUpdateStepsMetricsCollectedObjective extends Setup\Metrics\CollectedObjective +class ilDatabaseUpdateStepsMetricsCollectedObjective extends CollectedObjective { public const STEP_METHOD_PREFIX = "step_"; @@ -31,10 +32,10 @@ class ilDatabaseUpdateStepsMetricsCollectedObjective extends Setup\Metrics\Colle public function __construct(Storage $storage, ilDatabaseUpdateSteps $steps) { parent::__construct($storage); - $this->step_class = get_class($steps); + $this->step_class = $steps::class; } - protected function collectFrom(Setup\Environment $environment, Storage $storage): void + protected function collectFrom(Environment $environment, Storage $storage): void { $execution_log = $environment->getResource(ilDatabaseUpdateStepExecutionLog::class); $step_reader = $environment->getResource(ilDBStepReader::class); @@ -73,7 +74,7 @@ protected function collectFrom(Setup\Environment $environment, Storage $storage) $storage->store($this->step_class, $collection); } - protected function getTentativePreconditions(Setup\Environment $environment): array + protected function getTentativePreconditions(Environment $environment): array { return [ new ilDatabaseInitializedObjective(), @@ -82,11 +83,13 @@ protected function getTentativePreconditions(Setup\Environment $environment): ar ]; } + #[\Override] public function getHash(): string { return hash("sha256", static::class . $this->step_class); } + #[\Override] public function getLabel(): string { return "Status of database update steps in " . $this->step_class; diff --git a/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdatedObjective.php b/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdatedObjective.php index 32a0b1471f7e..c43037a17285 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdatedObjective.php +++ b/components/ILIAS/Database/classes/Setup/class.ilDatabaseUpdatedObjective.php @@ -18,10 +18,13 @@ declare(strict_types=1); -use ILIAS\Setup; -use ILIAS\DI; +use ILIAS\Setup\Objective; +use ILIAS\Setup\Environment; +use ILIAS\Setup\Objective\ClientIdReadObjective; +use ILIAS\DI\Container; +use ILIAS\Setup\UnachievableException; -class ilDatabaseUpdatedObjective implements Setup\Objective +class ilDatabaseUpdatedObjective implements Objective { public function getHash(): string { @@ -39,25 +42,20 @@ public function isNotable(): bool } /** - * @return \ilDatabaseInitializedObjective[]|\ILIAS\Setup\Objective\ClientIdReadObjective[]|\ilIniFilesPopulatedObjective[] + * @return \ilDatabaseInitializedObjective[]|ClientIdReadObjective[]|\ilIniFilesPopulatedObjective[] */ - public function getPreconditions(Setup\Environment $environment): array + public function getPreconditions(Environment $environment): array { - $preconditions = []; - $preconditions[] = new Setup\Objective\ClientIdReadObjective(); - $preconditions[] = new ilIniFilesPopulatedObjective(); - $preconditions[] = new ilDatabaseInitializedObjective(); - - return $preconditions; + return [new ClientIdReadObjective(), new ilIniFilesPopulatedObjective(), new ilDatabaseInitializedObjective()]; } - public function achieve(Setup\Environment $environment): Setup\Environment + public function achieve(Environment $environment): Environment { - $db = $environment->getResource(Setup\Environment::RESOURCE_DATABASE); - $io = $environment->getResource(Setup\Environment::RESOURCE_ADMIN_INTERACTION); - $ini = $environment->getResource(Setup\Environment::RESOURCE_ILIAS_INI); - $client_ini = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI); - $client_id = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_ID); + $db = $environment->getResource(Environment::RESOURCE_DATABASE); + $io = $environment->getResource(Environment::RESOURCE_ADMIN_INTERACTION); + $ini = $environment->getResource(Environment::RESOURCE_ILIAS_INI); + $client_ini = $environment->getResource(Environment::RESOURCE_CLIENT_INI); + $client_id = $environment->getResource(Environment::RESOURCE_CLIENT_ID); // ATTENTION: This is a total abomination. It only exists to allow the db- // update to run. This is a memento to the fact, that dependency injection @@ -65,15 +63,13 @@ public function achieve(Setup\Environment $environment): Setup\Environment // locate the whole world via the global $DIC. /** @noRector */ $DIC = $GLOBALS["DIC"] ?? []; - $GLOBALS["DIC"] = new DI\Container(); + $GLOBALS["DIC"] = new Container(); $GLOBALS["DIC"]["ilDB"] = $db; $GLOBALS["ilDB"] = $db; $GLOBALS["DIC"]["ilBench"] = null; $GLOBALS["DIC"]["ilLog"] = new class ($io) { - protected $io; - public function __construct($io) + public function __construct(protected $io) { - $this->io = $io; } public function write(): void @@ -89,9 +85,9 @@ public function warning($msg): void $this->io->inform($msg); } - public function error($msg): void + public function error($msg): never { - throw new Setup\UnachievableException( + throw new UnachievableException( "Problem in DB-Update: $msg" ); } @@ -149,7 +145,7 @@ public function setIniFile(): void /** * @inheritDoc */ - public function isApplicable(Setup\Environment $environment): bool + public function isApplicable(Environment $environment): bool { return true; } diff --git a/components/ILIAS/Database/classes/Setup/class.ilMysqlMyIsamToInnoDbMigration.php b/components/ILIAS/Database/classes/Setup/class.ilMysqlMyIsamToInnoDbMigration.php index c4d2c128974c..4bf402a595d0 100755 --- a/components/ILIAS/Database/classes/Setup/class.ilMysqlMyIsamToInnoDbMigration.php +++ b/components/ILIAS/Database/classes/Setup/class.ilMysqlMyIsamToInnoDbMigration.php @@ -22,7 +22,6 @@ use ilDatabaseUpdatedObjective; use ilDBConstants; use ilException; -use ILIAS\Setup; use ilIniFilesLoadedObjective; class ilMysqlMyIsamToInnoDbMigration implements Migration diff --git a/components/ILIAS/Database/classes/class.ilBenchmark.php b/components/ILIAS/Database/classes/class.ilBenchmark.php index 3d61a524760c..70b7c1860f41 100755 --- a/components/ILIAS/Database/classes/class.ilBenchmark.php +++ b/components/ILIAS/Database/classes/class.ilBenchmark.php @@ -37,7 +37,7 @@ class ilBenchmark private bool $stop_db_recording = false; - private int $bench_max_records; + private int $bench_max_records = 2000; private ?bool $db_bechmark_enabled = null; private ?int $db_bechmark_user_id = null; @@ -49,8 +49,7 @@ public function __construct() { global $DIC; $this->dic = $DIC; - $this->initSettins(); - $this->bench_max_records = 2000;//(int) ($this->retrieveSetting("bench_max_records") ?? 0); + $this->initSettins();//(int) ($this->retrieveSetting("bench_max_records") ?? 0); } private function initSettins(): void diff --git a/components/ILIAS/Database/classes/class.ilDBAnalyzer.php b/components/ILIAS/Database/classes/class.ilDBAnalyzer.php index b81c0baf33da..696426b5d640 100755 --- a/components/ILIAS/Database/classes/class.ilDBAnalyzer.php +++ b/components/ILIAS/Database/classes/class.ilDBAnalyzer.php @@ -35,7 +35,7 @@ class ilDBAnalyzer protected ilDBReverse $reverse; - protected ilDBInterface$il_db; + protected ilDBInterface $il_db; protected array $allowed_attributes; @@ -69,7 +69,7 @@ public function __construct(?ilDBInterface $ilDBInterface = null) public function getFieldInformation(string $a_table, bool $a_remove_not_allowed_attributes = false): array { $fields = $this->manager->listTableFields($a_table); - $inf = array(); + $inf = []; foreach ($fields as $field) { $rdef = $this->reverse->getTableFieldDefinition($a_table, $field); // is this possible? @@ -88,7 +88,7 @@ public function getFieldInformation(string $a_table, bool $a_remove_not_allowed_ } } - $inf[$field] = array( + $inf[$field] = [ "notnull" => $rdef[$best_alt]["notnull"] ?? null, "nativetype" => $rdef[$best_alt]["nativetype"] ?? null, "length" => $rdef[$best_alt]["length"] ?? null, @@ -98,7 +98,7 @@ public function getFieldInformation(string $a_table, bool $a_remove_not_allowed_ "autoincrement" => $rdef[$best_alt]["autoincrement"] ?? null, "type" => $rdef[$best_alt]["type"] ?? null, "alt_types" => $alt_types, - ); + ]; if ($a_remove_not_allowed_attributes) { foreach (array_keys($inf[$field]) as $k) { @@ -116,10 +116,10 @@ public function getFieldInformation(string $a_table, bool $a_remove_not_allowed_ /** * @return int|string */ - public function getBestDefinitionAlternative(array $a_def) + public function getBestDefinitionAlternative(array $a_def): int|string { // determine which type to choose - $car = array( + $car = [ "boolean" => 10, "integer" => 20, "decimal" => 30, @@ -130,7 +130,7 @@ public function getBestDefinitionAlternative(array $a_def) "text" => 80, "clob" => 90, "blob" => 100, - ); + ]; $cur_car = 0; $best_alt = 0; // best alternatice @@ -182,10 +182,10 @@ public function getPrimaryKeyInformation(string $a_table): array if ($info["primary"]) { $pk["name"] = $c; foreach ($info["fields"] as $k => $f) { - $pk["fields"][$k] = array( + $pk["fields"][$k] = [ "position" => $f["position"], "sorting" => $f["sorting"], - ); + ]; } } } @@ -207,7 +207,7 @@ public function getIndicesInformation(string $a_table, bool $a_abstract_table = $indexes = $this->manager->listTableIndexes($a_table); // get additional information if database is MySQL - $mysql_info = array(); + $mysql_info = []; $set = $this->il_db->query("SHOW INDEX FROM " . $a_table); while ($rec = $this->il_db->fetchAssoc($set)) { @@ -219,11 +219,11 @@ public function getIndicesInformation(string $a_table, bool $a_abstract_table = } - $ind = array(); + $ind = []; foreach ($indexes as $c) { $info = $this->reverse->getTableIndexDefinition($a_table, $c); - $i = array(); + $i = []; if (!$info["primary"]) { $i["name"] = $c; $i["fulltext"] = false; @@ -236,10 +236,10 @@ public function getIndicesInformation(string $a_table, bool $a_abstract_table = $i["fulltext"] = true; } foreach ($info["fields"] as $k => $f) { - $i["fields"][$k] = array( + $i["fields"][$k] = [ "position" => $f["position"], "sorting" => $f["sorting"], - ); + ]; } $ind[] = $i; } @@ -260,18 +260,18 @@ public function getConstraintsInformation(string $a_table, bool $a_abstract_tabl { $constraints = $this->manager->listTableConstraints($a_table); - $cons = array(); + $cons = []; foreach ($constraints as $c) { $info = $this->reverse->getTableConstraintDefinition($a_table, $c); - $i = array(); + $i = []; if ($info["unique"] ?? null) { $i["name"] = $c; $i["type"] = "unique"; foreach ($info["fields"] as $k => $f) { - $i["fields"][$k] = array( + $i["fields"][$k] = [ "position" => $f["position"], "sorting" => $f["sorting"], - ); + ]; } $cons[] = $i; } @@ -289,7 +289,7 @@ public function getConstraintsInformation(string $a_table, bool $a_abstract_tabl * @throws \ilDatabaseException * @deprecated Please do not use since this method will lead to a ilDatabaseException. Will be removed later */ - public function hasSequence(string $a_table) + public function hasSequence(string $a_table): int|float|false { $seq = $this->manager->listSequences(); if (is_array($seq) && in_array($a_table, $seq)) { diff --git a/components/ILIAS/Database/classes/class.ilDBConstants.php b/components/ILIAS/Database/classes/class.ilDBConstants.php index a076b14c84c1..551992ea10f8 100755 --- a/components/ILIAS/Database/classes/class.ilDBConstants.php +++ b/components/ILIAS/Database/classes/class.ilDBConstants.php @@ -93,7 +93,7 @@ class ilDBConstants /** * @var string[] */ - protected static array $descriptions = array( + protected static array $descriptions = [ // Main ilDBConstants::TYPE_MYSQL => "MySQL 5.7.x or higher with InnoDB-Engine", ilDBConstants::TYPE_MYSQLI => "MySQL 5.7.x or higher with InnoDB-Engine", @@ -101,7 +101,7 @@ class ilDBConstants ilDBConstants::TYPE_GALERA => "Galera-Cluster (experimental)", // Development identifiers (will be removed in 5.3) ilDBConstants::TYPE_PDO_MYSQL_GALERA => "Galera-Cluster (experimental) [developers-identifier]", - ); + ]; /** @@ -109,21 +109,21 @@ class ilDBConstants */ public static function getInstallableTypes(): array { - return array( + return [ // Main ilDBConstants::TYPE_MYSQL, ilDBConstants::TYPE_INNODB, // Experimental ilDBConstants::TYPE_GALERA, ilDBConstants::TYPE_GALERA, - ); + ]; } public static function getAvailableTypes(bool $with_descriptions = true): array { $types = self::getSupportedTypes(); if ($with_descriptions) { - $return = array(); + $return = []; foreach ($types as $type) { $return [$type] = self::describe($type); } @@ -136,11 +136,11 @@ public static function getAvailableTypes(bool $with_descriptions = true): array public static function getSupportedTypes(): array { - return array( + return [ ilDBConstants::TYPE_MYSQL, ilDBConstants::TYPE_INNODB, ilDBConstants::TYPE_GALERA, - ); + ]; } /** diff --git a/components/ILIAS/Database/classes/class.ilDBGenerator.php b/components/ILIAS/Database/classes/class.ilDBGenerator.php index c720d9950d93..25fdf07d91f4 100755 --- a/components/ILIAS/Database/classes/class.ilDBGenerator.php +++ b/components/ILIAS/Database/classes/class.ilDBGenerator.php @@ -28,10 +28,10 @@ class ilDBGenerator { protected string $target_encoding = 'UTF-8'; - protected array $whitelist = array(); - protected array $blacklist = array(); - protected array $tables = array(); - protected array $filter = array(); + protected array $whitelist = []; + protected array $blacklist = []; + protected array $tables = []; + protected array $filter = []; protected ilDBManager $manager; protected ilDBReverse $reverse; protected ilDBInterface $il_db; @@ -65,7 +65,7 @@ public static function lookupAbstractedTables(): array $query = "SELECT DISTINCT(table_name) FROM abstraction_progress "; $res = $ilDB->query($query); - $names = array(); + $names = []; while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { $names[] = $row->table_name; } @@ -73,7 +73,7 @@ public static function lookupAbstractedTables(): array // tables that have been already created in an abstracted // way or tables that have been renamed after being abstracted // (see db_update script) - $abs_tables = array_merge($names, array( + $abs_tables = array_merge($names, [ 'acc_access_key', 'acc_user_access_key', 'ldap_rg_mapping', @@ -120,7 +120,7 @@ public static function lookupAbstractedTables(): array 'tst_rnd_cpy', 'tst_rnd_qpl_title', 'qpl_a_mdef', - )); + ]); return $abs_tables; } @@ -202,13 +202,8 @@ public function checkProcessing(string $a_table): bool if (in_array($a_table, $this->blacklist, true)) { return false; } - // check white list - if (count($this->whitelist) > 0 && !in_array($a_table, $this->whitelist, true)) { - return false; - } - - return true; + return !($this->whitelist !== [] && !in_array($a_table, $this->whitelist, true)); } /** @@ -218,7 +213,7 @@ protected function openFile(string $a_path) { $start = ''; $file = fopen($a_path, 'wb'); - $start .= "\t" . 'global $ilDB;' . "\n\n"; + $start .= ' global $ilDB;' . "\n\n"; fwrite($file, $start); return $file; @@ -251,7 +246,7 @@ public function buildDBGenerationScript(string $a_filename = ""): void $file = fopen($a_filename, 'wb'); $start = '"; @@ -282,14 +277,14 @@ public function buildDBGenerationScript(string $a_filename = ""): void // auto increment sequence $this->buildCreateSequenceStatement($table, $file); - if (in_array($table, array('usr_session_stats', 'usr_session_raw', 'il_plugin'))) { + if (in_array($table, ['usr_session_stats', 'usr_session_raw', 'il_plugin'])) { continue; } // inserts if ($is_dir) { $this->buildInsertStatement($table, $path); - #$this->buildInsertStatementsXML($table,$path); + #$this->buildInsertStatementsXML($table,$path); } else { $this->buildInsertStatements($table, $file); } @@ -352,7 +347,7 @@ public function buildCreateTableStatement(string $a_table, $a_file = null): void $a_sep = ","; } } - $create_st .= "\t" . ')' . "\n"; + $create_st .= ' )' . "\n"; } $create_st .= ');' . "\n"; $create_st .= '$ilDB->createTable("' . $a_table . '", $fields);' . "\n"; @@ -371,10 +366,10 @@ public function buildAddPrimaryKeyStatement(string $a_table, $a_file = null): vo { $pk = $this->analyzer->getPrimaryKeyInformation($a_table); - if (isset($pk["fields"]) && is_array($pk["fields"]) && count($pk["fields"]) > 0) { + if (isset($pk["fields"]) && is_array($pk["fields"]) && $pk["fields"] !== []) { $pk_st = "\n" . '$pk_fields = array('; $sep = ""; - foreach ($pk["fields"] as $f => $pos) { + foreach (array_keys($pk["fields"]) as $f) { $pk_st .= $sep . '"' . $f . '"'; $sep = ","; } @@ -398,11 +393,7 @@ public function buildAddIndexStatements(string $a_table, $a_file = null): void if (is_array($ind)) { foreach ($ind as $i) { - if ($i["fulltext"]) { - $ft = ", true"; - } else { - $ft = ", false"; - } + $ft = $i["fulltext"] ? ", true" : ", false"; $in_st = "\n" . '$in_fields = array('; $sep = ""; foreach ($i["fields"] as $f => $pos) { @@ -514,16 +505,16 @@ public function buildInsertStatement(string $a_table, string $a_basedir): bool $filenum = 1; while ($rec = $this->il_db->fetchAssoc($set)) { - $values = array(); + $values = []; foreach ($rec as $f => $v) { if ($this->fields[$f]['type'] === 'text' && $this->fields[$f]['length'] >= 1000) { $v = $this->shortenText($a_table, $f, $v, $this->fields[$f]['length']); } - $values[$f] = array( + $values[$f] = [ $this->fields[$f]['type'], $v, - ); + ]; } $rows[$a_table][$row++] = $values; @@ -564,10 +555,10 @@ public function buildInsertStatements(string $a_table, $file_handle = null): voi $set = $this->il_db->query("SELECT * FROM " . $this->il_db->quoteIdentifier($a_table)); $ins_st = ""; while ($rec = $this->il_db->fetchAssoc($set)) { - $fields = array(); - $types = array(); - $values = array(); - $i_str = array(); + $fields = []; + $types = []; + $values = []; + $i_str = []; foreach ($rec as $f => $v) { $v = str_replace('\\', '\\\\', $v); $i_str[] = "'" . $f . "' => array('" . $this->fields[$f]["type"] . "', '" . str_replace( @@ -602,7 +593,7 @@ protected function shortenText(string $table, string $field, string $a_value, in // Convert back to UTF-8 $shortened = mb_convert_encoding($shortened, 'UTF-8', $this->getTargetEncoding()); - if (strlen($a_value) != strlen($shortened)) { + if (strlen($a_value) !== strlen($shortened)) { $ilLogger->log('Table : ' . $table); $ilLogger->log('Field : ' . $field); $ilLogger->log('Type : ' . $this->fields[$field]['type']); diff --git a/components/ILIAS/Database/classes/class.ilDBUpdate.php b/components/ILIAS/Database/classes/class.ilDBUpdate.php index 49526e814990..3ada9b047045 100755 --- a/components/ILIAS/Database/classes/class.ilDBUpdate.php +++ b/components/ILIAS/Database/classes/class.ilDBUpdate.php @@ -28,12 +28,10 @@ class ilDBUpdate { protected string $updateMsg; - protected ilDBInterface $db; - protected ?ilIniFile $client_ini = null; protected Iterator $ctrl_structure_iterator; protected string $error; - protected string $PATH = './'; + protected string $PATH = "./"; protected array $filecontent; @@ -43,12 +41,8 @@ class ilDBUpdate private ilSetting $custom_updates_setting; private array $custom_updates_content = []; - public function __construct(ilDBInterface $a_db_handler, ?ilIniFile $client_ini = null) + public function __construct(protected ilDBInterface $db, protected ?ilIniFile $client_ini = null) { - $this->client_ini = $client_ini; - $this->db = $a_db_handler; - $this->PATH = "./"; - $class_map = require ILIAS_ABSOLUTE_PATH . '/vendor/composer/vendor/composer/autoload_classmap.php'; $this->ctrl_structure_iterator = new ilCtrlArrayIterator($class_map); } @@ -61,12 +55,12 @@ private function execQuery(ilDBInterface $db, string $str): bool $sql[$i] = trim($statement); if ($statement !== "" && $statement[0] !== "#") { //take line per line, until last char is ";" - if (substr($statement, -1) === ";") { + if (str_ends_with($statement, ";")) { //query is complete /** @noinspection PhpUndefinedVariableInspection */ $q .= " " . substr($statement, 0, -1); $check = $this->checkQuery($q); - if ($check === true) { + if ($check) { $db->query($q); } else { $this->error = (string) $check; @@ -115,7 +109,7 @@ protected function initGlobalsRequiredForUpdateSteps( $GLOBALS['ilCtrlStructureReader'] = $ilCtrlStructureReader; - if ($this->client_ini) { + if ($this->client_ini !== null) { $ilCtrlStructureReader->setIniFile($this->client_ini); } $ilDB = $DIC->database(); @@ -138,7 +132,7 @@ protected function applyUpdateNr(int $nr, bool $custom_update = false): bool $i = 0; //go through filecontent - while (!preg_match("/^\<\#" . $nr . ">/", $this->filecontent[$i]) && $i < count($this->filecontent)) { + while (!preg_match("/^\<\#" . $nr . ">/", (string) $this->filecontent[$i]) && $i < count($this->filecontent)) { $i++; } @@ -153,8 +147,8 @@ protected function applyUpdateNr(int $nr, bool $custom_update = false): bool //update found, now extract this update to a new array $update = []; - while ($i < count($this->filecontent) && !preg_match("/^<#" . ($nr + 1) . ">/", $this->filecontent[$i])) { - $update[] = trim($this->filecontent[$i]); + while ($i < count($this->filecontent) && !preg_match("/^<#" . ($nr + 1) . ">/", (string) $this->filecontent[$i])) { + $update[] = trim((string) $this->filecontent[$i]); $i++; } @@ -165,7 +159,7 @@ protected function applyUpdateNr(int $nr, bool $custom_update = false): bool foreach ($update as $row) { if (preg_match("/<\?php/", $row)) { - if (count($sql) > 0) { + if ($sql !== []) { if ($this->execQuery($this->db, implode("\n", $sql)) === false) { return false; } @@ -173,7 +167,7 @@ protected function applyUpdateNr(int $nr, bool $custom_update = false): bool } $mode = 'php'; } elseif (preg_match("/\?>/", $row)) { - if (count($php) > 0) { + if ($php !== []) { $code = implode("\n", $php); if (eval($code) === false) { $this->error = 'Parse error: ' . $code; @@ -194,7 +188,7 @@ protected function applyUpdateNr(int $nr, bool $custom_update = false): bool } } - if ($mode === 'sql' && count($sql) > 0 && $this->execQuery($this->db, implode("\n", $sql)) === false) { + if ($mode === 'sql' && $sql !== [] && $this->execQuery($this->db, implode("\n", $sql)) === false) { $this->error = "dump_error: " . $this->error; return false; @@ -241,7 +235,7 @@ private function readCustomUpdatesFileVersion(array $a_file_content): int $regs = []; $version = 0; foreach ($a_file_content as $row) { - if (preg_match("/^<#([0-9]+)>/", $row, $regs)) { + if (preg_match("/^<#(\\d+)>/", (string) $row, $regs)) { $version = $regs[1]; } } diff --git a/components/ILIAS/Database/classes/class.ilDBWrapperFactory.php b/components/ILIAS/Database/classes/class.ilDBWrapperFactory.php index 0102592ca1cd..1a6873b74469 100755 --- a/components/ILIAS/Database/classes/class.ilDBWrapperFactory.php +++ b/components/ILIAS/Database/classes/class.ilDBWrapperFactory.php @@ -38,17 +38,11 @@ class ilDBWrapperFactory */ public static function getWrapper(string $a_type): \ilDBPdoInterface { - switch ($a_type) { - case 'pdo-mysql-innodb': - case ilDBConstants::TYPE_INNODB: - $ilDB = new ilDBPdoMySQLInnoDB(); - break; - case ilDBConstants::TYPE_GALERA: - $ilDB = new ilDBPdoMySQLGalera(); - break; - default: - throw new ilDatabaseException("No viable database-type given: " . var_export($a_type, true)); - } + $ilDB = match ($a_type) { + 'pdo-mysql-innodb', ilDBConstants::TYPE_INNODB => new ilDBPdoMySQLInnoDB(), + ilDBConstants::TYPE_GALERA => new ilDBPdoMySQLGalera(), + default => throw new ilDatabaseException("No viable database-type given: " . var_export($a_type, true)), + }; return $ilDB; } diff --git a/components/ILIAS/Database/exceptions/exception.ilAtomQueryException.php b/components/ILIAS/Database/exceptions/exception.ilAtomQueryException.php index 03f21ed90954..38950a597897 100755 --- a/components/ILIAS/Database/exceptions/exception.ilAtomQueryException.php +++ b/components/ILIAS/Database/exceptions/exception.ilAtomQueryException.php @@ -37,6 +37,7 @@ class ilAtomQueryException extends ilDatabaseException public const DB_ATOM_IDENTICAL_TABLES = 10909; + #[\Override] protected function tranlateException(int $code): string { $message = 'An undefined Exception occured'; diff --git a/components/ILIAS/Database/tests/Integrity/Suite.php b/components/ILIAS/Database/tests/Integrity/Suite.php index 4119720024ae..12b0410e705a 100755 --- a/components/ILIAS/Database/tests/Integrity/Suite.php +++ b/components/ILIAS/Database/tests/Integrity/Suite.php @@ -36,7 +36,7 @@ public static function suite(): Suite foreach (self::collectTestFiles() as $file) { require_once $file->getRealPath(); - $suite->addTestSuite($namespace . preg_replace('/.php$/', '', $file->getFileName())); + $suite->addTestSuite($namespace . preg_replace('/.php$/', '', (string) $file->getFileName())); } return $suite; diff --git a/components/ILIAS/Database/tests/Setup/ilDBStepExecutionDBTest.php b/components/ILIAS/Database/tests/Setup/ilDBStepExecutionDBTest.php index 20d3aad58ff4..5678cbc83f96 100755 --- a/components/ILIAS/Database/tests/Setup/ilDBStepExecutionDBTest.php +++ b/components/ILIAS/Database/tests/Setup/ilDBStepExecutionDBTest.php @@ -16,6 +16,7 @@ * *********************************************************************/ +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class ilDBStepExecutionDBTest extends TestCase @@ -23,15 +24,15 @@ class ilDBStepExecutionDBTest extends TestCase public const CLASS_NAME_200 = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; public const CLASS_NAME_201 = "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; /** - * @var ilDBInterface|(ilDBInterface&object&\PHPUnit\Framework\MockObject\MockObject)|(ilDBInterface&\PHPUnit\Framework\MockObject\MockObject)|(object&\PHPUnit\Framework\MockObject\MockObject)|\PHPUnit\Framework\MockObject\MockObject + * @var ilDBInterface|ilDBInterface&object&MockObject|ilDBInterface&MockObject|object&MockObject|MockObject */ - private ilDBInterface|\PHPUnit\Framework\MockObject\MockObject $db; + private ilDBInterface|MockObject $db; private ilDBStepExecutionDB $execution_db; protected function setUp(): void { $this->db = $this->createMock(\ilDBInterface::class); - $this->execution_db = new \ilDBStepExecutionDB($this->db, fn() => new \DateTime()); + $this->execution_db = new \ilDBStepExecutionDB($this->db, fn(): \DateTime => new \DateTime()); } public function testStartedThrowsOnLongClassName(): void @@ -65,7 +66,7 @@ public function testStartedThrowsOnStartStepNotLargerThenLastFinishedStep(): voi $execution_db = $this->getMockBuilder(\ilDBStepExecutionDB::class) ->onlyMethods(["getLastStartedStep", "getLastFinishedStep"]) - ->setConstructorArgs([$this->db, fn() => new \DateTime($NOW)]) + ->setConstructorArgs([$this->db, fn(): \DateTime => new \DateTime($NOW)]) ->getMock(); $execution_db->expects($this->once()) @@ -84,7 +85,7 @@ public function testStartedThrowsWhenLastStepNotFinished(): void $execution_db = $this->getMockBuilder(\ilDBStepExecutionDB::class) ->onlyMethods(["getLastStartedStep", "getLastFinishedStep"]) - ->setConstructorArgs([$this->db, fn() => new \DateTime($NOW)]) + ->setConstructorArgs([$this->db, fn(): \DateTime => new \DateTime($NOW)]) ->getMock(); $execution_db->expects($this->once()) @@ -110,7 +111,7 @@ public function testFinishedThrowsWhenOtherStepThenLastIsFinished(): void $execution_db = $this->getMockBuilder(\ilDBStepExecutionDB::class) ->onlyMethods(["getLastStartedStep", "getLastFinishedStep"]) - ->setConstructorArgs([$this->db, fn() => new \DateTime($NOW)]) + ->setConstructorArgs([$this->db, fn(): \DateTime => new \DateTime($NOW)]) ->getMock(); $execution_db->expects($this->once()) @@ -156,7 +157,7 @@ public function testStartedWritesToDB(): void $execution_db = $this->getMockBuilder(\ilDBStepExecutionDB::class) ->onlyMethods(["getLastStartedStep", "getLastFinishedStep"]) - ->setConstructorArgs([$this->db, fn() => new \DateTime($NOW)]) + ->setConstructorArgs([$this->db, fn(): \DateTime => new \DateTime($NOW)]) ->getMock(); $execution_db->expects($this->once()) @@ -190,7 +191,7 @@ public function testFinishedWritesToDB(): void $execution_db = $this->getMockBuilder(\ilDBStepExecutionDB::class) ->onlyMethods(["getLastStartedStep", "getLastFinishedStep"]) - ->setConstructorArgs([$this->db, fn() => new \DateTime($NOW)]) + ->setConstructorArgs([$this->db, fn(): \DateTime => new \DateTime($NOW)]) ->getMock(); $execution_db->expects($this->once()) @@ -221,7 +222,7 @@ public function testGetLastStartedStepQueriesDB(): void $this->db->expects($this->once()) ->method("quote") ->willReturnCallback( - function ($field, $type) { + function ($field, $type): string { $this->assertEquals(self::CLASS_NAME_200, $field); $this->assertEquals('text', $type); return 'CLASS'; @@ -251,7 +252,7 @@ public function testGetLastFinishedStepQueriesDB(): void $this->db->expects($this->once()) ->method("quote") ->willReturnCallback( - function ($field, $type) { + function ($field, $type): string { $this->assertEquals(self::CLASS_NAME_200, $field); $this->assertEquals('text', $type); return 'CLASS'; diff --git a/components/ILIAS/Database/tests/Setup/ilDBStepReaderTest.php b/components/ILIAS/Database/tests/Setup/ilDBStepReaderTest.php index 2ee9d90e1c50..8bb3beec3c2a 100755 --- a/components/ILIAS/Database/tests/Setup/ilDBStepReaderTest.php +++ b/components/ILIAS/Database/tests/Setup/ilDBStepReaderTest.php @@ -22,6 +22,10 @@ class ilDBStepReaderTestObject extends ilDBStepReader { + /** + * @var mixed[] + */ + public $step_numbers; public function setStepNumbers(array $arr): void { $this->step_numbers = $arr; diff --git a/components/ILIAS/Database/tests/Setup/ilDatabaseUpdateStepsExecutedObjectiveTest.php b/components/ILIAS/Database/tests/Setup/ilDatabaseUpdateStepsExecutedObjectiveTest.php index b79f981890d0..d5b623299c51 100755 --- a/components/ILIAS/Database/tests/Setup/ilDatabaseUpdateStepsExecutedObjectiveTest.php +++ b/components/ILIAS/Database/tests/Setup/ilDatabaseUpdateStepsExecutedObjectiveTest.php @@ -17,7 +17,6 @@ *********************************************************************/ use PHPUnit\Framework\TestCase; - use ILIAS\Setup\Environment; use ILIAS\Setup\ArrayEnvironment; @@ -108,11 +107,8 @@ public function getLastFinishedStep(string $class): int public function testUsesExecutionLock(): void { $execution_log = new class ($this) implements ilDatabaseUpdateStepExecutionLog { - protected ilDatabaseUpdateStepsExecutedObjectiveTest $test; - - public function __construct(ilDatabaseUpdateStepsExecutedObjectiveTest $test) + public function __construct(protected ilDatabaseUpdateStepsExecutedObjectiveTest $test) { - $this->test = $test; } public function started(string $class, int $step): void { diff --git a/components/ILIAS/File/File.php b/components/ILIAS/File/File.php index 354fc722f42b..1ae7f0b6c4da 100644 --- a/components/ILIAS/File/File.php +++ b/components/ILIAS/File/File.php @@ -20,7 +20,11 @@ namespace ILIAS; -class File implements Component\Component +use ILIAS\Component\Component; +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Factory; + +class File implements Component { public function init( array | \ArrayAccess &$define, @@ -32,9 +36,9 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $contribute[\ILIAS\Setup\Agent::class] = static fn() => + $contribute[Agent::class] = static fn(): \ilFileObjectAgent => new \ilFileObjectAgent( - $pull[\ILIAS\Refinery\Factory::class] + $pull[Factory::class] ); } } diff --git a/components/ILIAS/File/classes/Capabilities/CapabilityCollection.php b/components/ILIAS/File/classes/Capabilities/CapabilityCollection.php index 826fc75c65d0..3ee3aa74e337 100644 --- a/components/ILIAS/File/classes/Capabilities/CapabilityCollection.php +++ b/components/ILIAS/File/classes/Capabilities/CapabilityCollection.php @@ -20,8 +20,6 @@ namespace ILIAS\File\Capabilities; -use ILIAS\components\WOPI\Discovery\ActionRepository; - /** * @author Fabian Schmid */ diff --git a/components/ILIAS/File/classes/Capabilities/Check/ForcedInfo.php b/components/ILIAS/File/classes/Capabilities/Check/ForcedInfo.php index cc6e286609df..ccbfc8b67c76 100644 --- a/components/ILIAS/File/classes/Capabilities/Check/ForcedInfo.php +++ b/components/ILIAS/File/classes/Capabilities/Check/ForcedInfo.php @@ -30,11 +30,13 @@ */ class ForcedInfo extends Info implements Check { + #[\Override] public function canUnlock(): Capabilities { return Capabilities::FORCED_INFO_PAGE; } + #[\Override] public function maybeUnlock( Capability $capability, CheckHelpers $helpers, diff --git a/components/ILIAS/File/classes/Icons/IconAbstractRepository.php b/components/ILIAS/File/classes/Icons/IconAbstractRepository.php index 27eb8ac413fe..08deae470a58 100755 --- a/components/ILIAS/File/classes/Icons/IconAbstractRepository.php +++ b/components/ILIAS/File/classes/Icons/IconAbstractRepository.php @@ -20,12 +20,14 @@ namespace ILIAS\File\Icon; +use ILIAS\Refinery\Factory; + /** * @author Lukas Zehnder */ abstract class IconAbstractRepository implements IconRepositoryInterface { - private \ILIAS\Refinery\Factory $refinery; + private Factory $refinery; public function __construct() { @@ -44,7 +46,7 @@ final public function turnSuffixesArrayIntoString(array $a_suffixes): string final public function turnSuffixesStringIntoArray(string $a_suffixes): array { $a_suffixes = preg_replace('/\s+/', '', $a_suffixes); - return explode(",", $a_suffixes); + return explode(",", (string) $a_suffixes); } final public function hasSuffixInputOnlyAllowedCharacters(array $a_suffixes): bool diff --git a/components/ILIAS/File/classes/Icons/IconDatabaseRepository.php b/components/ILIAS/File/classes/Icons/IconDatabaseRepository.php index 78cf8a6fa65a..b48c8eb2dacc 100755 --- a/components/ILIAS/File/classes/Icons/IconDatabaseRepository.php +++ b/components/ILIAS/File/classes/Icons/IconDatabaseRepository.php @@ -43,8 +43,8 @@ public function __construct( ) { global $DIC; parent::__construct(); - $this->db = $this->db ?? $DIC->database(); - $this->irss = $this->irss ?? $DIC->resourceStorage(); + $this->db ??= $DIC->database(); + $this->irss ??= $DIC->resourceStorage(); } public function createIcon(string $a_rid, bool $a_active, bool $a_is_default_icon, array $a_suffixes): Icon @@ -78,8 +78,8 @@ public function getIconsForFilter(array $filter): array $rid_filter = null; // due to the database schema, the suffixes filter has to be handled separately if ($filter !== [] && ($filter['suffixes'] ?? null) !== null && $filter['suffixes'] !== '') { - $suffixes = explode(',', $filter['suffixes']); - $suffixes = array_map(fn($suffix) => $this->db->quote(trim($suffix), 'text'), $suffixes); + $suffixes = explode(',', (string) $filter['suffixes']); + $suffixes = array_map(fn($suffix): string => $this->db->quote(trim((string) $suffix), 'text'), $suffixes); $q = "SELECT rid FROM " . self::SUFFIX_TABLE_NAME . " WHERE suffix IN (" . implode(',', $suffixes) . ")"; $rid_filter = $this->db->fetchAll($this->db->query($q)); $rid_filter = array_map(fn($row) => $row['rid'], $rid_filter); @@ -100,7 +100,7 @@ public function getIconsForFilter(array $filter): array } if ($rid_filter) { - $rid_filter = array_map(fn($rid) => $this->db->quote(trim($rid), 'text'), $rid_filter); + $rid_filter = array_map(fn($rid): string => $this->db->quote(trim((string) $rid), 'text'), $rid_filter); $query .= " AND i.rid IN (" . implode(',', $rid_filter) . ")"; } @@ -127,7 +127,7 @@ public function getIconsForFilter(array $filter): array } /** - * @return array + * @return array */ public function getIcons(): array { diff --git a/components/ILIAS/File/classes/Icons/IconFormUI.php b/components/ILIAS/File/classes/Icons/IconFormUI.php index f7fa9144ecc5..b903db0b2ee3 100755 --- a/components/ILIAS/File/classes/Icons/IconFormUI.php +++ b/components/ILIAS/File/classes/Icons/IconFormUI.php @@ -20,6 +20,8 @@ namespace ILIAS\File\Icon; +use ILIAS\UI\Factory; +use ILIAS\UI\Component\Input\Container\Form\Standard; use ILIAS\FileUpload\MimeType; use ILIAS\HTTP\Wrapper\WrapperFactory; @@ -42,22 +44,16 @@ class IconFormUI private \ilCtrl $ctrl; private \ilLanguage $lng; private \ilTabsGUI $tabs; - private \ILIAS\UI\Factory $ui_factory; + private Factory $ui_factory; private WrapperFactory $wrapper; - private \ILIAS\UI\Component\Input\Container\Form\Standard $icon_form; + private Standard $icon_form; private \ILIAS\Refinery\Factory $refinery; - private Icon $icon; - private string $mode; - private IconRepositoryInterface $icon_repo; public function __construct( - Icon $icon, - string $mode, - IconRepositoryInterface $icon_repo + private Icon $icon, + private string $mode, + private IconRepositoryInterface $icon_repo ) { - $this->icon = $icon; - $this->mode = $mode; - $this->icon_repo = $icon_repo; global $DIC; $this->ctrl = $DIC->ctrl(); $this->lng = $DIC->language(); @@ -79,7 +75,7 @@ protected function initIconForm(): void ); $this->tabs->setBackTarget($this->lng->txt('back'), $back_target); - if ($this->mode == self::MODE_EDIT) { + if ($this->mode === self::MODE_EDIT) { $form_title = $this->lng->txt(self::FORM_ICON_UPDATING); $form_action = $this->ctrl->getFormActionByClass( ilObjFileIconsOverviewGUI::class, @@ -123,17 +119,11 @@ protected function initIconForm(): void )->withValue( $this->icon_repo->turnSuffixesArrayIntoString($this->icon->getSuffixes()) )->withAdditionalTransformation( - $this->refinery->custom()->transformation(function ($suffixes_input): array { - return $this->icon_repo->turnSuffixesStringIntoArray($suffixes_input); - }) + $this->refinery->custom()->transformation(fn($suffixes_input): array => $this->icon_repo->turnSuffixesStringIntoArray($suffixes_input)) )->withAdditionalTransformation( - $this->refinery->custom()->constraint(function ($suffixes_input): bool { - return $this->icon_repo->hasSuffixInputOnlyAllowedCharacters($suffixes_input); - }, $this->lng->txt('msg_error_suffixes_with_forbidden_characters')) + $this->refinery->custom()->constraint(fn($suffixes_input): bool => $this->icon_repo->hasSuffixInputOnlyAllowedCharacters($suffixes_input), $this->lng->txt('msg_error_suffixes_with_forbidden_characters')) )->withAdditionalTransformation( - $this->refinery->custom()->constraint(function ($suffixes_input): bool { - return $this->icon_repo->hasSuffixInputNoDuplicatesToItsOwnEntries($suffixes_input); - }, $this->lng->txt('msg_error_duplicate_suffix_entries')) + $this->refinery->custom()->constraint(fn($suffixes_input): bool => $this->icon_repo->hasSuffixInputNoDuplicatesToItsOwnEntries($suffixes_input), $this->lng->txt('msg_error_duplicate_suffix_entries')) )->withAdditionalTransformation( $this->refinery->custom()->constraint(function ($suffixes_input): bool { //retrieve the value of the active_input as it is needed for the causesNoActiveSuffixesConflict validation @@ -141,9 +131,7 @@ protected function initIconForm(): void $inputs = $section->getInputs(); $input_active = $inputs[self::INPUT_ACTIVE]; $field_is_active = $input_active->getName(); - $to_bool = $this->refinery->custom()->transformation(function ($checkbox_input_value): bool { - return $this->transformCheckboxInputValueToBool($checkbox_input_value); - }); + $to_bool = $this->refinery->custom()->transformation(fn($checkbox_input_value): bool => $this->transformCheckboxInputValueToBool($checkbox_input_value)); $post_is_active_value = $this->wrapper->post()->retrieve($field_is_active, $to_bool); return $this->icon_repo->causesNoActiveSuffixesConflict( @@ -162,7 +150,7 @@ protected function initIconForm(): void $this->icon_form = $this->ui_factory->input()->container()->form()->standard($form_action, [$section]); } - public function getIconForm(): \ILIAS\UI\Component\Input\Container\Form\Standard + public function getIconForm(): Standard { return $this->icon_form; } diff --git a/components/ILIAS/File/classes/Icons/IconListingUI.php b/components/ILIAS/File/classes/Icons/IconListingUI.php index d2d4c7aa9824..9c9a3747fe89 100755 --- a/components/ILIAS/File/classes/Icons/IconListingUI.php +++ b/components/ILIAS/File/classes/Icons/IconListingUI.php @@ -20,6 +20,9 @@ namespace ILIAS\File\Icon; +use ILIAS\UI\Factory; +use ILIAS\ResourceStorage\Services; +use ILIAS\UI\Component\Panel\Listing\Standard; use ILIAS\UI\Component\Modal\Interruptive; /** @@ -29,11 +32,11 @@ class IconListingUI { private \ilCtrl $ctrl; private \ilLanguage $lng; - private \ILIAS\UI\Factory $ui_factory; + private Factory $ui_factory; private \ILIAS\Refinery\Factory $refinery; - private \ILIAS\ResourceStorage\Services $storage; + private Services $storage; private array $deletion_modals = []; - private \ILIAS\UI\Component\Panel\Listing\Standard $icon_list; + private Standard $icon_list; private \ilUIFilterService $filter_service; private \ILIAS\UI\Component\Input\Container\Filter\Standard $filter; private \ILIAS\HTTP\Services $http; @@ -166,7 +169,7 @@ protected function initListing(): void ); } - public function getIconList(): \ILIAS\UI\Component\Panel\Listing\Standard + public function getIconList(): Standard { return $this->icon_list; } diff --git a/components/ILIAS/File/classes/Icons/class.ilIconUploadHandlerGUI.php b/components/ILIAS/File/classes/Icons/class.ilIconUploadHandlerGUI.php index f1d74b966bdd..d83dcace3828 100755 --- a/components/ILIAS/File/classes/Icons/class.ilIconUploadHandlerGUI.php +++ b/components/ILIAS/File/classes/Icons/class.ilIconUploadHandlerGUI.php @@ -20,6 +20,7 @@ namespace ILIAS\File\Icon; +use ILIAS\ResourceStorage\Identification\ResourceIdentification; use ILIAS\FileUpload\DTO\UploadResult; use ILIAS\FileUpload\Handler\AbstractCtrlAwareUploadHandler; use ILIAS\FileUpload\Handler\BasicFileInfoResult; @@ -124,7 +125,7 @@ protected function getRemoveResult(string $rid): HandlerResult public function getInfoResult(string $rid): ?FileInfoResult { $id = $this->storage->manage()->find($rid); - if (!$id instanceof \ILIAS\ResourceStorage\Identification\ResourceIdentification) { + if (!$id instanceof ResourceIdentification) { return new BasicFileInfoResult($this->getFileIdentifierParameterName(), 'unknown', 'unknown', 0, 'unknown'); } $r = $this->storage->manage()->getCurrentRevision($id)->getInformation(); @@ -139,14 +140,14 @@ public function getInfoResult(string $rid): ?FileInfoResult } /** - * @return \ILIAS\FileUpload\Handler\BasicFileInfoResult[] + * @return BasicFileInfoResult[] */ public function getInfoForExistingFiles(array $resource_identifiers): array { $infos = []; foreach ($resource_identifiers as $rid) { $id = $this->storage->manage()->find($rid); - if (!$id instanceof \ILIAS\ResourceStorage\Identification\ResourceIdentification) { + if (!$id instanceof ResourceIdentification) { continue; } $r = $this->storage->manage()->getCurrentRevision($id)->getInformation(); diff --git a/components/ILIAS/File/classes/Icons/class.ilObjFileDefaultIconsObjective.php b/components/ILIAS/File/classes/Icons/class.ilObjFileDefaultIconsObjective.php index e967744559be..4d2e25598dc8 100755 --- a/components/ILIAS/File/classes/Icons/class.ilObjFileDefaultIconsObjective.php +++ b/components/ILIAS/File/classes/Icons/class.ilObjFileDefaultIconsObjective.php @@ -20,15 +20,18 @@ namespace ILIAS\File\Icon; +use ILIAS\Setup\Objective; use ILIAS\Setup\Environment; use ilResourceStorageMigrationHelper; -use ilDBInterface; /** * @author Lukas Zehnder */ -class ilObjFileDefaultIconsObjective implements \ILIAS\Setup\Objective +class ilObjFileDefaultIconsObjective implements Objective { + /** + * @var string + */ private const PATH_DEFAULT_ICON_DIR = __DIR__ . "/../../../../../public/assets/images/default_file_icons/"; public function __construct( @@ -44,7 +47,7 @@ public function getHash(): string { return hash( "sha256", - get_class($this) + static::class ); } diff --git a/components/ILIAS/File/classes/Icons/class.ilObjFileIconsOverviewGUI.php b/components/ILIAS/File/classes/Icons/class.ilObjFileIconsOverviewGUI.php index 6895f9b6972f..292752b3f894 100755 --- a/components/ILIAS/File/classes/Icons/class.ilObjFileIconsOverviewGUI.php +++ b/components/ILIAS/File/classes/Icons/class.ilObjFileIconsOverviewGUI.php @@ -20,6 +20,13 @@ namespace ILIAS\File\Icon; +use ILIAS\UI\Factory; +use ILIAS\UI\Renderer; +use ILIAS\HTTP\Wrapper\WrapperFactory; +use Psr\Http\Message\RequestInterface; +use ILIAS\ResourceStorage\Services; +use ILIAS\ResourceStorage\Identification\ResourceIdentification; + /** * @property \ilFileServicesSettings $file_settings * @author Lukas Zehnder @@ -38,13 +45,13 @@ class ilObjFileIconsOverviewGUI private \ilCtrl $ctrl; private \ilLanguage $lng; private \ilToolbarGUI $toolbar; - private \ILIAS\UI\Factory $ui_factory; - private \ILIAS\UI\Renderer $ui_renderer; + private Factory $ui_factory; + private Renderer $ui_renderer; private \ilGlobalTemplateInterface $main_tpl; - private \ILIAS\HTTP\Wrapper\WrapperFactory $wrapper; - private \Psr\Http\Message\RequestInterface $http_request; + private WrapperFactory $wrapper; + private RequestInterface $http_request; private \ILIAS\Refinery\Factory $refinery; - private \ILIAS\ResourceStorage\Services $storage; + private Services $storage; private IconRepositoryInterface $icon_repo; private \ilFileServicesSettings $file_service_settings; @@ -258,7 +265,7 @@ public function delete(): void // delete icon from irss $is_deleted_from_irss = false; $id = $this->storage->manage()->find($rid); - if ($id instanceof \ILIAS\ResourceStorage\Identification\ResourceIdentification) { + if ($id instanceof ResourceIdentification) { $this->storage->manage()->remove($id, new ilObjFileIconStakeholder()); $is_deleted_from_irss = true; } diff --git a/components/ILIAS/File/classes/Implementation/class.ilObjFileImplementationStorage.php b/components/ILIAS/File/classes/Implementation/class.ilObjFileImplementationStorage.php index 7754a5a98b4f..1081fc53493b 100755 --- a/components/ILIAS/File/classes/Implementation/class.ilObjFileImplementationStorage.php +++ b/components/ILIAS/File/classes/Implementation/class.ilObjFileImplementationStorage.php @@ -84,7 +84,7 @@ public function getDirectory(int $a_version = 0): string } $stream = $consumer->getStream(); - return dirname($stream->getMetadata('uri')); + return dirname((string) $stream->getMetadata('uri')); } public function sendFile(?int $a_hist_entry_id = null, bool $inline = true): void @@ -140,17 +140,11 @@ public function getVersions(?array $version_ids = null): array $v->setAction('draft'); } else { $version_number = $revision->getVersionNumber(); - switch ($version_number) { - case 1: - $v->setAction('create'); - break; - case $current_revision->getVersionNumber(): - $v->setAction('published_version'); - break; - default: - $v->setAction('intermediate_version'); - break; - } + match ($version_number) { + 1 => $v->setAction('create'), + $current_revision->getVersionNumber() => $v->setAction('published_version'), + default => $v->setAction('intermediate_version'), + }; } $v->setTitle($revision->getTitle()); $v->setDate($information->getCreationDate()->format(DATE_ATOM)); diff --git a/components/ILIAS/File/classes/Info/class.ilObjFileInfo.php b/components/ILIAS/File/classes/Info/class.ilObjFileInfo.php index 8ead006a4bd6..b53fc8e006f9 100755 --- a/components/ILIAS/File/classes/Info/class.ilObjFileInfo.php +++ b/components/ILIAS/File/classes/Info/class.ilObjFileInfo.php @@ -16,13 +16,6 @@ * *********************************************************************/ -use ILIAS\DI\Container; -use ILIAS\Filesystem\Stream\FileStream; -use ILIAS\FileUpload\DTO\UploadResult; -use ILIAS\FileUpload\FileUpload; -use ILIAS\ResourceStorage\Manager\Manager; -use ILIAS\ResourceStorage\Revision\Revision; -use ILIAS\ResourceStorage\Policy\FileNamePolicyException; use ILIAS\Data\DataSize; use ILIAS\ResourceStorage\Identification\ResourceIdentification; @@ -33,45 +26,8 @@ class ilObjFileInfo { use ilObjFileSecureString; - protected ?ResourceIdentification $rid; - protected string $title; - protected string $file_name; - protected string $suffix; - protected bool $deliver_inline; - protected bool $download_directly; - protected int $version; - protected DateTimeImmutable $creation_date; - protected bool $is_zip; - protected string $mime_type; - protected DataSize $file_size; - protected ?int $page_count; - - public function __construct( - string $title, - ?ResourceIdentification $rid, - string $file_name, - string $suffix, - bool $deliver_inline, - bool $download_directly, - int $version, - DateTimeImmutable $creation_date, - bool $is_zip, - string $mime_type, - DataSize $file_size, - ?int $page_count - ) { - $this->title = $title; - $this->rid = $rid; - $this->file_name = $file_name; - $this->suffix = $suffix; - $this->deliver_inline = $deliver_inline; - $this->download_directly = $download_directly; - $this->version = $version; - $this->creation_date = $creation_date; - $this->is_zip = $is_zip; - $this->mime_type = $mime_type; - $this->file_size = $file_size; - $this->page_count = $page_count; + public function __construct(protected string $title, protected ?ResourceIdentification $rid, protected string $file_name, protected string $suffix, protected bool $deliver_inline, protected bool $download_directly, protected int $version, protected DateTimeImmutable $creation_date, protected bool $is_zip, protected string $mime_type, protected DataSize $file_size, protected ?int $page_count) + { } public function getFileName(): string diff --git a/components/ILIAS/File/classes/ObjectProperties/FileObjectPropertyProviders.php b/components/ILIAS/File/classes/ObjectProperties/FileObjectPropertyProviders.php index bb79b5afeb74..c2f214a2a2e2 100755 --- a/components/ILIAS/File/classes/ObjectProperties/FileObjectPropertyProviders.php +++ b/components/ILIAS/File/classes/ObjectProperties/FileObjectPropertyProviders.php @@ -30,7 +30,6 @@ use ILIAS\components\File\Preview\Settings; use ILIAS\Modules\File\Preview\SettingsFactory; use ILIAS\File\Icon\IconDatabaseRepository; -use ILIAS\File\Icon\IconRepositoryInterface; class FileObjectPropertyProviders implements ilObjectTypeSpecificPropertyProviders { @@ -96,7 +95,7 @@ private function getImageFromIRSS( $image = $factory->responsive($urls[count($available_widths)], ''); return array_reduce( $available_widths, - function ($carry, $size) use ($urls) { + function (array $carry, $size) use ($urls): array { $image = $carry['image']->withAdditionalHighResSource($urls[$carry['counter']], $size / 2); $counter = ++$carry['counter']; return [ @@ -114,7 +113,8 @@ public function getObjectTypeSpecificIcon( StorageService $irss ): ?CustomIcon { $info = $this->info->getByObjectId($obj_id); - if (($path = $this->icons->getIconFilePathBySuffix($info->getSuffix()))) { + $path = $this->icons->getIconFilePathBySuffix($info->getSuffix()); + if (($path !== '' && $path !== '0')) { return $icon_factory->custom($path, $info->getSuffix()); } diff --git a/components/ILIAS/File/classes/ObjectProperties/FirstPageToTileImageFlavourDefintion.php b/components/ILIAS/File/classes/ObjectProperties/FirstPageToTileImageFlavourDefintion.php index 5608025b3091..e2702b26b23a 100755 --- a/components/ILIAS/File/classes/ObjectProperties/FirstPageToTileImageFlavourDefintion.php +++ b/components/ILIAS/File/classes/ObjectProperties/FirstPageToTileImageFlavourDefintion.php @@ -24,16 +24,19 @@ class FirstPageToTileImageFlavourDefinition extends ilObjectTileImageFlavourDefi { private const ID = 'b9b2f16325492412304989a9b3e32479e612957582f60ed667af31e7b36e50ed'; + #[\Override] public function getId(): string { return self::ID; } + #[\Override] public function getFlavourMachineId(): string { return FirstPageToTileImageMachine::ID; } + #[\Override] public function getInternalName(): string { return 'first_page_tile_image'; diff --git a/components/ILIAS/File/classes/ObjectProperties/FirstPageToTileImageFlavourMachine.php b/components/ILIAS/File/classes/ObjectProperties/FirstPageToTileImageFlavourMachine.php index 052299ccc3e4..318b1e0b71a5 100755 --- a/components/ILIAS/File/classes/ObjectProperties/FirstPageToTileImageFlavourMachine.php +++ b/components/ILIAS/File/classes/ObjectProperties/FirstPageToTileImageFlavourMachine.php @@ -38,6 +38,9 @@ class FirstPageToTileImageMachine extends AbstractMachine implements FlavourMachine { public const ID = "be03e07e396a61f7d9b31a712f0913fe9c6cd43b009ce69d30aa0f10bd3500bd"; + /** + * @var int + */ private const FULL_QUALITY_SIZE_THRESHOLD = 100; private ExtractPages $extract_pages; private CropRectangle $crop; diff --git a/components/ILIAS/File/classes/ObjectProperties/class.ilFileCommonSettingsGUI.php b/components/ILIAS/File/classes/ObjectProperties/class.ilFileCommonSettingsGUI.php index 2a9c787d6007..bf4671128f74 100644 --- a/components/ILIAS/File/classes/ObjectProperties/class.ilFileCommonSettingsGUI.php +++ b/components/ILIAS/File/classes/ObjectProperties/class.ilFileCommonSettingsGUI.php @@ -23,44 +23,22 @@ class ilFileCommonSettingsGUI { public const CMD_EDIT = 'editSettings'; public const CMD_SAVE = 'saveSettings'; - private array $services; + private array $services = [ + ilObjectServiceSettingsGUI::CUSTOM_METADATA + ]; - protected ilObjFile $object; - protected ilCtrl $ctrl; - protected ilGlobalTemplateInterface $tpl; - protected ilLanguage $lng; - protected ilObjectService $object_service; - - public function __construct( - ilObjFile $object, - ilCtrl $ctrl, - ilGlobalTemplateInterface $tpl, - ilLanguage $lng, - ilObjectService $object_service - ) { - $this->object = $object; - $this->ctrl = $ctrl; - $this->tpl = $tpl; - $this->lng = $lng; - $this->object_service = $object_service; - $this->services = [ - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ]; + public function __construct(protected ilObjFile $object, protected ilCtrl $ctrl, protected ilGlobalTemplateInterface $tpl, protected ilLanguage $lng, protected ilObjectService $object_service) + { } public function executeCommand(): void { $cmd = $this->ctrl->getCmd(); - switch ($cmd) { - case self::CMD_EDIT: - $this->editSettings(); - break; - case self::CMD_SAVE: - $this->saveSettings(); - break; - default: - throw new Exception('Unknown command ' . $cmd); - } + match ($cmd) { + self::CMD_EDIT => $this->editSettings(), + self::CMD_SAVE => $this->saveSettings(), + default => throw new Exception('Unknown command ' . $cmd), + }; } protected function editSettings(?ilPropertyFormGUI $form = null): void diff --git a/components/ILIAS/File/classes/PreProcessors/class.ilCountPDFPagesPreProcessors.php b/components/ILIAS/File/classes/PreProcessors/class.ilCountPDFPagesPreProcessors.php index a09b1b6cb685..8db34502a9ef 100755 --- a/components/ILIAS/File/classes/PreProcessors/class.ilCountPDFPagesPreProcessors.php +++ b/components/ILIAS/File/classes/PreProcessors/class.ilCountPDFPagesPreProcessors.php @@ -37,7 +37,7 @@ public function __construct() $this->page_counter = new ilCountPDFPages(); } - public function process(FileStream $stream, Metadata $metadata): \ILIAS\FileUpload\DTO\ProcessingStatus + public function process(FileStream $stream, Metadata $metadata): ProcessingStatus { if ( $this->page_counter->isAvailable() diff --git a/components/ILIAS/File/classes/Preview/Form.php b/components/ILIAS/File/classes/Preview/Form.php index 83b135b645c3..4c8001fcffcf 100755 --- a/components/ILIAS/File/classes/Preview/Form.php +++ b/components/ILIAS/File/classes/Preview/Form.php @@ -18,6 +18,7 @@ namespace ILIAS\components\File\Preview; +use ILIAS\UI\Component\Input\Field\Factory; use ILIAS\UI\Component\Input\Field\Group; use ILIAS\UI\Component\Input\Field\Section; @@ -27,7 +28,7 @@ class Form { private \ilLanguage $language; - private \ILIAS\UI\Component\Input\Field\Factory $field_factory; + private Factory $field_factory; private \ILIAS\Refinery\Factory $refinery; public function __construct(private Settings $settings) diff --git a/components/ILIAS/File/classes/Preview/Settings.php b/components/ILIAS/File/classes/Preview/Settings.php index 92398d55110a..37f41a9f2863 100755 --- a/components/ILIAS/File/classes/Preview/Settings.php +++ b/components/ILIAS/File/classes/Preview/Settings.php @@ -35,17 +35,44 @@ class Settings extends ilSetting implements Setting public const V_IMAGE_SIZE_MIN = 50; public const V_IMAGE_SIZE_MAX = 1000; + /** + * @var int + */ private const V_IMAGE_QUALITY_DEFAULT = 85; + /** + * @var int + */ private const V_IMAGE_QUALITY_MIN = 1; + /** + * @var int + */ private const V_IMAGE_QUALITY_MAX = 100; public const MODULE_NAME = 'preview'; + /** + * @var string + */ private const F_PREVIEW_ENABLED = 'preview_enabled'; + /** + * @var string + */ private const F_MAX_PREVIEWS_PER_OBJECT = 'max_previews_per_object'; + /** + * @var string + */ private const F_PREVIEW_IMAGE_SIZE = 'preview_image_size'; + /** + * @var string + */ private const F_PREVIEW_PERSISTING = 'preview_persisting'; + /** + * @var string + */ private const F_PREVIEW_IMAGE_QUALITY = 'preview_image_quality'; + /** + * @var string + */ private const F_TILE_PREVIEWS = 'tile_previews'; /** * @readonly diff --git a/components/ILIAS/File/classes/Settings/Form.php b/components/ILIAS/File/classes/Settings/Form.php index 24215ee9cab3..596be63b313e 100755 --- a/components/ILIAS/File/classes/Settings/Form.php +++ b/components/ILIAS/File/classes/Settings/Form.php @@ -18,6 +18,7 @@ namespace ILIAS\components\File\Settings; +use ILIAS\UI\Component\Input\Field\Factory; use ILIAS\UI\Component\Input\Field\Group; use ILIAS\UI\Component\Input\Field\Section; @@ -27,7 +28,7 @@ class Form { private \ilLanguage $language; - private \ILIAS\UI\Component\Input\Field\Factory $field_factory; + private Factory $field_factory; private \ILIAS\Refinery\Factory $refinery; public function __construct(private General $settings) diff --git a/components/ILIAS/File/classes/Settings/General.php b/components/ILIAS/File/classes/Settings/General.php index 3fffed4844d8..a1f6ce8a04db 100755 --- a/components/ILIAS/File/classes/Settings/General.php +++ b/components/ILIAS/File/classes/Settings/General.php @@ -31,6 +31,9 @@ class General extends ilSetting implements Setting public const F_INLINE_FILE_EXTENSIONS = 'inline_file_extensions'; public const F_SHOW_AMOUNT_OF_DOWNLOADS = 'show_amount_of_downloads'; public const F_DOWNLOAD_ASCII_FILENAME = 'download_ascii_filename'; + /** + * @var string + */ private const SEPARATOR = ' '; private array $default_inline_extensions = [ @@ -69,9 +72,7 @@ public function setShowAmountOfDownloads(bool $value): void public function setInlineFileExtensions(array $extensions): void { - $extensions = array_map(function (string $extension): string { - return strtolower(trim($extension, " \t\n\r\0\x0B,")); - }, $extensions); + $extensions = array_map(fn(string $extension): string => strtolower(trim($extension, " \t\n\r\0\x0B,")), $extensions); $this->set(self::F_INLINE_FILE_EXTENSIONS, $this->arrayToStr($extensions)); } diff --git a/components/ILIAS/File/classes/Setup/Database/class.ilFileObjectRBACDatabase.php b/components/ILIAS/File/classes/Setup/Database/class.ilFileObjectRBACDatabase.php index 74d3b723211e..8322abf31f91 100755 --- a/components/ILIAS/File/classes/Setup/Database/class.ilFileObjectRBACDatabase.php +++ b/components/ILIAS/File/classes/Setup/Database/class.ilFileObjectRBACDatabase.php @@ -17,13 +17,6 @@ *********************************************************************/ declare(strict_types=1); - -use ILIAS\Setup\ObjectiveConstructor; -use ILIAS\Setup\Config; -use ILIAS\Refinery\Factory; -use ILIAS\Refinery; -use ILIAS\Setup; -use ILIAS\Setup\Objective; use ILIAS\Setup\Environment; use ILIAS\BookingManager\Setup\AccessRBACOperationClonedObjective; use ILIAS\File\Capabilities\Permissions; @@ -33,6 +26,7 @@ */ class ilFileObjectRBACDatabase extends ilDatabaseUpdateStepsExecutedObjective { + #[\Override] public function getPreconditions(Environment $environment): array { return array_merge( diff --git a/components/ILIAS/File/classes/Setup/class.ilFileObjectAgent.php b/components/ILIAS/File/classes/Setup/class.ilFileObjectAgent.php index 5cadd2a6d82b..352d5e3e2d40 100755 --- a/components/ILIAS/File/classes/Setup/class.ilFileObjectAgent.php +++ b/components/ILIAS/File/classes/Setup/class.ilFileObjectAgent.php @@ -18,24 +18,25 @@ declare(strict_types=1); +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Transformation; +use ILIAS\Setup\Objective; +use ILIAS\Setup\ObjectiveCollection; +use ILIAS\Setup\Objective\NullObjective; +use ILIAS\Setup\Metrics\Storage; use ILIAS\Setup\ObjectiveConstructor; use ILIAS\Setup\Config; use ILIAS\Refinery\Factory; -use ILIAS\Refinery; -use ILIAS\Setup; use ILIAS\File\Icon\ilObjFileDefaultIconsObjective; /** * @author Thibeau Fuhrer * @noinspection AutoloadingIssuesInspection */ -class ilFileObjectAgent implements Setup\Agent +class ilFileObjectAgent implements Agent { - protected Factory $refinery; - - public function __construct(Factory $refinery) + public function __construct(protected Factory $refinery) { - $this->refinery = $refinery; } public function hasConfig(): bool @@ -43,25 +44,25 @@ public function hasConfig(): bool return false; } - public function getArrayToConfigTransformation(): Refinery\Transformation + public function getArrayToConfigTransformation(): Transformation { throw new \LogicException("Agent has no config."); } - public function getInstallObjective(?Config $config = null): Setup\Objective + public function getInstallObjective(?Config $config = null): Objective { - return new \ILIAS\File\Icon\ilObjFileDefaultIconsObjective(true, true); + return new ilObjFileDefaultIconsObjective(true, true); } - public function getUpdateObjective(?Config $config = null): Setup\Objective + public function getUpdateObjective(?Config $config = null): Objective { - return new Setup\ObjectiveCollection( + return new ObjectiveCollection( "", true, new ilDatabaseUpdateStepsExecutedObjective( new ilFileObjectDatabaseObjective() ), - new \ILIAS\File\Icon\ilObjFileDefaultIconsObjective(false, false), + new ilObjFileDefaultIconsObjective(false, false), new ilFileObjectSettingsUpdatedObjective(), new ilFileObjectRBACDatabase( new ilFileObjectRBACDatabaseSteps() @@ -69,14 +70,14 @@ public function getUpdateObjective(?Config $config = null): Setup\Objective ); } - public function getBuildObjective(): Setup\Objective + public function getBuildObjective(): Objective { - return new Setup\Objective\NullObjective(); + return new NullObjective(); } - public function getStatusObjective(Setup\Metrics\Storage $storage): Setup\Objective + public function getStatusObjective(Storage $storage): Objective { - return new Setup\ObjectiveCollection( + return new ObjectiveCollection( 'Component File', true, new ilDatabaseUpdateStepsMetricsCollectedObjective($storage, new ilFileObjectDatabaseObjective()), @@ -96,9 +97,7 @@ public function getNamedObjectives(?Config $config = null): array return [ 'resetDefaultIcons' => new ObjectiveConstructor( 'resets the default suffix specific file icons.', - function (): \ILIAS\Setup\Objective { - return new ilObjFileDefaultIconsObjective(true, false); - } + fn(): Objective => new ilObjFileDefaultIconsObjective(true, false) ), ]; } diff --git a/components/ILIAS/File/classes/Setup/class.ilFileObjectSettingsUpdatedObjective.php b/components/ILIAS/File/classes/Setup/class.ilFileObjectSettingsUpdatedObjective.php index 839bc52d3931..b4a01a27e6a7 100755 --- a/components/ILIAS/File/classes/Setup/class.ilFileObjectSettingsUpdatedObjective.php +++ b/components/ILIAS/File/classes/Setup/class.ilFileObjectSettingsUpdatedObjective.php @@ -16,10 +16,10 @@ * *********************************************************************/ -use ILIAS\Setup; +use ILIAS\Setup\Objective; use ILIAS\Setup\Environment; -class ilFileObjectSettingsUpdatedObjective implements Setup\Objective +class ilFileObjectSettingsUpdatedObjective implements Objective { public function getHash(): string { @@ -53,8 +53,8 @@ public function achieve(Environment $environment): Environment * @var $db ilDBInterface * @var $client_ini ilIniFile */ - $db = $environment->getResource(Setup\Environment::RESOURCE_DATABASE); - $client_ini = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI); + $db = $environment->getResource(Environment::RESOURCE_DATABASE); + $client_ini = $environment->getResource(Environment::RESOURCE_CLIENT_INI); $use_ascii_characters_only = $client_ini->readVariable( 'file_access', @@ -82,7 +82,7 @@ public function isApplicable(Environment $environment): bool /** * @var $client_ini ilIniFile */ - $client_ini = $environment->getResource(Setup\Environment::RESOURCE_CLIENT_INI); + $client_ini = $environment->getResource(Environment::RESOURCE_CLIENT_INI); return $client_ini->groupExists("file_access"); } diff --git a/components/ILIAS/File/classes/Versions/class.ilFileVersionFormGUI.php b/components/ILIAS/File/classes/Versions/class.ilFileVersionFormGUI.php index f66aac055364..bbdc1da4dc5f 100755 --- a/components/ILIAS/File/classes/Versions/class.ilFileVersionFormGUI.php +++ b/components/ILIAS/File/classes/Versions/class.ilFileVersionFormGUI.php @@ -16,9 +16,11 @@ * *********************************************************************/ +use ILIAS\UI\Component\Input\Container\Form\Standard; +use ILIAS\UI\Factory; +use ILIAS\UI\Renderer; +use ILIAS\ResourceStorage\Services; use Psr\Http\Message\RequestInterface; -use ILIAS\Data\DataSize; -use ILIAS\UI\Implementation\Component\Input\UploadLimitResolver; /** * Class ilFileVersionFormGUI @@ -36,15 +38,14 @@ class ilFileVersionFormGUI public const F_SAVE_MODE = 'save_mode'; private \ilObjFile $file; - private ?\ILIAS\UI\Component\Input\Container\Form\Standard $form; - private \ILIAS\UI\Factory $ui_factory; - private \ILIAS\UI\Renderer $ui_renderer; + private ?Standard $form; + private Factory $ui_factory; + private Renderer $ui_renderer; private RequestInterface $request; private ilGlobalTemplateInterface $global_tpl; private ilLanguage $lng; - private \ILIAS\ResourceStorage\Services $resource_services; + private Services $resource_services; private string $post_url; - private UploadLimitResolver $upload_limit; /** * ilFileVersionFormGUI constructor. @@ -65,7 +66,6 @@ public function __construct(ilFileVersionsGUI $file_version_gui, private int $sa $this->resolveParentCommand($save_mode) ); $this->lng->loadLanguageModule('file'); - $this->upload_limit = $DIC['ui.upload_limit_resolver']; $this->initForm(); } @@ -90,11 +90,6 @@ private function initForm(): void : ilFileVersionsUploadHandlerGUI::MODE_APPEND ); - $size = new DataSize( - $this->upload_limit->getBestPossibleUploadLimitInBytes($upload_handler), - DataSize::MB - ); - $inputs = [ self::F_TITLE => $this->ui_factory->input()->field()->text( $this->lng->txt(self::F_TITLE), @@ -108,11 +103,7 @@ private function initForm(): void ), self::F_FILE => $this->ui_factory->input()->field()->file( $upload_handler, - $this->lng->txt(self::F_FILE), - sprintf( - $this->lng->txt('upload_files_limit'), - (string) $size - ), + $this->lng->txt(self::F_FILE) )->withMaxFiles(1) ->withRequired(true), ]; @@ -130,7 +121,7 @@ public function saveObject(): bool return false; } - $title = !empty($data[self::F_TITLE]) ? $data[self::F_TITLE] : $this->file->getTitle(); + $title = empty($data[self::F_TITLE]) ? $this->file->getTitle() : $data[self::F_TITLE]; $description = $data[self::F_DESCRIPTION] !== '' ? $data[self::F_DESCRIPTION] : $this->file->getDescription(); $revision_number = $data[self::F_FILE][0] ?? null; if ($revision_number === null) { diff --git a/components/ILIAS/File/classes/Versions/class.ilFileVersionsGUI.php b/components/ILIAS/File/classes/Versions/class.ilFileVersionsGUI.php index 1ef9c8fa6305..728d00aa73c2 100755 --- a/components/ILIAS/File/classes/Versions/class.ilFileVersionsGUI.php +++ b/components/ILIAS/File/classes/Versions/class.ilFileVersionsGUI.php @@ -16,6 +16,11 @@ * *********************************************************************/ +use ILIAS\DI\UIServices; +use ILIAS\Filesystem\Stream\Streams; +use ILIAS\ResourceStorage\Identification\ResourceIdentification; +use ILIAS\FileUpload\Collection\Exception\NoSuchElementException; +use ILIAS\FileUpload\Exception\IllegalStateException; use ILIAS\HTTP\Services; use ILIAS\Filesystem\Exception\FileNotFoundException; use ILIAS\ResourceStorage\Revision\Revision; @@ -27,8 +32,6 @@ use ILIAS\components\WOPI\Discovery\ActionRepository; use ILIAS\components\WOPI\Embed\EmbeddedApplication; use ILIAS\Data\URI; -use ILIAS\UI\Component\Modal\Modal; -use ILIAS\components\WOPI\Discovery\ActionTarget; use ILIAS\FileUpload\MimeType; use ILIAS\MetaData\Services\ServicesInterface as LOMServices; use ILIAS\File\Capabilities\Capabilities; @@ -71,7 +74,7 @@ class ilFileVersionsGUI private \ILIAS\ResourceStorage\Services $storage; private ActionRepository $action_repo; private ?Revision $current_revision; - protected \ILIAS\DI\UIServices $ui; + protected UIServices $ui; private ilAccessHandler $access; private \ilWorkspaceAccessHandler $wsp_access; private int $ref_id; @@ -122,8 +125,8 @@ public function __construct(private ilObjFile $file) /** - * @throws \ILIAS\FileUpload\Collection\Exception\NoSuchElementException - * @throws \ILIAS\FileUpload\Exception\IllegalStateException + * @throws NoSuchElementException + * @throws IllegalStateException */ protected function performCommand(): void { @@ -345,8 +348,8 @@ private function addVersion(int $mode = ilFileVersionFormGUI::MODE_ADD): void } /** - * @throws \ILIAS\FileUpload\Collection\Exception\NoSuchElementException - * @throws \ILIAS\FileUpload\Exception\IllegalStateException + * @throws NoSuchElementException + * @throws IllegalStateException */ private function saveVersion(int $mode = ilFileVersionFormGUI::MODE_ADD): void { @@ -500,7 +503,7 @@ protected function renderDeleteSelectedVersionsModal(): void $this->http->saveResponse( $this->http->response()->withBody( - \ILIAS\Filesystem\Stream\Streams::ofString( + Streams::ofString( (null !== $delete_selected_versions_modal) ? $this->ui->renderer()->renderAsync([$delete_selected_versions_modal]) : '' @@ -520,7 +523,7 @@ protected function getDeleteSelectedVersionsModal(): ?Interruptive $non_deletion_versions = array_udiff( $existing_versions, $deletion_version_ids, - static function ($a, $b) { + static function ($a, $b): int|float { if ($a instanceof ilObjFileVersion) { $a = $a->getHistEntryId(); } @@ -582,7 +585,7 @@ private function deleteVersions(): void $remaining_versions = array_udiff( $existing_versions, $version_ids, - static function ($a, $b) { + static function ($a, $b): int|float { if ($a instanceof ilObjFileVersion) { $a = $a->getHistEntryId(); } @@ -724,7 +727,7 @@ private function getFileProcessor(bool $keep_structure): ilObjFileProcessorInter ); } - private function getIdentification(): ?\ILIAS\ResourceStorage\Identification\ResourceIdentification + private function getIdentification(): ?ResourceIdentification { return $this->storage->manage()->find($this->file->getResourceId()); } diff --git a/components/ILIAS/File/classes/Versions/class.ilFileVersionsTableGUI.php b/components/ILIAS/File/classes/Versions/class.ilFileVersionsTableGUI.php index b799f826c750..c8e563c766cf 100755 --- a/components/ILIAS/File/classes/Versions/class.ilFileVersionsTableGUI.php +++ b/components/ILIAS/File/classes/Versions/class.ilFileVersionsTableGUI.php @@ -16,6 +16,8 @@ * *********************************************************************/ +use ILIAS\ResourceStorage\Services; +use ILIAS\DI\UIServices; use ILIAS\DI\Container; use ILIAS\UI\Component\Modal\Modal; use ILIAS\Data\DataSize; @@ -30,10 +32,10 @@ class ilFileVersionsTableGUI extends ilTable2GUI private Container $dic; private int $current_version; private \ilObjFile $file; - private \ILIAS\ResourceStorage\Services $irss; + private Services $irss; private bool $current_version_is_draft; private int $amount_of_versions; - protected \ILIAS\DI\UIServices $ui; + protected UIServices $ui; protected bool $has_been_migrated = false; /** @@ -117,6 +119,7 @@ private function initData(): void $this->setMaxCount(is_array($versions) ? count($versions) : 0); } + #[\Override] protected function fillRow(array $a_set): void { $action_entries = []; @@ -243,6 +246,7 @@ protected function fillRow(array $a_set): void * Since modals can contain forms as well, this would lead to invalid HTML * markup. */ + #[\Override] public function getHTML(): string { return parent::getHTML() . $this->ui->renderer()->render($this->modals); diff --git a/components/ILIAS/File/classes/Versions/class.ilFileVersionsUploadHandlerGUI.php b/components/ILIAS/File/classes/Versions/class.ilFileVersionsUploadHandlerGUI.php index f9e188b97cb5..b735d1dc6637 100755 --- a/components/ILIAS/File/classes/Versions/class.ilFileVersionsUploadHandlerGUI.php +++ b/components/ILIAS/File/classes/Versions/class.ilFileVersionsUploadHandlerGUI.php @@ -59,11 +59,13 @@ protected function getClassPath(): array return [self::class]; } + #[\Override] public function supportsChunkedUploads(): bool { return true; } + #[\Override] protected function getUploadResult(): HandlerResult { $this->upload->register(new ilCountPDFPagesPreProcessors()); @@ -99,6 +101,7 @@ protected function getUploadResult(): HandlerResult ); } + #[\Override] protected function processChunckedUpload(UploadResult $result): HandlerResult { $temp_path = "$this->chunk_id/{$result->getName()}"; diff --git a/components/ILIAS/File/classes/class.ilFileExporter.php b/components/ILIAS/File/classes/class.ilFileExporter.php index 9cd3013f48a4..9c21c9bcefed 100755 --- a/components/ILIAS/File/classes/class.ilFileExporter.php +++ b/components/ILIAS/File/classes/class.ilFileExporter.php @@ -41,6 +41,7 @@ public function init(): void * @param array ids * @return array array of array with keys "component", entity", "ids" */ + #[\Override] public function getXmlExportTailDependencies(string $a_entity, string $a_target_release, array $a_ids): array { $md_ids = []; @@ -72,7 +73,7 @@ public function getXmlExportTailDependencies(string $a_entity, string $a_target_ public function getXmlRepresentation(string $a_entity, string $a_schema_version, string $a_id): string { $xml = ''; - if (ilObject::_lookupType((int) $a_id) == 'file') { + if (ilObject::_lookupType((int) $a_id) === 'file') { $file = new ilObjFile((int) $a_id, false); $writer = new ilFileXMLWriter(); $writer->setFile($file); diff --git a/components/ILIAS/File/classes/class.ilFileKioskModeView.php b/components/ILIAS/File/classes/class.ilFileKioskModeView.php index eff906204455..34e1def7b74b 100755 --- a/components/ILIAS/File/classes/class.ilFileKioskModeView.php +++ b/components/ILIAS/File/classes/class.ilFileKioskModeView.php @@ -33,6 +33,9 @@ */ class ilFileKioskModeView extends ilKioskModeView { + /** + * @var string + */ private const CMD_TOGGLE_LEARNING_PROGRESS = 'toggleManualLearningProgress'; protected ilObjFile $file_obj; diff --git a/components/ILIAS/File/classes/class.ilFileLP.php b/components/ILIAS/File/classes/class.ilFileLP.php index f5262b953229..57b2905866ea 100755 --- a/components/ILIAS/File/classes/class.ilFileLP.php +++ b/components/ILIAS/File/classes/class.ilFileLP.php @@ -26,6 +26,7 @@ class ilFileLP extends ilObjectLP /** * @return int[] */ + #[\Override] public static function getDefaultModes(bool $a_lp_active): array { return [ @@ -35,11 +36,13 @@ public static function getDefaultModes(bool $a_lp_active): array ]; } + #[\Override] public function getDefaultMode(): int { return ilLPObjSettings::LP_MODE_DEACTIVATED; } + #[\Override] public function getValidModes(): array { return [ diff --git a/components/ILIAS/File/classes/class.ilFileNewsRendererGUI.php b/components/ILIAS/File/classes/class.ilFileNewsRendererGUI.php index 717e5e81800c..40293f19cd27 100755 --- a/components/ILIAS/File/classes/class.ilFileNewsRendererGUI.php +++ b/components/ILIAS/File/classes/class.ilFileNewsRendererGUI.php @@ -25,6 +25,7 @@ */ class ilFileNewsRendererGUI extends ilNewsDefaultRendererGUI { + #[\Override] public function getTimelineActions(): array { $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $this->news_ref_id); diff --git a/components/ILIAS/File/classes/class.ilFileStaticURLHandler.php b/components/ILIAS/File/classes/class.ilFileStaticURLHandler.php index 5d2ba9720e9f..d9b166005741 100755 --- a/components/ILIAS/File/classes/class.ilFileStaticURLHandler.php +++ b/components/ILIAS/File/classes/class.ilFileStaticURLHandler.php @@ -25,7 +25,6 @@ use ILIAS\File\Capabilities\CapabilityBuilder; use ILIAS\components\WOPI\Discovery\ActionDBRepository; use ILIAS\File\Capabilities\Capabilities; -use ILIAS\File\Capabilities\CoreTypeResolver; /** * @author Fabian Schmid diff --git a/components/ILIAS/File/classes/class.ilFileXMLParser.php b/components/ILIAS/File/classes/class.ilFileXMLParser.php index 5cbc3a382402..c78e9b45c057 100755 --- a/components/ILIAS/File/classes/class.ilFileXMLParser.php +++ b/components/ILIAS/File/classes/class.ilFileXMLParser.php @@ -132,7 +132,7 @@ public function handlerBeginTag($a_xml_parser, string $a_name, array $a_attribs) case 'File': if (isset($a_attribs["obj_id"])) { $read_obj_id = ilUtil::__extractId($a_attribs["obj_id"], IL_INST_ID); - if ($this->obj_id != -1 && (int) $read_obj_id != -1 && $this->obj_id != (int) $read_obj_id) { + if ($this->obj_id != -1 && (int) $read_obj_id != -1 && $this->obj_id !== (int) $read_obj_id) { throw new ilFileException( "Object IDs (xml $read_obj_id and argument " . $this->obj_id . ") do not match!", ilFileException::$ID_MISMATCH @@ -283,7 +283,7 @@ public function handlerEndTag($a_xml_parser, string $a_name): void } // if no file type is given => lookup mime type - if (!$this->file->getFileType()) { + if ($this->file->getFileType() === '' || $this->file->getFileType() === '0') { global $DIC; $this->file->setFileType(MimeType::getMimeType($this->tmpFilename)); } @@ -314,7 +314,7 @@ public function handlerEndTag($a_xml_parser, string $a_name): void */ public function handlerCharacterData($a_xml_parser, string $a_data): void { - if ($a_data != "\n") { + if ($a_data !== "\n") { // begin-patch fm if ($this->mode !== ilFileXMLParser::$CONTENT_COPY && $this->mode !== ilFileXMLParser::$CONTENT_REST @@ -342,9 +342,9 @@ public function setFileContents(): void continue; } // try to get first file of directory - $files = scandir(dirname($version["tmpFilename"])); + $files = scandir(dirname((string) $version["tmpFilename"])); $version["tmpFilename"] = rtrim( - dirname($version["tmpFilename"]), + dirname((string) $version["tmpFilename"]), "/" ) . "/" . $files[2];// because [0] = "." [1] = ".." if (!file_exists($version["tmpFilename"])) { @@ -406,12 +406,12 @@ public static function normalizeRelativePath(string $path): string { $path = str_replace('\\', '/', $path); - while (preg_match('#\p{C}+|^\./#u', $path)) { - $path = preg_replace('#\p{C}+|^\./#u', '', $path); + while (preg_match('#\p{C}+|^\./#u', (string) $path)) { + $path = preg_replace('#\p{C}+|^\./#u', '', (string) $path); } $parts = []; - foreach (explode('/', $path) as $part) { + foreach (explode('/', (string) $path) as $part) { switch ($part) { case '': case '.': diff --git a/components/ILIAS/File/classes/class.ilFileXMLWriter.php b/components/ILIAS/File/classes/class.ilFileXMLWriter.php index c87ac24bb37e..9e1623e77e43 100755 --- a/components/ILIAS/File/classes/class.ilFileXMLWriter.php +++ b/components/ILIAS/File/classes/class.ilFileXMLWriter.php @@ -157,7 +157,7 @@ public function start(): bool $attribs = [ "version" => $version["version"], "max_version" => $version["max_version"], - "date" => strtotime($version["date"]), + "date" => strtotime((string) $version["date"]), "usr_id" => "il_" . IL_INST_ID . "_usr_" . $version["user_id"], "action" => $version["action"], "rollback_version" => $version["rollback_version"], diff --git a/components/ILIAS/File/classes/class.ilObjFile.php b/components/ILIAS/File/classes/class.ilObjFile.php index 6aec4644465d..e3f438aeefc7 100755 --- a/components/ILIAS/File/classes/class.ilObjFile.php +++ b/components/ILIAS/File/classes/class.ilObjFile.php @@ -92,6 +92,7 @@ protected function initFileInfo(int $id, bool $is_ref_id): void $this->file_info = $is_ref_id ? $repository->getByRefId($id) : $repository->getByObjectId($id); } + #[\Override] public function getPresentationTitle(): string { return $this->file_info->getHeaderTitle(); @@ -500,6 +501,7 @@ protected function doUpdate(): void $this->initImplementation(); } + #[\Override] protected function beforeUpdate(): bool { $this->setTitle($this->ensureSuffix($this->getTitle(), $this->file_info->getSuffix())); @@ -513,6 +515,7 @@ protected function beforeUpdate(): bool return true; } + #[\Override] protected function beforeDelete(): bool { // check, if file is used somewhere @@ -571,7 +574,7 @@ protected function initType(): void /** * @return null */ - public function replaceFile($a_upload_file, $a_filename) + public function replaceFile($a_upload_file, $a_filename): null { return null; } diff --git a/components/ILIAS/File/classes/class.ilObjFileAccess.php b/components/ILIAS/File/classes/class.ilObjFileAccess.php index 1336adb2cb24..bf3818d9b08a 100755 --- a/components/ILIAS/File/classes/class.ilObjFileAccess.php +++ b/components/ILIAS/File/classes/class.ilObjFileAccess.php @@ -53,6 +53,7 @@ protected function checkAccessToObjectId(int $obj_id): bool return false; } + #[\Override] public function canBeDelivered(ilWACPath $ilWACPath): bool { return false; @@ -69,6 +70,7 @@ public function canBeDelivered(ilWACPath $ilWACPath): bool * ); * @return array */ + #[\Override] public static function _getCommands(): array { return [ @@ -120,6 +122,7 @@ public static function _getCommands(): array * checks whether a user may invoke a command or not * (this method is called by ilAccessHandler::checkAccess) */ + #[\Override] public function _checkAccess(string $cmd, string $permission, int $ref_id, int $obj_id, ?int $user_id = null): bool { global $DIC; @@ -169,6 +172,7 @@ public function _checkAccess(string $cmd, string $permission, int $ref_id, int $ /** * check whether goto script will succeed */ + #[\Override] public static function _checkGoto(string $a_target): bool { global $DIC; @@ -295,7 +299,7 @@ public static function _appendNumberOfCopyToFilename($a_file_name, $nth_copy = n ' ' . $lng->txt('copy_n_of_suffix') ); - $nthCopyRegex = '/' . preg_replace('/%1\\\\\$s/', '(\d+)', $nthCopyRegex) . '$/'; + $nthCopyRegex = '/' . preg_replace('/%1\\\\\$s/', '(\d+)', (string) $nthCopyRegex) . '$/'; // Get the filename without any previously added number of copy. // Determine the number of copy, if it has not been specified. diff --git a/components/ILIAS/File/classes/class.ilObjFileAccessSettingsGUI.php b/components/ILIAS/File/classes/class.ilObjFileAccessSettingsGUI.php index b8e20927528d..65c7529ee9fd 100755 --- a/components/ILIAS/File/classes/class.ilObjFileAccessSettingsGUI.php +++ b/components/ILIAS/File/classes/class.ilObjFileAccessSettingsGUI.php @@ -15,6 +15,10 @@ * *********************************************************************/ +use ILIAS\components\File\Preview\Form; +use ILIAS\UI\Factory; +use ILIAS\UI\Renderer; +use ILIAS\UI\Component\Input\Container\Form\Standard; use ILIAS\HTTP\Services; use ILIAS\File\Icon\ilObjFileIconsOverviewGUI; use ILIAS\components\File\Preview\Settings; @@ -40,10 +44,10 @@ class ilObjFileAccessSettingsGUI extends ilObjectGUI public const CMD_SAVE_SETTINGS = 'saveSettings'; public const CMD_VIEW = 'view'; private ilLanguage $language; - private \ILIAS\components\File\Preview\Form $preview_settings; + private Form $preview_settings; private \ILIAS\components\File\Settings\Form $file_object_settings; - protected \ILIAS\UI\Factory $ui_factory; - protected \ILIAS\UI\Renderer $ui_renderer; + protected Factory $ui_factory; + protected Renderer $ui_renderer; protected Services $http; /** @@ -56,7 +60,7 @@ public function __construct($a_data, int $a_id, bool $a_call_by_reference) global $DIC; $this->type = "facs"; parent::__construct($a_data, $a_id, $a_call_by_reference, false); - $this->preview_settings = new ILIAS\components\File\Preview\Form(new Settings()); + $this->preview_settings = new Form(new Settings()); $this->file_object_settings = new \ILIAS\components\File\Settings\Form(new General()); $this->http = $DIC->http(); $this->ui_factory = $DIC->ui()->factory(); @@ -74,7 +78,7 @@ protected function checkAccess(string $permission): void } } - private function buildForm(): \ILIAS\UI\Component\Input\Container\Form\Standard + private function buildForm(): Standard { return $this->ui_factory->input()->container()->form()->standard( $this->ctrl->getLinkTarget($this, self::CMD_SAVE_SETTINGS), @@ -85,6 +89,7 @@ private function buildForm(): \ILIAS\UI\Component\Input\Container\Form\Standard ); } + #[\Override] public function executeCommand(): void { $this->lng->loadLanguageModule("file"); @@ -126,6 +131,7 @@ public function executeCommand(): void } } + #[\Override] public function getAdminTabs(): void { if ($this->rbac_system->checkAccess("visible,read", $this->object->getRefId())) { @@ -150,12 +156,12 @@ protected function addFileObjectsSubTabs(): void $this->tabs_gui->addSubTabTarget( "settings", $this->ctrl->getLinkTarget($this, self::CMD_EDIT_SETTINGS), - array(self::CMD_EDIT_SETTINGS, "view") + [self::CMD_EDIT_SETTINGS, "view"] ); $this->tabs_gui->addSubTabTarget( self::SUBTAB_SUFFIX_SPECIFIC_ICONS, $this->ctrl->getLinkTargetByClass(ilObjFileIconsOverviewGUI::class, ilObjFileIconsOverviewGUI::CMD_INDEX), - array(ilObjFileIconsOverviewGUI::CMD_INDEX, "view") + [ilObjFileIconsOverviewGUI::CMD_INDEX, "view"] ); } diff --git a/components/ILIAS/File/classes/class.ilObjFileComponentBuilder.php b/components/ILIAS/File/classes/class.ilObjFileComponentBuilder.php index 5ad0ff397c68..6173a6004e8a 100755 --- a/components/ILIAS/File/classes/class.ilObjFileComponentBuilder.php +++ b/components/ILIAS/File/classes/class.ilObjFileComponentBuilder.php @@ -18,6 +18,7 @@ declare(strict_types=1); +use ILIAS\DI\UIServices; use ILIAS\UI\Implementation\Component\Modal\Interruptive; /** @@ -27,7 +28,7 @@ class ilObjFileComponentBuilder { public function __construct( protected ilLanguage $lng, - protected \ILIAS\DI\UIServices $ui + protected UIServices $ui ) { } diff --git a/components/ILIAS/File/classes/class.ilObjFileGUI.php b/components/ILIAS/File/classes/class.ilObjFileGUI.php index 659c2aa28324..5b7841b076ac 100755 --- a/components/ILIAS/File/classes/class.ilObjFileGUI.php +++ b/components/ILIAS/File/classes/class.ilObjFileGUI.php @@ -27,8 +27,6 @@ use ILIAS\UI\Component\Input\Container\Form\Standard; use ILIAS\File\Icon\IconDatabaseRepository; use ILIAS\components\File\Settings\General; -use ILIAS\UI\Implementation\Component\Input\UploadLimitResolver; -use ILIAS\Data\DataSize; use ILIAS\Refinery\String\Group; use ILIAS\Data\Factory; use ILIAS\components\WOPI\Discovery\ActionDBRepository; @@ -38,7 +36,6 @@ use ILIAS\File\Capabilities\Capabilities; use ILIAS\File\Capabilities\CapabilityBuilder; use ILIAS\File\Capabilities\CapabilityCollection; -use ILIAS\File\Capabilities\CoreTypeResolver; use ILIAS\File\Capabilities\Context; /** @@ -90,7 +87,6 @@ class ilObjFileGUI extends ilObject2GUI protected General $general_settings; protected ilFileServicesSettings $file_service_settings; protected IconDatabaseRepository $icon_repo; - private UploadLimitResolver $upload_limit; protected \ILIAS\UI\Component\Input\Factory $inputs; protected Renderer $renderer; protected ServerRequestInterface $request; @@ -120,7 +116,6 @@ public function __construct(int $a_id = 0, int $a_id_type = self::REPOSITORY_NOD $this->obj_service = $DIC->object(); $this->lng->loadLanguageModule(ilObjFile::OBJECT_TYPE); $this->icon_repo = new IconDatabaseRepository(); - $this->upload_limit = $DIC['ui.upload_limit_resolver']; $this->inputs = $DIC->ui()->factory()->input(); $this->renderer = $DIC->ui()->renderer(); $this->request = $DIC->http()->request(); @@ -169,6 +164,7 @@ public function getParentId(): int return $this->parent_id; } + #[\Override] public function executeCommand(): void { global $DIC; @@ -233,7 +229,7 @@ public function executeCommand(): void case "ilexportgui": $ilTabs->activateTab("export"); $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat('xml'); + $exp_gui->addFormat(); $this->ctrl->forwardCommand($exp_gui); break; @@ -395,11 +391,13 @@ protected function addLegacyFormToAccordion( /** * @return array */ + #[\Override] protected function initCreateForm(string $new_type): Standard { return $this->initUploadForm(); } + #[\Override] protected function getCreationFormTitle(): string { return $this->lng->txt('upload_files'); @@ -417,19 +415,10 @@ public function initUploadForm(): Standard self::UPLOAD_ORIGIN_STANDARD ); - // add file input - $size = new DataSize( - $this->upload_limit->getBestPossibleUploadLimitInBytes($this->upload_handler), - DataSize::MB - ); $inputs[self::PARAM_FILES] = $this->ui->factory()->input()->field()->file( $this->upload_handler, $this->lng->txt('upload_files'), - sprintf( - $this->lng->txt('upload_files_limit'), - (string) $size - ), $this->ui->factory()->input()->field()->group([ self::PARAM_TITLE => $this->ui->factory()->input()->field()->text( $this->lng->txt('title') @@ -537,6 +526,7 @@ protected function uploadFiles(): void $this->ctrl->redirectToURL($link); } + #[\Override] public function putObjectInTree(ilObject $obj, ?int $parent_node_id = null): void { // this is needed to support multi fileuploads in personal and shared resources @@ -548,6 +538,7 @@ public function putObjectInTree(ilObject $obj, ?int $parent_node_id = null): voi /** * updates object entry in object_data */ + #[\Override] public function update(): void { $data = []; @@ -604,6 +595,7 @@ public function update(): void $this->ctrl->redirectByClass(self::class, self::CMD_EDIT); } + #[\Override] public function edit(): void { global $DIC; @@ -981,6 +973,7 @@ public function buildInfoScreen(bool $kiosk_mode): ilInfoScreenGUI } // get tabs + #[\Override] protected function setTabs(): void { global $DIC; @@ -1125,6 +1118,7 @@ protected function addLocatorItems(): void } } + #[\Override] protected function initHeaderAction(?string $a_sub_type = null, ?int $a_sub_id = null): ?\ilObjectListGUI { $lg = parent::initHeaderAction($a_sub_type, $a_sub_id); diff --git a/components/ILIAS/File/classes/class.ilObjFileListGUI.php b/components/ILIAS/File/classes/class.ilObjFileListGUI.php index 14754eb7df79..25558e987ff3 100755 --- a/components/ILIAS/File/classes/class.ilObjFileListGUI.php +++ b/components/ILIAS/File/classes/class.ilObjFileListGUI.php @@ -22,7 +22,6 @@ use ILIAS\components\WOPI\Discovery\ActionDBRepository; use ILIAS\File\Capabilities\Capabilities; use ILIAS\File\Capabilities\CapabilityBuilder; -use ILIAS\File\Capabilities\CoreTypeResolver; use ILIAS\File\Capabilities\Context; /** @@ -87,6 +86,7 @@ public function insertCommands(): void /** * initialisation */ + #[\Override] public function init(): void { $this->delete_enabled = true; @@ -108,6 +108,7 @@ public function init(): void $this->updateContext(); } + #[\Override] public function getCommands(): array { $this->updateContext(); @@ -125,6 +126,7 @@ public function getCommands(): array return parent::getCommands(); } + #[\Override] public function getCommandLink(string $cmd): string { $this->updateContext(); @@ -157,6 +159,7 @@ public function getCommandLink(string $cmd): string + #[\Override] public function getTitle(): string { return $this->file_info->getByObjectId($this->obj_id)->getListTitle(); @@ -167,6 +170,7 @@ public function stripTitleOfFileExtension(string $a_title): string return $this->secure(preg_replace('/\.[^.]*$/', '', $a_title)); } + #[\Override] public function getCommandFrame(string $cmd): string { $this->updateContext(); @@ -186,6 +190,7 @@ public function getCommandFrame(string $cmd): string * e.g. 'crs_offline', and/or to express a specific kind of object, e.g. * 'file_inline'. */ + #[\Override] public function getIconImageType(): string { return $this->file_info->getByObjectId($this->obj_id)->shouldDeliverInline() @@ -201,6 +206,7 @@ public function getIconImageType(): string * "property" (string) => property name * "value" (string) => property value */ + #[\Override] public function getProperties(): array { global $DIC; @@ -269,11 +275,13 @@ public function getProperties(): array /** * Get command icon image */ + #[\Override] public function getCommandImage($a_cmd): string { return ""; } + #[\Override] public function checkCommandAccess( string $permission, string $cmd, diff --git a/components/ILIAS/File/classes/class.ilObjFileStakeholder.php b/components/ILIAS/File/classes/class.ilObjFileStakeholder.php index fe9e914e0ad8..3fd0790b03f0 100755 --- a/components/ILIAS/File/classes/class.ilObjFileStakeholder.php +++ b/components/ILIAS/File/classes/class.ilObjFileStakeholder.php @@ -38,6 +38,7 @@ public function getOwnerOfNewResources(): int return $this->default_owner; } + #[\Override] public function canBeAccessedByCurrentUser(ResourceIdentification $identification): bool { global $DIC; @@ -70,6 +71,7 @@ private function resolveObjectId(ResourceIdentification $identification): ?int return (isset($d->file_id) ? (int) $d->file_id : null); } + #[\Override] public function resourceHasBeenDeleted(ResourceIdentification $identification): bool { $object_id = $this->resolveObjectId($identification); diff --git a/components/ILIAS/File/classes/class.ilObjFileUploadDropzone.php b/components/ILIAS/File/classes/class.ilObjFileUploadDropzone.php index bea2186e30eb..b25fd5be5229 100755 --- a/components/ILIAS/File/classes/class.ilObjFileUploadDropzone.php +++ b/components/ILIAS/File/classes/class.ilObjFileUploadDropzone.php @@ -18,6 +18,7 @@ declare(strict_types=1); +use ILIAS\Refinery\Factory; use ILIAS\UI\Component\Dropzone\File\File as FileDropzone; use ILIAS\UI\Component\Input\Field\UploadHandler; use ILIAS\DI\UIServices; @@ -37,13 +38,10 @@ class ilObjFileUploadDropzone protected ilLanguage $language; protected ilAccess $access; protected UIServices $ui; - protected \ILIAS\Refinery\Factory $refinery; + protected Factory $refinery; protected LOMServices $lom_services; - protected int $target_ref_id; - protected ?string $content; - - public function __construct(int $target_ref_id, ?string $content = null) + public function __construct(protected int $target_ref_id, protected ?string $content = null) { global $DIC; @@ -57,8 +55,6 @@ public function __construct(int $target_ref_id, ?string $content = null) $this->lom_services = $DIC->learningObjectMetadata(); $this->upload_handler = new ilObjFileUploadHandlerGUI(); - $this->target_ref_id = $target_ref_id; - $this->content = $content; } private function isCopyrightSelectionActive(): bool @@ -159,7 +155,7 @@ protected function getLanguage(): \ilLanguage return $this->language; } - protected function getRefinery(): \ILIAS\Refinery\Factory + protected function getRefinery(): Factory { return $this->refinery; } diff --git a/components/ILIAS/File/classes/class.ilObjFileUploadHandlerGUI.php b/components/ILIAS/File/classes/class.ilObjFileUploadHandlerGUI.php index 0e64d92f2919..65fff456e107 100755 --- a/components/ILIAS/File/classes/class.ilObjFileUploadHandlerGUI.php +++ b/components/ILIAS/File/classes/class.ilObjFileUploadHandlerGUI.php @@ -17,16 +17,6 @@ *********************************************************************/ declare(strict_types=1); - -use ILIAS\FileUpload\Handler\AbstractCtrlAwareUploadHandler; -use ILIAS\FileUpload\Handler\HandlerResult; -use ILIAS\FileUpload\Handler\FileInfoResult; -use ILIAS\FileUpload\DTO\UploadResult; -use ILIAS\FileUpload\Handler\BasicHandlerResult; -use ILIAS\FileUpload\Handler\BasicFileInfoResult; -use ILIAS\ResourceStorage\Services; -use ILIAS\Filesystem\Filesystem; -use ILIAS\Filesystem\Stream\Streams; use ILIAS\FileUpload\Handler\AbstractCtrlAwareIRSSUploadHandler; use ILIAS\ResourceStorage\Stakeholder\ResourceStakeholder; @@ -47,6 +37,7 @@ protected function getClassPath(): array return [self::class]; } + #[\Override] public function supportsChunkedUploads(): bool { return true; diff --git a/components/ILIAS/File/classes/trait.ilObjFileCopyrightInput.php b/components/ILIAS/File/classes/trait.ilObjFileCopyrightInput.php index f7db6b3af1f0..380067628642 100755 --- a/components/ILIAS/File/classes/trait.ilObjFileCopyrightInput.php +++ b/components/ILIAS/File/classes/trait.ilObjFileCopyrightInput.php @@ -19,7 +19,6 @@ declare(strict_types=1); use ILIAS\UI\Factory; -use ILIAS\MetaData\Services\ServicesInterface as LOMServices; use ILIAS\UI\Implementation\Component\Input\Field\Radio; /** diff --git a/components/ILIAS/File/classes/trait.ilObjFileMetadata.php b/components/ILIAS/File/classes/trait.ilObjFileMetadata.php index 722ec5e8babc..52ea474651ca 100755 --- a/components/ILIAS/File/classes/trait.ilObjFileMetadata.php +++ b/components/ILIAS/File/classes/trait.ilObjFileMetadata.php @@ -73,7 +73,7 @@ public function createProperties(bool $a_upload = false): void } } - public function setNoMetaDataCreation(bool $a_status) + public function setNoMetaDataCreation(bool $a_status): void { $this->no_meta_data_creation = $a_status; } diff --git a/components/ILIAS/File/classes/trait.ilObjFileSecureString.php b/components/ILIAS/File/classes/trait.ilObjFileSecureString.php index 52fbf057df78..b8fd2eabf333 100755 --- a/components/ILIAS/File/classes/trait.ilObjFileSecureString.php +++ b/components/ILIAS/File/classes/trait.ilObjFileSecureString.php @@ -36,7 +36,7 @@ protected function extractSuffixFromFilename(string $filename): string protected function stripSuffix(string $title, ?string $suffix = null): string { - $suffix = $suffix ?? $this->extractSuffixFromFilename($title); + $suffix ??= $this->extractSuffixFromFilename($title); if ($suffix !== null && ($length = strrpos($title, "." . $suffix)) > 0) { $title = substr($title, 0, $length); @@ -48,21 +48,21 @@ protected function stripSuffix(string $title, ?string $suffix = null): string protected function ensureSuffix(string $title, ?string $suffix = null): string { $title = $this->stripSuffix($title, $suffix); - $suffix = $suffix ?? $this->extractSuffixFromFilename($title); + $suffix ??= $this->extractSuffixFromFilename($title); - if ($suffix !== null && strrpos($title, "." . $suffix) === false) { + if ($suffix !== null && strrpos((string) $title, "." . $suffix) === false) { $title .= "." . $suffix; } - return $this->secure(rtrim($title, ".")); + return $this->secure(rtrim((string) $title, ".")); } protected function ensureSuffixInBrackets(string $title, ?string $suffix = null): string { $title = $this->stripSuffix($title, $suffix); - $suffix = $suffix ?? $this->extractSuffixFromFilename($title); + $suffix ??= $this->extractSuffixFromFilename($title); - if ($suffix !== null && strrpos($title, "." . $suffix) === false) { + if ($suffix !== null && strrpos((string) $title, "." . $suffix) === false) { $title .= " (" . $suffix . ")"; } diff --git a/components/ILIAS/File/classes/trait.ilObjFileTransformation.php b/components/ILIAS/File/classes/trait.ilObjFileTransformation.php index ba37c6c22ff6..e1d2f0a81444 100755 --- a/components/ILIAS/File/classes/trait.ilObjFileTransformation.php +++ b/components/ILIAS/File/classes/trait.ilObjFileTransformation.php @@ -28,9 +28,7 @@ trait ilObjFileTransformation { public function getEmptyStringToNullTransformation(): Transformation { - return $this->getRefinery()->custom()->transformation(static function ($text) { - return (empty($text)) ? null : $text; - }); + return $this->getRefinery()->custom()->transformation(static fn($text) => (empty($text)) ? null : $text); } abstract protected function getRefinery(): Factory; diff --git a/components/ILIAS/File/classes/trait.ilObjFileUsages.php b/components/ILIAS/File/classes/trait.ilObjFileUsages.php index cd0dc8c86464..ae5a6744570a 100755 --- a/components/ILIAS/File/classes/trait.ilObjFileUsages.php +++ b/components/ILIAS/File/classes/trait.ilObjFileUsages.php @@ -38,7 +38,7 @@ public static function _deleteAllUsages($a_type, $a_id, int $a_usage_hist_nr = 0 $file_ids = []; $set = $ilDB->query( - "SELECT id FROM file_usage" . " WHERE usage_type = " + 'SELECT id FROM file_usage WHERE usage_type = ' . $ilDB->quote($a_type, "text") . " AND usage_id= " . $ilDB->quote($a_id, "integer") . " AND usage_lang= " . $ilDB->quote($a_usage_lang, "text") . $and_hist @@ -73,7 +73,7 @@ public static function _saveUsage( $ilDB = $DIC['ilDB']; // check if file really exists - if (ilObject::_lookupType($a_file_id) != "file") { + if (ilObject::_lookupType($a_file_id) !== "file") { return; } // #15143 @@ -128,12 +128,12 @@ public static function _getFilesOfObject( $ilDB = $DIC['ilDB']; $lstr = ""; - if ($a_usage_lang != "") { + if ($a_usage_lang !== "") { $lstr = "usage_lang = " . $ilDB->quote($a_usage_lang, "text") . " AND "; } // get usages in learning modules - $q = "SELECT * FROM file_usage WHERE " . "usage_id = " . $ilDB->quote($a_id, "integer") + $q = 'SELECT * FROM file_usage WHERE usage_id = ' . $ilDB->quote($a_id, "integer") . " AND " . "usage_type = " . $ilDB->quote($a_type, "text") . " AND " . $lstr . "usage_hist_nr = " . $ilDB->quote($a_usage_hist_nr, "integer"); $file_set = $ilDB->query($q); diff --git a/components/ILIAS/File/tests/ilModulesFileTest.php b/components/ILIAS/File/tests/ilModulesFileTest.php index fe10de4b3289..96fdececfd6f 100755 --- a/components/ILIAS/File/tests/ilModulesFileTest.php +++ b/components/ILIAS/File/tests/ilModulesFileTest.php @@ -18,6 +18,10 @@ declare(strict_types=1); +use PHPUnit\Framework\MockObject\MockObject; +use ILIAS\Refinery\Factory; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\TestCase; use ILIAS\Filesystem\Stream\Streams; use ILIAS\DI\Container; @@ -30,16 +34,16 @@ class ilModulesFileTest extends TestCase { - private ?\ILIAS\DI\Container $dic_backup = null; + private ?Container $dic_backup = null; /** - * @var Services|\PHPUnit\Framework\MockObject\MockObject + * @var Services|MockObject */ - protected $storage_mock; + protected ?MockObject $storage_mock = null; /** - * @var ilDBInterface|\PHPUnit\Framework\MockObject\MockObject + * @var ilDBInterface|MockObject */ - protected $db_mock; - protected $manager_mock; + protected ?MockObject $db_mock = null; + protected MockObject $manager_mock; protected function setUp(): void { @@ -65,7 +69,7 @@ protected function setUp(): void $DIC['ilAppEventHandler'] = $this->createMock(ilAppEventHandler::class); $DIC['lng'] = $this->createMock(ilLanguage::class); $DIC['ilCtrl'] = $this->createMock(ilCtrlInterface::class); - $DIC['refinery'] = $this->createMock(\ILIAS\Refinery\Factory::class); + $DIC['refinery'] = $this->createMock(Factory::class); $DIC['http'] = $this->createMock(\ILIAS\HTTP\Services::class); $DIC['object.customicons.factory'] = $this->createMock(ilObjectCustomIconFactory::class); /* $DIC['ilCtrl'] = $this->getMockBuilder(ilCtrl::class) @@ -84,10 +88,8 @@ protected function tearDown(): void $DIC = $this->dic_backup; } - /** - * @preserveGlobalState disabled - * @runInSeparateProcess - */ + #[PreserveGlobalState(false)] + #[RunInSeparateProcess] public function testAppendStream(): void { $this->markTestSkipped('Failed for some unknown reason.'); @@ -102,7 +104,7 @@ public function testAppendStream(): void $this->db_mock->expects($this->any()) ->method('query') - ->willReturnCallback(function ($query) { + ->willReturnCallback(function ($query): MockObject { $mock_object = $this->createMock(ilDBStatement::class); $mock_object->expects($this->any())->method('fetchAssoc')->willReturn([$query]); @@ -162,7 +164,7 @@ public function testAppendStream(): void ->willReturnCallback( function (string $id) use (&$consecutive): ?ResourceIdentification { $expected = array_shift($consecutive); - list($eid, $ret) = $consecutive; + [$eid, $ret] = $consecutive; $this->assertEquals($eid, $id); return $ret; } diff --git a/components/ILIAS/FileDelivery/FileDelivery.php b/components/ILIAS/FileDelivery/FileDelivery.php index 176de1acb63e..a86b6dbf3f8d 100644 --- a/components/ILIAS/FileDelivery/FileDelivery.php +++ b/components/ILIAS/FileDelivery/FileDelivery.php @@ -20,7 +20,13 @@ namespace ILIAS; -class FileDelivery implements Component\Component +use ILIAS\Component\Component; +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Factory; +use ILIAS\Component\Resource\PublicAsset; +use ILIAS\Component\Resource\Endpoint; + +class FileDelivery implements Component { public function init( array | \ArrayAccess &$define, @@ -32,12 +38,12 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $contribute[\ILIAS\Setup\Agent::class] = static fn() => + $contribute[Agent::class] = static fn(): \ILIAS\FileDelivery\Setup\Agent => new \ILIAS\FileDelivery\Setup\Agent( - $pull[\ILIAS\Refinery\Factory::class] + $pull[Factory::class] ); - $contribute[Component\Resource\PublicAsset::class] = fn() => - new Component\Resource\Endpoint($this, "deliver.php"); + $contribute[PublicAsset::class] = fn(): Endpoint => + new Endpoint($this, "deliver.php"); } } diff --git a/components/ILIAS/FileDelivery/classes/Delivery.php b/components/ILIAS/FileDelivery/classes/Delivery.php index 900d516ee195..454daeae940c 100755 --- a/components/ILIAS/FileDelivery/classes/Delivery.php +++ b/components/ILIAS/FileDelivery/classes/Delivery.php @@ -20,6 +20,7 @@ namespace ILIAS\FileDelivery; +use ILIAS\FileUpload\MimeType; use ILIAS\Filesystem\Stream\FileStream; use ILIAS\HTTP\Services; use ILIAS\FileDelivery\FileDeliveryTypes\DeliveryMethod; @@ -37,9 +38,21 @@ */ final class Delivery { + /** + * @var string + */ public const DIRECT_PHP_OUTPUT = 'php://output'; + /** + * @var string + */ public const DISP_ATTACHMENT = 'attachment'; + /** + * @var string + */ public const DISP_INLINE = 'inline'; + /** + * @var string + */ public const EXPIRES_IN = '+5 days'; private static ?string $delivery_type_static = null; private string $delivery_type = DeliveryMethod::PHP; @@ -57,7 +70,6 @@ final class Delivery private bool $hash_filename = false; private bool $delete_file = false; private static bool $DEBUG = false; - private Services $http; private FileDeliveryTypeFactory $factory; private ?FileStream $resource = null; @@ -66,9 +78,8 @@ final class Delivery * @param string|FileStream $path_to_file * @param Services $http */ - public function __construct($input, Services $http) + public function __construct($input, private Services $http) { - $this->http = $http; if ($input instanceof FileStream) { $this->resource = $input; $this->path_to_file = $input->getMetadata('uri'); @@ -83,7 +94,7 @@ public function __construct($input, Services $http) $this->determineDownloadFileName(); $this->setHasContext(\ilContext::getType() !== null); - $this->factory = new FileDeliveryTypeFactory($http); + $this->factory = new FileDeliveryTypeFactory($this->http); } @@ -181,8 +192,8 @@ public function close(): void private function determineMimeType(): void { - $info = \ILIAS\FileUpload\MimeType::lookupMimeType($this->getPathToFile(), \ILIAS\FileUpload\MimeType::APPLICATION__OCTET_STREAM); - if ($info) { + $info = MimeType::lookupMimeType($this->getPathToFile(), MimeType::APPLICATION__OCTET_STREAM); + if ($info !== '' && $info !== '0') { $this->setMimeType($info); return; @@ -200,7 +211,7 @@ private function determineMimeType(): void private function determineDownloadFileName(): void { - if (!$this->getDownloadFileName()) { + if ($this->getDownloadFileName() === '' || $this->getDownloadFileName() === '0') { $download_file_name = basename($this->getPathToFile()); $this->setDownloadFileName($download_file_name); } @@ -221,9 +232,9 @@ private function detemineDeliveryType(): void $this->setDeliveryType(DeliveryMethod::XSENDFILE); } -// if (function_exists('apache_get_version') && strpos(apache_get_version(), '2.4.') !== false) { -// $this->setDeliveryType(DeliveryMethod::XSENDFILE); -// } + // if (function_exists('apache_get_version') && strpos(apache_get_version(), '2.4.') !== false) { + // $this->setDeliveryType(DeliveryMethod::XSENDFILE); + // } if (is_file('./components/ILIAS/FileDelivery/classes/override.php')) { $override_delivery_type = false; @@ -241,7 +252,7 @@ private function detemineDeliveryType(): void } if ($this->getDeliveryType() === DeliveryMethod::XACCEL - && strpos($this->getPathToFile(), './public/data') !== 0 + && !str_starts_with($this->getPathToFile(), './public/data') ) { $this->setDeliveryType(DeliveryMethod::PHP); } @@ -408,7 +419,7 @@ public function setHashFilename(bool $hash_filename): void private function sendEtagHeader(): void { - if ($this->getEtag()) { + if ($this->getEtag() !== '' && $this->getEtag() !== '0') { $response = $this->http->response()->withHeader('ETag', $this->getEtag()); $this->http->saveResponse($response); } @@ -463,7 +474,7 @@ public function clearBuffer(): bool } ob_end_clean(); // fixed 0016469, 0016467, 0016468 return true; - } catch (\Throwable $t) { + } catch (\Throwable) { return false; } } @@ -513,13 +524,13 @@ public static function returnASCIIFileName(string $original_filename): string $ascii_filename = htmlentities($original_filename, ENT_NOQUOTES, 'UTF-8'); $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename); - $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename); + $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', (string) $ascii_filename); // OS do not allow the following characters in filenames: \/:*?"<>| $ascii_filename = preg_replace( '/[:\x5c\/\*\?\"<>\|]/', '_', - $ascii_filename + (string) $ascii_filename ); return $ascii_filename; } diff --git a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/FileDeliveryTypeFactory.php b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/FileDeliveryTypeFactory.php index 55c4753c92a8..bfa902743383 100755 --- a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/FileDeliveryTypeFactory.php +++ b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/FileDeliveryTypeFactory.php @@ -37,8 +37,7 @@ final class FileDeliveryTypeFactory /** * @var ilFileDeliveryType[] */ - private static array $instances = array(); - private \ILIAS\HTTP\Services $http; + private static array $instances = []; /** @@ -46,9 +45,8 @@ final class FileDeliveryTypeFactory * * @param Services $http */ - public function __construct(Services $http) + public function __construct(private Services $http) { - $this->http = $http; } @@ -62,28 +60,19 @@ public function __construct(Services $http) * * @see DeliveryMethod */ - public function getInstance(string $type): \ILIAS\FileDelivery\ilFileDeliveryType + public function getInstance(string $type): ilFileDeliveryType { assert(is_string($type)); if (isset(self::$instances[$type])) { return self::$instances[$type]; } - switch ($type) { - case DeliveryMethod::PHP: - self::$instances[$type] = new PHP($this->http); - break; - case DeliveryMethod::XSENDFILE: - self::$instances[$type] = new XSendfile($this->http); - break; - case DeliveryMethod::XACCEL: - self::$instances[$type] = new XAccel($this->http); - break; - case DeliveryMethod::PHP_CHUNKED: - self::$instances[$type] = new PHPChunked($this->http); - break; - default: - throw new \ilException("Unknown file delivery type \"$type\""); - } + self::$instances[$type] = match ($type) { + DeliveryMethod::PHP => new PHP($this->http), + DeliveryMethod::XSENDFILE => new XSendfile($this->http), + DeliveryMethod::XACCEL => new XAccel($this->http), + DeliveryMethod::PHP_CHUNKED => new PHPChunked($this->http), + default => throw new \ilException("Unknown file delivery type \"$type\""), + }; return self::$instances[$type]; } diff --git a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/PHP.php b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/PHP.php index 4a80deaf7db6..ee3031e7acbe 100755 --- a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/PHP.php +++ b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/PHP.php @@ -39,17 +39,15 @@ final class PHP implements ilFileDeliveryType * @var resource */ protected $file; - protected \ILIAS\HTTP\Services $httpService; /** * PHP constructor. * - * @param Services $httpState + * @param Services $httpService */ - public function __construct(Services $httpState) + public function __construct(protected Services $httpService) { - $this->httpService = $httpState; } @@ -68,11 +66,7 @@ public function doesFileExists(string $path_to_file): bool public function prepare(string $path_to_file, ?FileStream $possible_stream): bool { set_time_limit(0); - if ($possible_stream !== null) { - $this->file = $possible_stream->detach(); - } else { - $this->file = fopen($path_to_file, 'rb'); - } + $this->file = $possible_stream !== null ? $possible_stream->detach() : fopen($path_to_file, 'rb'); return true; } diff --git a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/PHPChunked.php b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/PHPChunked.php index 0c8e1850a5df..5e44b465127c 100755 --- a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/PHPChunked.php +++ b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/PHPChunked.php @@ -34,7 +34,6 @@ */ final class PHPChunked implements ilFileDeliveryType { - private \ILIAS\HTTP\Services $httpService; /** * @var resource|null */ @@ -44,11 +43,10 @@ final class PHPChunked implements ilFileDeliveryType /** * PHP constructor. * - * @param Services $httpState + * @param Services $httpService */ - public function __construct(Services $httpState) + public function __construct(private Services $httpService) { - $this->httpService = $httpState; } @@ -119,9 +117,9 @@ public function deliver(string $path_to_file, bool $file_marked_to_delete): void $c_end = $end; // Extract the range string - [, $range] = explode('=', $server['HTTP_RANGE'], 2); + [, $range] = explode('=', (string) $server['HTTP_RANGE'], 2); // Make sure the client hasn't sent us a multibyte range - if (strpos($range, ',') !== false) { + if (str_contains($range, ',')) { // (?) Shoud this be issued here, or should the first // range be used? Or should the header be ignored and // we output the whole content? @@ -220,7 +218,7 @@ public function supportsStreaming(): bool } - private function close(): void + private function close(): never { //render response $this->httpService->sendResponse(); diff --git a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/XAccel.php b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/XAccel.php index 08f9f37ba7be..2bbdca000c7d 100755 --- a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/XAccel.php +++ b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/XAccel.php @@ -35,20 +35,27 @@ final class XAccel implements ilFileDeliveryType { use HeaderBasedDeliveryHelper; + /** + * @var string + */ public const DATA = 'data'; + /** + * @var string + */ public const SECURED_DATA = 'secured-data'; - private \ILIAS\HTTP\Services $httpService; + /** + * @var string + */ public const X_ACCEL_REDIRECT = 'X-Accel-Redirect'; /** * PHP constructor. * - * @param Services $httpState + * @param Services $httpService */ - public function __construct(Services $httpState) + public function __construct(private Services $httpService) { - $this->httpService = $httpState; } /** @@ -80,7 +87,7 @@ public function prepare(string $path_to_file, ?FileStream $possible_stream): boo public function deliver(string $path_to_file, bool $file_marked_to_delete): void { // There is currently no way to delete the file after delivery - if (strpos($path_to_file, './' . self::DATA . '/') === 0) { + if (str_starts_with($path_to_file, './' . self::DATA . '/')) { $path_to_file = str_replace('./' . self::DATA . '/', '/' . self::SECURED_DATA . '/', $path_to_file); } diff --git a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/XSendfile.php b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/XSendfile.php index 26f481036535..c745d44375bc 100755 --- a/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/XSendfile.php +++ b/components/ILIAS/FileDelivery/classes/FileDeliveryTypes/XSendfile.php @@ -34,20 +34,23 @@ final class XSendfile implements ilFileDeliveryType { use HeaderBasedDeliveryHelper; + /** + * @var string + */ public const X_SENDFILE = 'X-Sendfile'; + /** + * @var string + */ public const X_SENDFILE_TEMPORARY = 'X-Sendfile-Temporary'; - private \ILIAS\HTTP\Services $httpService; /** * PHP constructor. * - * @param Services $httpState - * + * @param Services $httpService */ - public function __construct(Services $httpState) + public function __construct(private Services $httpService) { - $this->httpService = $httpState; } diff --git a/components/ILIAS/FileDelivery/classes/HttpServiceAware.php b/components/ILIAS/FileDelivery/classes/HttpServiceAware.php index 60a4259af2d8..de85044fc467 100755 --- a/components/ILIAS/FileDelivery/classes/HttpServiceAware.php +++ b/components/ILIAS/FileDelivery/classes/HttpServiceAware.php @@ -20,8 +20,6 @@ namespace ILIAS\FileDelivery; -use ILIAS\HTTP\Services; - /** * Trait HttpServiceAware * diff --git a/components/ILIAS/FileDelivery/classes/class.ilFileDelivery.php b/components/ILIAS/FileDelivery/classes/class.ilFileDelivery.php index 7693def1d3fd..3e2a80023e9b 100755 --- a/components/ILIAS/FileDelivery/classes/class.ilFileDelivery.php +++ b/components/ILIAS/FileDelivery/classes/class.ilFileDelivery.php @@ -36,12 +36,33 @@ final class ilFileDelivery implements ilFileDeliveryService { use HttpServiceAware; + /** + * @var string + */ public const DIRECT_PHP_OUTPUT = Delivery::DIRECT_PHP_OUTPUT; + /** + * @var string + */ public const DELIVERY_METHOD_XSENDFILE = DeliveryMethod::XSENDFILE; + /** + * @var string + */ public const DELIVERY_METHOD_XACCEL = DeliveryMethod::XACCEL; + /** + * @var string + */ public const DELIVERY_METHOD_PHP = DeliveryMethod::PHP; + /** + * @var string + */ public const DELIVERY_METHOD_PHP_CHUNKED = DeliveryMethod::PHP_CHUNKED; + /** + * @var string + */ public const DISP_ATTACHMENT = Delivery::DISP_ATTACHMENT; + /** + * @var string + */ public const DISP_INLINE = Delivery::DISP_INLINE; private Delivery $delivery; diff --git a/components/ILIAS/FileDelivery/classes/class.ilSecureTokenSrcBuilder.php b/components/ILIAS/FileDelivery/classes/class.ilSecureTokenSrcBuilder.php index c35e6434d6a7..2c8f41a552e2 100755 --- a/components/ILIAS/FileDelivery/classes/class.ilSecureTokenSrcBuilder.php +++ b/components/ILIAS/FileDelivery/classes/class.ilSecureTokenSrcBuilder.php @@ -16,13 +16,10 @@ *********************************************************************/ declare(strict_types=1); - -use ILIAS\GlobalScreen\Scope\MainMenu\Collector\Renderer\Hasher; use ILIAS\ResourceStorage\Consumer\InlineSrcBuilder; use ILIAS\ResourceStorage\Consumer\SrcBuilder; use ILIAS\ResourceStorage\Flavour\Flavour; use ILIAS\ResourceStorage\Revision\Revision; -use ILIAS\ResourceStorage\StorageHandler\StorageHandler; use ILIAS\FileDelivery\Delivery\Disposition; use ILIAS\FileDelivery\Services; diff --git a/components/ILIAS/FileDelivery/src/Delivery/BaseDelivery.php b/components/ILIAS/FileDelivery/src/Delivery/BaseDelivery.php index 51e48233bd83..46637c07d49b 100644 --- a/components/ILIAS/FileDelivery/src/Delivery/BaseDelivery.php +++ b/components/ILIAS/FileDelivery/src/Delivery/BaseDelivery.php @@ -20,10 +20,10 @@ namespace ILIAS\FileDelivery\Delivery; +use ILIAS\HTTP\Services; use ILIAS\FileDelivery\Delivery\ResponseBuilder\ResponseBuilder; use ILIAS\HTTP\Response\ResponseHeader; use Psr\Http\Message\ResponseInterface; -use ILIAS\FileDelivery\Token\Data\Stream; /** * @author Fabian Schmid @@ -35,7 +35,7 @@ abstract class BaseDelivery protected array $mime_type_map; public function __construct( - protected \ILIAS\HTTP\Services $http, + protected Services $http, protected ResponseBuilder $response_builder, protected ResponseBuilder $fallback_response_builder, ) { @@ -49,7 +49,7 @@ protected function saveAndClose( ResponseInterface $r, ?string $path_to_delete = null ): never { - $sender = function () use ($r) { + $sender = function () use ($r): void { $this->http->saveResponse($r); $this->http->sendResponse(); $this->http->close(); diff --git a/components/ILIAS/FileDelivery/src/Delivery/LegacyDelivery.php b/components/ILIAS/FileDelivery/src/Delivery/LegacyDelivery.php index dfc68d0952e5..9f4c1647a192 100755 --- a/components/ILIAS/FileDelivery/src/Delivery/LegacyDelivery.php +++ b/components/ILIAS/FileDelivery/src/Delivery/LegacyDelivery.php @@ -20,7 +20,6 @@ namespace ILIAS\FileDelivery\Delivery; -use ILIAS\FileDelivery\Token\Data\Stream; use ILIAS\Filesystem\Stream\Streams; /** diff --git a/components/ILIAS/FileDelivery/src/Delivery/ResponseBuilder/XAccelResponseBuilder.php b/components/ILIAS/FileDelivery/src/Delivery/ResponseBuilder/XAccelResponseBuilder.php index 39a2a7640325..9f9a4a1234b3 100755 --- a/components/ILIAS/FileDelivery/src/Delivery/ResponseBuilder/XAccelResponseBuilder.php +++ b/components/ILIAS/FileDelivery/src/Delivery/ResponseBuilder/XAccelResponseBuilder.php @@ -29,8 +29,17 @@ */ class XAccelResponseBuilder implements ResponseBuilder { + /** + * @var string + */ private const DATA = 'data'; + /** + * @var string + */ private const SECURED_DATA = 'secured-data'; + /** + * @var string + */ private const X_ACCEL_REDIRECT_HEADER = 'X-Accel-Redirect'; public function getName(): string diff --git a/components/ILIAS/FileDelivery/src/Delivery/ResponseBuilder/XSendFileResponseBuilder.php b/components/ILIAS/FileDelivery/src/Delivery/ResponseBuilder/XSendFileResponseBuilder.php index 71a635a9b4ce..393b00a952cd 100755 --- a/components/ILIAS/FileDelivery/src/Delivery/ResponseBuilder/XSendFileResponseBuilder.php +++ b/components/ILIAS/FileDelivery/src/Delivery/ResponseBuilder/XSendFileResponseBuilder.php @@ -29,6 +29,9 @@ */ class XSendFileResponseBuilder implements ResponseBuilder { + /** + * @var string + */ private const X_SENDFILE_HEADER = 'X-Sendfile'; public function getName(): string diff --git a/components/ILIAS/FileDelivery/src/Delivery/StreamDelivery.php b/components/ILIAS/FileDelivery/src/Delivery/StreamDelivery.php index e0a5c654b674..1bc46004c4fb 100644 --- a/components/ILIAS/FileDelivery/src/Delivery/StreamDelivery.php +++ b/components/ILIAS/FileDelivery/src/Delivery/StreamDelivery.php @@ -20,9 +20,11 @@ namespace ILIAS\FileDelivery\Delivery; +use ILIAS\HTTP\Services; +use Psr\Http\Message\ResponseInterface; +use ILIAS\HTTP\Response\Sender\ResponseSendingException; use ILIAS\FileDelivery\Token\DataSigner; use ILIAS\FileDelivery\Delivery\ResponseBuilder\ResponseBuilder; -use ILIAS\FileDelivery\Token\Data\Stream; use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileDelivery\Token\Signer\Payload\FilePayload; use ILIAS\Filesystem\Stream\Streams; @@ -34,11 +36,14 @@ */ final class StreamDelivery extends BaseDelivery { + /** + * @var string + */ public const SUBREQUEST_SEPARATOR = '/-/'; public function __construct( private DataSigner $data_signer, - \ILIAS\HTTP\Services $http, + Services $http, ResponseBuilder $response_builder, ResponseBuilder $fallback_response_builder, ) { @@ -46,11 +51,11 @@ public function __construct( } /** - * @param \Psr\Http\Message\ResponseInterface $r + * @param ResponseInterface $r * @return void - * @throws \ILIAS\HTTP\Response\Sender\ResponseSendingException + * @throws ResponseSendingException */ - protected function notFound(\Psr\Http\Message\ResponseInterface $r): void + protected function notFound(ResponseInterface $r): void { $this->http->saveResponse($r->withStatus(404)); $this->http->sendResponse(); diff --git a/components/ILIAS/FileDelivery/src/Init.php b/components/ILIAS/FileDelivery/src/Init.php index 3c7f01a7ed4d..22f9744cf978 100755 --- a/components/ILIAS/FileDelivery/src/Init.php +++ b/components/ILIAS/FileDelivery/src/Init.php @@ -20,6 +20,7 @@ namespace ILIAS\FileDelivery; +use ILIAS\FileDelivery\Delivery\StreamDelivery; use ILIAS\DI\Container; use ILIAS\FileDelivery\Setup\KeyRotationObjective; use ILIAS\FileDelivery\Token\Signer\Key\Secret\SecretKey; @@ -42,25 +43,17 @@ public static function init(Container $c): void $c['file_delivery.response_builder'] = static function (): ResponseBuilder { $settings = (@include DeliveryMethodObjective::PATH()) ?? []; - switch ($settings[DeliveryMethodObjective::SETTINGS] ?? null) { - case DeliveryMethodObjective::XACCEL: - return new XAccelResponseBuilder(); - case DeliveryMethodObjective::XSENDFILE: - return new XSendFileResponseBuilder(); - case DeliveryMethodObjective::PHP: - default: - return new PHPResponseBuilder(); - } + return match ($settings[DeliveryMethodObjective::SETTINGS] ?? null) { + DeliveryMethodObjective::XACCEL => new XAccelResponseBuilder(), + DeliveryMethodObjective::XSENDFILE => new XSendFileResponseBuilder(), + default => new PHPResponseBuilder(), + }; }; - $c['file_delivery.fallback_response_builder'] = static function (): ResponseBuilder { - return new PHPResponseBuilder(); - }; + $c['file_delivery.fallback_response_builder'] = (static fn(): ResponseBuilder => new PHPResponseBuilder()); $c['file_delivery.data_signer'] = static function (): DataSigner { - $keys = array_map(static function (string $key): SecretKey { - return new SecretKey($key); - }, (require KeyRotationObjective::PATH()) ?? []); + $keys = array_map(static fn(string $key): SecretKey => new SecretKey($key), (require KeyRotationObjective::PATH()) ?? []); $current_key = array_shift($keys); @@ -72,14 +65,14 @@ public static function init(Container $c): void ); }; - $c['file_delivery.delivery'] = static function () use ($c): \ILIAS\FileDelivery\Delivery\StreamDelivery { + $c['file_delivery.delivery'] = static function () use ($c): StreamDelivery { // if http is not initialized, we need to do it here if (!$c->offsetExists('http')) { $init_http = new \InitHttpServices(); $init_http->init($c); } - return new \ILIAS\FileDelivery\Delivery\StreamDelivery( + return new StreamDelivery( $c['file_delivery.data_signer'], $c['http'], $c['file_delivery.response_builder'], @@ -101,13 +94,11 @@ public static function init(Container $c): void ); }; - $c['file_delivery'] = static function () use ($c): Services { - return new Services( - $c['file_delivery.delivery'], - $c['file_delivery.legacy_delivery'], - $c['file_delivery.data_signer'], - $c['http'] - ); - }; + $c['file_delivery'] = (static fn(): Services => new Services( + $c['file_delivery.delivery'], + $c['file_delivery.legacy_delivery'], + $c['file_delivery.data_signer'], + $c['http'] + )); } } diff --git a/components/ILIAS/FileDelivery/src/Services.php b/components/ILIAS/FileDelivery/src/Services.php index 91b92d460aac..54ce4f44a460 100755 --- a/components/ILIAS/FileDelivery/src/Services.php +++ b/components/ILIAS/FileDelivery/src/Services.php @@ -20,6 +20,7 @@ namespace ILIAS\FileDelivery; +use ILIAS\FileDelivery\Delivery\StreamDelivery; use ILIAS\FileDelivery\Token\DataSigner; use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileDelivery\Delivery\Disposition; @@ -36,14 +37,14 @@ class Services private ?string $base_uri = null; public function __construct( - private \ILIAS\FileDelivery\Delivery\StreamDelivery $delivery, + private StreamDelivery $delivery, private LegacyDelivery $legacy_delivery, private DataSigner $data_signer, private \ILIAS\HTTP\Services $http ) { } - public function delivery(): \ILIAS\FileDelivery\Delivery\StreamDelivery + public function delivery(): StreamDelivery { return $this->delivery; } diff --git a/components/ILIAS/FileDelivery/src/Setup/Agent.php b/components/ILIAS/FileDelivery/src/Setup/Agent.php index 6fa5b58307c9..ca768527be11 100755 --- a/components/ILIAS/FileDelivery/src/Setup/Agent.php +++ b/components/ILIAS/FileDelivery/src/Setup/Agent.php @@ -20,10 +20,12 @@ namespace ILIAS\FileDelivery\Setup; +use ILIAS\Setup\ObjectiveCollection; +use ILIAS\Setup\Metrics\Storage; +use ILIAS\Setup\Objective\NullObjective; use ILIAS\Setup; use ILIAS\Setup\Objective; use ILIAS\Refinery\Transformation; -use ILIAS\Setup\Metrics; use ILIAS\Setup\Config; /** @@ -33,7 +35,7 @@ class Agent implements Setup\Agent { public function getBuildObjective(): Objective { - return new Setup\ObjectiveCollection( + return new ObjectiveCollection( 'File StreamDelivery Artifacts', true, new KeyRotationObjective(), @@ -67,9 +69,9 @@ public function getUpdateObjective(?Config $config = null): Objective return new DeliveryMethodObjective(); } - public function getStatusObjective(Metrics\Storage $storage): Objective + public function getStatusObjective(Storage $storage): Objective { - return new Objective\NullObjective(); + return new NullObjective(); } public function getMigrations(): array diff --git a/components/ILIAS/FileDelivery/src/Setup/BaseDirObjective.php b/components/ILIAS/FileDelivery/src/Setup/BaseDirObjective.php index 1a5f9a262090..a26f687dde76 100644 --- a/components/ILIAS/FileDelivery/src/Setup/BaseDirObjective.php +++ b/components/ILIAS/FileDelivery/src/Setup/BaseDirObjective.php @@ -20,8 +20,10 @@ namespace ILIAS\FileDelivery\Setup; +use ILIAS\Setup\Environment; +use ILIAS\Setup\Artifact; +use ILIAS\Setup\Artifact\ArrayArtifact; use ILIAS\Setup\Artifact\BuildArtifactObjective; -use ILIAS\Setup; /** * @author Fabian Schmid @@ -37,9 +39,10 @@ public function getArtifactPath(): string return self::BASE_DIR; } - public function buildIn(Setup\Environment $env): Setup\Artifact + #[\Override] + public function buildIn(Environment $env): Artifact { - $ilias_ini = $env->getResource(Setup\Environment::RESOURCE_ILIAS_INI); + $ilias_ini = $env->getResource(Environment::RESOURCE_ILIAS_INI); if ($ilias_ini instanceof \ilIniFile) { $base_dir = $ilias_ini->readVariable('clients', 'datadir'); $client_id = $ilias_ini->readVariable('clients', 'default'); @@ -55,12 +58,13 @@ public function getArtifactName(): string return 'base_dir'; } - public function build(): Setup\Artifact + public function build(): Artifact { - return new Setup\Artifact\ArrayArtifact($this->data); + return new ArrayArtifact($this->data); } - public function getPreconditions(Setup\Environment $environment): array + #[\Override] + public function getPreconditions(Environment $environment): array { return [ new \ilIniFilesLoadedObjective(), diff --git a/components/ILIAS/FileDelivery/src/Setup/DeliveryMethodObjective.php b/components/ILIAS/FileDelivery/src/Setup/DeliveryMethodObjective.php index 06973186d14e..70b22ac88d51 100755 --- a/components/ILIAS/FileDelivery/src/Setup/DeliveryMethodObjective.php +++ b/components/ILIAS/FileDelivery/src/Setup/DeliveryMethodObjective.php @@ -20,8 +20,10 @@ namespace ILIAS\FileDelivery\Setup; +use ILIAS\Setup\Artifact; +use ILIAS\Setup\Artifact\ArrayArtifact; +use ILIAS\Setup\Environment; use ILIAS\Setup\Artifact\BuildArtifactObjective; -use ILIAS\Setup; /** * @author Fabian Schmid @@ -40,16 +42,16 @@ public function getArtifactName(): string - public function build(): Setup\Artifact + public function build(): Artifact { // check if mod_xsendfile is loaded if ($this->isModXSendFileLoaded()) { - return new Setup\Artifact\ArrayArtifact([ + return new ArrayArtifact([ self::SETTINGS => self::XSENDFILE ]); } - return new Setup\Artifact\ArrayArtifact([ + return new ArrayArtifact([ self::SETTINGS => self::PHP ]); } @@ -66,19 +68,15 @@ private function isModXSendFileLoaded(): bool return false; } - $loaded_modules = array_map(static function ($module) { - return explode(" ", trim($module))[0] ?? ""; - }, explode("\n", shell_exec("apache2ctl -M 2>/dev/null") ?? '')); - } catch (\Throwable $e) { + $loaded_modules = array_map(static fn($module): string => explode(" ", trim((string) $module))[0] ?? "", explode("\n", shell_exec("apache2ctl -M 2>/dev/null") ?? '')); + } catch (\Throwable) { $loaded_modules = []; } - if (in_array('xsendfile_module', $loaded_modules, true)) { - return true; - } - return false; + return in_array('xsendfile_module', $loaded_modules, true); } - public function isApplicable(Setup\Environment $environment): bool + #[\Override] + public function isApplicable(Environment $environment): bool { return !file_exists(BuildArtifactObjective::PATH()); } diff --git a/components/ILIAS/FileDelivery/src/Setup/KeyRotationObjective.php b/components/ILIAS/FileDelivery/src/Setup/KeyRotationObjective.php index 8e3df5847288..37912eaa20c3 100755 --- a/components/ILIAS/FileDelivery/src/Setup/KeyRotationObjective.php +++ b/components/ILIAS/FileDelivery/src/Setup/KeyRotationObjective.php @@ -20,8 +20,9 @@ namespace ILIAS\FileDelivery\Setup; +use ILIAS\Setup\Artifact; +use ILIAS\Setup\Artifact\ArrayArtifact; use ILIAS\Setup\Artifact\BuildArtifactObjective; -use ILIAS\Setup; /** * @author Fabian Schmid @@ -29,6 +30,9 @@ class KeyRotationObjective extends BuildArtifactObjective { public const KEY_LENGTH = 32; + /** + * @var int + */ private const NUMBER_OF_KEYS = 5; public function getArtifactName(): string { @@ -36,7 +40,7 @@ public function getArtifactName(): string } - public function build(): Setup\Artifact + public function build(): Artifact { $current_keys = null; if (is_readable(self::PATH())) { @@ -58,7 +62,7 @@ public function build(): Setup\Artifact // keep only the first 5 keys $new_keys = array_slice($new_keys, 0, self::NUMBER_OF_KEYS); - return new Setup\Artifact\ArrayArtifact($new_keys); + return new ArrayArtifact($new_keys); } private function generateRandomString(int $length): string diff --git a/components/ILIAS/FileDelivery/src/Token/Compression/DeflateCompression.php b/components/ILIAS/FileDelivery/src/Token/Compression/DeflateCompression.php index dd3776152f2a..c4e858c55758 100755 --- a/components/ILIAS/FileDelivery/src/Token/Compression/DeflateCompression.php +++ b/components/ILIAS/FileDelivery/src/Token/Compression/DeflateCompression.php @@ -25,6 +25,9 @@ */ class DeflateCompression implements Compression { + /** + * @var int + */ private const LEVEL = 9; /** diff --git a/components/ILIAS/FileDelivery/src/Token/DataSigner.php b/components/ILIAS/FileDelivery/src/Token/DataSigner.php index b72b90b937a4..a7e593e2928e 100755 --- a/components/ILIAS/FileDelivery/src/Token/DataSigner.php +++ b/components/ILIAS/FileDelivery/src/Token/DataSigner.php @@ -26,17 +26,14 @@ use ILIAS\FileDelivery\Token\Signer\Payload\Payload; use ILIAS\FileDelivery\Token\Signer\HMACSigner; use ILIAS\FileDelivery\Token\Serializer\JSONSerializer; -use ILIAS\FileDelivery\Token\Signer\Key\DigestMethod\Concat as NoneDigest; use ILIAS\FileDelivery\Token\Signer\Key\Signing\HMACSigningKeyGenerator; use ILIAS\FileDelivery\Token\Signer\Algorithm\SHA1; -use ILIAS\FileDelivery\Token\Compression\GZipCompression; use ILIAS\FileDelivery\Token\Transport\URLSafeTransport; use ILIAS\FileDelivery\Token\Compression\DeflateCompression; use ILIAS\FileDelivery\Token\Signer\KeyRotatingSigner; use ILIAS\FileDelivery\Token\Signer\Salt\Factory; use ILIAS\FileDelivery\Token\Signer\Payload\StructuredPayload; use ILIAS\Filesystem\Stream\FileStream; -use ILIAS\FileDelivery\Token\Data\Stream; use ILIAS\FileDelivery\Token\Compression\Compression; use ILIAS\FileDelivery\Token\Transport\Transport; use ILIAS\FileDelivery\Token\Signer\Payload\Builder; @@ -90,8 +87,7 @@ public function getSignedStreamToken( ): string { $payload = $this->payload_builder->shortFile( $stream, - $filename, - $disposition + $filename ); if ($until !== null) { diff --git a/components/ILIAS/FileDelivery/src/Token/Request.php b/components/ILIAS/FileDelivery/src/Token/Request.php index 9f4e588f4cae..9c9ffd688976 100755 --- a/components/ILIAS/FileDelivery/src/Token/Request.php +++ b/components/ILIAS/FileDelivery/src/Token/Request.php @@ -20,7 +20,6 @@ namespace ILIAS\FileDelivery\Token; -use ILIAS\FileDelivery\Token\Compression\GZipCompression; use ILIAS\FileDelivery\Delivery\Disposition; use ILIAS\Filesystem\Stream\FileStream; diff --git a/components/ILIAS/FileDelivery/src/Token/Signer/HMACSigner.php b/components/ILIAS/FileDelivery/src/Token/Signer/HMACSigner.php index 97b4421319fb..67b2a7508b32 100755 --- a/components/ILIAS/FileDelivery/src/Token/Signer/HMACSigner.php +++ b/components/ILIAS/FileDelivery/src/Token/Signer/HMACSigner.php @@ -20,7 +20,6 @@ namespace ILIAS\FileDelivery\Token\Signer; -use ILIAS\FileDelivery\Token\Signer\Key\DigestMethod\DigestMethod; use ILIAS\FileDelivery\Token\Signer\Algorithm\Algorithm; use ILIAS\FileDelivery\Token\Signer\Key\Signing\SigningKey; @@ -62,10 +61,6 @@ public function verify( if ($signature_check !== $signature) { return false; } - if ($validity > 0 && $validity < time()) { - return false; - } - - return true; + return !($validity > 0 && $validity < time()); } } diff --git a/components/ILIAS/FileDelivery/src/Token/Signer/Payload/ShortFilePayload.php b/components/ILIAS/FileDelivery/src/Token/Signer/Payload/ShortFilePayload.php index 8b952338bfec..def01d49d44e 100644 --- a/components/ILIAS/FileDelivery/src/Token/Signer/Payload/ShortFilePayload.php +++ b/components/ILIAS/FileDelivery/src/Token/Signer/Payload/ShortFilePayload.php @@ -27,6 +27,9 @@ */ class ShortFilePayload extends StructuredPayload { + public $mime_type; + public $disposition; + public $user_id; public function __construct( private string $uri, private string $file_name @@ -57,7 +60,7 @@ public function getUri(): string // try to expand uri $base = BaseDirObjective::get(); if ($base !== null) { - $uri = $base . $uri; + return $base . $uri; } return $uri; diff --git a/components/ILIAS/FileDelivery/src/Token/Signer/Salt/Factory.php b/components/ILIAS/FileDelivery/src/Token/Signer/Salt/Factory.php index 53411c05f0f2..d7d8760327ca 100755 --- a/components/ILIAS/FileDelivery/src/Token/Signer/Salt/Factory.php +++ b/components/ILIAS/FileDelivery/src/Token/Signer/Salt/Factory.php @@ -36,11 +36,11 @@ */ class Factory { - private array $known_salts; + private array $known_salts = []; public function __construct() { - $this->known_salts = []; // TODO: load known salts from artifact + // TODO: load known salts from artifact } public function create(string $salt): Salt diff --git a/components/ILIAS/FileDelivery/src/Token/SigningSerializer.php b/components/ILIAS/FileDelivery/src/Token/SigningSerializer.php index c61c85a69488..72c203c2b65b 100755 --- a/components/ILIAS/FileDelivery/src/Token/SigningSerializer.php +++ b/components/ILIAS/FileDelivery/src/Token/SigningSerializer.php @@ -23,7 +23,6 @@ use ILIAS\FileDelivery\Token\Serializer\Serializer; use ILIAS\FileDelivery\Token\Signer\Payload\Payload; use ILIAS\FileDelivery\Token\Signer\Payload\StructuredPayload; -use ILIAS\FileDelivery\Token\Compression\GZipCompression; use ILIAS\FileDelivery\Token\Compression\Compression; use ILIAS\FileDelivery\Token\Transport\Transport; use ILIAS\FileDelivery\Token\Signer\KeyRotatingSigner; @@ -36,6 +35,9 @@ */ final class SigningSerializer { + /** + * @var string + */ private const SEPARATOR = '<<>>'; public function __construct( @@ -72,7 +74,7 @@ public function verify(string $data, Salt $salt): ?Payload $decompressed_payload = $this->compression->decompress( $this->transport->readFromTransport($data) ); - } catch (\Throwable $e) { + } catch (\Throwable) { return null; } diff --git a/components/ILIAS/FileDelivery/src/artifacts/delivery_method.php b/components/ILIAS/FileDelivery/src/artifacts/delivery_method.php index 2f521ce51ae8..2db7c2cb3503 100755 --- a/components/ILIAS/FileDelivery/src/artifacts/delivery_method.php +++ b/components/ILIAS/FileDelivery/src/artifacts/delivery_method.php @@ -1,4 +1,5 @@ - 'php', -); \ No newline at end of file +]; diff --git a/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/FileDeliveryTypeFactoryTest.php b/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/FileDeliveryTypeFactoryTest.php index a2d28ea44d6c..8378effff141 100755 --- a/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/FileDeliveryTypeFactoryTest.php +++ b/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/FileDeliveryTypeFactoryTest.php @@ -20,6 +20,12 @@ namespace ILIAS\Tests\FileDelivery\FileDeliveryTypes; +use PHPUnit\Framework\Attributes\BackupGlobals; +use PHPUnit\Framework\Attributes\BackupStaticProperties; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\MockObject\MockObject; use ilException; use ILIAS\HTTP\Services; use PHPUnit\Framework\TestCase; @@ -32,17 +38,16 @@ * Class FileDeliveryTypeFactoryTest * * @author Nicolas Schäfli - * - * @runInSeparateProcess - * @preserveGlobalState disabled - * @backupGlobals disabled - * @backupStaticAttributes disabled */ +#[BackupGlobals(false)] +#[BackupStaticProperties(false)] +#[PreserveGlobalState(false)] +#[RunInSeparateProcess] class FileDeliveryTypeFactoryTest extends TestCase { - private \ILIAS\FileDelivery\FileDeliveryTypes\FileDeliveryTypeFactory $subject; + private FileDeliveryTypeFactory $subject; /** - * @var Services|\PHPUnit\Framework\MockObject\MockObject + * @var Services|MockObject */ private Services $http; @@ -55,9 +60,7 @@ protected function setUp(): void } - /** - * @Test - */ + #[Test] public function testCreatePHPFileDeliveryWhichShouldSucceed(): void { $result = $this->subject->getInstance(DeliveryMethod::PHP); @@ -65,9 +68,7 @@ public function testCreatePHPFileDeliveryWhichShouldSucceed(): void $this->assertInstanceOf(PHP::class, $result); } - /** - * @Test - */ + #[Test] public function testCreatePHPChunkedFileDeliveryWhichShouldSucceed(): void { $result = $this->subject->getInstance(DeliveryMethod::PHP_CHUNKED); @@ -76,9 +77,7 @@ public function testCreatePHPChunkedFileDeliveryWhichShouldSucceed(): void } - /** - * @Test - */ + #[Test] public function testCreatePHPFileDeliveryTypeWhichShouldYieldTheSameInstance(): void { //fetch the php file delivery type two times to check that only one instance is created. @@ -88,9 +87,7 @@ public function testCreatePHPFileDeliveryTypeWhichShouldYieldTheSameInstance(): $this->assertEquals($firstResult, $secondResult); } - /** - * @Test - */ + #[Test] public function testCreateAnUnknownFileDeliveryTypeWhichShouldFail(): void { //get instance should throw an exception if the file delivery type is not known. diff --git a/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/XAccelTest.php b/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/XAccelTest.php index e58e684988fc..128f419671c9 100755 --- a/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/XAccelTest.php +++ b/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/XAccelTest.php @@ -25,6 +25,12 @@ namespace ILIAS\Tests\FileDelivery\FileDeliveryTypes; +use PHPUnit\Framework\Attributes\BackupGlobals; +use PHPUnit\Framework\Attributes\BackupStaticProperties; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\MockObject\MockObject; use ILIAS\HTTP\Services; use ILIAS\HTTP\Response\ResponseHeader; use PHPUnit\Framework\TestCase; @@ -35,16 +41,15 @@ * Class XSendfile * * @author Nicolas Schäfli - * - * @runInSeparateProcess - * @preserveGlobalState disabled - * @backupGlobals disabled - * @backupStaticAttributes disabled */ +#[BackupGlobals(false)] +#[BackupStaticProperties(false)] +#[PreserveGlobalState(false)] +#[RunInSeparateProcess] class XAccelTest extends TestCase { /** - * @var Services|\PHPUnit\Framework\MockObject\MockObject + * @var Services|MockObject */ public Services $httpServiceMock; @@ -58,9 +63,7 @@ protected function setUp(): void ->getMock(); } - /** - * @Test - */ + #[Test] public function testPrepareWhichShouldSucceed(): void { $expectedContentValue = ''; @@ -91,9 +94,7 @@ public function testPrepareWhichShouldSucceed(): void $this->assertTrue(true); } - /** - * @Test - */ + #[Test] public function testDeliverWithNormalPathWhichShouldSucceed(): void { $expectedHeader = 'X-Accel-Redirect'; @@ -124,9 +125,7 @@ public function testDeliverWithNormalPathWhichShouldSucceed(): void $xAccel->deliver($path, false); } - /** - * @Test - */ + #[Test] public function testDeliverWithDataPathWhichShouldSucceed(): void { $expectedHeader = 'X-Accel-Redirect'; diff --git a/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/XSendfileTest.php b/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/XSendfileTest.php index 4079140c85c9..9ececf543ede 100755 --- a/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/XSendfileTest.php +++ b/components/ILIAS/FileDelivery/tests/FileDeliveryTypes/XSendfileTest.php @@ -20,6 +20,12 @@ namespace ILIAS\Tests\FileDelivery\FileDeliveryTypes; +use PHPUnit\Framework\Attributes\BackupGlobals; +use PHPUnit\Framework\Attributes\BackupStaticProperties; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\MockObject\MockObject; use ILIAS\HTTP\Services; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; @@ -29,16 +35,15 @@ * Class XSendfile * * @author Nicolas Schäfli - * - * @runInSeparateProcess - * @preserveGlobalState disabled - * @backupGlobals disabled - * @backupStaticAttributes disabled */ +#[BackupGlobals(false)] +#[BackupStaticProperties(false)] +#[PreserveGlobalState(false)] +#[RunInSeparateProcess] class XSendfileTest extends TestCase { /** - * @var Services|\PHPUnit\Framework\MockObject\MockObject + * @var Services|MockObject */ public Services $httpServiceMock; @@ -52,9 +57,7 @@ protected function setUp(): void ->getMock(); } - /** - * @Test - */ + #[Test] public function testSendFileWithXSendHeaderWhichShouldSucceed(): void { $expectedHeader = 'X-Sendfile'; diff --git a/components/ILIAS/FileDelivery/tests/Token/TokenTest.php b/components/ILIAS/FileDelivery/tests/Token/TokenTest.php index 026ab8cb183c..170fe75b8a0e 100755 --- a/components/ILIAS/FileDelivery/tests/Token/TokenTest.php +++ b/components/ILIAS/FileDelivery/tests/Token/TokenTest.php @@ -18,6 +18,7 @@ namespace ILIAS\Tests\FileDelivery\Token; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use ILIAS\FileDelivery\Token\DataSigner; use ILIAS\FileDelivery\Token\Signer\Key\Secret\SecretKeyRotation; @@ -26,7 +27,6 @@ use ILIAS\FileDelivery\Token\Signer\KeyRotatingSigner; use ILIAS\FileDelivery\Token\Signer\NullSigner; use ILIAS\FileDelivery\Token\Signer\Key\Signing\ConcatSigningKeyGenerator; -use ILIAS\FileDelivery\Token\Compression\GZipCompression; /** * @author Fabian Schmid @@ -81,10 +81,8 @@ public static function providePayloads(): array ]; } - /** - * @dataProvider providePayloads - */ - public function testLargeAmountOfData($data): void + #[DataProvider('providePayloads')] + public function testLargeAmountOfData(string $data): void { $datasigner = new DataSigner( new SecretKeyRotation( diff --git a/components/ILIAS/FileServices/FileServices.php b/components/ILIAS/FileServices/FileServices.php index 22a4881fb6c2..adf595e35ca4 100644 --- a/components/ILIAS/FileServices/FileServices.php +++ b/components/ILIAS/FileServices/FileServices.php @@ -20,7 +20,14 @@ namespace ILIAS; -class FileServices implements Component\Component +use ILIAS\Component\Component; +use ILIAS\UI\Component\Input\Field\PhpUploadLimit; +use ILIAS\FileServices\FileServicesLegacyInitialisationAdapter; +use ILIAS\UI\Component\Input\Field\GlobalUploadLimit; +use ILIAS\Setup\Agent; +use ILIAS\Refinery\Factory; + +class FileServices implements Component { public function init( array | \ArrayAccess &$define, @@ -32,14 +39,14 @@ public function init( array | \ArrayAccess &$pull, array | \ArrayAccess &$internal, ): void { - $implement[UI\Component\Input\Field\PhpUploadLimit::class] = static fn() => - new FileServices\FileServicesLegacyInitialisationAdapter(); - $implement[UI\Component\Input\Field\GlobalUploadLimit::class] = static fn() => - new FileServices\FileServicesLegacyInitialisationAdapter(); + $implement[PhpUploadLimit::class] = static fn(): FileServicesLegacyInitialisationAdapter => + new FileServicesLegacyInitialisationAdapter(); + $implement[GlobalUploadLimit::class] = static fn(): FileServicesLegacyInitialisationAdapter => + new FileServicesLegacyInitialisationAdapter(); - $contribute[\ILIAS\Setup\Agent::class] = static fn() => + $contribute[Agent::class] = static fn(): \ilFileServicesSetupAgent => new \ilFileServicesSetupAgent( - $pull[\ILIAS\Refinery\Factory::class] + $pull[Factory::class] ); } } diff --git a/components/ILIAS/FileServices/classes/Setup/class.ilFileServicesSetupAgent.php b/components/ILIAS/FileServices/classes/Setup/class.ilFileServicesSetupAgent.php index f6b215a15f60..764085022a3e 100755 --- a/components/ILIAS/FileServices/classes/Setup/class.ilFileServicesSetupAgent.php +++ b/components/ILIAS/FileServices/classes/Setup/class.ilFileServicesSetupAgent.php @@ -18,17 +18,16 @@ declare(strict_types=1); +use ILIAS\Setup\Agent\NullAgent; use ILIAS\Setup\Agent; use ILIAS\Setup\Objective; -use ILIAS\Refinery\Transformation; -use ILIAS\Setup\Metrics; use ILIAS\Setup\Config; -use ILIAS\Setup\Migration; use ILIAS\Setup\ObjectiveCollection; use ILIAS\Setup\Condition\PHPExtensionLoadedCondition; -class ilFileServicesSetupAgent extends Agent\NullAgent implements Agent +class ilFileServicesSetupAgent extends NullAgent implements Agent { + #[\Override] public function getInstallObjective(?Config $config = null): Objective { return new ObjectiveCollection( @@ -43,6 +42,7 @@ public function getInstallObjective(?Config $config = null): Objective ); } + #[\Override] public function getUpdateObjective(?Config $config = null): Objective { return $this->getInstallObjective($config); diff --git a/components/ILIAS/FileServices/classes/StorageService/class.ilFileServicesPolicy.php b/components/ILIAS/FileServices/classes/StorageService/class.ilFileServicesPolicy.php index 3d9619f8bf0f..372fc90119cf 100755 --- a/components/ILIAS/FileServices/classes/StorageService/class.ilFileServicesPolicy.php +++ b/components/ILIAS/FileServices/classes/StorageService/class.ilFileServicesPolicy.php @@ -16,9 +16,6 @@ * *********************************************************************/ -use ILIAS\ResourceStorage\Policy\FileNamePolicy; -use ILIAS\ResourceStorage\Policy\FileNamePolicyException; -use ILIAS\FileUpload\Processor\BlacklistExtensionPreProcessor; use ILIAS\ResourceStorage\Policy\WhiteAndBlacklistedFileNamePolicy; /** @@ -43,13 +40,11 @@ class ilFileServicesPolicy extends WhiteAndBlacklistedFileNamePolicy ]; protected int $file_admin_ref_id; protected bool $as_ascii = true; - protected ilFileServicesSettings $settings; protected ilFileServicesFilenameSanitizer $sanitizer; protected ?bool $bypass = null; - public function __construct(ilFileServicesSettings $settings) + public function __construct(protected ilFileServicesSettings $settings) { - $this->settings = $settings; parent::__construct($this->settings->getBlackListedSuffixes(), $this->settings->getWhiteListedSuffixes()); $this->sanitizer = new ilFileServicesFilenameSanitizer($this->settings); $this->as_ascii = $this->settings->isASCIIConvertionEnabled(); @@ -75,17 +70,18 @@ public function ascii(string $filename): string $ascii_filename = htmlentities($filename, ENT_NOQUOTES, 'UTF-8'); $ascii_filename = preg_replace('/\&(.)[^;]*;/', '\\1', $ascii_filename); - $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', $ascii_filename); + $ascii_filename = preg_replace('/[\x7f-\xff]/', '_', (string) $ascii_filename); // OS do not allow the following characters in filenames: \/:*?"<>| $ascii_filename = preg_replace( '/[:\x5c\/\*\?\"<>\|]/', '_', - $ascii_filename + (string) $ascii_filename ); return $ascii_filename; } + #[\Override] public function isBlockedExtension(string $extension): bool { if ($this->settings->isByPassAllowedForCurrentUser()) { diff --git a/components/ILIAS/FileServices/classes/UploadService/UploadLimits/UploadPolicyFormUI.php b/components/ILIAS/FileServices/classes/UploadService/UploadLimits/UploadPolicyFormUI.php index c66557bf6a01..b32d14170e33 100755 --- a/components/ILIAS/FileServices/classes/UploadService/UploadLimits/UploadPolicyFormUI.php +++ b/components/ILIAS/FileServices/classes/UploadService/UploadLimits/UploadPolicyFormUI.php @@ -206,16 +206,11 @@ protected function getGlobalRoles(): array protected function getAudienceTransformation(): Transformation { - return $this->refinery->custom()->transformation(function ($audience_section): array { - switch ($audience_section[self::INPUT_FIELD_AUDIENCE][0]) { - case self::INPUT_OPTION_GLOBAL_ROLES: - $audience_type = UploadPolicy::AUDIENCE_TYPE_GLOBAL_ROLE; - break; - case self::INPUT_OPTION_ALL_USERS: - default: - $audience_type = UploadPolicy::AUDIENCE_TYPE_ALL_USERS; - break; - } + return $this->refinery->custom()->transformation(function (array $audience_section): array { + $audience_type = match ($audience_section[self::INPUT_FIELD_AUDIENCE][0]) { + self::INPUT_OPTION_GLOBAL_ROLES => UploadPolicy::AUDIENCE_TYPE_GLOBAL_ROLE, + default => UploadPolicy::AUDIENCE_TYPE_ALL_USERS, + }; return [ self::INPUT_FIELD_AUDIENCE_TYPE => $audience_type, diff --git a/components/ILIAS/FileServices/classes/UploadService/class.ilCtrlAwareStorageUploadHandler.php b/components/ILIAS/FileServices/classes/UploadService/class.ilCtrlAwareStorageUploadHandler.php index 7124621b4c01..3e4bdde60604 100755 --- a/components/ILIAS/FileServices/classes/UploadService/class.ilCtrlAwareStorageUploadHandler.php +++ b/components/ILIAS/FileServices/classes/UploadService/class.ilCtrlAwareStorageUploadHandler.php @@ -18,13 +18,9 @@ declare(strict_types=1); - -use ILIAS\Filesystem\Stream\Streams; -use ILIAS\FileUpload\FileUpload; -use ILIAS\HTTP\Services as HttpServices; +use ILIAS\ResourceStorage\Services; use ILIAS\FileUpload\Handler\FileInfoResult; use ILIAS\FileUpload\Handler\HandlerResult; -use ILIAS\FileUpload\Handler\ilCtrlAwareUploadHandler; use ILIAS\ResourceStorage\Stakeholder\ResourceStakeholder; use ILIAS\FileUpload\DTO\UploadResult; use ILIAS\FileUpload\Handler\BasicHandlerResult; @@ -38,15 +34,13 @@ */ class ilCtrlAwareStorageUploadHandler extends AbstractCtrlAwareUploadHandler { - protected ResourceStakeholder $stakeholder; - protected \ILIAS\ResourceStorage\Services $storage; + protected Services $storage; - public function __construct(ResourceStakeholder $stakeholder) + public function __construct(protected ResourceStakeholder $stakeholder) { global $DIC; parent::__construct(); $this->storage = $DIC->resourceStorage(); - $this->stakeholder = $stakeholder; } protected function getUploadResult(): HandlerResult diff --git a/components/ILIAS/FileServices/classes/UploadService/class.ilFileServicesPreProcessor.php b/components/ILIAS/FileServices/classes/UploadService/class.ilFileServicesPreProcessor.php index ff77f3773f6c..4378dd2bc385 100755 --- a/components/ILIAS/FileServices/classes/UploadService/class.ilFileServicesPreProcessor.php +++ b/components/ILIAS/FileServices/classes/UploadService/class.ilFileServicesPreProcessor.php @@ -16,10 +16,7 @@ * *********************************************************************/ -use ILIAS\ResourceStorage\Policy\FileNamePolicy; -use ILIAS\ResourceStorage\Policy\FileNamePolicyException; use ILIAS\FileUpload\Processor\BlacklistExtensionPreProcessor; -use ILIAS\ResourceStorage\Policy\WhiteAndBlacklistedFileNamePolicy; use ILIAS\FileUpload\DTO\Metadata; use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileUpload\DTO\ProcessingStatus; @@ -31,16 +28,14 @@ */ class ilFileServicesPreProcessor extends BlacklistExtensionPreProcessor { - private ilFileServicesSettings $settings; - public function __construct( - ilFileServicesSettings $settings, + private ilFileServicesSettings $settings, string $reason = 'Extension is blacklisted.' ) { - $this->settings = $settings; - parent::__construct($settings->getBlackListedSuffixes(), $reason); + parent::__construct($this->settings->getBlackListedSuffixes(), $reason); } + #[\Override] public function process(FileStream $stream, Metadata $metadata): ProcessingStatus { if ($this->settings->isByPassAllowedForCurrentUser()) { diff --git a/components/ILIAS/FileServices/classes/class.ilFileServicesSettings.php b/components/ILIAS/FileServices/classes/class.ilFileServicesSettings.php index 6b7df17e52ae..2db83fb1b388 100755 --- a/components/ILIAS/FileServices/classes/class.ilFileServicesSettings.php +++ b/components/ILIAS/FileServices/classes/class.ilFileServicesSettings.php @@ -25,8 +25,6 @@ */ class ilFileServicesSettings { - private ilSetting $settings; - private ilDBInterface $db; private array $white_list_default = []; private array $white_list_negative = []; private array $white_list_positive = []; @@ -38,15 +36,12 @@ class ilFileServicesSettings protected int $file_admin_ref_id; public function __construct( - ilSetting $settings, + private ilSetting $settings, ilIniFile $client_ini, - ilDBInterface $db + private ilDBInterface $db ) { - $this->db = $db; - $general_settings = new General(); $this->convert_to_ascii = $general_settings->isDownloadWithAsciiFileName(); - $this->settings = $settings; /** @noRector */ $this->white_list_default = include __DIR__ . "/../defaults/default_whitelist.php"; $this->file_admin_ref_id = $this->determineFileAdminRefId(); @@ -129,9 +124,7 @@ private function readBlackList(): void private function getCleaner(): Closure { - return function (string $suffix): string { - return trim(strtolower($suffix)); - }; + return fn(string $suffix): string => trim(strtolower($suffix)); } public function getWhiteListedSuffixes(): array @@ -147,7 +140,7 @@ public function getBlackListedSuffixes(): array /** * @internal */ - public function getDefaultWhitelist() + public function getDefaultWhitelist(): array { return $this->white_list_default; } diff --git a/components/ILIAS/FileServices/classes/class.ilObjFileServices.php b/components/ILIAS/FileServices/classes/class.ilObjFileServices.php index 75b1bf75652c..0ff410d50171 100755 --- a/components/ILIAS/FileServices/classes/class.ilObjFileServices.php +++ b/components/ILIAS/FileServices/classes/class.ilObjFileServices.php @@ -37,11 +37,13 @@ public function __construct(int $id = 0, bool $call_by_reference = true) parent::__construct($id, $call_by_reference); } + #[\Override] public function getPresentationTitle(): string { return $this->lng->txt("file_services"); } + #[\Override] public function getLongDescription(): string { return $this->lng->txt("file_services_description"); diff --git a/components/ILIAS/FileServices/classes/class.ilObjFileServicesGUI.php b/components/ILIAS/FileServices/classes/class.ilObjFileServicesGUI.php index 45a0d5f9f117..238e62233878 100755 --- a/components/ILIAS/FileServices/classes/class.ilObjFileServicesGUI.php +++ b/components/ILIAS/FileServices/classes/class.ilObjFileServicesGUI.php @@ -95,6 +95,7 @@ protected function hasUserPermissionTo(string $str): bool * Execute command * @access public */ + #[\Override] public function executeCommand(): void { $this->lng->loadLanguageModule("fils"); @@ -133,6 +134,7 @@ public function executeCommand(): void /** * Get tabs */ + #[\Override] public function getAdminTabs(): void { // General Settings for File-Services @@ -185,6 +187,7 @@ public function getAdminTabs(): void } } + #[\Override] public function setTitleAndDescription(): void { parent::setTitleAndDescription(); @@ -281,11 +284,9 @@ protected function saveSettings(): void // get form $form = $this->initSettingsForm(); if ($form->checkInput()) { - $trafo = function (string $id): ?string { - return $this->http->post()->has($id) - ? $this->http->post()->retrieve($id, $this->refinery->to()->string()) - : null; - }; + $trafo = (fn(string $id): ?string => $this->http->post()->has($id) + ? $this->http->post()->retrieve($id, $this->refinery->to()->string()) + : null); $this->settings->set("suffix_repl_additional", $trafo("suffix_repl_additional")); diff --git a/components/ILIAS/FileServices/tests/UploadPolicyResolverTest.php b/components/ILIAS/FileServices/tests/UploadPolicyResolverTest.php index 25f54d49db4e..8358636458f6 100755 --- a/components/ILIAS/FileServices/tests/UploadPolicyResolverTest.php +++ b/components/ILIAS/FileServices/tests/UploadPolicyResolverTest.php @@ -19,8 +19,6 @@ declare(strict_types=1); use PHPUnit\Framework\TestCase; -use ILIAS\UI\Component\Input\Field\UploadHandler; -use ILIAS\UI\Implementation\Component\Input\UploadLimitResolver; /** * @author Fabian Schmid diff --git a/components/ILIAS/FileServices/tests/ilServicesFileServicesTest.php b/components/ILIAS/FileServices/tests/ilServicesFileServicesTest.php index dbfbf79a514b..0a5cf9733990 100755 --- a/components/ILIAS/FileServices/tests/ilServicesFileServicesTest.php +++ b/components/ILIAS/FileServices/tests/ilServicesFileServicesTest.php @@ -18,23 +18,21 @@ declare(strict_types=1); +use ILIAS\DI\Container; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\Container; use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileUpload\DTO\Metadata; use ILIAS\FileUpload\DTO\ProcessingStatus; -use ILIAS\ResourceStorage\Services; -use ILIAS\ResourceStorage\Manager\Manager; -/** - * @runTestsInSeparateProcesses // this is necessary to avoid side effects with the DIC - * @preserveGlobalState disabled - */ +#[PreserveGlobalState(false)] +#[RunTestsInSeparateProcesses] class ilServicesFileServicesTest extends TestCase { - private ?\ILIAS\DI\Container $dic_backup; + private ?Container $dic_backup; /** - * @var ilDBInterface|(ilDBInterface&\PHPUnit\Framework\MockObject\MockObject)|\PHPUnit\Framework\MockObject\MockObject + * @var ilDBInterface|ilDBInterface&MockObject|MockObject */ private ?ilDBInterface $db_mock = null; @@ -43,7 +41,7 @@ protected function setUp(): void global $DIC; $this->dic_backup = is_object($DIC) ? clone $DIC : null; - $DIC = new \ILIAS\DI\Container(); + $DIC = new Container(); $DIC['ilDB'] = $this->db_mock = $this->createMock(ilDBInterface::class); } @@ -157,7 +155,7 @@ public function testActualWhitelist(): void ->method('get') ->willReturnCallback( function ($k) use (&$consecutive) { - list($expected, $return) = array_shift($consecutive); + [$expected, $return] = array_shift($consecutive); $this->assertEquals($expected, $k); return $return; } diff --git a/components/ILIAS/FileUpload/FileUpload.php b/components/ILIAS/FileUpload/FileUpload.php index b458f4c8acb4..cc499454c86c 100644 --- a/components/ILIAS/FileUpload/FileUpload.php +++ b/components/ILIAS/FileUpload/FileUpload.php @@ -20,7 +20,9 @@ namespace ILIAS; -class FileUpload implements Component\Component +use ILIAS\Component\Component; + +class FileUpload implements Component { public function init( array | \ArrayAccess &$define, diff --git a/components/ILIAS/FileUpload/src/Collection/ImmutableMapWrapper.php b/components/ILIAS/FileUpload/src/Collection/ImmutableMapWrapper.php index 6861e7305399..86eb2b006a14 100755 --- a/components/ILIAS/FileUpload/src/Collection/ImmutableMapWrapper.php +++ b/components/ILIAS/FileUpload/src/Collection/ImmutableMapWrapper.php @@ -32,9 +32,6 @@ */ final class ImmutableMapWrapper implements ImmutableStringMap { - private \ILIAS\FileUpload\Collection\StringMap $map; - - /** * ImmutableMapWrapper constructor. * @@ -42,9 +39,8 @@ final class ImmutableMapWrapper implements ImmutableStringMap * * @since 5.3 */ - public function __construct(StringMap $map) + public function __construct(private StringMap $map) { - $this->map = $map; } diff --git a/components/ILIAS/FileUpload/src/DTO/ProcessingStatus.php b/components/ILIAS/FileUpload/src/DTO/ProcessingStatus.php index a0b98ee8291a..405d625aad70 100755 --- a/components/ILIAS/FileUpload/src/DTO/ProcessingStatus.php +++ b/components/ILIAS/FileUpload/src/DTO/ProcessingStatus.php @@ -18,8 +18,6 @@ namespace ILIAS\FileUpload\DTO; -use ILIAS\FileUpload\ScalarTypeCheckAware; - /** * Class ProcessingStatus * @@ -37,36 +35,39 @@ final class ProcessingStatus { /** * Upload is ok + * @var int */ public const OK = 1; /** * Upload got rejected by a processor + * @var int */ public const REJECTED = 2; /** * Upload is pending + * @var int */ public const PENDING = 3; /** * Upload got denied by a processor, the upload will be removed immediately + * @var int */ public const DENIED = 4; private int $code; - private string $message; /** * ProcessingStatus constructor. * * @param int $code The code OK or REJECTED. - * @param string $reason The message which should be set to make the rejection more + * @param string $message The message which should be set to make the rejection more * understandable for other developers. * * @throws \InvalidArgumentException Thrown if the given code is not OK or REJECTED. The * exception can also be thrown if the given arguments are not * of the correct type. */ - public function __construct(int $code, string $reason) + public function __construct(int $code, private string $message) { if (!in_array($code, [self::OK, self::REJECTED, self::DENIED, self::PENDING], true)) { throw new \InvalidArgumentException( @@ -75,7 +76,6 @@ public function __construct(int $code, string $reason) } $this->code = $code; - $this->message = $reason; } public function getCode(): int diff --git a/components/ILIAS/FileUpload/src/DTO/UploadResult.php b/components/ILIAS/FileUpload/src/DTO/UploadResult.php index 652186c740bb..97a0e427366c 100755 --- a/components/ILIAS/FileUpload/src/DTO/UploadResult.php +++ b/components/ILIAS/FileUpload/src/DTO/UploadResult.php @@ -39,8 +39,6 @@ final class UploadResult private string $name; private int $size; private string $mimeType; - private ImmutableStringMap $metaData; - private ProcessingStatus $status; private string $path; @@ -57,7 +55,7 @@ final class UploadResult * * @since 5.3 */ - public function __construct(string $name, int $size, string $mimeType, ImmutableStringMap $metaData, ProcessingStatus $status, string $path) + public function __construct(string $name, int $size, string $mimeType, private ImmutableStringMap $metaData, private ProcessingStatus $status, string $path) { $this->stringTypeCheck($name, "name"); $this->stringTypeCheck($mimeType, "mimeType"); @@ -67,8 +65,6 @@ public function __construct(string $name, int $size, string $mimeType, Immutable $this->name = $name; $this->size = $size; $this->mimeType = $mimeType; - $this->metaData = $metaData; - $this->status = $status; $this->path = $path; } diff --git a/components/ILIAS/FileUpload/src/FileUploadImpl.php b/components/ILIAS/FileUpload/src/FileUploadImpl.php index 6962b102bf99..f64d914b2d1b 100755 --- a/components/ILIAS/FileUpload/src/FileUploadImpl.php +++ b/components/ILIAS/FileUpload/src/FileUploadImpl.php @@ -31,8 +31,6 @@ use ILIAS\FileUpload\Exception\IllegalStateException; use ILIAS\FileUpload\Processor\PreProcessor; use ILIAS\FileUpload\Processor\PreProcessorManager; -use ILIAS\HTTP\Services; -use Psr\Http\Message\UploadedFileInterface; use RecursiveArrayIterator; use RecursiveIteratorIterator; use ILIAS\HTTP\GlobalHttpState; @@ -47,19 +45,16 @@ */ final class FileUploadImpl implements FileUpload { - private PreProcessorManager $processorManager; - private Filesystems $filesystems; - private GlobalHttpState $globalHttpState; - private bool $processed; - private bool $moved; + private bool $processed = false; + private bool $moved = false; /** * @var UploadResult[] $uploadResult */ - private array $uploadResult; + private array $uploadResult = []; /** * @var UploadResult[] $uploadResult */ - private array $rejectedUploadResult; + private array $rejectedUploadResult = []; /** * @var FileStream[] $uploadStreams The uploaded streams have their temp urls (->getMetadata('uri') as an identifier. */ @@ -75,22 +70,15 @@ final class FileUploadImpl implements FileUpload * @param Filesystems $filesystems The Filesystems implementation which should be used. * @param GlobalHttpState $globalHttpState The http implementation which should be used to detect the uploaded files. */ - public function __construct(PreProcessorManager $processorManager, Filesystems $filesystems, GlobalHttpState $globalHttpState) + public function __construct(private PreProcessorManager $processorManager, private Filesystems $filesystems, private GlobalHttpState $globalHttpState) { - $this->processorManager = $processorManager; - $this->filesystems = $filesystems; - $this->globalHttpState = $globalHttpState; - $this->processed = false; - $this->moved = false; - $this->uploadResult = []; - $this->rejectedUploadResult = []; } /** * @description This is the very last thing we can do if a preprocessor DENIEs an upload. This is a hard removal, * not beautiful, but it works. */ - private function hardRemoveUpload(string $identifier, ProcessingStatus $status): void + private function hardRemoveUpload(string $identifier, ProcessingStatus $status): never { // we delete the file from the temporary directory and remove it from the global $_FILES array $file_stream = $this->uploadStreams[$identifier]; @@ -221,18 +209,13 @@ private function regenerateUploadResultWithCopyError(UploadResult $result, strin */ private function selectFilesystem(int $location): Filesystem { - switch ($location) { - case Location::CUSTOMIZING: - return $this->filesystems->customizing(); - case Location::STORAGE: - return $this->filesystems->storage(); - case Location::WEB: - return $this->filesystems->web(); - case Location::TEMPORARY: - return $this->filesystems->temp(); - default: - throw new \InvalidArgumentException("No filesystem found for location code \"$location\""); - } + return match ($location) { + Location::CUSTOMIZING => $this->filesystems->customizing(), + Location::STORAGE => $this->filesystems->storage(), + Location::WEB => $this->filesystems->web(), + Location::TEMPORARY => $this->filesystems->temp(), + default => throw new \InvalidArgumentException("No filesystem found for location code \"$location\""), + }; } @@ -273,7 +256,7 @@ public function process(): void $metadata = new Metadata($file->getClientFilename(), $file->getSize(), $file->getClientMediaType()); try { $stream = Streams::ofPsr7Stream($file->getStream()); - } catch (\RuntimeException $e) { + } catch (\RuntimeException) { $this->rejectFailedUpload($metadata); continue; } diff --git a/components/ILIAS/FileUpload/src/Handler/AbstractCtrlAwareIRSSUploadHandler.php b/components/ILIAS/FileUpload/src/Handler/AbstractCtrlAwareIRSSUploadHandler.php index e26993ada7d0..0390d12f6dcd 100755 --- a/components/ILIAS/FileUpload/src/Handler/AbstractCtrlAwareIRSSUploadHandler.php +++ b/components/ILIAS/FileUpload/src/Handler/AbstractCtrlAwareIRSSUploadHandler.php @@ -20,6 +20,8 @@ namespace ILIAS\FileUpload\Handler; +use ILIAS\ResourceStorage\Services; +use ILIAS\Filesystem\Filesystem; use ILIAS\ResourceStorage\Stakeholder\ResourceStakeholder; use ILIAS\FileUpload\DTO\UploadResult; @@ -32,9 +34,9 @@ abstract class AbstractCtrlAwareIRSSUploadHandler extends AbstractCtrlAwareUploa { protected \ilFileServicesFilenameSanitizer $sanitizer; protected \ilLanguage $language; - protected \ILIAS\ResourceStorage\Services $irss; + protected Services $irss; protected ResourceStakeholder $stakeholder; - protected \ILIAS\Filesystem\Filesystem $temp_filesystem; + protected Filesystem $temp_filesystem; protected array $class_path; public function __construct() @@ -123,16 +125,19 @@ protected function processChunckedUpload(UploadResult $result): HandlerResult ); } + #[\Override] public function getUploadURL(): string { return $this->ctrl->getLinkTargetByClass($this->class_path, self::CMD_UPLOAD, null, true); } + #[\Override] public function getExistingFileInfoURL(): string { return $this->ctrl->getLinkTargetByClass($this->class_path, self::CMD_INFO, null, true); } + #[\Override] public function getFileRemovalURL(): string { return $this->ctrl->getLinkTargetByClass($this->class_path, self::CMD_REMOVE, null, true); @@ -169,8 +174,6 @@ public function getInfoResult(string $identifier): ?FileInfoResult public function getInfoForExistingFiles(array $file_ids): array { - return array_map(function ($file_id): FileInfoResult { - return $this->getInfoResult($file_id); - }, $file_ids); + return array_map(fn($file_id): FileInfoResult => $this->getInfoResult($file_id), $file_ids); } } diff --git a/components/ILIAS/FileUpload/src/Handler/BasicFileInfoResult.php b/components/ILIAS/FileUpload/src/Handler/BasicFileInfoResult.php index 6ad3ec939b40..177ac449dd85 100755 --- a/components/ILIAS/FileUpload/src/Handler/BasicFileInfoResult.php +++ b/components/ILIAS/FileUpload/src/Handler/BasicFileInfoResult.php @@ -27,27 +27,11 @@ */ final class BasicFileInfoResult implements FileInfoResult { - private string $mime_type; - private string $file_identifier; - private int $size; - private string $name; - private string $file_identification_key; - /** * @param int $size in Bytes, we will change this to DataSize in the future */ - public function __construct( - string $file_identification_key, - string $file_identifier, - string $name, - int $size, - string $mime_type - ) { - $this->file_identification_key = $file_identification_key; - $this->file_identifier = $file_identifier; - $this->name = $name; - $this->size = $size; - $this->mime_type = $mime_type; + public function __construct(private string $file_identification_key, private string $file_identifier, private string $name, private int $size, private string $mime_type) + { } diff --git a/components/ILIAS/FileUpload/src/Handler/BasicHandlerResult.php b/components/ILIAS/FileUpload/src/Handler/BasicHandlerResult.php index 7afb935bf2fc..98397301df0d 100755 --- a/components/ILIAS/FileUpload/src/Handler/BasicHandlerResult.php +++ b/components/ILIAS/FileUpload/src/Handler/BasicHandlerResult.php @@ -27,25 +27,11 @@ */ final class BasicHandlerResult implements HandlerResult { - private string $file_identification_key; - private int $status; - private string $file_identifier; - private string $message; - - /** * BasicHandlerResult constructor. */ - public function __construct( - string $file_identification_key, - int $status, - string $file_identifier, - string $message - ) { - $this->file_identification_key = $file_identification_key; - $this->status = $status; - $this->file_identifier = $file_identifier; - $this->message = $message; + public function __construct(private string $file_identification_key, private int $status, private string $file_identifier, private string $message) + { } diff --git a/components/ILIAS/FileUpload/src/MimeType.php b/components/ILIAS/FileUpload/src/MimeType.php index 978577dfaccf..5676871eff78 100755 --- a/components/ILIAS/FileUpload/src/MimeType.php +++ b/components/ILIAS/FileUpload/src/MimeType.php @@ -501,7 +501,7 @@ class MimeType protected function __construct(string $path_to_file) { /** @noinspection HttpUrlsUsage */ - if (strpos($path_to_file, 'http://') !== false || strpos($path_to_file, 'https://') !== false) { + if (str_contains($path_to_file, 'http://') || str_contains($path_to_file, 'https://')) { $this->setExternal(true); } $parts = parse_url($path_to_file); @@ -572,9 +572,8 @@ public function get(): string if ($this->getSuffix() !== '' && $this->getSuffix() !== '0' && isset($suffix_map[$this->getSuffix()])) { if (!is_array($suffix_map[$this->getSuffix()])) { return $suffix_map[$this->getSuffix()]; - } else { - return $suffix_map[$this->getSuffix()][0]; } + return $suffix_map[$this->getSuffix()][0]; } if (extension_loaded('Fileinfo') && is_file($this->getPath())) { $finfo = finfo_open(FILEINFO_MIME_TYPE); diff --git a/components/ILIAS/FileUpload/src/Processor/AbstractRecursiveZipPreProcessor.php b/components/ILIAS/FileUpload/src/Processor/AbstractRecursiveZipPreProcessor.php index a858fad8bc70..be921ced812b 100755 --- a/components/ILIAS/FileUpload/src/Processor/AbstractRecursiveZipPreProcessor.php +++ b/components/ILIAS/FileUpload/src/Processor/AbstractRecursiveZipPreProcessor.php @@ -57,7 +57,7 @@ public function process(FileStream $stream, Metadata $metadata): ProcessingStatu } } $zip->close(); - } catch (\Throwable $e) { + } catch (\Throwable) { return new ProcessingStatus(ProcessingStatus::PENDING, ''); } } diff --git a/components/ILIAS/FileUpload/src/Processor/BlacklistExtensionPreProcessor.php b/components/ILIAS/FileUpload/src/Processor/BlacklistExtensionPreProcessor.php index 02b9f08215a0..abee5ccda655 100755 --- a/components/ILIAS/FileUpload/src/Processor/BlacklistExtensionPreProcessor.php +++ b/components/ILIAS/FileUpload/src/Processor/BlacklistExtensionPreProcessor.php @@ -20,12 +20,6 @@ class BlacklistExtensionPreProcessor extends AbstractRecursiveZipPreProcessor implements PreProcessor { - private string $reason; - /** - * @var string[] - */ - private array $blacklist; - /** * BlacklistExtensionPreProcessor constructor. * Example: @@ -42,10 +36,8 @@ class BlacklistExtensionPreProcessor extends AbstractRecursiveZipPreProcessor im * * @param \string[] $blacklist The file extensions which should be blacklisted. */ - public function __construct(array $blacklist, string $reason = 'Extension is blacklisted.') + public function __construct(private array $blacklist, private string $reason = 'Extension is blacklisted.') { - $this->blacklist = $blacklist; - $this->reason = $reason; } protected function checkPath(string $path): bool diff --git a/components/ILIAS/FileUpload/src/Processor/BlacklistFileHeaderPreProcessor.php b/components/ILIAS/FileUpload/src/Processor/BlacklistFileHeaderPreProcessor.php index 392f2dc3ee2b..140e95815a5f 100755 --- a/components/ILIAS/FileUpload/src/Processor/BlacklistFileHeaderPreProcessor.php +++ b/components/ILIAS/FileUpload/src/Processor/BlacklistFileHeaderPreProcessor.php @@ -22,7 +22,6 @@ use ILIAS\FileUpload\DTO\Metadata; use ILIAS\FileUpload\DTO\ProcessingStatus; use ILIAS\FileUpload\ScalarTypeCheckAware; -use Psr\Http\Message\StreamInterface; /** * Class BlacklistFileHeaderPreProcessor diff --git a/components/ILIAS/FileUpload/src/Processor/BlacklistMimeTypePreProcessor.php b/components/ILIAS/FileUpload/src/Processor/BlacklistMimeTypePreProcessor.php index b567aea2c335..7f0ea740066d 100755 --- a/components/ILIAS/FileUpload/src/Processor/BlacklistMimeTypePreProcessor.php +++ b/components/ILIAS/FileUpload/src/Processor/BlacklistMimeTypePreProcessor.php @@ -21,7 +21,6 @@ use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileUpload\DTO\Metadata; use ILIAS\FileUpload\DTO\ProcessingStatus; -use Psr\Http\Message\StreamInterface; /** * Class BlacklistMimeTypePreProcessor diff --git a/components/ILIAS/FileUpload/src/Processor/FilenameSanitizerPreProcessor.php b/components/ILIAS/FileUpload/src/Processor/FilenameSanitizerPreProcessor.php index 9ff418cebb2a..1ad85b7938af 100755 --- a/components/ILIAS/FileUpload/src/Processor/FilenameSanitizerPreProcessor.php +++ b/components/ILIAS/FileUpload/src/Processor/FilenameSanitizerPreProcessor.php @@ -54,7 +54,7 @@ private function normalizeRelativePath(string $path): string $path = preg_replace('#\p{C}+#u', '', $path); $parts = []; - foreach (explode('/', $path) as $part) { + foreach (explode('/', (string) $path) as $part) { switch ($part) { case '': case '.': diff --git a/components/ILIAS/FileUpload/src/Processor/InsecureFilenameSanitizerPreProcessor.php b/components/ILIAS/FileUpload/src/Processor/InsecureFilenameSanitizerPreProcessor.php index 9c4d60f98870..814688430a6a 100755 --- a/components/ILIAS/FileUpload/src/Processor/InsecureFilenameSanitizerPreProcessor.php +++ b/components/ILIAS/FileUpload/src/Processor/InsecureFilenameSanitizerPreProcessor.php @@ -35,7 +35,7 @@ protected function checkPath(string $path): bool { $path = str_replace('\\', '/', $path); $path = preg_replace('/\/+/', '/', $path); - $path = trim($path, '/'); + $path = trim((string) $path, '/'); $parts = explode('/', $path); foreach ($parts as $part) { if (in_array($part, $this->prohibited_names)) { diff --git a/components/ILIAS/FileUpload/src/Processor/IsMimeTypeOrExtension.php b/components/ILIAS/FileUpload/src/Processor/IsMimeTypeOrExtension.php index 76faee8d9002..7c7b33589468 100755 --- a/components/ILIAS/FileUpload/src/Processor/IsMimeTypeOrExtension.php +++ b/components/ILIAS/FileUpload/src/Processor/IsMimeTypeOrExtension.php @@ -18,7 +18,6 @@ namespace ILIAS\FileUpload\Processor; -use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileUpload\DTO\Metadata; /** @@ -38,15 +37,12 @@ protected function isMimeTypeOrExtension( return true; } // is extension - if (substr_compare( + return substr_compare( $metadata->getFilename(), $extention, -strlen($extention), null, true - ) === 0) { - return true; - } - return false; + ) === 0; } } diff --git a/components/ILIAS/FileUpload/src/Processor/PreProcessor.php b/components/ILIAS/FileUpload/src/Processor/PreProcessor.php index eb2b1ff4e188..85f1a4d27fea 100755 --- a/components/ILIAS/FileUpload/src/Processor/PreProcessor.php +++ b/components/ILIAS/FileUpload/src/Processor/PreProcessor.php @@ -21,7 +21,6 @@ use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileUpload\DTO\Metadata; use ILIAS\FileUpload\DTO\ProcessingStatus; -use Psr\Http\Message\StreamInterface; /** * Class PreProcessor diff --git a/components/ILIAS/FileUpload/src/Processor/PreProcessorManager.php b/components/ILIAS/FileUpload/src/Processor/PreProcessorManager.php index 3a62ab32d465..b206daed60a2 100755 --- a/components/ILIAS/FileUpload/src/Processor/PreProcessorManager.php +++ b/components/ILIAS/FileUpload/src/Processor/PreProcessorManager.php @@ -21,7 +21,6 @@ use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileUpload\DTO\Metadata; use ILIAS\FileUpload\DTO\ProcessingStatus; -use Psr\Http\Message\StreamInterface; /** * Class PreProcessorManager diff --git a/components/ILIAS/FileUpload/src/Processor/PreProcessorManagerImpl.php b/components/ILIAS/FileUpload/src/Processor/PreProcessorManagerImpl.php index d27554b63b3c..f3d1fc5a1ee6 100755 --- a/components/ILIAS/FileUpload/src/Processor/PreProcessorManagerImpl.php +++ b/components/ILIAS/FileUpload/src/Processor/PreProcessorManagerImpl.php @@ -21,7 +21,6 @@ use ILIAS\Filesystem\Stream\FileStream; use ILIAS\FileUpload\DTO\Metadata; use ILIAS\FileUpload\DTO\ProcessingStatus; -use Psr\Http\Message\StreamInterface; /** * Class PreProcessorManagerImpl @@ -67,7 +66,7 @@ public function process(FileStream $stream, Metadata $metadata): ProcessingStatu } if (is_null($result)) { - $result = new ProcessingStatus(ProcessingStatus::OK, 'No processors were registered.'); + return new ProcessingStatus(ProcessingStatus::OK, 'No processors were registered.'); } return $result; diff --git a/components/ILIAS/FileUpload/src/Processor/SVGBlacklistPreProcessor.php b/components/ILIAS/FileUpload/src/Processor/SVGBlacklistPreProcessor.php index e05596fd5341..95e8cc844a2e 100755 --- a/components/ILIAS/FileUpload/src/Processor/SVGBlacklistPreProcessor.php +++ b/components/ILIAS/FileUpload/src/Processor/SVGBlacklistPreProcessor.php @@ -33,9 +33,21 @@ final class SVGBlacklistPreProcessor implements PreProcessor { use IsMimeTypeOrExtension; + /** + * @var string + */ private const SVG_MIME_TYPE = 'image/svg+xml'; + /** + * @var string + */ private const REGEX_SCRIPT = '/