From 1c8fb0ea1a5604f4b111e8694f037868992c5f0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20D?= Date: Mon, 6 Jun 2022 08:17:34 +0200 Subject: [PATCH] refactor: [WIP] Use hexagonal architecture and implement interfaces for services and repositories. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Controllers are being splited into commands to better dependency management. Signed-off-by: Rubén D --- .../api/Controllers/AccountController.php | 54 +- .../api/Controllers/CategoryController.php | 4 +- .../api/Controllers/ClientController.php | 7 +- .../api/Controllers/ConfigController.php | 8 +- .../api/Controllers/ControllerBase.php | 61 +- app/modules/api/Controllers/TagController.php | 7 +- .../api/Controllers/UserGroupController.php | 7 +- app/modules/api/Init.php | 19 +- app/modules/cli/Commands/BackupCommand.php | 10 +- app/modules/cli/Commands/CommandBase.php | 11 +- .../Crypt/UpdateMasterPasswordCommand.php | 81 +- app/modules/cli/Commands/InstallCommand.php | 11 +- app/modules/cli/Init.php | 3 +- .../Controllers/AccessManagerController.php | 12 +- .../Account/AccountControllerBase.php | 54 + .../Controllers/Account/CopyController.php | 109 ++ .../Account/CopyPassController.php | 93 ++ .../Account/CopyPassHistoryController.php | 93 ++ .../Controllers/Account/CreateController.php | 92 ++ .../Controllers/Account/DeleteController.php | 109 ++ .../Controllers/Account/EditController.php | 111 ++ .../Account/EditPassController.php | 110 ++ .../Controllers/Account/IndexController.php | 73 + .../Account/RequestAccessController.php | 94 ++ .../Account/SaveCopyController.php | 116 ++ .../Account/SaveCreateController.php | 117 ++ .../Account/SaveDeleteController.php | 98 ++ .../Account/SaveEditController.php | 123 ++ .../Account/SaveEditPassController.php | 110 ++ .../Account/SaveEditRestoreController.php | 100 ++ .../Account/SaveRequestController.php | 135 ++ .../Controllers/Account/SearchController.php | 76 + .../Controllers/Account/ViewController.php | 109 ++ .../Account/ViewHistoryController.php | 101 ++ .../Account/ViewLinkController.php | 173 +++ .../Account/ViewPassController.php | 124 ++ .../Account/ViewPassHistoryController.php | 121 ++ .../web/Controllers/AccountController.php | 1316 ----------------- .../Controllers/AccountFavoriteController.php | 2 +- .../web/Controllers/AccountFileController.php | 158 +- .../AccountHistoryManagerController.php | 94 +- .../Controllers/AccountManagerController.php | 151 +- .../web/Controllers/AuthTokenController.php | 10 +- .../GetEnvironmentController.php} | 38 +- .../web/Controllers/CategoryController.php | 8 +- .../web/Controllers/ClientController.php | 9 +- .../Controllers/ConfigBackupController.php | 10 +- .../ConfigEncryptionController.php | 83 +- .../Controllers/ConfigGeneralController.php | 6 +- .../Controllers/ConfigImportController.php | 6 +- .../web/Controllers/ConfigLdapController.php | 6 +- .../web/Controllers/ConfigMailController.php | 4 +- .../Controllers/ConfigManagerController.php | 122 +- .../web/Controllers/ControllerBase.php | 67 +- .../web/Controllers/CustomFieldController.php | 8 +- .../web/Controllers/ErrorController.php | 23 +- .../web/Controllers/EventlogController.php | 4 +- .../Helpers/Account/AccountActionsHelper.php | 24 +- .../Helpers/Account/AccountHelper.php | 203 +-- .../Helpers/Account/AccountHistoryHelper.php | 134 +- .../Helpers/Account/AccountPasswordHelper.php | 92 +- .../Helpers/Account/AccountSearchHelper.php | 175 +-- .../Controllers/Helpers/Grid/AccountGrid.php | 2 +- .../Helpers/Grid/AccountHistoryGrid.php | 2 +- .../Helpers/Grid/AuthTokenGrid.php | 2 +- .../Controllers/Helpers/Grid/CategoryGrid.php | 2 +- .../Controllers/Helpers/Grid/ClientGrid.php | 2 +- .../Helpers/Grid/CustomFieldGrid.php | 4 +- .../Controllers/Helpers/Grid/EventlogGrid.php | 2 +- .../web/Controllers/Helpers/Grid/FileGrid.php | 2 +- .../Helpers/Grid/GridInterface.php | 2 +- .../Helpers/Grid/ItemPresetGrid.php | 4 +- .../Helpers/Grid/NotificationGrid.php | 2 +- .../Controllers/Helpers/Grid/PluginGrid.php | 2 +- .../Helpers/Grid/PublicLinkGrid.php | 2 +- .../web/Controllers/Helpers/Grid/TagGrid.php | 2 +- .../Controllers/Helpers/Grid/TrackGrid.php | 2 +- .../web/Controllers/Helpers/Grid/UserGrid.php | 2 +- .../Helpers/Grid/UserGroupGrid.php | 2 +- .../Helpers/Grid/UserProfileGrid.php | 2 +- .../web/Controllers/Helpers/HelperBase.php | 51 +- .../Controllers/Helpers/ItemPresetHelper.php | 6 +- .../web/Controllers/Helpers/LayoutHelper.php | 55 +- .../{ => Index}/IndexController.php | 23 +- .../web/Controllers/InstallController.php | 19 +- .../web/Controllers/ItemManagerController.php | 206 +-- .../web/Controllers/ItemPresetController.php | 8 +- .../web/Controllers/ItemsController.php | 10 +- .../web/Controllers/Login/IndexController.php | 47 + .../web/Controllers/Login/LoginController.php | 129 ++ .../Controllers/Login/LogoutController.php | 72 + .../web/Controllers/LoginController.php | 210 --- .../Controllers/NotificationController.php | 8 +- .../web/Controllers/PluginController.php | 10 +- .../web/Controllers/PublicLinkController.php | 6 +- .../Controllers/Resource/CssController.php | 92 ++ .../JsController.php} | 84 +- .../Controllers/SecurityManagerController.php | 6 +- .../web/Controllers/SimpleControllerBase.php | 11 +- app/modules/web/Controllers/TagController.php | 6 +- .../web/Controllers/TaskController.php | 11 +- .../web/Controllers/TrackController.php | 4 +- .../web/Controllers/Traits/ConfigTrait.php | 6 +- .../Controllers/Traits/WebControllerTrait.php | 3 +- .../web/Controllers/UpgradeController.php | 6 +- .../web/Controllers/UserController.php | 14 +- .../web/Controllers/UserGroupController.php | 10 +- .../Controllers/UserPassResetController.php | 18 +- .../web/Controllers/UserProfileController.php | 8 +- .../UserSettingsGeneralController.php | 2 +- .../UserSettingsManagerController.php | 8 +- app/modules/web/Forms/AccountForm.php | 33 +- app/modules/web/Forms/AuthTokenForm.php | 2 +- app/modules/web/Forms/FormBase.php | 45 +- app/modules/web/Forms/ItemsPresetForm.php | 4 +- app/modules/web/Forms/PublicLinkForm.php | 2 +- app/modules/web/Init.php | 35 +- .../material-blue/views/_layouts/main.inc | 2 +- .../views/_partials/error-full.inc | 2 +- .../views/_partials/error-list.inc | 2 +- .../material-blue/views/_partials/error.inc | 2 +- .../views/_partials/fixed-header.inc | 2 +- .../material-blue/views/_partials/footer.inc | 2 +- .../views/_partials/no_records_found.inc | 2 +- .../views/account/account-editpass.inc | 4 +- .../views/account/account-history.inc | 4 +- .../views/account/account-link.inc | 4 +- .../views/account/account-permissions.inc | 4 +- .../views/account/account-request.inc | 4 +- .../material-blue/views/account/account.inc | 4 +- .../material-blue/views/account/actions.inc | 4 +- .../material-blue/views/account/details.inc | 4 +- .../views/account/files-list.inc | 2 +- .../material-blue/views/account/files.inc | 4 +- .../views/account/linkedAccounts.inc | 2 +- .../views/account/search-header.inc | 4 +- .../views/account/search-index.inc | 4 +- .../views/account/search-rows.inc | 4 +- .../views/account/search-searchbox.inc | 4 +- .../material-blue/views/account/viewpass.inc | 4 +- .../views/common/aux-customfields.inc | 9 +- .../material-blue/views/common/datatabs.inc | 6 +- .../material-blue/views/common/debug.inc | 4 +- .../material-blue/views/config/accounts.inc | 9 +- .../material-blue/views/config/backup.inc | 11 +- .../material-blue/views/config/encryption.inc | 9 +- .../views/config/general-auth.inc | 9 +- .../views/config/general-events.inc | 9 +- .../views/config/general-proxy.inc | 9 +- .../views/config/general-site.inc | 9 +- .../material-blue/views/config/general.inc | 9 +- .../material-blue/views/config/import.inc | 9 +- .../material-blue/views/config/info.inc | 11 +- .../material-blue/views/config/ldap.inc | 9 +- .../material-blue/views/config/mail.inc | 9 +- .../views/config/wiki-dokuwiki.inc | 9 +- .../material-blue/views/config/wiki.inc | 9 +- .../views/error/error-database.inc | 2 +- .../views/error/error-maintenance.inc | 2 +- .../views/eventlog/datagrid-rows.inc | 11 +- .../material-blue/views/eventlog/index.inc | 2 +- .../views/grid/datagrid-grid.inc | 11 +- .../views/grid/datagrid-nav-full.inc | 4 +- .../views/grid/datagrid-rows.inc | 4 +- .../views/grid/datagrid-table-simple.inc | 4 +- .../views/grid/datagrid-table.inc | 6 +- .../views/grid/datatabs-grid.inc | 11 +- .../material-blue/views/install/index.inc | 9 +- .../views/itemshow/account_bulkedit.inc | 19 +- .../views/itemshow/auth_token.inc | 11 +- .../material-blue/views/itemshow/category.inc | 11 +- .../material-blue/views/itemshow/client.inc | 11 +- .../views/itemshow/custom_field.inc | 11 +- .../material-blue/views/itemshow/file.inc | 11 +- .../views/itemshow/item_preset-password.inc | 11 +- .../views/itemshow/item_preset-permission.inc | 9 +- .../views/itemshow/item_preset-private.inc | 11 +- .../itemshow/item_preset-session_timeout.inc | 11 +- .../views/itemshow/item_preset.inc | 11 +- .../views/itemshow/public_link.inc | 11 +- .../material-blue/views/itemshow/results.inc | 9 +- .../material-blue/views/itemshow/tag.inc | 11 +- .../material-blue/views/itemshow/user.inc | 11 +- .../views/itemshow/user_group.inc | 13 +- .../views/itemshow/user_pass.inc | 11 +- .../views/itemshow/user_profile.inc | 13 +- .../material-blue/views/login/index.inc | 9 +- .../material-blue/views/main/update.inc | 9 +- .../material-blue/views/main/upgrade.inc | 9 +- .../views/notification/index.inc | 2 +- .../views/notification/notification.inc | 5 +- .../material-blue/views/plugin/index.inc | 2 +- .../material-blue/views/plugin/plugin.inc | 15 +- .../material-blue/views/upgrade/index.inc | 2 +- .../views/userpassreset/reset.inc | 9 +- .../views/usersettings/general.inc | 11 +- .../material-blue/views/wiki/wikipage.inc | 9 +- composer.lock | 33 +- lib/Base.php | 17 +- lib/BaseFunctions.php | 58 +- lib/Definitions.php | 154 +- lib/SP/Adapters/AccountAdapter.php | 2 +- lib/SP/Adapters/AdapterBase.php | 2 +- lib/SP/Adapters/CategoryAdapter.php | 2 +- lib/SP/Adapters/ClientAdapter.php | 2 +- lib/SP/Adapters/CustomFieldAdapter.php | 2 +- lib/SP/Core/Acl/Acl.php | 2 +- lib/SP/Core/Acl/Actions.php | 8 +- lib/SP/Core/Application.php | 23 +- lib/SP/Core/Bootstrap/BootstrapApi.php | 4 +- lib/SP/Core/Bootstrap/BootstrapBase.php | 35 +- lib/SP/Core/Bootstrap/BootstrapWeb.php | 13 +- .../Core/Bootstrap/UpgradeConfigChecker.php | 13 +- lib/SP/Core/Context/ContextInterface.php | 2 +- lib/SP/Core/Context/SessionContext.php | 6 +- lib/SP/Core/Context/StatelessContext.php | 4 +- lib/SP/Core/Crypt/CSRF.php | 13 +- lib/SP/Core/Crypt/Cookie.php | 7 +- lib/SP/Core/Crypt/Crypt.php | 2 +- lib/SP/Core/Crypt/CryptPKI.php | 6 +- lib/SP/Core/Crypt/CryptSessionHandler.php | 2 +- lib/SP/Core/Crypt/OldCrypt.php | 4 +- lib/SP/Core/Crypt/SecureKeyCookie.php | 5 +- lib/SP/Core/Crypt/Session.php | 2 +- lib/SP/Core/Crypt/UUIDCookie.php | 3 +- lib/SP/Core/Events/Event.php | 2 +- lib/SP/Core/HttpModuleBase.php | 3 +- lib/SP/Core/Language.php | 37 +- lib/SP/Core/LanguageInterface.php | 61 + lib/SP/Core/MimeTypes.php | 8 +- lib/SP/Core/MimeTypesInterface.php | 43 + lib/SP/Core/ModuleBase.php | 6 +- lib/SP/Core/UI/Theme.php | 12 +- lib/SP/DataModel/UserLoginData.php | 2 +- .../Account/AccountAclServiceInterface.php | 92 ++ .../Account/AccountCryptServiceInterface.php | 51 + .../Account/AccountFileServiceInterface.php | 123 ++ .../AccountHistoryServiceInterface.php | 141 ++ .../Account/AccountPresetServiceInterface.php | 48 + .../Account/AccountSearchServiceInterface.php | 57 + .../Account/AccountServiceInterface.php | 8 +- .../AccountToFavoriteServiceInterface.php | 61 + .../Account/AccountToTagServiceInterface.php | 43 + .../In/AccountFileRepositoryInterface.php | 59 + .../In/AccountHistoryRepositoryInterface.php | 82 + .../Account/In/AccountRepositoryInterface.php | 190 +++ .../AccountToFavoriteRepositoryInterface.php | 73 + .../In/AccountToTagRepositoryInterface.php | 80 + .../AccountToUserGroupRepositoryInterface.php | 109 ++ .../In/AccountToUserRepositoryInterface.php | 98 ++ .../Account/PublicLinkServiceInterface.php | 146 ++ .../Account/Services}/AccountAcl.php | 118 +- .../Account/Services}/AccountAclService.php | 178 +-- .../Account/Services}/AccountBulkRequest.php | 14 +- .../Account/Services}/AccountCryptService.php | 96 +- .../Account/Services}/AccountFileService.php | 81 +- .../Account/Services}/AccountFilterUser.php | 37 +- .../Services}/AccountHistoryService.php | 89 +- .../Services}/AccountPasswordRequest.php | 10 +- .../Services}/AccountPresetService.php | 24 +- .../Account/Services/AccountRequest.php | 61 + .../Account/Services}/AccountSearchFilter.php | 44 +- .../Account/Services}/AccountSearchItem.php | 7 +- .../Services}/AccountSearchService.php | 239 +-- .../Account/Services}/AccountService.php | 234 +-- .../Services}/AccountToFavoriteService.php | 36 +- .../Account/Services}/AccountToTagService.php | 37 +- .../Account/Services}/PublicLinkKey.php | 8 +- .../Account/Services}/PublicLinkService.php | 148 +- .../Services/UpgradePublicLinkService.php} | 78 +- .../UpgradePublicLinkServiceInterface.php | 39 + lib/SP/Domain/Api/ApiServiceInterface.php | 113 ++ .../Api/Services}/ApiRequest.php | 27 +- .../Api/Services}/ApiRequestData.php | 6 +- .../Api/Services}/ApiRequestException.php | 6 +- .../Api/Services}/ApiResponse.php | 40 +- .../Api/Services}/ApiService.php | 156 +- .../Api/Services}/JsonRpcResponse.php | 52 +- .../Domain/Auth/AuthTokenServiceInterface.php | 123 ++ .../Domain/Auth/LdapCheckServiceInterface.php | 64 + lib/SP/Domain/Auth/LoginServiceInterface.php | 64 + .../Auth/Services}/AuthException.php | 6 +- .../Auth/Services}/AuthTokenService.php | 112 +- .../Auth/Services}/LdapCheckService.php | 123 +- .../Auth/Services}/LoginResponse.php | 12 +- .../Auth/Services}/LoginService.php | 328 ++-- .../Services/UpgradeAuthTokenService.php} | 75 +- .../Auth/UpgradeAuthTokenServiceInterface.php | 43 + .../Category/CategoryServiceInterface.php | 103 ++ .../In/CategoryRepositoryInterface.php | 50 + .../Category/Services}/CategoryService.php | 60 +- .../Domain/Client/ClientServiceInterface.php | 117 ++ .../Client/In/ClientRepositoryInterface.php | 66 + .../Client/Services}/ClientService.php | 82 +- .../Common/In}/RepositoryInterface.php | 8 +- .../{ => Domain/Common}/Services/Service.php | 47 +- .../Common}/Services/ServiceException.php | 6 +- .../Common}/Services/ServiceItemTrait.php | 8 +- .../Config/Adapters}/ConfigData.php | 37 +- .../Config/ConfigBackupServiceInterface.php | 54 + lib/SP/Domain/Config/ConfigInterface.php | 77 + .../Domain/Config/ConfigServiceInterface.php | 79 + .../Config/In}/ConfigDataInterface.php | 2 +- .../Config/In/ConfigRepositoryInterface.php | 93 ++ .../Config/Services}/ConfigBackupService.php | 39 +- .../Config/Services/ConfigFileService.php} | 48 +- .../Config/Services}/ConfigService.php | 65 +- .../Config/Services}/ConfigUtil.php | 4 +- .../Config/Services}/UpgradeConfigService.php | 243 +-- .../Config/UpgradeConfigServiceInterface.php | 43 + .../Crypt/MasterPassServiceInterface.php | 64 + .../Crypt/SecureSessionServiceInterface.php | 48 + .../Crypt/Services}/MasterPassService.php | 56 +- .../Crypt/Services}/SecureSessionService.php | 57 +- .../Services}/TemporaryMasterPassService.php | 114 +- .../Services}/UpdateMasterPassRequest.php | 23 +- .../TemporaryMasterPassServiceInterface.php | 85 ++ .../CustomFieldCryptServiceInterface.php | 46 + .../CustomFieldDefServiceInterface.php | 99 ++ .../CustomFieldServiceInterface.php | 140 ++ .../CustomFieldTypeServiceInterface.php | 63 + .../In/CustomFieldDefRepositoryInterface.php | 41 + .../In/CustomFieldRepositoryInterface.php | 131 ++ .../In/CustomFieldTypeRepositoryInterface.php | 37 + .../Services}/CustomFieldCryptService.php | 81 +- .../Services}/CustomFieldDefService.php | 148 +- .../CustomField/Services}/CustomFieldItem.php | 34 +- .../Services}/CustomFieldService.php | 113 +- .../Services}/CustomFieldTypeService.php | 35 +- .../UpgradeCustomFieldDataService.php} | 75 +- .../UpgradeCustomFieldDefinitionService.php} | 182 ++- ...UpgradeCustomFieldDataServiceInterface.php | 43 + ...eCustomFieldDefinitionServiceInterface.php | 57 + .../Export/FileBackupServiceInterface.php | 43 + .../Export/Services}/BackupFiles.php | 24 +- .../Export/Services}/FileBackupService.php | 39 +- .../Export/Services}/VerifyResult.php | 10 +- .../Export/Services}/XmlExportService.php | 231 ++- .../Export/Services}/XmlVerifyService.php | 55 +- .../Export/XmlExportServiceInterface.php | 58 + .../Export/XmlVerifyServiceInterface.php | 55 + lib/SP/Domain/Import/FileImportInterface.php | 60 + .../Import/ImportInterface.php | 4 +- .../Domain/Import/ImportServiceInterface.php | 43 + .../Import/LdapImportServiceInterface.php | 56 + .../Import/Services}/CsvImport.php | 13 +- .../Import/Services}/CsvImportBase.php | 104 +- .../Import/Services}/FileImport.php | 57 +- .../Import/Services}/ImportException.php | 6 +- .../Domain/Import/Services/ImportHelper.php | 74 + .../Import/Services}/ImportParams.php | 14 +- .../Import/Services}/ImportService.php | 75 +- .../Import/Services}/ImportTrait.php | 64 +- .../Import/Services}/KeepassImport.php | 37 +- .../Import/Services}/LdapImportParams.php | 16 +- .../Import/Services}/LdapImportService.php | 101 +- .../Import/Services}/SyspassImport.php | 190 +-- .../Import/Services}/XmlFileImport.php | 25 +- .../Import/Services}/XmlImport.php | 51 +- .../Import/Services}/XmlImportBase.php | 81 +- .../Domain/Import/XmlFileImportInterface.php | 46 + lib/SP/Domain/Import/XmlImportInterface.php | 36 + .../Install/DatabaseSetupInterface.php | 6 +- lib/SP/Domain/Install/InstallerInterface.php | 42 + .../Install/Services}/InstallData.php | 2 +- .../Install/Services}/Installer.php | 81 +- .../Install/Services}/MySQL.php | 17 +- .../In/ItemPresetRepositoryInterface.php | 53 + .../ItemPreset/ItemPresetInterface.php | 12 +- .../ItemPreset/ItemPresetServiceInterface.php | 111 ++ .../Services}/ItemPresetRequest.php | 8 +- .../Services}/ItemPresetService.php | 56 +- .../In/NotificationRepositoryInterface.php | 137 ++ .../Notification/MailServiceInterface.php | 63 + .../NotificationServiceInterface.php | 174 +++ .../Notification/Services}/MailService.php | 154 +- .../Services}/NotificationService.php | 115 +- .../UpgradeDatabaseServiceInterface.php | 37 + .../In/PluginDataRepositoryInterface.php | 138 ++ .../Plugin/In/PluginRepositoryInterface.php | 121 ++ .../Plugin/PluginDataServiceInterface.php | 119 ++ .../Domain/Plugin/PluginServiceInterface.php | 180 +++ .../Plugin/Services}/PluginDataService.php | 93 +- .../Plugin/Services}/PluginService.php | 89 +- .../Plugin/UpgradePluginServiceInterface.php | 43 + .../Providers/MailProviderInterface.php | 52 + lib/SP/Domain/Providers/MailerInterface.php | 45 + .../Security/EventlogServiceInterface.php | 60 + .../In/EventlogRepositoryInterface.php | 69 + .../Security/In/TrackRepositoryInterface.php | 114 ++ .../Security/Services}/EventlogService.php | 46 +- .../Security/Services}/TrackService.php | 91 +- .../Domain/Security/TrackServiceInterface.php | 112 ++ .../Domain/Tag/In/TagRepositoryInterface.php | 50 + .../Tag/Services}/TagService.php | 75 +- lib/SP/Domain/Tag/TagServiceInterface.php | 100 ++ .../Task => Domain/Task/Services}/Task.php | 52 +- .../Task/Services}/TaskFactory.php | 14 +- .../Task/Services}/TaskService.php | 72 +- lib/SP/Domain/Task/TaskServiceInterface.php | 44 + .../Upgrade/Services/UpgradeAppService.php | 172 +++ .../Services}/UpgradeDatabaseService.php | 97 +- .../Upgrade/Services}/UpgradeException.php | 6 +- .../Services/UpgradePluginService.php} | 42 +- .../Upgrade/Services}/UpgradeUtil.php | 21 +- .../Upgrade/UpgradeAppServiceInterface.php | 35 + .../Upgrade/UpgradeInterface.php | 8 +- .../User/In/UserGroupRepositoryInterface.php | 72 + .../In/UserPassRecoverRepositoryInterface.php | 86 ++ .../In/UserProfileRepositoryInterface.php | 50 + .../User/In/UserRepositoryInterface.php | 168 +++ .../In/UserToUserGroupRepositoryInterface.php | 107 ++ .../User/Services}/UpdatePassRequest.php | 10 +- .../Services}/UpdatedMasterPassException.php | 12 +- .../User/Services}/UserGroupService.php | 105 +- .../User/Services}/UserLoginRequest.php | 14 +- .../User/Services}/UserLoginResponse.php | 71 +- .../User/Services}/UserPassRecoverService.php | 58 +- .../User/Services}/UserPassResponse.php | 6 +- .../User/Services}/UserPassService.php | 106 +- .../User/Services}/UserProfileService.php | 79 +- .../User/Services}/UserService.php | 118 +- .../User/Services}/UserToUserGroupService.php | 75 +- .../Domain/User/UserGroupServiceInterface.php | 114 ++ .../User/UserPassRecoverServiceInterface.php | 76 + .../Domain/User/UserPassServiceInterface.php | 88 ++ .../User/UserProfileServiceInterface.php | 99 ++ lib/SP/Domain/User/UserServiceInterface.php | 200 +++ .../User/UserToUserGroupServiceInterface.php | 78 + lib/SP/Html/DataGrid/DataGridDataBase.php | 2 +- .../Html/DataGrid/DataGridDataInterface.php | 2 +- lib/SP/Html/Minify.php | 5 +- lib/SP/Http/Client.php | 21 +- lib/SP/Http/Message.php | 4 - lib/SP/Http/Request.php | 2 +- lib/SP/Http/RequestInterface.php | 123 ++ lib/SP/Http/XMLRPCResponseParse.php | 276 ---- .../Repositories}/AccountFileRepository.php | 56 +- .../AccountHistoryRepository.php | 58 +- .../Repositories}/AccountRepository.php | 130 +- .../AccountToFavoriteRepository.php | 15 +- .../Repositories}/AccountToTagRepository.php | 32 +- .../AccountToUserGroupRepository.php | 39 +- .../Repositories}/AccountToUserRepository.php | 40 +- .../Repositories}/PublicLinkRepository.php | 68 +- .../Repositories}/AuthTokenRepository.php | 72 +- .../Repositories}/CategoryRepository.php | 56 +- .../Client/Repositories}/ClientRepository.php | 62 +- .../Repositories/DuplicatedItemException.php | 6 +- .../Repositories/NoSuchItemException.php | 6 +- .../Common}/Repositories/Repository.php | 14 +- .../Repositories/RepositoryItemTrait.php | 27 +- .../Config/Repositories}/ConfigRepository.php | 25 +- .../CustomFieldDefCollection.php | 6 +- .../CustomFieldDefRepository.php | 55 +- .../Repositories}/CustomFieldRepository.php | 77 +- .../CustomFieldTypeRepository.php | 38 +- .../Database/DBStorageInterface.php | 4 +- .../Database/Database.php | 95 +- .../Database/DatabaseConnectionData.php | 106 +- .../Database/DatabaseException.php | 6 +- .../Database/DatabaseFileInterface.php | 2 +- .../Database/DatabaseInterface.php | 4 +- .../Database/DatabaseUtil.php | 31 +- .../Database/MySQLFileParser.php | 17 +- .../Database/MySQLHandler.php | 36 +- .../Database/QueryData.php | 82 +- .../Database/QueryResult.php | 32 +- .../File/ArchiveHandler.php | 14 +- .../File/ArchiveHandlerInterface.php | 48 + .../File/FileCache.php | 6 +- .../File/FileCacheBase.php | 10 +- .../File/FileCacheInterface.php | 6 +- .../File/FileCachePacked.php | 30 +- .../File/FileException.php | 6 +- .../File/FileHandler.php | 97 +- .../File/FileHandlerInterface.php | 144 ++ .../File/XmlFileStorageInterface.php | 12 +- .../File/XmlHandler.php | 185 ++- .../Repositories}/ItemPresetRepository.php | 92 +- .../Repositories}/NotificationRepository.php | 92 +- .../Plugin/Repositories}/PluginDataModel.php | 12 +- .../Repositories}/PluginDataRepository.php | 45 +- .../Plugin/Repositories}/PluginModel.php | 16 +- .../Plugin/Repositories}/PluginRepository.php | 98 +- .../Repositories}/EventlogRepository.php | 24 +- .../Repositories}/TrackRepository.php | 35 +- .../Security/Repositories}/TrackRequest.php | 24 +- .../Tag/Repositories}/TagRepository.php | 56 +- .../Repositories}/UserGroupRepository.php | 50 +- .../UserPassRecoverRepository.php | 31 +- .../Repositories}/UserProfileRepository.php | 54 +- .../User/Repositories}/UserRepository.php | 113 +- .../UserToUserGroupRepository.php | 34 +- lib/SP/Mvc/Controller/ControllerTrait.php | 15 +- .../ExtensibleControllerInterface.php | 6 +- lib/SP/Mvc/Controller/ItemTrait.php | 60 +- lib/SP/Mvc/Controller/WebControllerHelper.php | 107 ++ lib/SP/Mvc/View/Components/DataTab.php | 8 +- lib/SP/Mvc/View/Template.php | 32 +- lib/SP/Mvc/View/TemplateInterface.php | 171 +++ lib/SP/Plugin/PluginBase.php | 4 +- lib/SP/Plugin/PluginManager.php | 22 +- lib/SP/Plugin/PluginOperation.php | 17 +- lib/SP/Providers/Acl/AclHandler.php | 15 +- lib/SP/Providers/Auth/AuthDataBase.php | 18 +- lib/SP/Providers/Auth/AuthProvider.php | 89 +- .../Providers/Auth/AuthProviderInterface.php | 61 + .../Browser/{Browser.php => BrowserAuth.php} | 31 +- .../Auth/Browser/BrowserAuthInterface.php | 54 + .../{Database.php => DatabaseAuth.php} | 57 +- .../Auth/Database/DatabaseAuthInterface.php | 55 + lib/SP/Providers/Auth/Ldap/Ldap.php | 44 +- lib/SP/Providers/Auth/Ldap/LdapAuth.php | 65 +- .../Providers/Auth/Ldap/LdapAuthInterface.php | 64 + lib/SP/Providers/Auth/Ldap/LdapParams.php | 60 +- lib/SP/Providers/Log/DatabaseLogHandler.php | 12 +- lib/SP/Providers/Log/LoggerBase.php | 6 +- lib/SP/Providers/Mail/MailHandler.php | 8 +- lib/SP/Providers/Mail/MailProvider.php | 59 +- lib/SP/Providers/Mail/PhpMailerWrapper.php | 99 ++ .../Notification/NotificationHandler.php | 7 +- lib/SP/Providers/Provider.php | 6 +- lib/SP/Services/Account/AccountRequest.php | 61 - lib/SP/Services/Upgrade/UpgradeAppService.php | 141 -- lib/SP/Util/ArrayUtil.php | 43 +- lib/SP/Util/Checks.php | 6 +- lib/SP/Util/Connection.php | 24 +- lib/SP/Util/ConnectionInterface.php | 4 +- lib/SP/Util/DateUtil.php | 4 +- lib/SP/Util/ErrorUtil.php | 104 +- lib/SP/Util/FileUtil.php | 11 +- lib/SP/Util/Filter.php | 8 +- lib/SP/Util/HttpUtil.php | 50 +- lib/SP/Util/ImageUtil.php | 2 +- lib/SP/Util/Link.php | 2 +- lib/SP/Util/PasswordUtil.php | 29 +- lib/SP/Util/Util.php | 46 +- lib/SP/Util/VersionUtil.php | 16 +- tests/SP/Config/ConfigTest.php | 30 +- tests/SP/Core/Acl/AclTest.php | 2 +- tests/SP/Core/Crypt/CryptPKITest.php | 2 +- tests/SP/DatabaseTrait.php | 2 +- tests/SP/DatabaseUtil.php | 4 +- tests/SP/Modules/Api/ApiTestCase.php | 16 +- tests/SP/Modules/Cli/CliTestCase.php | 2 +- .../Cli/Commands/BackupCommandTest.php | 6 +- .../Cli/Commands/InstallCommandTest.php | 10 +- .../AccountFileRepositoryTest.php | 5 +- .../AccountHistoryRepositoryTest.php | 7 +- .../SP/Repositories/AccountRepositoryTest.php | 11 +- .../AccountToFavoriteRepositoryTest.php | 5 +- .../AccountToTagRepositoryTest.php | 7 +- .../AccountToUserGroupRepositoryTest.php | 7 +- .../AccountToUserRepositoryTest.php | 7 +- .../Repositories/AuthTokenRepositoryTest.php | 6 +- .../Repositories/CategoryRepositoryTest.php | 7 +- .../SP/Repositories/ClientRepositoryTest.php | 4 +- .../SP/Repositories/ConfigRepositoryTest.php | 5 +- .../CustomFieldDefRepositoryTest.php | 7 +- .../CustomFieldRepositoryTest.php | 5 +- .../CustomFieldTypeRepositoryTest.php | 5 +- .../Repositories/EventlogRepositoryTest.php | 5 +- .../Repositories/ItemPresetRepositoryTest.php | 5 +- .../NotificationRepositoryTest.php | 5 +- .../Repositories/PluginDataRepositoryTest.php | 15 +- .../SP/Repositories/PluginRepositoryTest.php | 7 +- .../Repositories/PublicLinkRepositoryTest.php | 6 +- tests/SP/Repositories/TagRepositoryTest.php | 7 +- tests/SP/Repositories/TrackRepositoryTest.php | 7 +- .../Repositories/UserGroupRepositoryTest.php | 7 +- .../UserPassRecoverRepositoryTest.php | 5 +- .../UserProfileRepositoryTest.php | 7 +- tests/SP/Repositories/UserRepositoryTest.php | 9 +- .../UserToUserGroupRepositoryTest.php | 7 +- .../Account/AccountAclServiceTest.php | 201 +-- .../Account/AccountCryptServiceTest.php | 15 +- .../Account/AccountFileServiceTest.php | 8 +- .../Account/AccountHistoryServiceTest.php | 11 +- .../Account/AccountSearchServiceTest.php | 13 +- .../Services/Account/AccountServiceTest.php | 27 +- .../Account/AccountToFavoriteServiceTest.php | 5 +- .../Account/AccountToTagServiceTest.php | 5 +- tests/SP/Services/Api/ApiRequestTest.php | 4 +- tests/SP/Services/Api/ApiServiceTest.php | 17 +- .../AuthToken/AuthTokenServiceTest.php | 10 +- .../Services/Backup/FileBackupServiceTest.php | 14 +- .../Services/Category/CategoryServiceTest.php | 10 +- .../SP/Services/Client/ClientServiceTest.php | 12 +- .../Config/ConfigBackupServiceTest.php | 14 +- .../SP/Services/Config/ConfigServiceTest.php | 13 +- .../Services/Crypt/MasterPassServiceTest.php | 19 +- .../Crypt/SecureSessionServiceTest.php | 2 +- .../Crypt/TemporaryMasterPassServiceTest.php | 15 +- .../CustomFieldCryptServiceTest.php | 15 +- .../CustomField/CustomFieldDefServiceTest.php | 10 +- .../CustomField/CustomFieldServiceTest.php | 10 +- .../Services/Eventlog/EventlogServiceTest.php | 5 +- .../Services/Export/XmlExportServiceTest.php | 23 +- .../Services/Export/XmlVerifyServiceTest.php | 15 +- tests/SP/Services/Import/CsvImportTest.php | 18 +- .../SP/Services/Import/KeepassImportTest.php | 22 +- .../SP/Services/Import/SyspassImportTest.php | 20 +- .../SP/Services/Import/XmlFileImportTest.php | 8 +- tests/SP/Services/Import/XmlImportTest.php | 12 +- tests/SP/Services/Install/InstallerTest.php | 35 +- tests/SP/Services/Install/MySQLTest.php | 16 +- .../ItemPreset/ItemPresetServiceTest.php | 6 +- .../Notification/NotificationServiceTest.php | 10 +- .../Services/Plugin/PluginDataServiceTest.php | 37 +- .../Services/Plugin/PluginOperationTest.php | 12 +- .../SP/Services/Plugin/PluginServiceTest.php | 11 +- .../PublicLink/PublicLinkServiceTest.php | 13 +- tests/SP/Services/Tag/TagServiceTest.php | 10 +- tests/SP/Services/Task/TaskServiceTest.php | 10 +- tests/SP/Services/Track/TrackServiceTest.php | 12 +- .../SP/Services/User/UserPassServiceTest.php | 11 +- tests/SP/Services/User/UserServiceTest.php | 27 +- .../UserGroup/UserGroupServiceTest.php | 21 +- .../UserGroup/UserToUserGroupServiceTest.php | 9 +- .../UserPassRecoverServiceTest.php | 9 +- .../UserProfile/UserProfileServiceTest.php | 14 +- tests/SP/Storage/ArchiveHandlerTest.php | 4 +- tests/SP/Storage/FileCachePackedTest.php | 4 +- tests/SP/Storage/FileCacheTest.php | 4 +- tests/SP/Storage/FileHandlerTest.php | 6 +- tests/SP/Storage/XmlHandlerTest.php | 8 +- tests/SP/UnitaryTestCase.php | 18 +- tests/SP/bootstrap.php | 8 +- 629 files changed, 18541 insertions(+), 9626 deletions(-) create mode 100644 app/modules/web/Controllers/Account/AccountControllerBase.php create mode 100644 app/modules/web/Controllers/Account/CopyController.php create mode 100644 app/modules/web/Controllers/Account/CopyPassController.php create mode 100644 app/modules/web/Controllers/Account/CopyPassHistoryController.php create mode 100644 app/modules/web/Controllers/Account/CreateController.php create mode 100644 app/modules/web/Controllers/Account/DeleteController.php create mode 100644 app/modules/web/Controllers/Account/EditController.php create mode 100644 app/modules/web/Controllers/Account/EditPassController.php create mode 100644 app/modules/web/Controllers/Account/IndexController.php create mode 100644 app/modules/web/Controllers/Account/RequestAccessController.php create mode 100644 app/modules/web/Controllers/Account/SaveCopyController.php create mode 100644 app/modules/web/Controllers/Account/SaveCreateController.php create mode 100644 app/modules/web/Controllers/Account/SaveDeleteController.php create mode 100644 app/modules/web/Controllers/Account/SaveEditController.php create mode 100644 app/modules/web/Controllers/Account/SaveEditPassController.php create mode 100644 app/modules/web/Controllers/Account/SaveEditRestoreController.php create mode 100644 app/modules/web/Controllers/Account/SaveRequestController.php create mode 100644 app/modules/web/Controllers/Account/SearchController.php create mode 100644 app/modules/web/Controllers/Account/ViewController.php create mode 100644 app/modules/web/Controllers/Account/ViewHistoryController.php create mode 100644 app/modules/web/Controllers/Account/ViewLinkController.php create mode 100644 app/modules/web/Controllers/Account/ViewPassController.php create mode 100644 app/modules/web/Controllers/Account/ViewPassHistoryController.php delete mode 100644 app/modules/web/Controllers/AccountController.php rename app/modules/web/Controllers/{BootstrapController.php => Bootstrap/GetEnvironmentController.php} (83%) rename app/modules/web/Controllers/{ => Index}/IndexController.php (67%) create mode 100644 app/modules/web/Controllers/Login/IndexController.php create mode 100644 app/modules/web/Controllers/Login/LoginController.php create mode 100644 app/modules/web/Controllers/Login/LogoutController.php delete mode 100644 app/modules/web/Controllers/LoginController.php create mode 100644 app/modules/web/Controllers/Resource/CssController.php rename app/modules/web/Controllers/{ResourceController.php => Resource/JsController.php} (57%) create mode 100644 lib/SP/Core/LanguageInterface.php create mode 100644 lib/SP/Core/MimeTypesInterface.php create mode 100644 lib/SP/Domain/Account/AccountAclServiceInterface.php create mode 100644 lib/SP/Domain/Account/AccountCryptServiceInterface.php create mode 100644 lib/SP/Domain/Account/AccountFileServiceInterface.php create mode 100644 lib/SP/Domain/Account/AccountHistoryServiceInterface.php create mode 100644 lib/SP/Domain/Account/AccountPresetServiceInterface.php create mode 100644 lib/SP/Domain/Account/AccountSearchServiceInterface.php rename lib/SP/{Services => Domain}/Account/AccountServiceInterface.php (87%) create mode 100644 lib/SP/Domain/Account/AccountToFavoriteServiceInterface.php create mode 100644 lib/SP/Domain/Account/AccountToTagServiceInterface.php create mode 100644 lib/SP/Domain/Account/In/AccountFileRepositoryInterface.php create mode 100644 lib/SP/Domain/Account/In/AccountHistoryRepositoryInterface.php create mode 100644 lib/SP/Domain/Account/In/AccountRepositoryInterface.php create mode 100644 lib/SP/Domain/Account/In/AccountToFavoriteRepositoryInterface.php create mode 100644 lib/SP/Domain/Account/In/AccountToTagRepositoryInterface.php create mode 100644 lib/SP/Domain/Account/In/AccountToUserGroupRepositoryInterface.php create mode 100644 lib/SP/Domain/Account/In/AccountToUserRepositoryInterface.php create mode 100644 lib/SP/Domain/Account/PublicLinkServiceInterface.php rename lib/SP/{Services/Account => Domain/Account/Services}/AccountAcl.php (70%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountAclService.php (70%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountBulkRequest.php (85%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountCryptService.php (78%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountFileService.php (69%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountFilterUser.php (81%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountHistoryService.php (70%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountPasswordRequest.php (81%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountPresetService.php (79%) create mode 100644 lib/SP/Domain/Account/Services/AccountRequest.php rename lib/SP/{Services/Account => Domain/Account/Services}/AccountSearchFilter.php (85%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountSearchItem.php (97%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountSearchService.php (71%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountService.php (77%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountToFavoriteService.php (70%) rename lib/SP/{Services/Account => Domain/Account/Services}/AccountToTagService.php (61%) rename lib/SP/{Services/PublicLink => Domain/Account/Services}/PublicLinkKey.php (88%) rename lib/SP/{Services/PublicLink => Domain/Account/Services}/PublicLinkService.php (74%) rename lib/SP/{Services/Upgrade/UpgradePublicLink.php => Domain/Account/Services/UpgradePublicLinkService.php} (59%) create mode 100644 lib/SP/Domain/Account/UpgradePublicLinkServiceInterface.php create mode 100644 lib/SP/Domain/Api/ApiServiceInterface.php rename lib/SP/{Services/Api => Domain/Api/Services}/ApiRequest.php (86%) rename lib/SP/{Services/Api => Domain/Api/Services}/ApiRequestData.php (86%) rename lib/SP/{Services/Api => Domain/Api/Services}/ApiRequestException.php (86%) rename lib/SP/{Services/Api => Domain/Api/Services}/ApiResponse.php (72%) rename lib/SP/{Services/Api => Domain/Api/Services}/ApiService.php (65%) rename lib/SP/{Services/Api => Domain/Api/Services}/JsonRpcResponse.php (67%) create mode 100644 lib/SP/Domain/Auth/AuthTokenServiceInterface.php create mode 100644 lib/SP/Domain/Auth/LdapCheckServiceInterface.php create mode 100644 lib/SP/Domain/Auth/LoginServiceInterface.php rename lib/SP/{Services/Auth => Domain/Auth/Services}/AuthException.php (86%) rename lib/SP/{Services/AuthToken => Domain/Auth/Services}/AuthTokenService.php (67%) rename lib/SP/{Services/Ldap => Domain/Auth/Services}/LdapCheckService.php (77%) rename lib/SP/{Services/Auth => Domain/Auth/Services}/LoginResponse.php (84%) rename lib/SP/{Services/Auth => Domain/Auth/Services}/LoginService.php (68%) rename lib/SP/{Services/Upgrade/UpgradeAuthToken.php => Domain/Auth/Services/UpgradeAuthTokenService.php} (65%) create mode 100644 lib/SP/Domain/Auth/UpgradeAuthTokenServiceInterface.php create mode 100644 lib/SP/Domain/Category/CategoryServiceInterface.php create mode 100644 lib/SP/Domain/Category/In/CategoryRepositoryInterface.php rename lib/SP/{Services/Category => Domain/Category/Services}/CategoryService.php (72%) create mode 100644 lib/SP/Domain/Client/ClientServiceInterface.php create mode 100644 lib/SP/Domain/Client/In/ClientRepositoryInterface.php rename lib/SP/{Services/Client => Domain/Client/Services}/ClientService.php (67%) rename lib/SP/{Repositories => Domain/Common/In}/RepositoryInterface.php (93%) rename lib/SP/{ => Domain/Common}/Services/Service.php (75%) rename lib/SP/{ => Domain/Common}/Services/ServiceException.php (86%) rename lib/SP/{ => Domain/Common}/Services/ServiceItemTrait.php (89%) rename lib/SP/{Config => Domain/Config/Adapters}/ConfigData.php (96%) create mode 100644 lib/SP/Domain/Config/ConfigBackupServiceInterface.php create mode 100644 lib/SP/Domain/Config/ConfigInterface.php create mode 100644 lib/SP/Domain/Config/ConfigServiceInterface.php rename lib/SP/{Config => Domain/Config/In}/ConfigDataInterface.php (99%) create mode 100644 lib/SP/Domain/Config/In/ConfigRepositoryInterface.php rename lib/SP/{Services/Config => Domain/Config/Services}/ConfigBackupService.php (74%) rename lib/SP/{Config/Config.php => Domain/Config/Services/ConfigFileService.php} (84%) rename lib/SP/{Services/Config => Domain/Config/Services}/ConfigService.php (78%) rename lib/SP/{Config => Domain/Config/Services}/ConfigUtil.php (96%) rename lib/SP/{Services/Upgrade => Domain/Config/Services}/UpgradeConfigService.php (52%) create mode 100644 lib/SP/Domain/Config/UpgradeConfigServiceInterface.php create mode 100644 lib/SP/Domain/Crypt/MasterPassServiceInterface.php create mode 100644 lib/SP/Domain/Crypt/SecureSessionServiceInterface.php rename lib/SP/{Services/Crypt => Domain/Crypt/Services}/MasterPassService.php (64%) rename lib/SP/{Services/Crypt => Domain/Crypt/Services}/SecureSessionService.php (72%) rename lib/SP/{Services/Crypt => Domain/Crypt/Services}/TemporaryMasterPassService.php (71%) rename lib/SP/{Services/Crypt => Domain/Crypt/Services}/UpdateMasterPassRequest.php (81%) create mode 100644 lib/SP/Domain/Crypt/TemporaryMasterPassServiceInterface.php create mode 100644 lib/SP/Domain/CustomField/CustomFieldCryptServiceInterface.php create mode 100644 lib/SP/Domain/CustomField/CustomFieldDefServiceInterface.php create mode 100644 lib/SP/Domain/CustomField/CustomFieldServiceInterface.php create mode 100644 lib/SP/Domain/CustomField/CustomFieldTypeServiceInterface.php create mode 100644 lib/SP/Domain/CustomField/In/CustomFieldDefRepositoryInterface.php create mode 100644 lib/SP/Domain/CustomField/In/CustomFieldRepositoryInterface.php create mode 100644 lib/SP/Domain/CustomField/In/CustomFieldTypeRepositoryInterface.php rename lib/SP/{Services/CustomField => Domain/CustomField/Services}/CustomFieldCryptService.php (67%) rename lib/SP/{Services/CustomField => Domain/CustomField/Services}/CustomFieldDefService.php (65%) rename lib/SP/{Services/CustomField => Domain/CustomField/Services}/CustomFieldItem.php (60%) rename lib/SP/{Services/CustomField => Domain/CustomField/Services}/CustomFieldService.php (70%) rename lib/SP/{Services/CustomField => Domain/CustomField/Services}/CustomFieldTypeService.php (65%) rename lib/SP/{Services/Upgrade/UpgradeCustomFieldData.php => Domain/CustomField/Services/UpgradeCustomFieldDataService.php} (55%) rename lib/SP/{Services/Upgrade/UpgradeCustomFieldDefinition.php => Domain/CustomField/Services/UpgradeCustomFieldDefinitionService.php} (57%) create mode 100644 lib/SP/Domain/CustomField/UpgradeCustomFieldDataServiceInterface.php create mode 100644 lib/SP/Domain/CustomField/UpgradeCustomFieldDefinitionServiceInterface.php create mode 100644 lib/SP/Domain/Export/FileBackupServiceInterface.php rename lib/SP/{Services/Backup => Domain/Export/Services}/BackupFiles.php (87%) rename lib/SP/{Services/Backup => Domain/Export/Services}/FileBackupService.php (90%) rename lib/SP/{Services/Export => Domain/Export/Services}/VerifyResult.php (86%) rename lib/SP/{Services/Export => Domain/Export/Services}/XmlExportService.php (74%) rename lib/SP/{Services/Export => Domain/Export/Services}/XmlVerifyService.php (83%) create mode 100644 lib/SP/Domain/Export/XmlExportServiceInterface.php create mode 100644 lib/SP/Domain/Export/XmlVerifyServiceInterface.php create mode 100644 lib/SP/Domain/Import/FileImportInterface.php rename lib/SP/{Services => Domain}/Import/ImportInterface.php (92%) create mode 100644 lib/SP/Domain/Import/ImportServiceInterface.php create mode 100644 lib/SP/Domain/Import/LdapImportServiceInterface.php rename lib/SP/{Services/Import => Domain/Import/Services}/CsvImport.php (80%) rename lib/SP/{Services/Import => Domain/Import/Services}/CsvImportBase.php (61%) rename lib/SP/{Services/Import => Domain/Import/Services}/FileImport.php (78%) rename lib/SP/{Services/Import => Domain/Import/Services}/ImportException.php (86%) create mode 100644 lib/SP/Domain/Import/Services/ImportHelper.php rename lib/SP/{Services/Import => Domain/Import/Services}/ImportParams.php (85%) rename lib/SP/{Services/Import => Domain/Import/Services}/ImportService.php (58%) rename lib/SP/{Services/Import => Domain/Import/Services}/ImportTrait.php (80%) rename lib/SP/{Services/Import => Domain/Import/Services}/KeepassImport.php (82%) rename lib/SP/{Services/Ldap => Domain/Import/Services}/LdapImportParams.php (68%) rename lib/SP/{Services/Ldap => Domain/Import/Services}/LdapImportService.php (67%) rename lib/SP/{Services/Import => Domain/Import/Services}/SyspassImport.php (73%) rename lib/SP/{Services/Import => Domain/Import/Services}/XmlFileImport.php (83%) rename lib/SP/{Services/Import => Domain/Import/Services}/XmlImport.php (63%) rename lib/SP/{Services/Import => Domain/Import/Services}/XmlImportBase.php (52%) create mode 100644 lib/SP/Domain/Import/XmlFileImportInterface.php create mode 100644 lib/SP/Domain/Import/XmlImportInterface.php rename lib/SP/{Services => Domain}/Install/DatabaseSetupInterface.php (93%) create mode 100644 lib/SP/Domain/Install/InstallerInterface.php rename lib/SP/{Services/Install => Domain/Install/Services}/InstallData.php (99%) rename lib/SP/{Services/Install => Domain/Install/Services}/Installer.php (86%) rename lib/SP/{Services/Install => Domain/Install/Services}/MySQL.php (96%) create mode 100644 lib/SP/Domain/ItemPreset/In/ItemPresetRepositoryInterface.php rename lib/SP/{Services => Domain}/ItemPreset/ItemPresetInterface.php (72%) create mode 100644 lib/SP/Domain/ItemPreset/ItemPresetServiceInterface.php rename lib/SP/{Services/ItemPreset => Domain/ItemPreset/Services}/ItemPresetRequest.php (89%) rename lib/SP/{Services/ItemPreset => Domain/ItemPreset/Services}/ItemPresetService.php (74%) create mode 100644 lib/SP/Domain/Notification/In/NotificationRepositoryInterface.php create mode 100644 lib/SP/Domain/Notification/MailServiceInterface.php create mode 100644 lib/SP/Domain/Notification/NotificationServiceInterface.php rename lib/SP/{Services/Mail => Domain/Notification/Services}/MailService.php (62%) rename lib/SP/{Services/Notification => Domain/Notification/Services}/NotificationService.php (66%) create mode 100644 lib/SP/Domain/Persistence/UpgradeDatabaseServiceInterface.php create mode 100644 lib/SP/Domain/Plugin/In/PluginDataRepositoryInterface.php create mode 100644 lib/SP/Domain/Plugin/In/PluginRepositoryInterface.php create mode 100644 lib/SP/Domain/Plugin/PluginDataServiceInterface.php create mode 100644 lib/SP/Domain/Plugin/PluginServiceInterface.php rename lib/SP/{Services/Plugin => Domain/Plugin/Services}/PluginDataService.php (59%) rename lib/SP/{Services/Plugin => Domain/Plugin/Services}/PluginService.php (74%) create mode 100644 lib/SP/Domain/Plugin/UpgradePluginServiceInterface.php create mode 100644 lib/SP/Domain/Providers/MailProviderInterface.php create mode 100644 lib/SP/Domain/Providers/MailerInterface.php create mode 100644 lib/SP/Domain/Security/EventlogServiceInterface.php create mode 100644 lib/SP/Domain/Security/In/EventlogRepositoryInterface.php create mode 100644 lib/SP/Domain/Security/In/TrackRepositoryInterface.php rename lib/SP/{Services/EventLog => Domain/Security/Services}/EventlogService.php (66%) rename lib/SP/{Services/Track => Domain/Security/Services}/TrackService.php (66%) create mode 100644 lib/SP/Domain/Security/TrackServiceInterface.php create mode 100644 lib/SP/Domain/Tag/In/TagRepositoryInterface.php rename lib/SP/{Services/Tag => Domain/Tag/Services}/TagService.php (65%) create mode 100644 lib/SP/Domain/Tag/TagServiceInterface.php rename lib/SP/{Services/Task => Domain/Task/Services}/Task.php (82%) rename lib/SP/{Services/Task => Domain/Task/Services}/TaskFactory.php (92%) rename lib/SP/{Services/Task => Domain/Task/Services}/TaskService.php (76%) create mode 100644 lib/SP/Domain/Task/TaskServiceInterface.php create mode 100644 lib/SP/Domain/Upgrade/Services/UpgradeAppService.php rename lib/SP/{Services/Upgrade => Domain/Upgrade/Services}/UpgradeDatabaseService.php (65%) rename lib/SP/{Services/Upgrade => Domain/Upgrade/Services}/UpgradeException.php (86%) rename lib/SP/{Services/Upgrade/UpgradePlugin.php => Domain/Upgrade/Services/UpgradePluginService.php} (53%) rename lib/SP/{Services/Upgrade => Domain/Upgrade/Services}/UpgradeUtil.php (75%) create mode 100644 lib/SP/Domain/Upgrade/UpgradeAppServiceInterface.php rename lib/SP/{Services => Domain}/Upgrade/UpgradeInterface.php (85%) create mode 100644 lib/SP/Domain/User/In/UserGroupRepositoryInterface.php create mode 100644 lib/SP/Domain/User/In/UserPassRecoverRepositoryInterface.php create mode 100644 lib/SP/Domain/User/In/UserProfileRepositoryInterface.php create mode 100644 lib/SP/Domain/User/In/UserRepositoryInterface.php create mode 100644 lib/SP/Domain/User/In/UserToUserGroupRepositoryInterface.php rename lib/SP/{Services/User => Domain/User/Services}/UpdatePassRequest.php (86%) rename lib/SP/{Services/User => Domain/User/Services}/UpdatedMasterPassException.php (84%) rename lib/SP/{Services/UserGroup => Domain/User/Services}/UserGroupService.php (63%) rename lib/SP/{Services/User => Domain/User/Services}/UserLoginRequest.php (85%) rename lib/SP/{Services/User => Domain/User/Services}/UserLoginResponse.php (80%) rename lib/SP/{Services/UserPassRecover => Domain/User/Services}/UserPassRecoverService.php (75%) rename lib/SP/{Services/User => Domain/User/Services}/UserPassResponse.php (93%) rename lib/SP/{Services/User => Domain/User/Services}/UserPassService.php (75%) rename lib/SP/{Services/UserProfile => Domain/User/Services}/UserProfileService.php (65%) rename lib/SP/{Services/User => Domain/User/Services}/UserService.php (80%) rename lib/SP/{Services/UserGroup => Domain/User/Services}/UserToUserGroupService.php (68%) create mode 100644 lib/SP/Domain/User/UserGroupServiceInterface.php create mode 100644 lib/SP/Domain/User/UserPassRecoverServiceInterface.php create mode 100644 lib/SP/Domain/User/UserPassServiceInterface.php create mode 100644 lib/SP/Domain/User/UserProfileServiceInterface.php create mode 100644 lib/SP/Domain/User/UserServiceInterface.php create mode 100644 lib/SP/Domain/User/UserToUserGroupServiceInterface.php create mode 100644 lib/SP/Http/RequestInterface.php delete mode 100644 lib/SP/Http/XMLRPCResponseParse.php rename lib/SP/{Repositories/Account => Infrastructure/Account/Repositories}/AccountFileRepository.php (89%) rename lib/SP/{Repositories/Account => Infrastructure/Account/Repositories}/AccountHistoryRepository.php (89%) rename lib/SP/{Repositories/Account => Infrastructure/Account/Repositories}/AccountRepository.php (87%) rename lib/SP/{Repositories/Account => Infrastructure/Account/Repositories}/AccountToFavoriteRepository.php (85%) rename lib/SP/{Repositories/Account => Infrastructure/Account/Repositories}/AccountToTagRepository.php (79%) rename lib/SP/{Repositories/Account => Infrastructure/Account/Repositories}/AccountToUserGroupRepository.php (85%) rename lib/SP/{Repositories/Account => Infrastructure/Account/Repositories}/AccountToUserRepository.php (81%) rename lib/SP/{Repositories/PublicLink => Infrastructure/Account/Repositories}/PublicLinkRepository.php (91%) rename lib/SP/{Repositories/AuthToken => Infrastructure/Auth/Repositories}/AuthTokenRepository.php (89%) rename lib/SP/{Repositories/Category => Infrastructure/Category/Repositories}/CategoryRepository.php (87%) rename lib/SP/{Repositories/Client => Infrastructure/Client/Repositories}/ClientRepository.php (86%) rename lib/SP/{ => Infrastructure/Common}/Repositories/DuplicatedItemException.php (84%) rename lib/SP/{ => Infrastructure/Common}/Repositories/NoSuchItemException.php (84%) rename lib/SP/{ => Infrastructure/Common}/Repositories/Repository.php (72%) rename lib/SP/{ => Infrastructure/Common}/Repositories/RepositoryItemTrait.php (83%) rename lib/SP/{Repositories/Config => Infrastructure/Config/Repositories}/ConfigRepository.php (84%) rename lib/SP/{Repositories/CustomField => Infrastructure/CustomField/Repositories}/CustomFieldDefCollection.php (83%) rename lib/SP/{Repositories/CustomField => Infrastructure/CustomField/Repositories}/CustomFieldDefRepository.php (86%) rename lib/SP/{Repositories/CustomField => Infrastructure/CustomField/Repositories}/CustomFieldRepository.php (86%) rename lib/SP/{Repositories/CustomField => Infrastructure/CustomField/Repositories}/CustomFieldTypeRepository.php (86%) rename lib/SP/{Storage => Infrastructure}/Database/DBStorageInterface.php (93%) rename lib/SP/{Storage => Infrastructure}/Database/Database.php (80%) rename lib/SP/{Storage => Infrastructure}/Database/DatabaseConnectionData.php (75%) rename lib/SP/{Storage => Infrastructure}/Database/DatabaseException.php (86%) rename lib/SP/{Storage => Infrastructure}/Database/DatabaseFileInterface.php (96%) rename lib/SP/{Storage => Infrastructure}/Database/DatabaseInterface.php (94%) rename lib/SP/{Storage => Infrastructure}/Database/DatabaseUtil.php (85%) rename lib/SP/{Storage => Infrastructure}/Database/MySQLFileParser.php (84%) rename lib/SP/{Storage => Infrastructure}/Database/MySQLHandler.php (84%) rename lib/SP/{Storage => Infrastructure}/Database/QueryData.php (69%) rename lib/SP/{Storage => Infrastructure}/Database/QueryResult.php (81%) rename lib/SP/{Storage => Infrastructure}/File/ArchiveHandler.php (89%) create mode 100644 lib/SP/Infrastructure/File/ArchiveHandlerInterface.php rename lib/SP/{Storage => Infrastructure}/File/FileCache.php (90%) rename lib/SP/{Storage => Infrastructure}/File/FileCacheBase.php (89%) rename lib/SP/{Storage => Infrastructure}/File/FileCacheInterface.php (91%) rename lib/SP/{Storage => Infrastructure}/File/FileCachePacked.php (71%) rename lib/SP/{Storage => Infrastructure}/File/FileException.php (86%) rename lib/SP/{Storage => Infrastructure}/File/FileHandler.php (71%) create mode 100644 lib/SP/Infrastructure/File/FileHandlerInterface.php rename lib/SP/{Storage => Infrastructure}/File/XmlFileStorageInterface.php (81%) rename lib/SP/{Storage => Infrastructure}/File/XmlHandler.php (92%) rename lib/SP/{Repositories/ItemPreset => Infrastructure/ItemPreset/Repositories}/ItemPresetRepository.php (84%) rename lib/SP/{Repositories/Notification => Infrastructure/Notification/Repositories}/NotificationRepository.php (89%) rename lib/SP/{Repositories/Plugin => Infrastructure/Plugin/Repositories}/PluginDataModel.php (87%) rename lib/SP/{Repositories/Plugin => Infrastructure/Plugin/Repositories}/PluginDataRepository.php (86%) rename lib/SP/{Repositories/Plugin => Infrastructure/Plugin/Repositories}/PluginModel.php (89%) rename lib/SP/{Repositories/Plugin => Infrastructure/Plugin/Repositories}/PluginRepository.php (89%) rename lib/SP/{Repositories/EventLog => Infrastructure/Security/Repositories}/EventlogRepository.php (82%) rename lib/SP/{Repositories/Track => Infrastructure/Security/Repositories}/TrackRepository.php (88%) rename lib/SP/{Repositories/Track => Infrastructure/Security/Repositories}/TrackRequest.php (78%) rename lib/SP/{Repositories/Tag => Infrastructure/Tag/Repositories}/TagRepository.php (86%) rename lib/SP/{Repositories/UserGroup => Infrastructure/User/Repositories}/UserGroupRepository.php (89%) rename lib/SP/{Repositories/User => Infrastructure/User/Repositories}/UserPassRecoverRepository.php (83%) rename lib/SP/{Repositories/UserProfile => Infrastructure/User/Repositories}/UserProfileRepository.php (86%) rename lib/SP/{Repositories/User => Infrastructure/User/Repositories}/UserRepository.php (91%) rename lib/SP/{Repositories/UserGroup => Infrastructure/User/Repositories}/UserToUserGroupRepository.php (84%) create mode 100644 lib/SP/Mvc/Controller/WebControllerHelper.php create mode 100644 lib/SP/Mvc/View/TemplateInterface.php create mode 100644 lib/SP/Providers/Auth/AuthProviderInterface.php rename lib/SP/Providers/Auth/Browser/{Browser.php => BrowserAuth.php} (85%) create mode 100644 lib/SP/Providers/Auth/Browser/BrowserAuthInterface.php rename lib/SP/Providers/Auth/Database/{Database.php => DatabaseAuth.php} (61%) create mode 100644 lib/SP/Providers/Auth/Database/DatabaseAuthInterface.php create mode 100644 lib/SP/Providers/Auth/Ldap/LdapAuthInterface.php create mode 100644 lib/SP/Providers/Mail/PhpMailerWrapper.php delete mode 100644 lib/SP/Services/Account/AccountRequest.php delete mode 100644 lib/SP/Services/Upgrade/UpgradeAppService.php diff --git a/app/modules/api/Controllers/AccountController.php b/app/modules/api/Controllers/AccountController.php index 5b7ae16b..2c7c60be 100644 --- a/app/modules/api/Controllers/AccountController.php +++ b/app/modules/api/Controllers/AccountController.php @@ -24,25 +24,26 @@ namespace SP\Modules\Api\Controllers; -use DI\DependencyException; -use DI\NotFoundException; use Exception; +use Klein\Klein; use League\Fractal\Resource\Item; use SP\Adapters\AccountAdapter; +use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Core\Exceptions\InvalidClassException; use SP\DataModel\Dto\AccountDetailsResponse; +use SP\Domain\Account\AccountPresetServiceInterface; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Domain\Api\ApiServiceInterface; +use SP\Domain\Api\Services\ApiResponse; use SP\Modules\Api\Controllers\Help\AccountHelp; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\Model\QueryCondition; -use SP\Services\Account\AccountPresetService; -use SP\Services\Account\AccountRequest; -use SP\Services\Account\AccountSearchFilter; -use SP\Services\Account\AccountService; -use SP\Services\Api\ApiResponse; use SP\Util\Util; /** @@ -54,8 +55,24 @@ final class AccountController extends ControllerBase { use ItemTrait; - private ?AccountPresetService $accountPresetService = null; - private ?AccountService $accountService = null; + private AccountPresetServiceInterface $accountPresetService; + private AccountServiceInterface $accountService; + + public function __construct( + Application $application, + Klein $router, + ApiServiceInterface $apiService, + Acl $acl, + AccountPresetServiceInterface $accountPresetService, + AccountServiceInterface $accountService + ) { + $this->accountPresetService = $accountPresetService; + $this->accountService = $accountService; + + parent::__construct($application, $router, $apiService, $acl); + + $this->apiService->setHelpClass(AccountHelp::class); + } /** * viewAction @@ -226,7 +243,8 @@ final class AccountController extends ControllerBase $userData = $this->context->getUserData(); $accountRequest->userId = $this->apiService->getParamInt('userId', false, $userData->getId()); - $accountRequest->userGroupId = $this->apiService->getParamInt('userGroupId', false, $userData->getUserGroupId()); + $accountRequest->userGroupId = + $this->apiService->getParamInt('userGroupId', false, $userData->getUserGroupId()); $accountRequest->tags = array_map( 'intval', @@ -363,7 +381,9 @@ final class AccountController extends ControllerBase } $accountSearchFilter->setLimitCount($this->apiService->getParamInt('count', false, 50)); - $accountSearchFilter->setSortOrder($this->apiService->getParamInt('order', false, AccountSearchFilter::SORT_DEFAULT)); + $accountSearchFilter->setSortOrder( + $this->apiService->getParamInt('order', false, AccountSearchFilter::SORT_DEFAULT) + ); $this->returnResponse( ApiResponse::makeSuccess( @@ -416,14 +436,4 @@ final class AccountController extends ControllerBase $this->returnResponseException($e); } } - - /** - * @throws \SP\Core\Exceptions\InvalidClassException - */ - protected function initialize(): void - { - $this->accountService = $this->dic->get(AccountService::class); - $this->accountPresetService = $this->dic->get(AccountPresetService::class); - $this->apiService->setHelpClass(AccountHelp::class); - } } \ No newline at end of file diff --git a/app/modules/api/Controllers/CategoryController.php b/app/modules/api/Controllers/CategoryController.php index 9f76bee0..a6b91190 100644 --- a/app/modules/api/Controllers/CategoryController.php +++ b/app/modules/api/Controllers/CategoryController.php @@ -32,10 +32,10 @@ use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\DataModel\CategoryData; use SP\DataModel\ItemSearchData; +use SP\Domain\Api\Services\ApiResponse; +use SP\Domain\Category\Services\CategoryService; use SP\Modules\Api\Controllers\Help\CategoryHelp; use SP\Mvc\Controller\ItemTrait; -use SP\Services\Api\ApiResponse; -use SP\Services\Category\CategoryService; use SP\Util\Util; diff --git a/app/modules/api/Controllers/ClientController.php b/app/modules/api/Controllers/ClientController.php index 9852902a..55357f63 100644 --- a/app/modules/api/Controllers/ClientController.php +++ b/app/modules/api/Controllers/ClientController.php @@ -24,21 +24,18 @@ namespace SP\Modules\Api\Controllers; -use DI\DependencyException; -use DI\NotFoundException; use Exception; use League\Fractal\Resource\Item; use SP\Adapters\ClientAdapter; use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Core\Exceptions\InvalidClassException; use SP\DataModel\ClientData; use SP\DataModel\ItemSearchData; +use SP\Domain\Api\Services\ApiResponse; +use SP\Domain\Client\Services\ClientService; use SP\Modules\Api\Controllers\Help\ClientHelp; use SP\Mvc\Controller\ItemTrait; -use SP\Services\Api\ApiResponse; -use SP\Services\Client\ClientService; use SP\Util\Util; /** diff --git a/app/modules/api/Controllers/ConfigController.php b/app/modules/api/Controllers/ConfigController.php index c6431051..40b93b2c 100644 --- a/app/modules/api/Controllers/ConfigController.php +++ b/app/modules/api/Controllers/ConfigController.php @@ -29,11 +29,11 @@ use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\InvalidClassException; +use SP\Domain\Api\Services\ApiResponse; +use SP\Domain\Export\Services\BackupFiles; +use SP\Domain\Export\Services\FileBackupService; +use SP\Domain\Export\Services\XmlExportService; use SP\Modules\Api\Controllers\Help\ConfigHelp; -use SP\Services\Api\ApiResponse; -use SP\Services\Backup\BackupFiles; -use SP\Services\Backup\FileBackupService; -use SP\Services\Export\XmlExportService; /** * Class ConfigController diff --git a/app/modules/api/Controllers/ControllerBase.php b/app/modules/api/Controllers/ControllerBase.php index d48760fb..a160c745 100644 --- a/app/modules/api/Controllers/ControllerBase.php +++ b/app/modules/api/Controllers/ControllerBase.php @@ -28,16 +28,16 @@ use Exception; use Klein\Klein; use League\Fractal\Manager; use Psr\Container\ContainerInterface; -use SP\Config\ConfigDataInterface; use SP\Core\Acl\Acl; +use SP\Core\Application; use SP\Core\Context\ContextInterface; use SP\Core\Events\EventDispatcher; use SP\Core\Exceptions\SPException; +use SP\Domain\Api\ApiServiceInterface; +use SP\Domain\Api\Services\ApiResponse; +use SP\Domain\Api\Services\JsonRpcResponse; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Http\Json; -use SP\Services\Api\ApiResponse; -use SP\Services\Api\ApiService; -use SP\Services\Api\JsonRpcResponse; -use SP\Services\ServiceException; /** * Class ControllerBase @@ -48,34 +48,34 @@ abstract class ControllerBase { protected const SEARCH_COUNT_ITEMS = 25; - protected ContainerInterface $dic; - protected string $controllerName; - protected string $actionName; - protected ContextInterface $context; - protected EventDispatcher $eventDispatcher; - protected ApiService $apiService; - protected Klein $router; + protected ContainerInterface $dic; + protected string $controllerName; + protected ContextInterface $context; + protected EventDispatcher $eventDispatcher; + protected ApiServiceInterface $apiService; + protected Klein $router; protected ConfigDataInterface $configData; - protected Manager $fractal; - protected Acl $acl; - private bool $isAuthenticated = false; + protected Manager $fractal; + protected Acl $acl; + private bool $isAuthenticated = false; - final public function __construct( - ContainerInterface $container, - string $actionName - ) - { - $this->dic = $container; - $this->context = $container->get(ContextInterface::class); - $this->configData = $container->get(ConfigDataInterface::class); - $this->eventDispatcher = $container->get(EventDispatcher::class); - $this->router = $container->get(Klein::class); - $this->apiService = $container->get(ApiService::class); - $this->acl = $container->get(Acl::class); + public function __construct( + Application $application, + Klein $router, + ApiServiceInterface $apiService, + Acl $acl + ) { + $this->context = $application->getContext(); + $this->configData = $application->getConfig()->getConfigData(); + $this->eventDispatcher = $application->getEventDispatcher(); + $this->router = $router; + $this->apiService = $apiService; + $this->acl = $acl; $this->fractal = new Manager(); $this->controllerName = $this->getControllerName(); - $this->actionName = $actionName; + // FIXME: provide action name +// $this->actionName = $actionName; if (method_exists($this, 'initialize')) { $this->initialize(); @@ -89,12 +89,13 @@ abstract class ControllerBase return substr( $class, strrpos($class, '\\') + 1, - -strlen('Controller')) ?: ''; + -strlen('Controller') + ) ?: ''; } /** * @throws SPException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ final protected function setupApi(int $actionId): void { diff --git a/app/modules/api/Controllers/TagController.php b/app/modules/api/Controllers/TagController.php index 11e9ac0e..2af702aa 100644 --- a/app/modules/api/Controllers/TagController.php +++ b/app/modules/api/Controllers/TagController.php @@ -24,18 +24,15 @@ namespace SP\Modules\Api\Controllers; -use DI\DependencyException; -use DI\NotFoundException; use Exception; use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Core\Exceptions\InvalidClassException; use SP\DataModel\ItemSearchData; use SP\DataModel\TagData; +use SP\Domain\Api\Services\ApiResponse; +use SP\Domain\Tag\Services\TagService; use SP\Modules\Api\Controllers\Help\TagHelp; -use SP\Services\Api\ApiResponse; -use SP\Services\Tag\TagService; /** * Class TagController diff --git a/app/modules/api/Controllers/UserGroupController.php b/app/modules/api/Controllers/UserGroupController.php index c81b07e3..62875a31 100644 --- a/app/modules/api/Controllers/UserGroupController.php +++ b/app/modules/api/Controllers/UserGroupController.php @@ -24,18 +24,15 @@ namespace SP\Modules\Api\Controllers; -use DI\DependencyException; -use DI\NotFoundException; use Exception; use SP\Core\Acl\ActionsInterface; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Core\Exceptions\InvalidClassException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserGroupData; +use SP\Domain\Api\Services\ApiResponse; +use SP\Domain\User\Services\UserGroupService; use SP\Modules\Api\Controllers\Help\TagHelp; -use SP\Services\Api\ApiResponse; -use SP\Services\UserGroup\UserGroupService; /** * Class UserGroupController diff --git a/app/modules/api/Init.php b/app/modules/api/Init.php index 21a649db..be0f3744 100644 --- a/app/modules/api/Init.php +++ b/app/modules/api/Init.php @@ -30,13 +30,14 @@ use SP\Core\Application; use SP\Core\Exceptions\InitializationException; use SP\Core\HttpModuleBase; use SP\Core\Language; +use SP\Core\LanguageInterface; use SP\Core\ProvidersHelper; -use SP\Http\Request; -use SP\Services\Upgrade\UpgradeAppService; -use SP\Services\Upgrade\UpgradeDatabaseService; -use SP\Services\Upgrade\UpgradeUtil; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\File\FileException; +use SP\Domain\Upgrade\Services\UpgradeAppService; +use SP\Domain\Upgrade\Services\UpgradeDatabaseService; +use SP\Domain\Upgrade\Services\UpgradeUtil; +use SP\Http\RequestInterface; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\File\FileException; use SP\Util\HttpUtil; /** @@ -50,9 +51,9 @@ final class Init extends HttpModuleBase public function __construct( Application $application, ProvidersHelper $providersHelper, - Request $request, + RequestInterface $request, Klein $router, - Language $language, + LanguageInterface $language, DatabaseUtil $databaseUtil ) { parent::__construct( @@ -71,7 +72,7 @@ final class Init extends HttpModuleBase * @throws \JsonException * @throws \SP\Core\Context\ContextException * @throws \SP\Core\Exceptions\InitializationException - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\File\FileException */ public function initialize(string $controller): void { diff --git a/app/modules/cli/Commands/BackupCommand.php b/app/modules/cli/Commands/BackupCommand.php index 18d72a3a..01a4f1b0 100644 --- a/app/modules/cli/Commands/BackupCommand.php +++ b/app/modules/cli/Commands/BackupCommand.php @@ -27,8 +27,9 @@ namespace SP\Modules\Cli\Commands; use Exception; use Psr\Log\LoggerInterface; use RuntimeException; -use SP\Config\Config; -use SP\Services\Backup\FileBackupService; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Export\FileBackupServiceInterface; +use SP\Domain\Export\Services\FileBackupService; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; @@ -54,9 +55,10 @@ final class BackupCommand extends CommandBase protected static $defaultName = 'sp:backup'; private FileBackupService $fileBackupService; - public function __construct(FileBackupService $fileBackupService, + public function __construct( + FileBackupServiceInterface $fileBackupService, LoggerInterface $logger, - Config $config) + ConfigInterface $config) { $this->fileBackupService = $fileBackupService; diff --git a/app/modules/cli/Commands/CommandBase.php b/app/modules/cli/Commands/CommandBase.php index 4ac7eb74..75fc59e6 100644 --- a/app/modules/cli/Commands/CommandBase.php +++ b/app/modules/cli/Commands/CommandBase.php @@ -25,8 +25,9 @@ namespace SP\Modules\Cli\Commands; use Psr\Log\LoggerInterface; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigFileService; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; @@ -38,13 +39,13 @@ use Symfony\Component\Console\Input\InputInterface; abstract class CommandBase extends Command { public static array $envVarsMapping = []; - protected LoggerInterface $logger; - protected Config $config; + protected LoggerInterface $logger; + protected ConfigFileService $config; protected ConfigDataInterface $configData; public function __construct( LoggerInterface $logger, - Config $config + ConfigInterface $config ) { $this->logger = $logger; diff --git a/app/modules/cli/Commands/Crypt/UpdateMasterPasswordCommand.php b/app/modules/cli/Commands/Crypt/UpdateMasterPasswordCommand.php index 95879504..b3dd79c6 100644 --- a/app/modules/cli/Commands/Crypt/UpdateMasterPasswordCommand.php +++ b/app/modules/cli/Commands/Crypt/UpdateMasterPasswordCommand.php @@ -27,13 +27,15 @@ namespace SP\Modules\Cli\Commands\Crypt; use Exception; use Psr\Log\LoggerInterface; use RuntimeException; -use SP\Config\Config; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Config\Services\ConfigService; +use SP\Domain\Crypt\MasterPassServiceInterface; +use SP\Domain\Crypt\Services\MasterPassService; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; use SP\Modules\Cli\Commands\CommandBase; use SP\Modules\Cli\Commands\Validators; -use SP\Services\Account\AccountService; -use SP\Services\Config\ConfigService; -use SP\Services\Crypt\MasterPassService; -use SP\Services\Crypt\UpdateMasterPassRequest; use SP\Util\Util; use Symfony\Component\Console\Command\LockableTrait; use Symfony\Component\Console\Input\InputInterface; @@ -56,23 +58,24 @@ final class UpdateMasterPasswordCommand extends CommandBase */ public static array $envVarsMapping = [ 'currentMasterPassword' => 'CURRENT_MASTER_PASSWORD', - 'masterPassword' => 'MASTER_PASSWORD', - 'update' => 'UPDATE', + 'masterPassword' => 'MASTER_PASSWORD', + 'update' => 'UPDATE', ]; /** * @var string */ - protected static $defaultName = 'sp:crypt:update-master-password'; - private MasterPassService $masterPassService; - private ConfigService $configService; + protected static $defaultName = 'sp:crypt:update-master-password'; + private \SP\Domain\Crypt\MasterPassServiceInterface $masterPassService; + private ConfigService $configService; private AccountService $accountService; - public function __construct(MasterPassService $masterPassService, - AccountService $accountService, - ConfigService $configService, - LoggerInterface $logger, - Config $config) - { + public function __construct( + MasterPassServiceInterface $masterPassService, + AccountService $accountService, + ConfigServiceInterface $configService, + LoggerInterface $logger, + ConfigInterface $config + ) { $this->masterPassService = $masterPassService; $this->accountService = $accountService; $this->configService = $configService; @@ -84,25 +87,30 @@ final class UpdateMasterPasswordCommand extends CommandBase { $this->setDescription(__('Update sysPass master password')) ->setHelp(__('This command updates sysPass master password for all the encrypted data')) - ->addOption('masterPassword', + ->addOption( + 'masterPassword', null, InputOption::VALUE_REQUIRED, - __('The new master password to encrypt the data')) - ->addOption('currentMasterPassword', + __('The new master password to encrypt the data') + ) + ->addOption( + 'currentMasterPassword', null, InputOption::VALUE_REQUIRED, - __('The current master password')) - ->addOption('update', + __('The current master password') + ) + ->addOption( + 'update', null, InputOption::VALUE_NONE, - __('Skip asking to confirm the update')); + __('Skip asking to confirm the update') + ); } protected function execute( - InputInterface $input, + InputInterface $input, OutputInterface $output - ): int - { + ): int { $style = new SymfonyStyle($input, $output); if (!$this->lock()) { @@ -143,10 +151,12 @@ final class UpdateMasterPasswordCommand extends CommandBase $style->warning(__('You should save the new password on a secure place')); $style->warning(__('All accounts passwords will be encrypted again.')); $style->warning(__('Users will need to enter the new Master Password.')); - $style->warning(printf( - __('It will be updated %s accounts. This process could take some time long.'), - $this->accountService->getTotalNumAccounts() - )); + $style->warning( + printf( + __('It will be updated %s accounts. This process could take some time long.'), + $this->accountService->getTotalNumAccounts() + ) + ); $style->newLine(); $style->caution(__('This is a critical process, please do not cancel/close this CLI')); @@ -194,8 +204,7 @@ final class UpdateMasterPasswordCommand extends CommandBase private function getMasterPassword( InputInterface $input, StyleInterface $style - ) - { + ) { $password = self::getEnvVarOrOption('masterPassword', $input); if (empty($password)) { @@ -232,8 +241,7 @@ final class UpdateMasterPasswordCommand extends CommandBase private function getCurrentMasterPassword( InputInterface $input, StyleInterface $style - ) - { + ) { $password = self::getEnvVarOrOption('currentMasterPassword', $input); if (empty($password)) { @@ -265,8 +273,8 @@ final class UpdateMasterPasswordCommand extends CommandBase } /** - * @throws \SP\Services\ServiceException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ private function checkMasterPassword(string $password): void { @@ -278,8 +286,7 @@ final class UpdateMasterPasswordCommand extends CommandBase private function getUpdate( InputInterface $input, StyleInterface $style - ): bool - { + ): bool { $option = 'update'; $envUpdate = self::getEnvVarForOption($option); diff --git a/app/modules/cli/Commands/InstallCommand.php b/app/modules/cli/Commands/InstallCommand.php index e0debc03..d5d5ef76 100644 --- a/app/modules/cli/Commands/InstallCommand.php +++ b/app/modules/cli/Commands/InstallCommand.php @@ -26,12 +26,13 @@ namespace SP\Modules\Cli\Commands; use Exception; use Psr\Log\LoggerInterface; -use SP\Config\Config; use SP\Core\Exceptions\InstallError; use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Language; -use SP\Services\Install\InstallData; -use SP\Services\Install\Installer; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Install\InstallerInterface; +use SP\Domain\Install\Services\InstallData; +use SP\Domain\Install\Services\Installer; use SP\Util\Util; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -71,8 +72,8 @@ final class InstallCommand extends CommandBase public function __construct( LoggerInterface $logger, - Config $config, - Installer $installer + ConfigInterface $config, + InstallerInterface $installer ) { parent::__construct($logger, $config); diff --git a/app/modules/cli/Init.php b/app/modules/cli/Init.php index b9c939c8..3e91a265 100644 --- a/app/modules/cli/Init.php +++ b/app/modules/cli/Init.php @@ -26,6 +26,7 @@ namespace SP\Modules\Cli; use SP\Core\Application; use SP\Core\Language; +use SP\Core\LanguageInterface; use SP\Core\ModuleBase; use SP\Core\ProvidersHelper; use SP\Util\VersionUtil; @@ -49,7 +50,7 @@ final class Init extends ModuleBase public function __construct( Application $application, ProvidersHelper $providersHelper, - Language $language, + LanguageInterface $language, ConsoleApplication $consoleApplication, InputInterface $input, OutputInterface $output, diff --git a/app/modules/web/Controllers/AccessManagerController.php b/app/modules/web/Controllers/AccessManagerController.php index d7901bb0..5e699a3e 100644 --- a/app/modules/web/Controllers/AccessManagerController.php +++ b/app/modules/web/Controllers/AccessManagerController.php @@ -33,6 +33,12 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SessionTimeout; use SP\DataModel\ItemSearchData; +use SP\Domain\Account\Services\PublicLinkService; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserProfileService; +use SP\Domain\User\Services\UserService; use SP\Html\DataGrid\DataGridTab; use SP\Modules\Web\Controllers\Helpers\Grid\AuthTokenGrid; use SP\Modules\Web\Controllers\Helpers\Grid\PublicLinkGrid; @@ -40,12 +46,6 @@ use SP\Modules\Web\Controllers\Helpers\Grid\UserGrid; use SP\Modules\Web\Controllers\Helpers\Grid\UserGroupGrid; use SP\Modules\Web\Controllers\Helpers\Grid\UserProfileGrid; use SP\Modules\Web\Controllers\Helpers\TabsGridHelper; -use SP\Services\Auth\AuthException; -use SP\Services\AuthToken\AuthTokenService; -use SP\Services\PublicLink\PublicLinkService; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserProfile\UserProfileService; /** * Class AccessManagerController diff --git a/app/modules/web/Controllers/Account/AccountControllerBase.php b/app/modules/web/Controllers/Account/AccountControllerBase.php new file mode 100644 index 00000000..9e7ce908 --- /dev/null +++ b/app/modules/web/Controllers/Account/AccountControllerBase.php @@ -0,0 +1,54 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + +use SP\Core\Context\ContextBase; +use SP\Domain\Account\Services\AccountAclService; +use SP\Modules\Web\Controllers\ControllerBase; + +abstract class AccountControllerBase extends ControllerBase +{ + private const LOGIN_NOT_REQUIRED = ['ViewLinkController']; + + /** + * Initialize class + * + * @throws \SP\Core\Exceptions\SessionTimeout + * @throws \SP\Domain\Auth\Services\AuthException + */ + protected function initialize(): void + { + if (in_array(static::class, self::LOGIN_NOT_REQUIRED)) { + $this->checkLoggedIn(); + } + + if (DEBUG === true && $this->session->getAppStatus() === ContextBase::APP_STATUS_RELOADED) { + $this->session->resetAppStatus(); + + // Reset de los datos de ACL de cuentas + AccountAclService::clearAcl($this->session->getUserData()->getId()); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/CopyController.php b/app/modules/web/Controllers/Account/CopyController.php new file mode 100644 index 00000000..4703ae42 --- /dev/null +++ b/app/modules/web/Controllers/Account/CopyController.php @@ -0,0 +1,109 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\AccountServiceInterface; +use SP\Modules\Web\Controllers\Helpers\Account\AccountHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class CopyController extends AccountControllerBase +{ + private AccountHelper $accountHelper; + private ThemeIcons $icons; + private AccountServiceInterface $accountService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountHelper $accountHelper, + AccountServiceInterface $accountService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountHelper = $accountHelper; + $this->accountService = $accountService; + $this->icons = $this->theme->getIcons(); + } + + /** + * Copy action + * + * @param int $id Account's ID + */ + public function copyAction(int $id): void + { + try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse) + ->withTagsById($accountDetailsResponse); + + $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_COPY); + + $this->view->addTemplate('account'); + $this->view->assign( + 'title', + [ + 'class' => 'titleGreen', + 'name' => __('New Account'), + 'icon' => $this->icons->getIconAdd()->getIcon(), + ] + ); + $this->view->assign('formRoute', 'account/saveCopy'); + + $this->eventDispatcher->notifyEvent('show.account.copy', new Event($this)); + + if ($this->isAjax === false) { + $this->upgradeView(); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent( + 'exception', + new Event($e) + ); + + if ($this->isAjax === false && !$this->view->isUpgraded()) { + $this->upgradeView(); + } + + ErrorUtil::showExceptionInView($this->view, $e, 'account'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/CopyPassController.php b/app/modules/web/Controllers/Account/CopyPassController.php new file mode 100644 index 00000000..072ed7bb --- /dev/null +++ b/app/modules/web/Controllers/Account/CopyPassController.php @@ -0,0 +1,93 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Modules\Web\Controllers\Helpers\Account\AccountPasswordHelper; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class CopyPassController extends AccountControllerBase +{ + use JsonTrait; + + private \SP\Domain\Account\AccountServiceInterface $accountService; + private AccountPasswordHelper $accountPasswordHelper; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + \SP\Domain\Account\AccountServiceInterface $accountService, + AccountPasswordHelper $accountPasswordHelper, + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->accountPasswordHelper = $accountPasswordHelper; + } + + /** + * Copy account's password + * + * @param int $id Account's ID + * + * @return bool + * @throws \Defuse\Crypto\Exception\BadFormatException + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException + * @throws \JsonException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Modules\Web\Controllers\Helpers\HelperException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function copyPassAction(int $id): bool + { + $account = $this->accountService->getPasswordForId($id); + + $data = [ + 'accpass' => $this->accountPasswordHelper->getPasswordClear($account), + ]; + + $this->eventDispatcher->notifyEvent( + 'copy.account.pass', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Password copied')) + ->addDetail(__u('Account'), $account->getName()) + ) + ); + + return $this->returnJsonResponseData($data); + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/CopyPassHistoryController.php b/app/modules/web/Controllers/Account/CopyPassHistoryController.php new file mode 100644 index 00000000..f0c0596e --- /dev/null +++ b/app/modules/web/Controllers/Account/CopyPassHistoryController.php @@ -0,0 +1,93 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Modules\Web\Controllers\Helpers\Account\AccountPasswordHelper; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class CopyPassHistoryController extends AccountControllerBase +{ + use JsonTrait; + + private \SP\Domain\Account\AccountServiceInterface $accountService; + private AccountPasswordHelper $accountPasswordHelper; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + \SP\Domain\Account\AccountServiceInterface $accountService, + AccountPasswordHelper $accountPasswordHelper, + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->accountPasswordHelper = $accountPasswordHelper; + } + + /** + * Copy account's password + * + * @param int $id Account's ID + * + * @return bool + * @throws \Defuse\Crypto\Exception\BadFormatException + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException + * @throws \JsonException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Modules\Web\Controllers\Helpers\HelperException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function copyPassHistoryAction(int $id): bool + { + $account = $this->accountService->getPasswordHistoryForId($id); + + $data = [ + 'accpass' => $this->accountPasswordHelper->getPasswordClear($account), + ]; + + $this->eventDispatcher->notifyEvent( + 'copy.account.pass.history', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Password copied')) + ->addDetail(__u('Account'), $account->getName()) + ) + ); + + return $this->returnJsonResponseData($data); + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/CreateController.php b/app/modules/web/Controllers/Account/CreateController.php new file mode 100644 index 00000000..47add5ba --- /dev/null +++ b/app/modules/web/Controllers/Account/CreateController.php @@ -0,0 +1,92 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\UI\ThemeIcons; +use SP\Modules\Web\Controllers\Helpers\Account\AccountHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class CreateController extends AccountControllerBase +{ + private AccountHelper $accountHelper; + private ThemeIcons $icons; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountHelper $accountHelper + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountHelper = $accountHelper; + $this->icons = $this->theme->getIcons(); + } + + /** + * Create action + */ + public function createAction(): void + { + try { + $this->accountHelper->setViewForBlank(ActionsInterface::ACCOUNT_CREATE); + + $this->view->addTemplate('account'); + $this->view->assign( + 'title', + [ + 'class' => 'titleGreen', + 'name' => __('New Account'), + 'icon' => $this->icons->getIconAdd()->getIcon(), + ] + ); + $this->view->assign('formRoute', 'account/saveCreate'); + + $this->eventDispatcher->notifyEvent('show.account.create', new Event($this)); + + if ($this->isAjax === false) { + $this->upgradeView(); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + if ($this->isAjax === false && !$this->view->isUpgraded()) { + $this->upgradeView(); + } + + ErrorUtil::showExceptionInView($this->view, $e, 'account'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/DeleteController.php b/app/modules/web/Controllers/Account/DeleteController.php new file mode 100644 index 00000000..33a96470 --- /dev/null +++ b/app/modules/web/Controllers/Account/DeleteController.php @@ -0,0 +1,109 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\AccountServiceInterface; +use SP\Modules\Web\Controllers\Helpers\Account\AccountHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class DeleteController extends AccountControllerBase +{ + private AccountHelper $accountHelper; + private ThemeIcons $icons; + private AccountServiceInterface $accountService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountHelper $accountHelper, + AccountServiceInterface $accountService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountHelper = $accountHelper; + $this->accountService = $accountService; + + $this->icons = $this->theme->getIcons(); + } + + /** + * Delete action + * + * @param int|null $id Account's ID + */ + public function deleteAction(?int $id = null): void + { + try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse); + + $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_DELETE); + + $this->view->addTemplate('account'); + $this->view->assign( + 'title', + [ + 'class' => 'titleRed', + 'name' => __('Remove Account'), + 'icon' => $this->icons->getIconDelete()->getIcon(), + ] + ); + $this->view->assign('formRoute', 'account/saveDelete'); + + $this->eventDispatcher->notifyEvent('show.account.delete', new Event($this)); + + if ($this->isAjax === false) { + $this->upgradeView(); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent( + 'exception', + new Event($e) + ); + + if ($this->isAjax === false && !$this->view->isUpgraded()) { + $this->upgradeView(); + } + + ErrorUtil::showExceptionInView($this->view, $e, 'account'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/EditController.php b/app/modules/web/Controllers/Account/EditController.php new file mode 100644 index 00000000..95067425 --- /dev/null +++ b/app/modules/web/Controllers/Account/EditController.php @@ -0,0 +1,111 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\AccountServiceInterface; +use SP\Modules\Web\Controllers\Helpers\Account\AccountHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class EditController extends AccountControllerBase +{ + private AccountHelper $accountHelper; + private ThemeIcons $icons; + private AccountServiceInterface $accountService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountHelper $accountHelper, + \SP\Domain\Account\AccountServiceInterface $accountService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountHelper = $accountHelper; + $this->accountService = $accountService; + $this->icons = $this->theme->getIcons(); + } + + /** + * Edit action + * + * @param int $id Account's ID + */ + public function editAction(int $id): void + { + try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse) + ->withTagsById($accountDetailsResponse); + + $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_EDIT); + + $this->view->addTemplate('account'); + $this->view->assign( + 'title', + [ + 'class' => 'titleOrange', + 'name' => __('Edit Account'), + 'icon' => $this->icons->getIconEdit()->getIcon(), + ] + ); + $this->view->assign('formRoute', 'account/saveEdit'); + + $this->accountService->incrementViewCounter($id); + + $this->eventDispatcher->notifyEvent('show.account.edit', new Event($this)); + + if ($this->isAjax === false) { + $this->upgradeView(); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent( + 'exception', + new Event($e) + ); + + if ($this->isAjax === false && !$this->view->isUpgraded()) { + $this->upgradeView(); + } + + ErrorUtil::showExceptionInView($this->view, $e, 'account'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/EditPassController.php b/app/modules/web/Controllers/Account/EditPassController.php new file mode 100644 index 00000000..29e3da85 --- /dev/null +++ b/app/modules/web/Controllers/Account/EditPassController.php @@ -0,0 +1,110 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\AccountServiceInterface; +use SP\Modules\Web\Controllers\Helpers\Account\AccountHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class EditPassController extends AccountControllerBase +{ + private AccountHelper $accountHelper; + private ThemeIcons $icons; + private \SP\Domain\Account\AccountServiceInterface $accountService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountHelper $accountHelper, + AccountServiceInterface $accountService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountHelper = $accountHelper; + $this->accountService = $accountService; + $this->icons = $this->theme->getIcons(); + } + + /** + * Obtener los datos para mostrar el interface para modificar la clave de cuenta + * + * @param int $id Account's ID + * + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function editPassAction(int $id): void + { + try { + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse); + + $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_EDIT_PASS); + + $this->view->addTemplate('account-editpass'); + $this->view->assign( + 'title', + [ + 'class' => 'titleOrange', + 'name' => __('Edit Account Password'), + 'icon' => $this->icons->getIconEditPass()->getIcon(), + ] + ); + $this->view->assign('formRoute', 'account/saveEditPass'); + + $this->eventDispatcher->notifyEvent('show.account.editpass', new Event($this)); + + if ($this->isAjax === false) { + $this->upgradeView(); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + if ($this->isAjax === false && !$this->view->isUpgraded()) { + $this->upgradeView(); + } + + ErrorUtil::showExceptionInView($this->view, $e, 'account-editpass'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/IndexController.php b/app/modules/web/Controllers/Account/IndexController.php new file mode 100644 index 00000000..587e4bd1 --- /dev/null +++ b/app/modules/web/Controllers/Account/IndexController.php @@ -0,0 +1,73 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Modules\Web\Controllers\Helpers\Account\AccountSearchHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class IndexController extends AccountControllerBase +{ + private AccountSearchHelper $accountSearchHelper; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountSearchHelper $accountSearchHelper + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountSearchHelper = $accountSearchHelper; + } + + /** + * Index action + * + */ + public function indexAction(): void + { + try { + $this->accountSearchHelper->getSearchBox(); + $this->accountSearchHelper->getAccountSearch(); + + $this->eventDispatcher->notifyEvent('show.account.search', new Event($this)); + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + ErrorUtil::showExceptionInView($this->view, $e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/RequestAccessController.php b/app/modules/web/Controllers/Account/RequestAccessController.php new file mode 100644 index 00000000..7de72efe --- /dev/null +++ b/app/modules/web/Controllers/Account/RequestAccessController.php @@ -0,0 +1,94 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Domain\Account\AccountServiceInterface; +use SP\Modules\Web\Controllers\Helpers\Account\AccountHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class RequestAccessController extends AccountControllerBase +{ + private AccountHelper $accountHelper; + private AccountServiceInterface $accountService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountHelper $accountHelper, + AccountServiceInterface $accountService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountHelper = $accountHelper; + $this->accountService = $accountService; + } + + /** + * Obtener los datos para mostrar el interface de solicitud de cambios en una cuenta + * + * @param int $id Account's ID + * + */ + public function requestAccessAction(int $id): void + { + try { + $this->accountHelper->setIsView(true); + $this->accountHelper->setViewForRequest( + $this->accountService->getById($id), + ActionsInterface::ACCOUNT_REQUEST + ); + + $this->view->addTemplate('account-request'); + $this->view->assign('formRoute', 'account/saveRequest'); + + $this->eventDispatcher->notifyEvent('show.account.request', new Event($this)); + + if ($this->isAjax === false) { + $this->upgradeView(); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + if ($this->isAjax === false && !$this->view->isUpgraded()) { + $this->upgradeView(); + } + + ErrorUtil::showExceptionInView($this->view, $e, 'account-request'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/SaveCopyController.php b/app/modules/web/Controllers/Account/SaveCopyController.php new file mode 100644 index 00000000..795c6402 --- /dev/null +++ b/app/modules/web/Controllers/Account/SaveCopyController.php @@ -0,0 +1,116 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Core\Exceptions\ValidationException; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Http\JsonResponse; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Modules\Web\Forms\AccountForm; +use SP\Mvc\Controller\ItemTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class SaveCopyController extends AccountControllerBase +{ + use JsonTrait, ItemTrait; + + private AccountServiceInterface $accountService; + private AccountForm $accountForm; + private CustomFieldServiceInterface $customFieldService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountServiceInterface $accountService, + \SP\Domain\Account\AccountPresetServiceInterface $accountPresetService, + CustomFieldServiceInterface $customFieldService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->customFieldService = $customFieldService; + $this->accountForm = new AccountForm($application, $this->request, $accountPresetService); + } + + /** + * @return bool + * @throws \JsonException + */ + public function saveCopyAction(): ?bool + { + try { + $this->accountForm->validate(ActionsInterface::ACCOUNT_CREATE); + + $accountId = $this->accountService->create($this->accountForm->getItemData()); + + $accountDetails = $this->accountService->getById($accountId)->getAccountVData(); + + $this->eventDispatcher->notifyEvent( + 'create.account', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Account created')) + ->addDetail(__u('Account'), $accountDetails->getName()) + ->addDetail(__u('Client'), $accountDetails->getClientName()) + ) + ); + + $this->addCustomFieldsForItem( + ActionsInterface::ACCOUNT, + $accountId, + $this->request, + $this->customFieldService + ); + + return $this->returnJsonResponseData( + [ + 'itemId' => $accountId, + 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_EDIT), + ], + JsonResponse::JSON_SUCCESS, + __u('Account created') + ); + } catch (ValidationException $e) { + return $this->returnJsonResponseException($e); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/SaveCreateController.php b/app/modules/web/Controllers/Account/SaveCreateController.php new file mode 100644 index 00000000..6f9ecfea --- /dev/null +++ b/app/modules/web/Controllers/Account/SaveCreateController.php @@ -0,0 +1,117 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Core\Exceptions\ValidationException; +use SP\Domain\Account\AccountPresetServiceInterface; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Http\JsonResponse; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Modules\Web\Forms\AccountForm; +use SP\Mvc\Controller\ItemTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class SaveCreateController extends AccountControllerBase +{ + use JsonTrait, ItemTrait; + + private AccountServiceInterface $accountService; + private AccountForm $accountForm; + private CustomFieldServiceInterface $customFieldService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountServiceInterface $accountService, + AccountPresetServiceInterface $accountPresetService, + CustomFieldServiceInterface $customFieldService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->customFieldService = $customFieldService; + $this->accountForm = new AccountForm($application, $this->request, $accountPresetService); + } + + /** + * @return bool + * @throws \JsonException + */ + public function saveCreateAction(): ?bool + { + try { + $this->accountForm->validate(ActionsInterface::ACCOUNT_CREATE); + + $accountId = $this->accountService->create($this->accountForm->getItemData()); + + $accountDetails = $this->accountService->getById($accountId)->getAccountVData(); + + $this->eventDispatcher->notifyEvent( + 'create.account', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Account created')) + ->addDetail(__u('Account'), $accountDetails->getName()) + ->addDetail(__u('Client'), $accountDetails->getClientName()) + ) + ); + + $this->addCustomFieldsForItem( + ActionsInterface::ACCOUNT, + $accountId, + $this->request, + $this->customFieldService + ); + + return $this->returnJsonResponseData( + [ + 'itemId' => $accountId, + 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_EDIT), + ], + JsonResponse::JSON_SUCCESS, + __u('Account created') + ); + } catch (ValidationException $e) { + return $this->returnJsonResponseException($e); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/SaveDeleteController.php b/app/modules/web/Controllers/Account/SaveDeleteController.php new file mode 100644 index 00000000..e3252cca --- /dev/null +++ b/app/modules/web/Controllers/Account/SaveDeleteController.php @@ -0,0 +1,98 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Http\JsonResponse; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\ItemTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class SaveDeleteController extends AccountControllerBase +{ + use JsonTrait, ItemTrait; + + private \SP\Domain\Account\AccountServiceInterface $accountService; + private CustomFieldServiceInterface $customFieldService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountServiceInterface $accountService, + CustomFieldServiceInterface $customFieldService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->customFieldService = $customFieldService; + } + + /** + * Saves delete action + * + * @param int $id Account's ID + * + * @return bool + * @throws \JsonException + */ + public function saveDeleteAction(int $id): bool + { + try { + $accountDetails = $this->accountService->getById($id)->getAccountVData(); + + $this->accountService->delete($id); + + $this->eventDispatcher->notifyEvent( + 'delete.account', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Account removed')) + ->addDetail(__u('Account'), $accountDetails->getName()) + ->addDetail(__u('Client'), $accountDetails->getClientName()) + ) + ); + + $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id, $this->customFieldService); + + return $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Account removed')); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/SaveEditController.php b/app/modules/web/Controllers/Account/SaveEditController.php new file mode 100644 index 00000000..38303be1 --- /dev/null +++ b/app/modules/web/Controllers/Account/SaveEditController.php @@ -0,0 +1,123 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Core\Exceptions\ValidationException; +use SP\Domain\Account\AccountPresetServiceInterface; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Http\JsonResponse; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Modules\Web\Forms\AccountForm; +use SP\Mvc\Controller\ItemTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class SaveEditController extends AccountControllerBase +{ + use JsonTrait, ItemTrait; + + private \SP\Domain\Account\AccountServiceInterface $accountService; + private AccountForm $accountForm; + private CustomFieldServiceInterface $customFieldService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + \SP\Domain\Account\AccountServiceInterface $accountService, + AccountPresetServiceInterface $accountPresetService, + CustomFieldServiceInterface $customFieldService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->customFieldService = $customFieldService; + $this->accountForm = new AccountForm($application, $this->request, $accountPresetService); + } + + /** + * Saves edit action + * + * @param int $id Account's ID + * + * @return bool + * @throws \JsonException + */ + public function saveEditAction(int $id): ?bool + { + try { + $this->accountForm->setItemId($id); + $this->accountForm->validate(ActionsInterface::ACCOUNT_EDIT); + + $itemData = $this->accountForm->getItemData(); + + $this->accountService->update($itemData); + + $accountDetails = $this->accountService->getById($id)->getAccountVData(); + + $this->eventDispatcher->notifyEvent( + 'edit.account', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Account updated')) + ->addDetail(__u('Account'), $accountDetails->getName()) + ->addDetail(__u('Client'), $accountDetails->getClientName()) + ) + ); + + $this->updateCustomFieldsForItem( + ActionsInterface::ACCOUNT, + $id, + $this->request, + $this->customFieldService + ); + + return $this->returnJsonResponseData( + [ + 'itemId' => $id, + 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW), + ], + JsonResponse::JSON_SUCCESS, + __u('Account updated') + ); + } catch (ValidationException $e) { + return $this->returnJsonResponseException($e); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/SaveEditPassController.php b/app/modules/web/Controllers/Account/SaveEditPassController.php new file mode 100644 index 00000000..32a733d0 --- /dev/null +++ b/app/modules/web/Controllers/Account/SaveEditPassController.php @@ -0,0 +1,110 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Core\Exceptions\ValidationException; +use SP\Domain\Account\AccountPresetServiceInterface; +use SP\Domain\Account\AccountServiceInterface; +use SP\Http\JsonResponse; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Modules\Web\Forms\AccountForm; +use SP\Mvc\Controller\WebControllerHelper; + +final class SaveEditPassController extends AccountControllerBase +{ + use JsonTrait; + + private AccountServiceInterface $accountService; + private AccountForm $accountForm; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountServiceInterface $accountService, + AccountPresetServiceInterface $accountPresetService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->accountForm = new AccountForm($application, $this->request, $accountPresetService); + } + + /** + * Saves edit action + * + * @param int $id Account's ID + * + * @return bool + * @throws \JsonException + */ + public function saveEditPassAction(int $id): bool + { + try { + $this->accountForm->setItemId($id); + $this->accountForm->validate(ActionsInterface::ACCOUNT_EDIT_PASS); + + $this->accountService->editPassword($this->accountForm->getItemData()); + + $accountDetails = $this->accountService->getById($id)->getAccountVData(); + + $this->eventDispatcher->notifyEvent( + 'edit.account.pass', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Password updated')) + ->addDetail(__u('Account'), $accountDetails->getName()) + ->addDetail(__u('Client'), $accountDetails->getClientName()) + ) + ); + + return $this->returnJsonResponseData( + [ + 'itemId' => $id, + 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW), + ], + JsonResponse::JSON_SUCCESS, + __u('Password updated') + ); + } catch (ValidationException $e) { + return $this->returnJsonResponseException($e); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/SaveEditRestoreController.php b/app/modules/web/Controllers/Account/SaveEditRestoreController.php new file mode 100644 index 00000000..e9a84a43 --- /dev/null +++ b/app/modules/web/Controllers/Account/SaveEditRestoreController.php @@ -0,0 +1,100 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Domain\Account\AccountServiceInterface; +use SP\Http\JsonResponse; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class SaveEditRestoreController extends AccountControllerBase +{ + use JsonTrait; + + private AccountServiceInterface $accountService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + \SP\Domain\Account\AccountServiceInterface $accountService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + } + + /** + * Saves restore action + * + * @param int $historyId Account's history ID + * @param int $id Account's ID + * + * @return bool + * @throws \JsonException + */ + public function saveEditRestoreAction(int $historyId, int $id): bool + { + try { + $this->accountService->editRestore($historyId, $id); + + $accountDetails = $this->accountService->getById($id)->getAccountVData(); + + $this->eventDispatcher->notifyEvent( + 'edit.account.restore', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Account restored')) + ->addDetail(__u('Account'), $accountDetails->getName()) + ->addDetail(__u('Client'), $accountDetails->getClientName()) + ) + ); + + return $this->returnJsonResponseData( + [ + 'itemId' => $id, + 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW), + ], + JsonResponse::JSON_SUCCESS, + __u('Account restored') + ); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/SaveRequestController.php b/app/modules/web/Controllers/Account/SaveRequestController.php new file mode 100644 index 00000000..a8cc6744 --- /dev/null +++ b/app/modules/web/Controllers/Account/SaveRequestController.php @@ -0,0 +1,135 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Bootstrap\BootstrapBase; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Core\Exceptions\ValidationException; +use SP\Domain\User\UserServiceInterface; +use SP\Http\JsonResponse; +use SP\Http\Uri; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\ItemTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class SaveRequestController extends AccountControllerBase +{ + use JsonTrait, ItemTrait; + + private \SP\Domain\Account\AccountServiceInterface $accountService; + private UserServiceInterface $userService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + \SP\Domain\Account\AccountServiceInterface $accountService, + UserServiceInterface $userService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->userService = $userService; + } + + /** + * Saves a request action + * + * @param int $id Account's ID + * + * @return bool + * @throws \JsonException + */ + public function saveRequestAction(int $id): bool + { + try { + $description = $this->request->analyzeString('description'); + + if (empty($description)) { + throw new ValidationException(__u('A description is needed')); + } + + $accountDetails = $this->accountService->getById($id)->getAccountVData(); + + $baseUrl = ($this->configData->getApplicationUrl() ?: BootstrapBase::$WEBURI).BootstrapBase::$SUBURI; + + $deepLink = new Uri($baseUrl); + $deepLink->addParam('r', Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW).'/'.$id); + + $usersId = [$accountDetails->userId, $accountDetails->userEditId]; + + $this->eventDispatcher->notifyEvent( + 'request.account', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Request')) + ->addDetail( + __u('Requester'), + sprintf('%s (%s)', $this->userData->getName(), $this->userData->getLogin()) + ) + ->addDetail(__u('Account'), $accountDetails->getName()) + ->addDetail(__u('Client'), $accountDetails->getClientName()) + ->addDetail(__u('Description'), $description) + ->addDetail(__u('Link'), $deepLink->getUriSigned($this->configData->getPasswordSalt())) + ->addExtra('accountId', $id) + ->addExtra('whoId', $this->userData->getId()) + ->setExtra('userId', $usersId) + ->setExtra( + 'email', + array_map( + static fn($value) => $value->email, + $this->userService->getUserEmailById($usersId) + ) + ) + ) + ); + + return $this->returnJsonResponseData( + [ + 'itemId' => $id, + 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT), + ], + JsonResponse::JSON_SUCCESS, + __u('Request done') + ); + } catch (ValidationException $e) { + return $this->returnJsonResponseException($e); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/SearchController.php b/app/modules/web/Controllers/Account/SearchController.php new file mode 100644 index 00000000..79b664b3 --- /dev/null +++ b/app/modules/web/Controllers/Account/SearchController.php @@ -0,0 +1,76 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Modules\Web\Controllers\Helpers\Account\AccountSearchHelper; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class SearchController extends AccountControllerBase +{ + use JsonTrait; + + private AccountSearchHelper $accountSearchHelper; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountSearchHelper $accountSearchHelper + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountSearchHelper = $accountSearchHelper; + } + + /** + * @return bool + * @throws \JsonException + */ + public function searchAction(): ?bool + { + try { + $this->accountSearchHelper->getAccountSearch(); + + $this->eventDispatcher->notifyEvent('show.account.search', new Event($this)); + + return $this->returnJsonResponseData([ + 'html' => $this->render(), + ]); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/ViewController.php b/app/modules/web/Controllers/Account/ViewController.php new file mode 100644 index 00000000..2a18547a --- /dev/null +++ b/app/modules/web/Controllers/Account/ViewController.php @@ -0,0 +1,109 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\AccountServiceInterface; +use SP\Modules\Web\Controllers\Helpers\Account\AccountHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class ViewController extends AccountControllerBase +{ + private \SP\Domain\Account\AccountServiceInterface $accountService; + private AccountHelper $accountHelper; + private ThemeIcons $icons; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountServiceInterface $accountService, + AccountHelper $accountHelper + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->accountHelper = $accountHelper; + $this->icons = $this->theme->getIcons(); + } + + /** + * View action + * + * @param int $id Account's ID + */ + public function viewAction(int $id): void + { + try { + $this->view->addTemplate('account'); + + $accountDetailsResponse = $this->accountService->getById($id); + $this->accountService + ->withUsersById($accountDetailsResponse) + ->withUserGroupsById($accountDetailsResponse) + ->withTagsById($accountDetailsResponse); + + $this->accountHelper->setIsView(true); + $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_VIEW); + + $this->view->assign( + 'title', + [ + 'class' => 'titleNormal', + 'name' => __('Account Details'), + 'icon' => $this->icons->getIconView()->getIcon(), + ] + ); + + $this->accountService->incrementViewCounter($id); + + $this->eventDispatcher->notifyEvent('show.account', new Event($this)); + + if ($this->isAjax === false) { + $this->upgradeView(); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + if ($this->isAjax === false && !$this->view->isUpgraded()) { + $this->upgradeView(); + } + + ErrorUtil::showExceptionInView($this->view, $e, 'account'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/ViewHistoryController.php b/app/modules/web/Controllers/Account/ViewHistoryController.php new file mode 100644 index 00000000..f1411817 --- /dev/null +++ b/app/modules/web/Controllers/Account/ViewHistoryController.php @@ -0,0 +1,101 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Modules\Web\Controllers\Helpers\Account\AccountHistoryHelper; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; + +final class ViewHistoryController extends AccountControllerBase +{ + private \SP\Domain\Account\AccountHistoryServiceInterface $accountHistoryService; + private AccountHistoryHelper $accountHistoryHelper; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + \SP\Domain\Account\AccountHistoryServiceInterface $accountHistoryService, + AccountHistoryHelper $accountHistoryHelper + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountHistoryService = $accountHistoryService; + $this->accountHistoryHelper = $accountHistoryHelper; + } + + /** + * Obtener los datos para mostrar el interface para ver cuenta en fecha concreta + * + * @param int $id Account's ID + */ + public function viewHistoryAction(int $id): void + { + try { + $accountHistoryData = $this->accountHistoryService->getById($id); + + $this->accountHistoryHelper->setView($accountHistoryData, ActionsInterface::ACCOUNT_HISTORY_VIEW); + + $this->view->addTemplate('account-history'); + + $this->view->assign( + 'title', + [ + 'class' => 'titleNormal', + 'name' => __('Account Details'), + 'icon' => 'access_time', + ] + ); + + $this->view->assign('formRoute', 'account/saveRestore'); + + $this->eventDispatcher->notifyEvent('show.account.history', new Event($this)); + + if ($this->isAjax === false) { + $this->upgradeView(); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + if ($this->isAjax === false && !$this->view->isUpgraded()) { + $this->upgradeView(); + } + + ErrorUtil::showExceptionInView($this->view, $e, 'account-history'); + } + } + +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/ViewLinkController.php b/app/modules/web/Controllers/Account/ViewLinkController.php new file mode 100644 index 00000000..b6b0f40d --- /dev/null +++ b/app/modules/web/Controllers/Account/ViewLinkController.php @@ -0,0 +1,173 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; +use SP\Core\Bootstrap\BootstrapBase; +use SP\Core\Crypt\Vault; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Core\UI\ThemeIcons; +use SP\DataModel\AccountExtData; +use SP\Domain\Account\PublicLinkServiceInterface; +use SP\Domain\Account\Services\PublicLinkService; +use SP\Http\Uri; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Util\ErrorUtil; +use SP\Util\ImageUtil; +use SP\Util\Util; + +final class ViewLinkController extends AccountControllerBase +{ + private \SP\Domain\Account\AccountServiceInterface $accountService; + private ThemeIcons $icons; + private PublicLinkService $publicLinkService; + private ImageUtil $imageUtil; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + \SP\Domain\Account\AccountServiceInterface $accountService, + PublicLinkServiceInterface $publicLinkService, + ImageUtil $imageUtil + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->publicLinkService = $publicLinkService; + $this->imageUtil = $imageUtil; + + $this->icons = $this->theme->getIcons(); + } + + /** + * View public link action + * + * @param string $hash Link's hash + */ + public function viewLinkAction(string $hash): void + { + try { + $this->layoutHelper->getPublicLayout('account-link', 'account'); + + $publicLinkData = $this->publicLinkService->getByHash($hash); + + if (time() < $publicLinkData->getDateExpire() + && $publicLinkData->getCountViews() < $publicLinkData->getMaxCountViews() + ) { + $this->publicLinkService->addLinkView($publicLinkData); + + $this->accountService->incrementViewCounter($publicLinkData->getItemId()); + $this->accountService->incrementDecryptCounter($publicLinkData->getItemId()); + + /** @var Vault $vault */ + $vault = unserialize($publicLinkData->getData(), ['allowed_classes' => [Vault::class]]); + + /** @var AccountExtData $accountData */ + $accountData = Util::unserialize( + AccountExtData::class, + $vault->getData($this->publicLinkService->getPublicLinkKey($publicLinkData->getHash())->getKey()) + ); + + $this->view->assign( + 'title', + [ + 'class' => 'titleNormal', + 'name' => __('Account Details'), + 'icon' => $this->icons->getIconView()->getIcon(), + ] + ); + + $this->view->assign('isView', true); + $this->view->assign( + 'useImage', + $this->configData->isPublinksImageEnabled() + || $this->configData->isAccountPassToImage() + ); + + if ($this->view->useImage) { + $this->view->assign( + 'accountPassImage', + $this->imageUtil->convertText($accountData->getPass()) + ); + } else { + $this->view->assign( + 'copyPassRoute', + Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW_PASS) + ); + } + + $this->view->assign('accountData', $accountData); + + $clientAddress = $this->configData->isDemoEnabled() + ? '***' + : $this->request->getClientAddress(true); + + $baseUrl = ($this->configData->getApplicationUrl() ?: BootstrapBase::$WEBURI).BootstrapBase::$SUBURI; + + $deepLink = new Uri($baseUrl); + $deepLink->addParam('r', Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW).'/'.$accountData->getId()); + + $this->eventDispatcher->notifyEvent( + 'show.account.link', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Link viewed')) + ->addDetail(__u('Account'), $accountData->getName()) + ->addDetail(__u('Client'), $accountData->getClientName()) + ->addDetail(__u('Agent'), $this->request->getHeader('User-Agent')) + ->addDetail(__u('HTTPS'), $this->request->isHttps() ? __u('ON') : __u('OFF')) + ->addDetail(__u('IP'), $clientAddress) + ->addDetail(__u('Link'), $deepLink->getUriSigned($this->configData->getPasswordSalt())) + ->addExtra('userId', $publicLinkData->getUserId()) + ->addExtra('notify', $publicLinkData->isNotify()) + ) + ); + } else { + ErrorUtil::showErrorInView( + $this->view, + ErrorUtil::ERR_PAGE_NO_PERMISSION, + true, + 'account-link' + ); + } + + $this->view(); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + ErrorUtil::showExceptionInView($this->view, $e, 'account-link'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/ViewPassController.php b/app/modules/web/Controllers/Account/ViewPassController.php new file mode 100644 index 00000000..c2a531e9 --- /dev/null +++ b/app/modules/web/Controllers/Account/ViewPassController.php @@ -0,0 +1,124 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\DataModel\ItemPreset\Password; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\ItemPreset\ItemPresetInterface; +use SP\Domain\ItemPreset\ItemPresetServiceInterface; +use SP\Modules\Web\Controllers\Helpers\Account\AccountPasswordHelper; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class ViewPassController extends AccountControllerBase +{ + use JsonTrait; + + private AccountServiceInterface $accountService; + private AccountPasswordHelper $accountPasswordHelper; + private ItemPresetServiceInterface $itemPresetService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountServiceInterface $accountService, + AccountPasswordHelper $accountPasswordHelper, + ItemPresetServiceInterface $itemPresetService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->accountPasswordHelper = $accountPasswordHelper; + $this->itemPresetService = $itemPresetService; + } + + /** + * Display account's password + * + * @param int $id Account's ID + * @param int $parentId + * + * @return bool + * @throws \JsonException + */ + public function viewPassAction(int $id, int $parentId = 0): ?bool + { + try { + $account = $this->accountService->getPasswordForId($id); + + $passwordPreset = $this->getPasswordPreset(); + $useImage = $this->configData->isAccountPassToImage() + || ($passwordPreset !== null && $passwordPreset->isUseImage()); + + $this->view->assign('isLinked', $parentId > 0); + + $data = $this->accountPasswordHelper->getPasswordView($account, $useImage); + + $this->accountService->incrementDecryptCounter($id); + + $this->eventDispatcher->notifyEvent( + 'show.account.pass', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Password viewed')) + ->addDetail(__u('Account'), $account->getName()) + ) + ); + + return $this->returnJsonResponseData($data); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } + + /** + * @return Password + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\NoSuchPropertyException + * @throws \SP\Core\Exceptions\QueryException + */ + private function getPasswordPreset(): ?Password + { + $itemPreset = $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PASSWORD); + + if ($itemPreset !== null && $itemPreset->getFixed() === 1) { + return $itemPreset->hydrate(Password::class); + } + + return null; + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Account/ViewPassHistoryController.php b/app/modules/web/Controllers/Account/ViewPassHistoryController.php new file mode 100644 index 00000000..d361821f --- /dev/null +++ b/app/modules/web/Controllers/Account/ViewPassHistoryController.php @@ -0,0 +1,121 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Account; + + +use Exception; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\DataModel\ItemPreset\Password; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\ItemPreset\ItemPresetInterface; +use SP\Domain\ItemPreset\ItemPresetServiceInterface; +use SP\Modules\Web\Controllers\Helpers\Account\AccountPasswordHelper; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\WebControllerHelper; + +final class ViewPassHistoryController extends AccountControllerBase +{ + use JsonTrait; + + private AccountServiceInterface $accountService; + private AccountPasswordHelper $accountPasswordHelper; + private ItemPresetServiceInterface $itemPresetService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + AccountServiceInterface $accountService, + AccountPasswordHelper $accountPasswordHelper, + ItemPresetServiceInterface $itemPresetService + ) { + parent::__construct( + $application, + $webControllerHelper + ); + + $this->accountService = $accountService; + $this->accountPasswordHelper = $accountPasswordHelper; + $this->itemPresetService = $itemPresetService; + } + + /** + * Display account's password + * + * @param int $id Account's ID + * + * @return bool + * @throws \JsonException + */ + public function viewPassHistoryAction(int $id): ?bool + { + try { + $account = $this->accountService->getPasswordHistoryForId($id); + + $passwordPreset = $this->getPasswordPreset(); + $useImage = $this->configData->isAccountPassToImage() + || ($passwordPreset !== null && $passwordPreset->isUseImage()); + + $this->view->assign('isLinked', 0); + + $data = $this->accountPasswordHelper->getPasswordView($account, $useImage); + + $this->eventDispatcher->notifyEvent( + 'show.account.pass.history', + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Password viewed')) + ->addDetail(__u('Account'), $account->getName()) + ) + ); + + return $this->returnJsonResponseData($data); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponseException($e); + } + } + + /** + * @return Password + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\NoSuchPropertyException + * @throws \SP\Core\Exceptions\QueryException + */ + private function getPasswordPreset(): ?Password + { + $itemPreset = $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PASSWORD); + + if ($itemPreset !== null && $itemPreset->getFixed() === 1) { + return $itemPreset->hydrate(Password::class); + } + + return null; + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/AccountController.php b/app/modules/web/Controllers/AccountController.php deleted file mode 100644 index 1f2a2580..00000000 --- a/app/modules/web/Controllers/AccountController.php +++ /dev/null @@ -1,1316 +0,0 @@ -. - */ - -namespace SP\Modules\Web\Controllers; - -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; -use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Core\Acl\Acl; -use SP\Core\Acl\ActionsInterface; -use SP\Core\Bootstrap\BootstrapBase; -use SP\Core\Context\ContextBase; -use SP\Core\Crypt\Vault; -use SP\Core\Events\Event; -use SP\Core\Events\EventMessage; -use SP\Core\Exceptions\ConstraintException; -use SP\Core\Exceptions\NoSuchPropertyException; -use SP\Core\Exceptions\QueryException; -use SP\Core\Exceptions\SessionTimeout; -use SP\Core\Exceptions\SPException; -use SP\Core\Exceptions\ValidationException; -use SP\Core\UI\ThemeIcons; -use SP\DataModel\AccountExtData; -use SP\DataModel\ItemPreset\Password; -use SP\Http\JsonResponse; -use SP\Http\Uri; -use SP\Modules\Web\Controllers\Helpers\Account\AccountHelper; -use SP\Modules\Web\Controllers\Helpers\Account\AccountHistoryHelper; -use SP\Modules\Web\Controllers\Helpers\Account\AccountPasswordHelper; -use SP\Modules\Web\Controllers\Helpers\Account\AccountSearchHelper; -use SP\Modules\Web\Controllers\Helpers\LayoutHelper; -use SP\Modules\Web\Controllers\Traits\JsonTrait; -use SP\Modules\Web\Forms\AccountForm; -use SP\Mvc\Controller\CrudControllerInterface; -use SP\Mvc\Controller\ItemTrait; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountAclService; -use SP\Services\Account\AccountHistoryService; -use SP\Services\Account\AccountService; -use SP\Services\Auth\AuthException; -use SP\Services\ItemPreset\ItemPresetInterface; -use SP\Services\ItemPreset\ItemPresetService; -use SP\Services\PublicLink\PublicLinkService; -use SP\Services\ServiceException; -use SP\Services\User\UserService; -use SP\Util\ErrorUtil; -use SP\Util\ImageUtil; -use SP\Util\Util; - -/** - * Class AccountController - * - * @package SP\Modules\Web\Controllers - */ -final class AccountController extends ControllerBase implements CrudControllerInterface -{ - use JsonTrait, ItemTrait; - - protected ?AccountService $accountService = null; - protected ?ThemeIcons $icons = null; - - /** - * Index action - * - * @throws ContainerExceptionInterface - */ - public function indexAction(): void - { - try { - $accountSearchHelper = $this->dic->get(AccountSearchHelper::class); - $accountSearchHelper->getSearchBox(); - $accountSearchHelper->getAccountSearch(); - - $this->eventDispatcher->notifyEvent( - 'show.account.search', - new Event($this) - ); - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - ErrorUtil::showExceptionInView($this->view, $e); - } - } - - /** - * @return bool - * @throws DependencyException - * @throws NotFoundException - * @throws \JsonException - */ - public function searchAction(): ?bool - { - try { - $accountSearchHelper = $this->dic->get(AccountSearchHelper::class); - $accountSearchHelper->getAccountSearch(); - - $this->eventDispatcher->notifyEvent( - 'show.account.search', - new Event($this) - ); - - return $this->returnJsonResponseData([ - 'html' => $this->render(), - ]); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * View action - * - * @param int $id Account's ID - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function viewAction(int $id): void - { - try { - $this->view->addTemplate('account'); - - $accountDetailsResponse = $this->accountService->getById($id); - $this->accountService - ->withUsersById($accountDetailsResponse) - ->withUserGroupsById($accountDetailsResponse) - ->withTagsById($accountDetailsResponse); - - $accountHelper = $this->dic->get(AccountHelper::class); - $accountHelper->setIsView(true); - $accountHelper->setViewForAccount( - $accountDetailsResponse, - ActionsInterface::ACCOUNT_VIEW - ); - - $this->view->assign( - 'title', - [ - 'class' => 'titleNormal', - 'name' => __('Account Details'), - 'icon' => $this->icons->getIconView()->getIcon(), - ] - ); - - $this->accountService->incrementViewCounter($id); - - $this->eventDispatcher->notifyEvent( - 'show.account', - new Event($this) - ); - - if ($this->isAjax === false) { - $this->upgradeView(); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - if ($this->isAjax === false - && !$this->view->isUpgraded() - ) { - $this->upgradeView(); - } - - ErrorUtil::showExceptionInView($this->view, $e, 'account'); - } - } - - /** - * View public link action - * - * @param string $hash Link's hash - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function viewLinkAction(string $hash): void - { - try { - $layoutHelper = $this->dic->get(LayoutHelper::class); - $layoutHelper->getPublicLayout('account-link', 'account'); - - $publicLinkService = $this->dic->get(PublicLinkService::class); - $publicLinkData = $publicLinkService->getByHash($hash); - - if (time() < $publicLinkData->getDateExpire() - && $publicLinkData->getCountViews() < $publicLinkData->getMaxCountViews() - ) { - $publicLinkService->addLinkView($publicLinkData); - - $this->accountService->incrementViewCounter($publicLinkData->getItemId()); - $this->accountService->incrementDecryptCounter($publicLinkData->getItemId()); - - /** @var Vault $vault */ - $vault = unserialize( - $publicLinkData->getData(), - ['allowed_classes' => [Vault::class]] - ); - - /** @var AccountExtData $accountData */ - $accountData = Util::unserialize( - AccountExtData::class, - $vault->getData($publicLinkService->getPublicLinkKey($publicLinkData->getHash())->getKey()) - ); - - $this->view->assign( - 'title', - [ - 'class' => 'titleNormal', - 'name' => __('Account Details'), - 'icon' => $this->icons->getIconView()->getIcon(), - ] - ); - - $this->view->assign('isView', true); - $this->view->assign( - 'useImage', - $this->configData->isPublinksImageEnabled() - || $this->configData->isAccountPassToImage() - ); - - if ($this->view->useImage) { - $imageUtil = $this->dic->get(ImageUtil::class); - $this->view->assign( - 'accountPassImage', - $imageUtil->convertText($accountData->getPass()) - ); - } else { - $this->view->assign( - 'copyPassRoute', - Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW_PASS) - ); - } - - $this->view->assign('accountData', $accountData); - - $clientAddress = $this->configData->isDemoEnabled() - ? '***' - : $this->request->getClientAddress(true); - - $baseUrl = ($this->configData->getApplicationUrl() ?: BootstrapBase::$WEBURI).BootstrapBase::$SUBURI; - - $deepLink = new Uri($baseUrl); - $deepLink->addParam('r', Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW).'/'.$accountData->getId()); - - $this->eventDispatcher->notifyEvent( - 'show.account.link', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Link viewed')) - ->addDetail(__u('Account'), $accountData->getName()) - ->addDetail(__u('Client'), $accountData->getClientName()) - ->addDetail(__u('Agent'), $this->request->getHeader('User-Agent')) - ->addDetail(__u('HTTPS'), $this->request->isHttps() ? __u('ON') : __u('OFF')) - ->addDetail(__u('IP'), $clientAddress) - ->addDetail(__u('Link'), $deepLink->getUriSigned($this->configData->getPasswordSalt())) - ->addExtra('userId', $publicLinkData->getUserId()) - ->addExtra('notify', $publicLinkData->isNotify()) - ) - ); - } else { - ErrorUtil::showErrorInView( - $this->view, - ErrorUtil::ERR_PAGE_NO_PERMISSION, - true, - 'account-link' - ); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - ErrorUtil::showExceptionInView($this->view, $e, 'account-link'); - } - } - - /** - * Create action - */ - public function createAction(): void - { - try { - $accountHelper = $this->dic->get(AccountHelper::class); - $accountHelper->setViewForBlank(ActionsInterface::ACCOUNT_CREATE); - - $this->view->addTemplate('account'); - $this->view->assign( - 'title', - [ - 'class' => 'titleGreen', - 'name' => __('New Account'), - 'icon' => $this->icons->getIconAdd()->getIcon(), - ] - ); - $this->view->assign('formRoute', 'account/saveCreate'); - - $this->eventDispatcher->notifyEvent( - 'show.account.create', - new Event($this) - ); - - if ($this->isAjax === false) { - $this->upgradeView(); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - if ($this->isAjax === false - && !$this->view->isUpgraded() - ) { - $this->upgradeView(); - } - - ErrorUtil::showExceptionInView($this->view, $e, 'account'); - } - } - - /** - * Copy action - * - * @param int $id Account's ID - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function copyAction(int $id): void - { - try { - $accountDetailsResponse = $this->accountService->getById($id); - $this->accountService - ->withUsersById($accountDetailsResponse) - ->withUserGroupsById($accountDetailsResponse) - ->withTagsById($accountDetailsResponse); - - $accountHelper = $this->dic->get(AccountHelper::class); - $accountHelper->setViewForAccount( - $accountDetailsResponse, - ActionsInterface::ACCOUNT_COPY - ); - - $this->view->addTemplate('account'); - $this->view->assign( - 'title', - [ - 'class' => 'titleGreen', - 'name' => __('New Account'), - 'icon' => $this->icons->getIconAdd()->getIcon(), - ] - ); - $this->view->assign('formRoute', 'account/saveCopy'); - - $this->eventDispatcher->notifyEvent( - 'show.account.copy', - new Event($this) - ); - - if ($this->isAjax === false) { - $this->upgradeView(); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - if ($this->isAjax === false - && !$this->view->isUpgraded() - ) { - $this->upgradeView(); - } - - ErrorUtil::showExceptionInView($this->view, $e, 'account'); - } - } - - /** - * Edit action - * - * @param int $id Account's ID - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function editAction(int $id): void - { - try { - $accountDetailsResponse = $this->accountService->getById($id); - $this->accountService - ->withUsersById($accountDetailsResponse) - ->withUserGroupsById($accountDetailsResponse) - ->withTagsById($accountDetailsResponse); - - $accountHelper = $this->dic->get(AccountHelper::class); - $accountHelper->setViewForAccount( - $accountDetailsResponse, - ActionsInterface::ACCOUNT_EDIT - ); - - $this->view->addTemplate('account'); - $this->view->assign( - 'title', - [ - 'class' => 'titleOrange', - 'name' => __('Edit Account'), - 'icon' => $this->icons->getIconEdit()->getIcon(), - ] - ); - $this->view->assign('formRoute', 'account/saveEdit'); - - $this->accountService->incrementViewCounter($id); - - $this->eventDispatcher->notifyEvent( - 'show.account.edit', - new Event($this) - ); - - if ($this->isAjax === false) { - $this->upgradeView(); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - if ($this->isAjax === false - && !$this->view->isUpgraded() - ) { - $this->upgradeView(); - } - - ErrorUtil::showExceptionInView($this->view, $e, 'account'); - } - } - - /** - * Delete action - * - * @param int|null $id Account's ID - * - */ - public function deleteAction(?int $id = null): void - { - try { - $accountDetailsResponse = $this->accountService->getById($id); - $this->accountService - ->withUsersById($accountDetailsResponse) - ->withUserGroupsById($accountDetailsResponse); - - $accountHelper = $this->dic->get(AccountHelper::class); - $accountHelper->setViewForAccount( - $accountDetailsResponse, - ActionsInterface::ACCOUNT_DELETE - ); - - $this->view->addTemplate('account'); - $this->view->assign( - 'title', - [ - 'class' => 'titleRed', - 'name' => __('Remove Account'), - 'icon' => $this->icons->getIconDelete()->getIcon(), - ] - ); - $this->view->assign('formRoute', 'account/saveDelete'); - - $this->eventDispatcher->notifyEvent( - 'show.account.delete', - new Event($this) - ); - - if ($this->isAjax === false) { - $this->upgradeView(); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - if ($this->isAjax === false - && !$this->view->isUpgraded() - ) { - $this->upgradeView(); - } - - ErrorUtil::showExceptionInView($this->view, $e, 'account'); - } - } - - /** - * Obtener los datos para mostrar el interface para modificar la clave de cuenta - * - * @param int $id Account's ID - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function editPassAction(int $id): void - { - try { - $accountDetailsResponse = $this->accountService->getById($id); - $this->accountService - ->withUsersById($accountDetailsResponse) - ->withUserGroupsById($accountDetailsResponse); - - $accountHelper = $this->dic->get(AccountHelper::class); - $accountHelper->setViewForAccount( - $accountDetailsResponse, - ActionsInterface::ACCOUNT_EDIT_PASS - ); - - $this->view->addTemplate('account-editpass'); - $this->view->assign( - 'title', - [ - 'class' => 'titleOrange', - 'name' => __('Edit Account Password'), - 'icon' => $this->icons->getIconEditPass()->getIcon(), - ] - ); - $this->view->assign('formRoute', 'account/saveEditPass'); - - $this->eventDispatcher->notifyEvent( - 'show.account.editpass', - new Event($this) - ); - - if ($this->isAjax === false) { - $this->upgradeView(); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - if ($this->isAjax === false - && !$this->view->isUpgraded() - ) { - $this->upgradeView(); - } - - ErrorUtil::showExceptionInView( - $this->view, - $e, - 'account-editpass' - ); - } - } - - /** - * Obtener los datos para mostrar el interface para ver cuenta en fecha concreta - * - * @param int $id Account's ID - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function viewHistoryAction(int $id): void - { - try { - $accountHistoryService = $this->dic->get(AccountHistoryService::class); - $accountHistoryData = $accountHistoryService->getById($id); - - $accountHistoryHelper = $this->dic->get(AccountHistoryHelper::class); - $accountHistoryHelper->setView( - $accountHistoryData, - ActionsInterface::ACCOUNT_HISTORY_VIEW - ); - - $this->view->addTemplate('account-history'); - - $this->view->assign( - 'title', - [ - 'class' => 'titleNormal', - 'name' => __('Account Details'), - 'icon' => 'access_time', - ] - ); - - $this->view->assign('formRoute', 'account/saveRestore'); - - $this->eventDispatcher->notifyEvent( - 'show.account.history', - new Event($this) - ); - - if ($this->isAjax === false) { - $this->upgradeView(); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - if ($this->isAjax === false - && !$this->view->isUpgraded() - ) { - $this->upgradeView(); - } - - ErrorUtil::showExceptionInView( - $this->view, - $e, - 'account-history' - ); - } - } - - /** - * Obtener los datos para mostrar el interface de solicitud de cambios en una cuenta - * - * @param int $id Account's ID - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function requestAccessAction(int $id): void - { - try { - $accountHelper = $this->dic->get(AccountHelper::class); - $accountHelper->setIsView(true); - $accountHelper->setViewForRequest( - $this->accountService->getById($id), - ActionsInterface::ACCOUNT_REQUEST - ); - - $this->view->addTemplate('account-request'); - $this->view->assign('formRoute', 'account/saveRequest'); - - $this->eventDispatcher->notifyEvent( - 'show.account.request', - new Event($this) - ); - - if ($this->isAjax === false) { - $this->upgradeView(); - } - - $this->view(); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - if ($this->isAjax === false - && !$this->view->isUpgraded() - ) { - $this->upgradeView(); - } - - ErrorUtil::showExceptionInView( - $this->view, - $e, - 'account-request' - ); - } - } - - /** - * Display account's password - * - * @param int $id Account's ID - * @param int $parentId - * - * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException - * @throws \JsonException - */ - public function viewPassAction(int $id, int $parentId = 0): ?bool - { - try { - $accountPassHelper = $this->dic->get(AccountPasswordHelper::class); - - $account = $this->accountService->getPasswordForId($id); - - $passwordPreset = $this->getPasswordPreset(); - $useImage = $this->configData->isAccountPassToImage() - || ($passwordPreset !== null && $passwordPreset->isUseImage()); - - $this->view->assign('isLinked', $parentId > 0); - - $data = $accountPassHelper->getPasswordView($account, $useImage); - - $this->accountService->incrementDecryptCounter($id); - - $this->eventDispatcher->notifyEvent( - 'show.account.pass', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Password viewed')) - ->addDetail(__u('Account'), $account->getName()) - ) - ); - - return $this->returnJsonResponseData($data); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * @return Password - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws NoSuchPropertyException - * @throws QueryException - */ - private function getPasswordPreset(): ?Password - { - $itemPreset = $this->dic->get(ItemPresetService::class) - ->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PASSWORD); - - if ($itemPreset !== null && $itemPreset->getFixed() === 1) { - return $itemPreset->hydrate(Password::class); - } - - return null; - } - - /** - * Display account's password - * - * @param int $id Account's ID - * - * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException - * @throws \JsonException - */ - public function viewPassHistoryAction(int $id): ?bool - { - try { - $accountPassHelper = $this->dic->get(AccountPasswordHelper::class); - - $account = $this->accountService->getPasswordHistoryForId($id); - - $passwordPreset = $this->getPasswordPreset(); - $useImage = $this->configData->isAccountPassToImage() - || ($passwordPreset !== null && $passwordPreset->isUseImage()); - - $this->view->assign('isLinked', 0); - - $data = $accountPassHelper->getPasswordView($account, $useImage); - - $this->eventDispatcher->notifyEvent( - 'show.account.pass.history', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Password viewed')) - ->addDetail(__u('Account'), $account->getName()) - ) - ); - - return $this->returnJsonResponseData($data); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * Copy account's password - * - * @param int $id Account's ID - * - * @return bool - * @throws Helpers\HelperException - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - * @throws ServiceException - * @throws SPException - */ - public function copyPassAction(int $id): bool - { - $accountPassHelper = $this->dic->get(AccountPasswordHelper::class); - - $account = $this->accountService->getPasswordForId($id); - - $data = [ - 'accpass' => $accountPassHelper->getPasswordClear($account), - ]; - - $this->eventDispatcher->notifyEvent( - 'copy.account.pass', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Password copied')) - ->addDetail(__u('Account'), $account->getName()) - ) - ); - - return $this->returnJsonResponseData($data); - } - - /** - * Copy account's password - * - * @param int $id Account's ID - * - * @return bool - * @throws Helpers\HelperException - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - * @throws ServiceException - * @throws SPException - */ - public function copyPassHistoryAction(int $id): bool - { - $accountPassHelper = $this->dic->get(AccountPasswordHelper::class); - - $account = $this->accountService->getPasswordHistoryForId($id); - - $data = [ - 'accpass' => $accountPassHelper->getPasswordClear($account), - ]; - - $this->eventDispatcher->notifyEvent( - 'copy.account.pass.history', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Password copied')) - ->addDetail(__u('Account'), $account->getName()) - ) - ); - - return $this->returnJsonResponseData($data); - } - - /** - * @throws DependencyException - * @throws NotFoundException - * @throws \JsonException - */ - public function saveCopyAction(): void - { - $this->saveCreateAction(); - } - - /** - * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException - * @throws \JsonException - */ - public function saveCreateAction(): ?bool - { - try { - $form = new AccountForm($this->dic); - $form->validate(ActionsInterface::ACCOUNT_CREATE); - - $accountId = $this->accountService->create($form->getItemData()); - - $accountDetails = $this->accountService - ->getById($accountId) - ->getAccountVData(); - - $this->eventDispatcher->notifyEvent( - 'create.account', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Account created')) - ->addDetail(__u('Account'), $accountDetails->getName()) - ->addDetail(__u('Client'), $accountDetails->getClientName()) - ) - ); - - $this->addCustomFieldsForItem( - ActionsInterface::ACCOUNT, - $accountId, - $this->request - ); - - return $this->returnJsonResponseData( - [ - 'itemId' => $accountId, - 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_EDIT), - ], - JsonResponse::JSON_SUCCESS, - __u('Account created') - ); - } catch (ValidationException $e) { - return $this->returnJsonResponseException($e); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * Saves edit action - * - * @param int $id Account's ID - * - * @return bool - * @throws DependencyException - * @throws NotFoundException - * @throws \JsonException - */ - public function saveEditAction(int $id): ?bool - { - try { - $form = new AccountForm($this->dic, $id); - $form->validate(ActionsInterface::ACCOUNT_EDIT); - - $itemData = $form->getItemData(); - - $this->accountService->update($itemData); - - $accountDetails = $this->accountService - ->getById($id) - ->getAccountVData(); - - $this->eventDispatcher->notifyEvent( - 'edit.account', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Account updated')) - ->addDetail(__u('Account'), $accountDetails->getName()) - ->addDetail(__u('Client'), $accountDetails->getClientName()) - ) - ); - - $this->updateCustomFieldsForItem( - ActionsInterface::ACCOUNT, - $id, - $this->request - ); - - return $this->returnJsonResponseData( - [ - 'itemId' => $id, - 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW), - ], - JsonResponse::JSON_SUCCESS, - __u('Account updated') - ); - } catch (ValidationException $e) { - return $this->returnJsonResponseException($e); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * Saves edit action - * - * @param int $id Account's ID - * - * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException - * @throws \JsonException - */ - public function saveEditPassAction(int $id): bool - { - try { - $form = new AccountForm($this->dic, $id); - $form->validate(ActionsInterface::ACCOUNT_EDIT_PASS); - - $this->accountService->editPassword($form->getItemData()); - - $accountDetails = $this->accountService - ->getById($id) - ->getAccountVData(); - - $this->eventDispatcher->notifyEvent( - 'edit.account.pass', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Password updated')) - ->addDetail(__u('Account'), $accountDetails->getName()) - ->addDetail(__u('Client'), $accountDetails->getClientName()) - ) - ); - - return $this->returnJsonResponseData( - [ - 'itemId' => $id, - 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW), - ], - JsonResponse::JSON_SUCCESS, - __u('Password updated') - ); - } catch (ValidationException $e) { - return $this->returnJsonResponseException($e); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * Saves restore action - * - * @param int $historyId Account's history ID - * @param int $id Account's ID - * - * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException - * @throws \JsonException - */ - public function saveEditRestoreAction(int $historyId, int $id): bool - { - try { - $this->accountService->editRestore($historyId, $id); - - $accountDetails = $this->accountService - ->getById($id) - ->getAccountVData(); - - $this->eventDispatcher->notifyEvent( - 'edit.account.restore', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Account restored')) - ->addDetail(__u('Account'), $accountDetails->getName()) - ->addDetail(__u('Client'), $accountDetails->getClientName()) - ) - ); - - return $this->returnJsonResponseData( - [ - 'itemId' => $id, - 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW), - ], - JsonResponse::JSON_SUCCESS, - __u('Account restored') - ); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * Saves delete action - * - * @param int $id Account's ID - * - * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException - * @throws \JsonException - */ - public function saveDeleteAction(int $id): bool - { - try { - $accountDetails = $this->accountService - ->getById($id) - ->getAccountVData(); - - $this->accountService->delete($id); - - $this->eventDispatcher->notifyEvent( - 'delete.account', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Account removed')) - ->addDetail(__u('Account'), $accountDetails->getName()) - ->addDetail(__u('Client'), $accountDetails->getClientName()) - ) - ); - - $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id); - - return $this->returnJsonResponse( - JsonResponse::JSON_SUCCESS, - __u('Account removed') - ); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * Saves a request action - * - * @param int $id Account's ID - * - * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException - * @throws \JsonException - */ - public function saveRequestAction(int $id): bool - { - try { - $description = $this->request->analyzeString('description'); - - if (empty($description)) { - throw new ValidationException(__u('A description is needed')); - } - - $accountDetails = $this->accountService->getById($id)->getAccountVData(); - - $baseUrl = ($this->configData->getApplicationUrl() ?: BootstrapBase::$WEBURI).BootstrapBase::$SUBURI; - - $deepLink = new Uri($baseUrl); - $deepLink->addParam('r', Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW).'/'.$id); - - $usersId = [$accountDetails->userId, $accountDetails->userEditId]; - - $userService = $this->dic->get(UserService::class); - - $this->eventDispatcher->notifyEvent( - 'request.account', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Request')) - ->addDetail( - __u('Requester'), - sprintf('%s (%s)', $this->userData->getName(), $this->userData->getLogin()) - ) - ->addDetail(__u('Account'), $accountDetails->getName()) - ->addDetail(__u('Client'), $accountDetails->getClientName()) - ->addDetail(__u('Description'), $description) - ->addDetail(__u('Link'), $deepLink->getUriSigned($this->configData->getPasswordSalt())) - ->addExtra('accountId', $id) - ->addExtra('whoId', $this->userData->getId()) - ->setExtra('userId', $usersId) - ->setExtra( - 'email', - array_map( - static function ($value) { - return $value->email; - }, - $userService->getUserEmailById($usersId) - ) - ) - ) - ); - - return $this->returnJsonResponseData( - [ - 'itemId' => $id, - 'nextAction' => Acl::getActionRoute(ActionsInterface::ACCOUNT), - ], - JsonResponse::JSON_SUCCESS, - __u('Request done') - ); - } catch (ValidationException $e) { - return $this->returnJsonResponseException($e); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponseException($e); - } - } - - /** - * Initialize class - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws AuthException - * @throws SessionTimeout - */ - protected function initialize(): void - { - if ($this->actionName !== 'viewLinkAction') { - $this->checkLoggedIn(); - } - - if (DEBUG === true - && $this->session->getAppStatus() === ContextBase::APP_STATUS_RELOADED - ) { - $this->session->resetAppStatus(); - - // Reset de los datos de ACL de cuentas - AccountAclService::clearAcl($this->session->getUserData()->getId()); - } - - $this->accountService = $this->dic->get(AccountService::class); - $this->icons = $this->theme->getIcons(); - } -} \ No newline at end of file diff --git a/app/modules/web/Controllers/AccountFavoriteController.php b/app/modules/web/Controllers/AccountFavoriteController.php index 9941ebeb..737f4909 100644 --- a/app/modules/web/Controllers/AccountFavoriteController.php +++ b/app/modules/web/Controllers/AccountFavoriteController.php @@ -29,9 +29,9 @@ use DI\NotFoundException; use Exception; use SP\Core\Events\Event; use SP\Core\Exceptions\SessionTimeout; +use SP\Domain\Account\Services\AccountToFavoriteService; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Traits\JsonTrait; -use SP\Services\Account\AccountToFavoriteService; /** * Class AccountFavoriteController diff --git a/app/modules/web/Controllers/AccountFileController.php b/app/modules/web/Controllers/AccountFileController.php index d9f3005b..a7579c5f 100644 --- a/app/modules/web/Controllers/AccountFileController.php +++ b/app/modules/web/Controllers/AccountFileController.php @@ -24,32 +24,34 @@ namespace SP\Modules\Web\Controllers; -use DI\DependencyException; -use DI\NotFoundException; use Exception; -use Psr\Container\ContainerExceptionInterface; +use Klein\Klein; use RuntimeException; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Core\Exceptions\ConstraintException; -use SP\Core\Exceptions\QueryException; -use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; +use SP\Core\PhpExtensionChecker; +use SP\Core\UI\ThemeInterface; use SP\DataModel\FileData; +use SP\Domain\Account\AccountFileServiceInterface; +use SP\Domain\Account\AccountServiceInterface; use SP\Html\DataGrid\DataGridInterface; use SP\Html\Html; use SP\Http\JsonResponse; +use SP\Http\RequestInterface; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; +use SP\Infrastructure\File\FileHandlerInterface; use SP\Modules\Web\Controllers\Helpers\Grid\FileGrid; +use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; -use SP\Services\Account\AccountFileService; -use SP\Services\Account\AccountService; -use SP\Services\Auth\AuthException; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Mvc\View\TemplateInterface; +use SP\Providers\Auth\Browser\BrowserAuthInterface; use SP\Util\ErrorUtil; use SP\Util\FileUtil; @@ -64,16 +66,43 @@ final class AccountFileController extends ControllerBase implements CrudControll use JsonTrait, ItemTrait; - protected ?AccountFileService $accountFileService = null; + private AccountFileServiceInterface $accountFileService; + private AccountServiceInterface $accountService; + private FileGrid $fileGrid; + + public function __construct( + Application $application, + ThemeInterface $theme, + Klein $router, + Acl $acl, + RequestInterface $request, + PhpExtensionChecker $extensionChecker, + TemplateInterface $template, + BrowserAuthInterface $browser, + LayoutHelper $layoutHelper + ) { + parent::__construct( + $application, + $theme, + $router, + $acl, + $request, + $extensionChecker, + $template, + $browser, + $layoutHelper + ); + + $this->checkLoggedIn(); + } + /** * View action * - * @param int $id + * @param int $id * * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException */ public function viewAction(int $id): bool @@ -92,10 +121,12 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->eventDispatcher->notifyEvent( 'show.accountFile', - new Event($this, + new Event( + $this, EventMessage::factory() ->addDescription(__u('File viewed')) - ->addDetail(__u('File'), $fileData->getName())) + ->addDetail(__u('File'), $fileData->getName()) + ) ); return $this->returnJsonResponseData(['html' => $this->render()]); @@ -109,10 +140,12 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->eventDispatcher->notifyEvent( 'show.accountFile', - new Event($this, + new Event( + $this, EventMessage::factory() ->addDescription(__u('File viewed')) - ->addDetail(__u('File'), $fileData->getName())) + ->addDetail(__u('File'), $fileData->getName()) + ) ); return $this->returnJsonResponseData(['html' => $this->render()]); @@ -137,7 +170,7 @@ final class AccountFileController extends ControllerBase implements CrudControll /** * Download action * - * @param int $id + * @param int $id * * @return string */ @@ -150,9 +183,11 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->eventDispatcher->notifyEvent( 'download.accountFile', - new Event($this, EventMessage::factory() + new Event( + $this, EventMessage::factory() ->addDescription(__u('File downloaded')) - ->addDetail(__u('File'), $fileData->getName())) + ->addDetail(__u('File'), $fileData->getName()) + ) ); $response = $this->router->response(); @@ -196,11 +231,9 @@ final class AccountFileController extends ControllerBase implements CrudControll /** * Upload action * - * @param int $accountId + * @param int $accountId * * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException */ public function uploadAction(int $accountId): bool @@ -257,20 +290,19 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->accountFileService->create($fileData); - $account = $this->dic->get(AccountService::class) - ->getById($accountId) - ->getAccountVData(); + $account = $this->accountService->getById($accountId)->getAccountVData(); $this->eventDispatcher->notifyEvent( 'upload.accountFile', - new Event($this, + new Event( + $this, EventMessage::factory() ->addDescription(__u('File saved')) ->addDetail(__u('File'), $fileData->getName()) ->addDetail(__u('Account'), $account->getName()) ->addDetail(__u('Client'), $account->getClientName()) ->addDetail(__u('Type'), $fileData->getType()) - ->addDetail(__u('Size'), $fileData->getRoundSize() . 'KB') + ->addDetail(__u('Size'), $fileData->getRoundSize().'KB') ) ); @@ -301,15 +333,14 @@ final class AccountFileController extends ControllerBase implements CrudControll } /** - * @param FileData $fileData - * - * @param FileHandler $fileHandler + * @param FileData $fileData + * @param FileHandlerInterface $fileHandler * * @return string * @throws SPException * @throws FileException */ - private function checkAllowedMimeType(FileData $fileData, FileHandler $fileHandler): string + private function checkAllowedMimeType(FileData $fileData, FileHandlerInterface $fileHandler): string { if (in_array($fileData->getType(), $this->configData->getFilesAllowedMime(), true)) { return $fileData->getType(); @@ -330,12 +361,9 @@ final class AccountFileController extends ControllerBase implements CrudControll * Search action * * @return bool - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException - * @throws SPException * @throws \JsonException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ public function searchAction(): bool { @@ -359,10 +387,9 @@ final class AccountFileController extends ControllerBase implements CrudControll /** * getSearchGrid * - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException + * @return \SP\Html\DataGrid\DataGridInterface + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ protected function getSearchGrid(): DataGridInterface { @@ -371,10 +398,8 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->request ); - $fileGrid = $this->dic->get(FileGrid::class); - - return $fileGrid->updatePager( - $fileGrid->getGrid($this->accountFileService->search($itemSearchData)), + return $this->fileGrid->updatePager( + $this->fileGrid->getGrid($this->accountFileService->search($itemSearchData)), $itemSearchData ); } @@ -400,11 +425,9 @@ final class AccountFileController extends ControllerBase implements CrudControll /** * Delete action * - * @param int|null $id + * @param int|null $id * * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException */ public function deleteAction(?int $id = null): bool @@ -415,8 +438,10 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->eventDispatcher->notifyEvent( 'delete.accountFile.selection', - new Event($this, EventMessage::factory() - ->addDescription(__u('Files deleted'))) + new Event( + $this, + EventMessage::factory()->addDescription(__u('Files deleted')) + ) ); return $this->returnJsonResponse(0, __u('Files deleted')); @@ -424,9 +449,10 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->eventDispatcher->notifyEvent( 'delete.accountFile', - new Event($this, EventMessage::factory() - ->addDescription(__u('File deleted')) - ->addDetail(__u('File'), $id)) + new Event( + $this, + EventMessage::factory()->addDescription(__u('File deleted'))->addDetail(__u('File'), $id) + ) ); $this->accountFileService->delete($id); @@ -465,14 +491,13 @@ final class AccountFileController extends ControllerBase implements CrudControll /** * Obtener los datos para la vista de archivos de una cuenta * - * @param int $accountId Account's ID - * - * @throws ContainerExceptionInterface + * @param int $accountId Account's ID */ public function listAction(int $accountId): void { if (!$this->configData->isFilesEnabled()) { echo __('Files management disabled'); + return; } @@ -480,7 +505,7 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->view->addTemplate('files-list', 'account'); $this->view->assign('deleteEnabled', $this->request->analyzeInt('del', false)); - $this->view->assign('files', $this->dic->get(AccountFileService::class)->getByAccountId($accountId)); + $this->view->assign('files', $this->accountFileService->getByAccountId($accountId)); $this->view->assign('fileViewRoute', Acl::getActionRoute(ActionsInterface::ACCOUNT_FILE_VIEW)); $this->view->assign('fileDownloadRoute', Acl::getActionRoute(ActionsInterface::ACCOUNT_FILE_DOWNLOAD)); $this->view->assign('fileDeleteRoute', Acl::getActionRoute(ActionsInterface::ACCOUNT_FILE_DELETE)); @@ -519,19 +544,4 @@ final class AccountFileController extends ControllerBase implements CrudControll $this->view(); } - - /** - * Initialize class - * - * @throws AuthException - * @throws DependencyException - * @throws NotFoundException - * @throws SessionTimeout - */ - protected function initialize(): void - { - $this->checkLoggedIn(); - - $this->accountFileService = $this->dic->get(AccountFileService::class); - } } diff --git a/app/modules/web/Controllers/AccountHistoryManagerController.php b/app/modules/web/Controllers/AccountHistoryManagerController.php index 3c96bcef..4a61fc6a 100644 --- a/app/modules/web/Controllers/AccountHistoryManagerController.php +++ b/app/modules/web/Controllers/AccountHistoryManagerController.php @@ -24,23 +24,28 @@ namespace SP\Modules\Web\Controllers; -use DI\DependencyException; -use DI\NotFoundException; use Exception; +use Klein\Klein; +use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Core\Exceptions\SessionTimeout; +use SP\Core\PhpExtensionChecker; +use SP\Core\UI\ThemeInterface; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Account\AccountServiceInterface; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\Grid\AccountHistoryGrid; +use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Mvc\Controller\ItemTrait; -use SP\Services\Account\AccountHistoryService; -use SP\Services\Account\AccountService; -use SP\Services\Auth\AuthException; +use SP\Mvc\View\TemplateInterface; +use SP\Providers\Auth\Browser\BrowserAuthInterface; /** * Class AccountHistoryManagerController @@ -51,12 +56,46 @@ final class AccountHistoryManagerController extends ControllerBase { use JsonTrait, ItemTrait; - protected ?AccountHistoryService $accountHistoryService = null; + private AccountHistoryServiceInterface $accountHistoryService; + private AccountHistoryGrid $accountHistoryGrid; + private AccountServiceInterface $accountService; + + public function __construct( + Application $application, + ThemeInterface $theme, + Klein $router, + Acl $acl, + RequestInterface $request, + PhpExtensionChecker $extensionChecker, + TemplateInterface $template, + BrowserAuthInterface $browser, + LayoutHelper $layoutHelper, + AccountHistoryServiceInterface $accountHistoryService, + Helpers\Grid\AccountHistoryGrid $accountHistoryGrid, + AccountServiceInterface $accountService + ) { + $this->accountHistoryService = $accountHistoryService; + $this->accountHistoryGrid = $accountHistoryGrid; + $this->accountService = $accountService; + + parent::__construct( + $application, + $theme, + $router, + $acl, + $request, + $extensionChecker, + $template, + $browser, + $layoutHelper + ); + + $this->checkLoggedIn(); + } + /** * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException @@ -80,8 +119,6 @@ final class AccountHistoryManagerController extends ControllerBase /** * getSearchGrid * - * @throws DependencyException - * @throws NotFoundException * @throws ConstraintException * @throws QueryException */ @@ -92,10 +129,8 @@ final class AccountHistoryManagerController extends ControllerBase $this->request ); - $historyGrid = $this->dic->get(AccountHistoryGrid::class); - - return $historyGrid->updatePager( - $historyGrid->getGrid($this->accountHistoryService->search($itemSearchData)), + return $this->accountHistoryGrid->updatePager( + $this->accountHistoryGrid->getGrid($this->accountHistoryService->search($itemSearchData)), $itemSearchData ); } @@ -103,11 +138,9 @@ final class AccountHistoryManagerController extends ControllerBase /** * Delete action * - * @param int|null $id + * @param int|null $id * * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException */ public function deleteAction(?int $id = null): bool @@ -164,11 +197,9 @@ final class AccountHistoryManagerController extends ControllerBase /** * Saves restore action * - * @param int $id Account's history ID + * @param int $id Account's history ID * * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException */ public function restoreAction(int $id): bool @@ -176,12 +207,10 @@ final class AccountHistoryManagerController extends ControllerBase try { $accountDetails = $this->accountHistoryService->getById($id); - $accountService = $this->dic->get(AccountService::class); - if ($accountDetails->isModify) { - $accountService->editRestore($id, $accountDetails->getAccountId()); + $this->accountService->editRestore($id, $accountDetails->getAccountId()); } else { - $accountService->createFromHistory($accountDetails); + $this->accountService->createFromHistory($accountDetails); } $this->eventDispatcher->notifyEvent( @@ -210,19 +239,4 @@ final class AccountHistoryManagerController extends ControllerBase return $this->returnJsonResponseException($e); } } - - /** - * Initialize class - * - * @throws AuthException - * @throws DependencyException - * @throws NotFoundException - * @throws SessionTimeout - */ - protected function initialize(): void - { - $this->checkLoggedIn(); - - $this->accountHistoryService = $this->dic->get(AccountHistoryService::class); - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/AccountManagerController.php b/app/modules/web/Controllers/AccountManagerController.php index 8c626173..fd832c1e 100644 --- a/app/modules/web/Controllers/AccountManagerController.php +++ b/app/modules/web/Controllers/AccountManagerController.php @@ -24,35 +24,37 @@ namespace SP\Modules\Web\Controllers; -use DI\DependencyException; -use DI\NotFoundException; use Exception; +use Klein\Klein; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Core\Exceptions\ConstraintException; -use SP\Core\Exceptions\QueryException; -use SP\Core\Exceptions\SessionTimeout; -use SP\Core\Exceptions\SPException; +use SP\Core\PhpExtensionChecker; +use SP\Core\UI\ThemeInterface; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Account\AccountSearchServiceInterface; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Account\Services\AccountBulkRequest; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Client\Services\ClientService; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Domain\Tag\Services\TagService; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\Grid\AccountGrid; +use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\AccountForm; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Services\Account\AccountBulkRequest; -use SP\Services\Account\AccountHistoryService; -use SP\Services\Account\AccountSearchFilter; -use SP\Services\Account\AccountSearchService; -use SP\Services\Account\AccountService; -use SP\Services\Auth\AuthException; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Tag\TagService; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; +use SP\Mvc\View\TemplateInterface; +use SP\Providers\Auth\Browser\BrowserAuthInterface; use SP\Util\Util; /** @@ -64,17 +66,55 @@ final class AccountManagerController extends ControllerBase { use JsonTrait, ItemTrait; - protected ?AccountService $accountService = null; - protected ?AccountSearchService $accountSearchService = null; + private AccountServiceInterface $accountService; + private AccountSearchServiceInterface $accountSearchService; + private AccountHistoryServiceInterface $accountHistoryService; + private AccountGrid $accountGrid; + private CustomFieldServiceInterface $customFieldService; + + public function __construct( + Application $application, + ThemeInterface $theme, + Klein $router, + Acl $acl, + RequestInterface $request, + PhpExtensionChecker $extensionChecker, + TemplateInterface $template, + BrowserAuthInterface $browser, + LayoutHelper $layoutHelper, + AccountServiceInterface $accountService, + AccountSearchServiceInterface $accountSearchService, + AccountHistoryServiceInterface $accountHistoryService, + Helpers\Grid\AccountGrid $accountGrid, + CustomFieldServiceInterface $customFieldService + ) { + $this->accountService = $accountService; + $this->accountSearchService = $accountSearchService; + $this->accountHistoryService = $accountHistoryService; + $this->accountGrid = $accountGrid; + $this->customFieldService = $customFieldService; + + parent::__construct( + $application, + $theme, + $router, + $acl, + $request, + $extensionChecker, + $template, + $browser, + $layoutHelper + ); + + $this->checkLoggedIn(); + } /** * @return bool - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException - * @throws SPException * @throws \JsonException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\SPException */ public function searchAction(): bool { @@ -95,11 +135,10 @@ final class AccountManagerController extends ControllerBase /** * getSearchGrid * - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException - * @throws SPException + * @return \SP\Html\DataGrid\DataGridInterface + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\SPException */ protected function getSearchGrid(): DataGridInterface { @@ -108,31 +147,31 @@ final class AccountManagerController extends ControllerBase $this->request ); - $accountGrid = $this->dic->get(AccountGrid::class); - $filter = new AccountSearchFilter(); $filter->setLimitCount($itemSearchData->getLimitCount()); $filter->setLimitStart($itemSearchData->getLimitStart()); if (!empty($itemSearchData->getSeachString())) { - $filter->setStringFilters($this->accountSearchService->analyzeQueryFilters($itemSearchData->getSeachString())); + $filter->setStringFilters( + $this->accountSearchService->analyzeQueryFilters($itemSearchData->getSeachString()) + ); $filter->setCleanTxtSearch($this->accountSearchService->getCleanString()); } - return $accountGrid->updatePager( - $accountGrid->getGrid( - $this->accountService->getByFilter($filter)), - $itemSearchData); + return $this->accountGrid->updatePager( + $this->accountGrid->getGrid( + $this->accountService->getByFilter($filter) + ), + $itemSearchData + ); } /** * Delete action * - * @param int|null $id + * @param int|null $id * * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException */ public function deleteAction(?int $id = null): bool @@ -141,7 +180,7 @@ final class AccountManagerController extends ControllerBase if ($id === null) { $this->accountService->deleteByIdBatch($this->getItemsIdFromRequest($this->request)); - $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id, $this->customFieldService); $this->eventDispatcher->notifyEvent( 'delete.account.selection', @@ -164,7 +203,7 @@ final class AccountManagerController extends ControllerBase $this->accountService->delete($id); - $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id); + $this->deleteCustomFieldsForItem(ActionsInterface::ACCOUNT, $id, $this->customFieldService); $this->eventDispatcher->notifyEvent( 'delete.account', @@ -192,8 +231,6 @@ final class AccountManagerController extends ControllerBase * saveBulkEditAction * * @return bool - * @throws DependencyException - * @throws NotFoundException * @throws \JsonException */ public function saveBulkEditAction(): bool @@ -204,12 +241,12 @@ final class AccountManagerController extends ControllerBase $request = new AccountBulkRequest( Util::itemsIdAdapter($this->request->analyzeString('itemsId')), - $form->getItemData()); + $form->getItemData() + ); $request->setDeleteHistory($this->request->analyzeBool('delete_history', false)); if ($request->isDeleteHistory()) { - $accountHistoryService = $this->dic->get(AccountHistoryService::class); - $accountHistoryService->deleteByAccountIdBatch($request->getItemsId()); + $this->accountHistoryService->deleteByAccountIdBatch($request->getItemsId()); } $this->accountService->updateBulk($request); @@ -238,8 +275,6 @@ final class AccountManagerController extends ControllerBase * bulkEditAction * * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException */ public function bulkEditAction(): bool @@ -279,12 +314,12 @@ final class AccountManagerController extends ControllerBase { $this->view->addTemplate('account_bulkedit', 'itemshow'); - $this->view->assign('nextAction', Acl::getActionRoute(Acl::ITEMS_MANAGE)); + $this->view->assign('nextAction', Acl::getActionRoute(ActionsInterface::ITEMS_MANAGE)); + // FIXME: Use IoC $clients = SelectItemAdapter::factory(ClientService::getItemsBasic())->getItemsFromModel(); $categories = SelectItemAdapter::factory(CategoryService::getItemsBasic())->getItemsFromModel(); $tags = SelectItemAdapter::factory(TagService::getItemsBasic())->getItemsFromModel(); - $users = SelectItemAdapter::factory(UserService::getItemsBasic())->getItemsFromModel(); $userGroups = SelectItemAdapter::factory(UserGroupService::getItemsBasic())->getItemsFromModel(); @@ -303,20 +338,4 @@ final class AccountManagerController extends ControllerBase $this->view->assign('readonly', false); } } - - /** - * Initialize class - * - * @throws AuthException - * @throws DependencyException - * @throws NotFoundException - * @throws SessionTimeout - */ - protected function initialize(): void - { - $this->checkLoggedIn(); - - $this->accountService = $this->dic->get(AccountService::class); - $this->accountSearchService = $this->dic->get(AccountSearchService::class); - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/AuthTokenController.php b/app/modules/web/Controllers/AuthTokenController.php index 641cf82c..5c957031 100644 --- a/app/modules/web/Controllers/AuthTokenController.php +++ b/app/modules/web/Controllers/AuthTokenController.php @@ -37,6 +37,10 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\AuthTokenData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\User\Services\UserService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Helpers\Grid\AuthTokenGrid; @@ -45,10 +49,6 @@ use SP\Modules\Web\Forms\AuthTokenForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Services\Auth\AuthException; -use SP\Services\AuthToken\AuthTokenService; -use SP\Services\ServiceException; -use SP\Services\User\UserService; /** * Class AuthTokenController @@ -164,7 +164,7 @@ final class AuthTokenController extends ControllerBase implements CrudController * @throws NotFoundException * @throws QueryException * @throws SPException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ protected function setViewData(?int $authTokenId = null): void { diff --git a/app/modules/web/Controllers/BootstrapController.php b/app/modules/web/Controllers/Bootstrap/GetEnvironmentController.php similarity index 83% rename from app/modules/web/Controllers/BootstrapController.php rename to app/modules/web/Controllers/Bootstrap/GetEnvironmentController.php index e0c27585..6714de59 100644 --- a/app/modules/web/Controllers/BootstrapController.php +++ b/app/modules/web/Controllers/Bootstrap/GetEnvironmentController.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Modules\Web\Controllers; +namespace SP\Modules\Web\Controllers\Bootstrap; use Exception; use Klein\Klein; @@ -32,36 +32,37 @@ use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Crypt\CryptPKI; use SP\Core\PhpExtensionChecker; use SP\Core\UI\ThemeInterface; -use SP\Http\Request; +use SP\Domain\Import\Services\ImportService; +use SP\Http\RequestInterface; +use SP\Infrastructure\File\FileException; +use SP\Modules\Web\Controllers\SimpleControllerBase; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Plugin\PluginManager; -use SP\Providers\Auth\Browser\Browser; -use SP\Services\Import\ImportService; -use SP\Storage\File\FileException; +use SP\Providers\Auth\Browser\BrowserAuthInterface; /** - * Class BootstrapController + * Class GetEnvironmentController * * @package SP\Modules\Web\Controllers */ -final class BootstrapController extends SimpleControllerBase +final class GetEnvironmentController extends SimpleControllerBase { use JsonTrait; - private CryptPKI $cryptPKI; - private PluginManager $pluginManager; - private Browser $browser; + private CryptPKI $cryptPKI; + private PluginManager $pluginManager; + private BrowserAuthInterface $browser; public function __construct( Application $application, ThemeInterface $theme, Klein $router, Acl $acl, - Request $request, + RequestInterface $request, PhpExtensionChecker $extensionChecker, CryptPKI $cryptPKI, PluginManager $pluginManager, - Browser $browser + BrowserAuthInterface $browser ) { $this->cryptPKI = $cryptPKI; $this->pluginManager = $pluginManager; @@ -135,10 +136,7 @@ final class BootstrapController extends SimpleControllerBase */ private function getCookiesEnabled(): bool { - return $this->router - ->request() - ->cookies() - ->get(session_name()) !== null; + return $this->router->request()->cookies()->get(session_name()) !== null; } /** @@ -160,8 +158,7 @@ final class BootstrapController extends SimpleControllerBase */ private function getAuthBasicAutologinEnabled(): bool { - return $this->browser->getServerAuthUser() !== null - && $this->configData->isAuthBasicAutoLoginEnabled(); + return $this->browser->getServerAuthUser() !== null && $this->configData->isAuthBasicAutoLoginEnabled(); } /** @@ -170,8 +167,7 @@ final class BootstrapController extends SimpleControllerBase private function getPublicKey(): string { try { - return $this->session->getPublicKey() - ?: $this->cryptPKI->getPublicKey(); + return $this->session->getPublicKey() ?: $this->cryptPKI->getPublicKey(); } catch (FileException $e) { processException($e); diff --git a/app/modules/web/Controllers/CategoryController.php b/app/modules/web/Controllers/CategoryController.php index 658bc1b8..7a12e853 100644 --- a/app/modules/web/Controllers/CategoryController.php +++ b/app/modules/web/Controllers/CategoryController.php @@ -37,17 +37,17 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\CategoryData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Common\Services\ServiceException; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\Grid\CategoryGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\CategoryForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; -use SP\Repositories\NoSuchItemException; -use SP\Services\Auth\AuthException; -use SP\Services\Category\CategoryService; -use SP\Services\ServiceException; /** * Class CategoryController diff --git a/app/modules/web/Controllers/ClientController.php b/app/modules/web/Controllers/ClientController.php index 7f94d375..1a79dd86 100644 --- a/app/modules/web/Controllers/ClientController.php +++ b/app/modules/web/Controllers/ClientController.php @@ -38,17 +38,16 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\ClientData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Client\Services\ClientService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\Grid\ClientGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\ClientForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; -use SP\Repositories\NoSuchItemException; -use SP\Services\Auth\AuthException; -use SP\Services\Client\ClientService; -use SP\Services\ServiceException; /** * Class ClientController @@ -165,7 +164,7 @@ final class ClientController extends ControllerBase implements CrudControllerInt * @throws NotFoundException * @throws QueryException * @throws SPException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ protected function setViewData(?int $clientId = null): void { diff --git a/app/modules/web/Controllers/ConfigBackupController.php b/app/modules/web/Controllers/ConfigBackupController.php index 7cb67e6b..a9ec9182 100644 --- a/app/modules/web/Controllers/ConfigBackupController.php +++ b/app/modules/web/Controllers/ConfigBackupController.php @@ -33,13 +33,13 @@ use SP\Core\Context\SessionContext; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SessionTimeout; +use SP\Domain\Export\Services\BackupFiles; +use SP\Domain\Export\Services\FileBackupService; +use SP\Domain\Export\Services\XmlExportService; +use SP\Domain\Export\Services\XmlVerifyService; use SP\Http\JsonResponse; +use SP\Infrastructure\File\FileHandler; use SP\Modules\Web\Controllers\Traits\ConfigTrait; -use SP\Services\Backup\BackupFiles; -use SP\Services\Backup\FileBackupService; -use SP\Services\Export\XmlExportService; -use SP\Services\Export\XmlVerifyService; -use SP\Storage\File\FileHandler; /** * Class ConfigBackupController diff --git a/app/modules/web/Controllers/ConfigEncryptionController.php b/app/modules/web/Controllers/ConfigEncryptionController.php index 925b607d..a878668f 100644 --- a/app/modules/web/Controllers/ConfigEncryptionController.php +++ b/app/modules/web/Controllers/ConfigEncryptionController.php @@ -27,19 +27,28 @@ namespace SP\Modules\Web\Controllers; use DI\DependencyException; use DI\NotFoundException; use Exception; +use Klein\Klein; +use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\Acl\UnauthorizedPageException; +use SP\Core\Application; use SP\Core\Crypt\Hash; use SP\Core\Crypt\Session as CryptSession; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; +use SP\Core\PhpExtensionChecker; +use SP\Core\UI\ThemeInterface; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Config\Services\ConfigService; +use SP\Domain\Crypt\MasterPassServiceInterface; +use SP\Domain\Crypt\Services\MasterPassService; +use SP\Domain\Crypt\Services\TemporaryMasterPassService; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; +use SP\Domain\Crypt\TemporaryMasterPassServiceInterface; +use SP\Domain\Task\Services\TaskFactory; use SP\Http\JsonResponse; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Traits\JsonTrait; -use SP\Services\Config\ConfigService; -use SP\Services\Crypt\MasterPassService; -use SP\Services\Crypt\TemporaryMasterPassService; -use SP\Services\Crypt\UpdateMasterPassRequest; -use SP\Services\Task\TaskFactory; /** * Class ConfigEncryptionController @@ -50,18 +59,36 @@ final class ConfigEncryptionController extends SimpleControllerBase { use JsonTrait; + private MasterPassServiceInterface $masterPassService; + private ConfigService $configService; + private TemporaryMasterPassService $temporaryMasterPassService; + + public function __construct( + Application $application, + ThemeInterface $theme, + Klein $router, + Acl $acl, + RequestInterface $request, + PhpExtensionChecker $extensionChecker, + MasterPassServiceInterface $masterPassService, + TemporaryMasterPassServiceInterface $temporaryMasterPassService, + ConfigServiceInterface $configService + ) { + parent::__construct($application, $theme, $router, $acl, $request, $extensionChecker); + + $this->masterPassService = $masterPassService; + $this->configService = $configService; + $this->temporaryMasterPassService = $temporaryMasterPassService; + } + /** * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException - * @throws \SP\Repositories\NoSuchItemException - * @throws \SP\Services\ServiceException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException */ public function saveAction(): bool { - $mastePassService = $this->dic->get(MasterPassService::class); - $currentMasterPass = $this->request->analyzeEncrypted('current_masterpass'); $newMasterPass = $this->request->analyzeEncrypted('new_masterpass'); $newMasterPassR = $this->request->analyzeEncrypted('new_masterpass_repeat'); @@ -69,7 +96,7 @@ final class ConfigEncryptionController extends SimpleControllerBase $noAccountPassChange = $this->request->analyzeBool('no_account_change', false); $taskId = $this->request->analyzeString('taskId'); - if (!$mastePassService->checkUserUpdateMPass($this->session->getUserData()->getLastUpdateMPass())) { + if (!$this->masterPassService->checkUserUpdateMPass($this->session->getUserData()->getLastUpdateMPass())) { return $this->returnJsonResponse( JsonResponse::JSON_SUCCESS_STICKY, __u('Master password updated'), @@ -105,7 +132,7 @@ final class ConfigEncryptionController extends SimpleControllerBase ); } - if (!$mastePassService->checkMasterPassword($currentMasterPass)) { + if (!$this->masterPassService->checkMasterPassword($currentMasterPass)) { return $this->returnJsonResponse( JsonResponse::JSON_ERROR, __u('The current master password does not match') @@ -127,8 +154,6 @@ final class ConfigEncryptionController extends SimpleControllerBase ); } - $configService = $this->dic->get(ConfigService::class); - if (!$noAccountPassChange) { try { $task = $taskId !== null @@ -138,7 +163,7 @@ final class ConfigEncryptionController extends SimpleControllerBase $request = new UpdateMasterPassRequest( $currentMasterPass, $newMasterPass, - $configService->getByParam(MasterPassService::PARAM_MASTER_PASS_HASH), + $this->configService->getByParam(MasterPassService::PARAM_MASTER_PASS_HASH), $task ); @@ -147,7 +172,7 @@ final class ConfigEncryptionController extends SimpleControllerBase new Event($this) ); - $mastePassService->changeMasterPassword($request); + $this->masterPassService->changeMasterPassword($request); $this->eventDispatcher->notifyEvent( 'update.masterPassword.end', @@ -157,7 +182,8 @@ final class ConfigEncryptionController extends SimpleControllerBase processException($e); $this->eventDispatcher->notifyEvent( - 'exception', new Event($e) + 'exception', + new Event($e) ); return $this->returnJsonResponseException($e); @@ -173,7 +199,7 @@ final class ConfigEncryptionController extends SimpleControllerBase new Event($this) ); - $mastePassService->updateConfig(Hash::hashKey($newMasterPass)); + $this->masterPassService->updateConfig(Hash::hashKey($newMasterPass)); } catch (Exception $e) { processException($e); @@ -214,8 +240,7 @@ final class ConfigEncryptionController extends SimpleControllerBase ); } - $masterPassService = $this->dic->get(MasterPassService::class); - $masterPassService->updateConfig(Hash::hashKey(CryptSession::getSessionKey($this->session))); + $this->masterPassService->updateConfig(Hash::hashKey(CryptSession::getSessionKey($this->session))); $this->eventDispatcher->notifyEvent( 'refresh.masterPassword.hash', @@ -250,26 +275,26 @@ final class ConfigEncryptionController extends SimpleControllerBase * Create a temporary master pass * * @return bool - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException */ public function saveTempAction(): bool { try { - $temporaryMasterPassService = $this->dic->get(TemporaryMasterPassService::class); - $key = $temporaryMasterPassService->create($this->request->analyzeInt('temporary_masterpass_maxtime', 3600)); + $key = + $this->temporaryMasterPassService->create( + $this->request->analyzeInt('temporary_masterpass_maxtime', 3600) + ); $groupId = $this->request->analyzeInt('temporary_masterpass_group', 0); $sendEmail = $this->configData->isMailEnabled() - && $this->request->analyzeBool('temporary_masterpass_email'); + && $this->request->analyzeBool('temporary_masterpass_email'); if ($sendEmail) { try { if ($groupId > 0) { - $temporaryMasterPassService->sendByEmailForGroup($groupId, $key); + $this->temporaryMasterPassService->sendByEmailForGroup($groupId, $key); } else { - $temporaryMasterPassService->sendByEmailForAllUsers($key); + $this->temporaryMasterPassService->sendByEmailForAllUsers($key); } return $this->returnJsonResponse( @@ -311,8 +336,6 @@ final class ConfigEncryptionController extends SimpleControllerBase /** * @return void - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \JsonException * @throws \SP\Core\Exceptions\SessionTimeout */ diff --git a/app/modules/web/Controllers/ConfigGeneralController.php b/app/modules/web/Controllers/ConfigGeneralController.php index 50a40793..5e7ae6ed 100644 --- a/app/modules/web/Controllers/ConfigGeneralController.php +++ b/app/modules/web/Controllers/ConfigGeneralController.php @@ -26,16 +26,16 @@ namespace SP\Modules\Web\Controllers; use Exception; use RuntimeException; -use SP\Config\ConfigUtil; use SP\Core\Acl\ActionsInterface; use SP\Core\Acl\UnauthorizedPageException; use SP\Core\Context\SessionContext; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; +use SP\Domain\Config\Services\ConfigBackupService; +use SP\Domain\Config\Services\ConfigUtil; use SP\Http\JsonResponse; +use SP\Infrastructure\File\FileHandler; use SP\Modules\Web\Controllers\Traits\ConfigTrait; -use SP\Services\Config\ConfigBackupService; -use SP\Storage\File\FileHandler; use SP\Util\Util; /** diff --git a/app/modules/web/Controllers/ConfigImportController.php b/app/modules/web/Controllers/ConfigImportController.php index 86bc571f..45b5cf39 100644 --- a/app/modules/web/Controllers/ConfigImportController.php +++ b/app/modules/web/Controllers/ConfigImportController.php @@ -35,11 +35,11 @@ use SP\Core\Context\SessionContext; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SessionTimeout; +use SP\Domain\Import\Services\FileImport; +use SP\Domain\Import\Services\ImportParams; +use SP\Domain\Import\Services\ImportService; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Traits\JsonTrait; -use SP\Services\Import\FileImport; -use SP\Services\Import\ImportParams; -use SP\Services\Import\ImportService; /** * Class ConfigImportController diff --git a/app/modules/web/Controllers/ConfigLdapController.php b/app/modules/web/Controllers/ConfigLdapController.php index a9580ff3..80071229 100644 --- a/app/modules/web/Controllers/ConfigLdapController.php +++ b/app/modules/web/Controllers/ConfigLdapController.php @@ -36,14 +36,14 @@ use SP\Core\Events\EventMessage; use SP\Core\Exceptions\CheckException; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; +use SP\Domain\Auth\Services\LdapCheckService; +use SP\Domain\Import\Services\LdapImportParams; +use SP\Domain\Import\Services\LdapImportService; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Traits\ConfigTrait; use SP\Mvc\View\Template; use SP\Providers\Auth\Ldap\LdapParams; use SP\Providers\Auth\Ldap\LdapTypeInterface; -use SP\Services\Ldap\LdapCheckService; -use SP\Services\Ldap\LdapImportParams; -use SP\Services\Ldap\LdapImportService; /** * Class ConfigLdapController diff --git a/app/modules/web/Controllers/ConfigMailController.php b/app/modules/web/Controllers/ConfigMailController.php index 56ceb048..38265005 100644 --- a/app/modules/web/Controllers/ConfigMailController.php +++ b/app/modules/web/Controllers/ConfigMailController.php @@ -27,15 +27,15 @@ namespace SP\Modules\Web\Controllers; use DI\DependencyException; use DI\NotFoundException; use Exception; -use SP\Config\ConfigUtil; use SP\Core\Acl\ActionsInterface; use SP\Core\Acl\UnauthorizedPageException; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; +use SP\Domain\Config\Services\ConfigUtil; +use SP\Domain\Notification\Services\MailService; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Traits\ConfigTrait; use SP\Providers\Mail\MailParams; -use SP\Services\Mail\MailService; /** * Class ConfigMailController diff --git a/app/modules/web/Controllers/ConfigManagerController.php b/app/modules/web/Controllers/ConfigManagerController.php index 52f9617c..bc75e145 100644 --- a/app/modules/web/Controllers/ConfigManagerController.php +++ b/app/modules/web/Controllers/ConfigManagerController.php @@ -39,7 +39,21 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\Language; -use SP\Core\MimeTypes; +use SP\Core\MimeTypesInterface; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Config\Services\ConfigService; +use SP\Domain\Crypt\Services\TemporaryMasterPassService; +use SP\Domain\Export\Services\BackupFiles; +use SP\Domain\Export\Services\XmlExportService; +use SP\Domain\Task\Services\Task; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserProfileService; +use SP\Domain\User\Services\UserService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; use SP\Modules\Web\Controllers\Helpers\TabsHelper; use SP\Mvc\View\Components\DataTab; use SP\Mvc\View\Components\SelectItemAdapter; @@ -49,21 +63,6 @@ use SP\Providers\Auth\Ldap\LdapStd; use SP\Providers\Auth\Ldap\LdapTypeInterface; use SP\Providers\Log\LogInterface; use SP\Providers\Mail\MailHandler; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountService; -use SP\Services\Auth\AuthException; -use SP\Services\Backup\BackupFiles; -use SP\Services\Config\ConfigService; -use SP\Services\Crypt\TemporaryMasterPassService; -use SP\Services\Export\XmlExportService; -use SP\Services\ServiceException; -use SP\Services\Task\Task; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserProfile\UserProfileService; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; use SP\Util\Util; /** @@ -155,42 +154,51 @@ final class ConfigManagerController extends ControllerBase $template->setBase('config'); $template->addTemplate('general'); - $template->assign('langs', + $template->assign( + 'langs', SelectItemAdapter::factory( Language::getAvailableLanguages() )->getItemsFromArraySelected([$this->configData->getSiteLang()]) ); - $template->assign('themes', + $template->assign( + 'themes', SelectItemAdapter::factory( $this->theme->getThemesAvailable() )->getItemsFromArraySelected([$this->configData->getSiteTheme()]) ); - $template->assign('isDemoMode', + $template->assign( + 'isDemoMode', $this->configData->isDemoEnabled() && !$this->userData->getIsAdminApp() ); - $template->assign('isDisabled', + $template->assign( + 'isDisabled', $this->configData->isDemoEnabled() && !$this->userData->getIsAdminApp() ? 'disabled' : '' ); - $template->assign('users', + $template->assign( + 'users', SelectItemAdapter::factory( UserService::getItemsBasic() )->getItemsFromModel() ); - $template->assign('userGroups', + $template->assign( + 'userGroups', SelectItemAdapter::factory( UserGroupService::getItemsBasic() )->getItemsFromModel() ); - $template->assign('userProfiles', + $template->assign( + 'userProfiles', SelectItemAdapter::factory( UserProfileService::getItemsBasic() )->getItemsFromModel() ); - $template->assign('curlIsAvailable', - $this->extensionChecker->checkCurlAvailable()); + $template->assign( + 'curlIsAvailable', + $this->extensionChecker->checkCurlAvailable() + ); $events = array_merge( LogInterface::EVENTS, @@ -199,7 +207,8 @@ final class ConfigManagerController extends ControllerBase sort($events, SORT_STRING); - $template->assign('logEvents', + $template->assign( + 'logEvents', SelectItemAdapter::factory($events) ->getItemsFromArraySelected( $this->configData->getLogEvents(), @@ -230,7 +239,7 @@ final class ConfigManagerController extends ControllerBase static function ($value) { return $value['type']; }, - $this->dic->get(MimeTypes::class)->getMimeTypes() + $this->dic->get(MimeTypesInterface::class)->getMimeTypes() ); $mimeTypes = SelectItemAdapter::factory( @@ -280,23 +289,31 @@ final class ConfigManagerController extends ControllerBase $template->setBase('config'); $template->addTemplate('ldap'); - $template->assign('ldapIsAvailable', - $this->extensionChecker->checkIsAvailable('ldap')); - $template->assign('userGroups', + $template->assign( + 'ldapIsAvailable', + $this->extensionChecker->checkIsAvailable('ldap') + ); + $template->assign( + 'userGroups', SelectItemAdapter::factory(UserGroupService::getItemsBasic()) - ->getItemsFromModel()); - $template->assign('userProfiles', + ->getItemsFromModel() + ); + $template->assign( + 'userProfiles', SelectItemAdapter::factory(UserProfileService::getItemsBasic()) - ->getItemsFromModel()); + ->getItemsFromModel() + ); $serverTypes = [ LdapTypeInterface::LDAP_STD => 'Standard', - LdapTypeInterface::LDAP_ADS => 'Active Directory' + LdapTypeInterface::LDAP_ADS => 'Active Directory', ]; - $template->assign('serverTypes', + $template->assign( + 'serverTypes', SelectItemAdapter::factory($serverTypes) - ->getItemsFromArraySelected([$this->configData->getLdapType()])); + ->getItemsFromArraySelected([$this->configData->getLdapType()]) + ); $userAttributes = array_merge( LdapStd::DEFAULT_FILTER_USER_ATTRIBUTES, @@ -304,9 +321,11 @@ final class ConfigManagerController extends ControllerBase $this->configData->getLdapFilterUserAttributes() ); - $template->assign('userAttributes', + $template->assign( + 'userAttributes', SelectItemAdapter::factory($userAttributes) - ->getItemsFromArraySelected($this->configData->getLdapFilterUserAttributes())); + ->getItemsFromArraySelected($this->configData->getLdapFilterUserAttributes()) + ); $groupAttributes = array_merge( LdapStd::DEFAULT_FILTER_GROUP_ATTRIBUTES, @@ -314,9 +333,11 @@ final class ConfigManagerController extends ControllerBase $this->configData->getLdapFilterGroupAttributes() ); - $template->assign('groupAttributes', + $template->assign( + 'groupAttributes', SelectItemAdapter::factory($groupAttributes) - ->getItemsFromArraySelected($this->configData->getLdapFilterGroupAttributes())); + ->getItemsFromArraySelected($this->configData->getLdapFilterGroupAttributes()) + ); return new DataTab(__('LDAP'), $template); } @@ -332,12 +353,14 @@ final class ConfigManagerController extends ControllerBase $template->addTemplate('mail'); $template->assign('mailSecurity', ['SSL', 'TLS']); - $template->assign('userGroups', + $template->assign( + 'userGroups', SelectItemAdapter::factory( UserGroupService::getItemsBasic() )->getItemsFromModel() ); - $template->assign('userProfiles', + $template->assign( + 'userProfiles', SelectItemAdapter::factory( UserProfileService::getItemsBasic() )->getItemsFromModel() @@ -370,7 +393,7 @@ final class ConfigManagerController extends ControllerBase * @throws ConstraintException * @throws QueryException * @throws NoSuchItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ protected function getEncryptionConfig(): DataTab { @@ -457,7 +480,8 @@ final class ConfigManagerController extends ControllerBase $exportFile = new FileHandler( XmlExportService::getExportFilename( BACKUP_PATH, - $this->configData->getExportHash() ?: '', true + $this->configData->getExportHash() ?: '', + true ) ); @@ -482,12 +506,14 @@ final class ConfigManagerController extends ControllerBase $exportFile->checkFileExists(); $template->assign('hasExport', true); - $template->assign('lastExportTime', + $template->assign( + 'lastExportTime', date('r', $exportFile->getFileTime()) ); } catch (FileException $e) { $template->assign('hasExport', false); - $template->assign('lastExportTime', + $template->assign( + 'lastExportTime', __('No export file found') ); } @@ -523,7 +549,7 @@ final class ConfigManagerController extends ControllerBase * @throws DependencyException * @throws NotFoundException * @throws NoSuchItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ protected function getInfo(): DataTab { @@ -536,7 +562,7 @@ final class ConfigManagerController extends ControllerBase $template->assign('dbInfo', $databaseUtil->getDBinfo()); $template->assign( 'dbName', - $this->configData->getDbName() . '@' . $this->configData->getDbHost() + $this->configData->getDbName().'@'.$this->configData->getDbHost() ); $template->assign( 'configBackupDate', diff --git a/app/modules/web/Controllers/ControllerBase.php b/app/modules/web/Controllers/ControllerBase.php index 9d60314f..10024a3b 100644 --- a/app/modules/web/Controllers/ControllerBase.php +++ b/app/modules/web/Controllers/ControllerBase.php @@ -29,8 +29,6 @@ defined('APP_ROOT') || die(); use Exception; use Klein\Klein; use Psr\Container\ContainerInterface; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; use SP\Core\Acl\Acl; use SP\Core\Application; use SP\Core\Bootstrap\BootstrapBase; @@ -43,13 +41,16 @@ use SP\Core\Exceptions\SPException; use SP\Core\PhpExtensionChecker; use SP\Core\UI\ThemeInterface; use SP\DataModel\ProfileData; -use SP\Http\Request; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Traits\WebControllerTrait; -use SP\Mvc\View\Template; -use SP\Providers\Auth\Browser\Browser; -use SP\Services\Auth\AuthException; -use SP\Services\User\UserLoginResponse; +use SP\Mvc\Controller\WebControllerHelper; +use SP\Mvc\View\TemplateInterface; +use SP\Providers\Auth\Browser\BrowserAuthInterface; /** * Clase base para los controladores @@ -63,22 +64,21 @@ abstract class ControllerBase // TODO: remove when controllers are ready protected ContainerInterface $dic; - protected EventDispatcher $eventDispatcher; - protected Config $config; - protected ContextInterface $session; + protected EventDispatcher $eventDispatcher; + protected ConfigFileService $config; + protected ContextInterface $session; protected ThemeInterface $theme; protected Klein $router; protected Acl $acl; protected ConfigDataInterface $configData; - protected Request $request; + protected RequestInterface $request; protected PhpExtensionChecker $extensionChecker; - protected Template $view; - protected ?string $actionName = null; + protected TemplateInterface $view; protected ?UserLoginResponse $userData = null; protected ?ProfileData $userProfileData = null; protected bool $isAjax; protected LayoutHelper $layoutHelper; - private Browser $browser; + private BrowserAuthInterface $browser; /** * @throws \SP\Core\Exceptions\SessionTimeout @@ -86,14 +86,7 @@ abstract class ControllerBase */ public function __construct( Application $application, - ThemeInterface $theme, - Klein $router, - Acl $acl, - Request $request, - PhpExtensionChecker $extensionChecker, - Template $template, - Browser $browser, - LayoutHelper $layoutHelper + WebControllerHelper $webControllerHelper ) { // TODO: remove when controllers are ready $this->dic = BootstrapBase::getContainer(); @@ -103,16 +96,16 @@ abstract class ControllerBase $this->configData = $this->config->getConfigData(); $this->eventDispatcher = $application->getEventDispatcher(); $this->session = $application->getContext(); - $this->theme = $theme; - $this->router = $router; - $this->acl = $acl; - $this->request = $request; - $this->extensionChecker = $extensionChecker; - $this->browser = $browser; - $this->layoutHelper = $layoutHelper; + $this->theme = $webControllerHelper->getTheme(); + $this->router = $webControllerHelper->getRouter(); + $this->acl = $webControllerHelper->getAcl(); + $this->request = $webControllerHelper->getRequest(); + $this->extensionChecker = $webControllerHelper->getExtensionChecker(); + $this->browser = $webControllerHelper->getBrowser(); + $this->layoutHelper = $webControllerHelper->getLayoutHelper(); + $this->view = $webControllerHelper->getTemplate(); - $this->view = $template; - $this->view->setBase(strtolower($this->controllerName)); + $this->view->setBase($this->getViewBaseName()); $this->isAjax = $this->request->isAjax(); $loggedIn = $this->session->isLoggedIn(); @@ -132,14 +125,12 @@ abstract class ControllerBase $this->initialize(); } } catch (SessionTimeout $sessionTimeout) { - $this->handleSessionTimeout( - function () { - return true; - } - ); + $this->handleSessionTimeout(static fn() => true); throw $sessionTimeout; } + + logger(static::class); } /** @@ -225,7 +216,7 @@ abstract class ControllerBase $this->view->assign( 'contentPage', - $page ?: strtolower($this->controllerName) + $page ?: strtolower($this->getViewBaseName()) ); try { @@ -258,7 +249,7 @@ abstract class ControllerBase * @param bool $requireAuthCompleted * * @throws \SP\Core\Exceptions\SessionTimeout - * @throws \SP\Services\Auth\AuthException + * @throws \SP\Domain\Auth\Services\AuthException */ protected function checkLoggedIn(bool $requireAuthCompleted = true): void { diff --git a/app/modules/web/Controllers/CustomFieldController.php b/app/modules/web/Controllers/CustomFieldController.php index 53ce173d..681082c1 100644 --- a/app/modules/web/Controllers/CustomFieldController.php +++ b/app/modules/web/Controllers/CustomFieldController.php @@ -36,18 +36,18 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\ValidationException; use SP\DataModel\CustomFieldDefinitionData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\CustomField\Services\CustomFieldDefService; +use SP\Domain\CustomField\Services\CustomFieldTypeService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\Grid\CustomFieldGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\CustomFieldDefForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Repositories\NoSuchItemException; -use SP\Services\Auth\AuthException; -use SP\Services\CustomField\CustomFieldDefService; -use SP\Services\CustomField\CustomFieldTypeService; /** * Class CustomFieldController diff --git a/app/modules/web/Controllers/ErrorController.php b/app/modules/web/Controllers/ErrorController.php index bbda186c..2fd75dc6 100644 --- a/app/modules/web/Controllers/ErrorController.php +++ b/app/modules/web/Controllers/ErrorController.php @@ -32,6 +32,7 @@ use SP\Core\Exceptions\FileNotFoundException; use SP\Core\Exceptions\SPException; use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Mvc\View\Template; +use SP\Mvc\View\TemplateInterface; /** * Class ErrorController @@ -40,15 +41,15 @@ use SP\Mvc\View\Template; */ final class ErrorController { - protected Template $view; - protected Klein $router; - protected LayoutHelper $layoutHelper; + protected TemplateInterface $view; + protected Klein $router; + protected LayoutHelper $layoutHelper; /** * ErrorController constructor. * - * @param Container $container - * @param string $actionName + * @param Container $container + * @param string $actionName * * @throws DependencyException * @throws NotFoundException @@ -98,9 +99,9 @@ final class ErrorController $this->view->append( 'errors', [ - 'type' => SPException::WARNING, + 'type' => SPException::WARNING, 'description' => __('Application on maintenance'), - 'hint' => __('It will be running shortly') + 'hint' => __('It will be running shortly'), ] ); @@ -117,9 +118,9 @@ final class ErrorController $this->view->append( 'errors', [ - 'type' => SPException::CRITICAL, + 'type' => SPException::CRITICAL, 'description' => __('Error while checking the database'), - 'hint' => __('Please contact to the administrator') + 'hint' => __('Please contact to the administrator'), ] ); @@ -136,9 +137,9 @@ final class ErrorController $this->view->append( 'errors', [ - 'type' => SPException::CRITICAL, + 'type' => SPException::CRITICAL, 'description' => __('Unable to connect to DB'), - 'hint' => __('Please contact to the administrator') + 'hint' => __('Please contact to the administrator'), ] ); diff --git a/app/modules/web/Controllers/EventlogController.php b/app/modules/web/Controllers/EventlogController.php index ae2a606c..69869ddb 100644 --- a/app/modules/web/Controllers/EventlogController.php +++ b/app/modules/web/Controllers/EventlogController.php @@ -34,12 +34,12 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Security\Services\EventlogService; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Helpers\Grid\EventlogGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Mvc\Controller\ItemTrait; -use SP\Services\Auth\AuthException; -use SP\Services\EventLog\EventlogService; /** * Class EventlogController diff --git a/app/modules/web/Controllers/Helpers/Account/AccountActionsHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountActionsHelper.php index 62252fb5..1226887c 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountActionsHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountActionsHelper.php @@ -27,11 +27,11 @@ namespace SP\Modules\Web\Controllers\Helpers\Account; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\Services\AccountAcl; +use SP\Domain\Account\Services\AccountSearchItem; use SP\Html\DataGrid\Action\DataGridAction; use SP\Html\DataGrid\Action\DataGridActionType; use SP\Modules\Web\Controllers\Helpers\HelperBase; -use SP\Services\Account\AccountAcl; -use SP\Services\Account\AccountSearchItem; /** * Class AccountIconsHelper @@ -41,7 +41,7 @@ use SP\Services\Account\AccountSearchItem; final class AccountActionsHelper extends HelperBase { protected ?ThemeIcons $icons = null; - protected ?string $sk = null; + protected ?string $sk = null; /** * @return DataGridAction @@ -75,16 +75,15 @@ final class AccountActionsHelper extends HelperBase /** * Set icons for view * - * @param AccountAcl $accountAcl - * @param AccountActionsDto $accountActionsDto + * @param AccountAcl $accountAcl + * @param AccountActionsDto $accountActionsDto * * @return DataGridAction[] */ public function getActionsForAccount( - AccountAcl $accountAcl, + AccountAcl $accountAcl, AccountActionsDto $accountActionsDto - ): array - { + ): array { $actions = []; $actionBack = $this->getBackAction(); @@ -294,16 +293,15 @@ final class AccountActionsHelper extends HelperBase /** * Set icons for view * - * @param AccountAcl $accountAcl - * @param AccountActionsDto $accountActionsDto + * @param AccountAcl $accountAcl + * @param AccountActionsDto $accountActionsDto * * @return DataGridAction[] */ public function getActionsGrouppedForAccount( - AccountAcl $accountAcl, + AccountAcl $accountAcl, AccountActionsDto $accountActionsDto - ): array - { + ): array { $userData = $this->context->getUserData(); $actions = []; diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php index 782df64c..033bbf01 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php @@ -24,14 +24,13 @@ namespace SP\Modules\Web\Controllers\Helpers\Account; -use DI\DependencyException; -use DI\NotFoundException; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use SP\Core\Acl\AccountPermissionException; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\Acl\UnauthorizedPageException; +use SP\Core\Application; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; @@ -40,25 +39,29 @@ use SP\DataModel\Dto\AccountAclDto; use SP\DataModel\Dto\AccountDetailsResponse; use SP\DataModel\ItemPreset\AccountPermission; use SP\DataModel\ItemPreset\AccountPrivate; +use SP\Domain\Account\AccountAclServiceInterface; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Account\PublicLinkServiceInterface; +use SP\Domain\Account\Services\AccountAcl; +use SP\Domain\Account\Services\PublicLinkService; +use SP\Domain\Category\CategoryServiceInterface; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Client\ClientServiceInterface; +use SP\Domain\Client\Services\ClientService; +use SP\Domain\Crypt\MasterPassServiceInterface; +use SP\Domain\ItemPreset\ItemPresetInterface; +use SP\Domain\ItemPreset\Services\ItemPresetService; +use SP\Domain\Tag\Services\TagService; +use SP\Domain\User\Services\UpdatedMasterPassException; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserService; +use SP\Http\RequestInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\HelperBase; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountAcl; -use SP\Services\Account\AccountAclService; -use SP\Services\Account\AccountHistoryService; -use SP\Services\Account\AccountService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Crypt\MasterPassService; -use SP\Services\ItemPreset\ItemPresetInterface; -use SP\Services\ItemPreset\ItemPresetService; -use SP\Services\PublicLink\PublicLinkService; -use SP\Services\ServiceException; -use SP\Services\Tag\TagService; -use SP\Services\User\UpdatedMasterPassException; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; +use SP\Mvc\View\TemplateInterface; use SP\Util\Link; /** @@ -70,15 +73,54 @@ final class AccountHelper extends HelperBase { use ItemTrait; - private ?Acl $acl = null; - private ?AccountService $accountService = null; - private ?AccountHistoryService $accountHistoryService = null; - private ?PublicLinkService $publicLinkService = null; - private ?ItemPresetService $itemPresetService = null; - private ?int $actionId = null; - private ?AccountAcl $accountAcl = null; - private ?int $accountId = null; - private bool $isView = false; + private Acl $acl; + private \SP\Domain\Account\AccountServiceInterface $accountService; + private AccountHistoryServiceInterface $accountHistoryService; + private PublicLinkService $publicLinkService; + private ItemPresetService $itemPresetService; + private MasterPassServiceInterface $masterPassService; + private AccountActionsHelper $accountActionsHelper; + private \SP\Domain\Account\AccountAclServiceInterface $accountAclService; + private CategoryService $categoryService; + private ClientService $clientService; + private ?int $actionId = null; + private ?AccountAcl $accountAcl = null; + private ?int $accountId = null; + private bool $isView = false; + + public function __construct( + Application $application, + TemplateInterface $template, + RequestInterface $request, + Acl $acl, + AccountServiceInterface $accountService, + \SP\Domain\Account\AccountHistoryServiceInterface $accountHistoryService, + PublicLinkServiceInterface $publicLinkService, + ItemPresetService $itemPresetService, + MasterPassServiceInterface $masterPassService, + AccountActionsHelper $accountActionsHelper, + AccountAclServiceInterface $accountAclService, + CategoryServiceInterface $categoryService, + ClientServiceInterface $clientService + ) { + parent::__construct($application, $template, $request); + + $this->acl = $acl; + $this->accountService = $accountService; + $this->accountHistoryService = $accountHistoryService; + $this->publicLinkService = $publicLinkService; + $this->itemPresetService = $itemPresetService; + $this->masterPassService = $masterPassService; + $this->accountActionsHelper = $accountActionsHelper; + $this->accountAclService = $accountAclService; + $this->categoryService = $categoryService; + $this->clientService = $clientService; + + $this->view->assign('changesHash'); + $this->view->assign('chkUserEdit', false); + $this->view->assign('chkGroupEdit', false); + } + /** * Sets account's view variables @@ -111,6 +153,7 @@ final class AccountHelper extends HelperBase $accountData->getParentId() ); + // FIXME: use IoC $selectUsers = SelectItemAdapter::factory(UserService::getItemsBasic()); $selectUserGroups = SelectItemAdapter::factory(UserGroupService::getItemsBasic()); $selectTags = SelectItemAdapter::factory(TagService::getItemsBasic()); @@ -205,8 +248,7 @@ final class AccountHelper extends HelperBase $accountActionsDto->setPublicLinkId($publicLinkData->getId()); $accountActionsDto->setPublicLinkCreatorId($publicLinkData->getUserId()); - $baseUrl = ($this->configData->getApplicationUrl() - ?: BootstrapBase::$WEBURI).BootstrapBase::$SUBURI; + $baseUrl = ($this->configData->getApplicationUrl() ?: BootstrapBase::$WEBURI).BootstrapBase::$SUBURI; $this->view->assign( 'publicLinkUrl', @@ -265,18 +307,16 @@ final class AccountHelper extends HelperBase $this->view->assign('accountData', $accountData); $this->view->assign('gotData', true); - $accountActionsHelper = $this->dic->get(AccountActionsHelper::class); - $this->view->assign( 'accountActions', - $accountActionsHelper->getActionsForAccount( + $this->accountActionsHelper->getActionsForAccount( $this->accountAcl, $accountActionsDto ) ); $this->view->assign( 'accountActionsMenu', - $accountActionsHelper->getActionsGrouppedForAccount( + $this->accountActionsHelper->getActionsGrouppedForAccount( $this->accountAcl, $accountActionsDto ) @@ -289,9 +329,7 @@ final class AccountHelper extends HelperBase * @throws NoSuchItemException * @throws UnauthorizedPageException * @throws UpdatedMasterPassException - * @throws DependencyException - * @throws NotFoundException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function checkActionAccess(): void { @@ -299,8 +337,7 @@ final class AccountHelper extends HelperBase throw new UnauthorizedPageException(SPException::INFO); } - if (!$this->dic->get(MasterPassService::class) - ->checkUserUpdateMPass($this->context->getUserData()->getLastUpdateMPass()) + if (!$this->masterPassService->checkUserUpdateMPass($this->context->getUserData()->getLastUpdateMPass()) ) { throw new UpdatedMasterPassException(SPException::INFO); } @@ -313,21 +350,17 @@ final class AccountHelper extends HelperBase * * @return AccountAcl * @throws AccountPermissionException - * @throws DependencyException - * @throws NotFoundException * @throws ConstraintException * @throws QueryException */ protected function checkAccess(AccountDetailsResponse $accountDetailsResponse): AccountAcl { - $accountAcl = $this->dic->get(AccountAclService::class) - ->getAcl( - $this->actionId, - AccountAclDto::makeFromAccount($accountDetailsResponse) - ); + $accountAcl = $this->accountAclService->getAcl( + $this->actionId, + AccountAclDto::makeFromAccount($accountDetailsResponse) + ); - if ($accountAcl === null - || $accountAcl->checkAccountAccess($this->actionId) === false) { + if ($accountAcl->checkAccountAccess($this->actionId) === false) { throw new AccountPermissionException(SPException::INFO); } @@ -337,12 +370,10 @@ final class AccountHelper extends HelperBase /** * Sets account's view common data * - * @throws ConstraintException - * @throws DependencyException - * @throws NotFoundException - * @throws QueryException - * @throws SPException - * @throws ServiceException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\SPException + * @throws \SP\Domain\Common\Services\ServiceException */ protected function setViewCommon(): void { @@ -361,15 +392,13 @@ final class AccountHelper extends HelperBase $this->view->assign( 'categories', SelectItemAdapter::factory( - $this->dic->get(CategoryService::class) - ->getAllBasic() + $this->categoryService->getAllBasic() )->getItemsFromModel() ); $this->view->assign( 'clients', SelectItemAdapter::factory( - $this->dic->get(ClientService::class) - ->getAllForUser() + $this->clientService->getAllForUser() )->getItemsFromModel() ); $this->view->assign( @@ -451,16 +480,14 @@ final class AccountHelper extends HelperBase * @param int $actionId * * @return void - * @throws \DI\DependencyException - * @throws \DI\NotFoundException * @throws \SP\Core\Acl\UnauthorizedPageException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\NoSuchPropertyException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Repositories\NoSuchItemException - * @throws \SP\Services\ServiceException - * @throws \SP\Services\User\UpdatedMasterPassException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \SP\Domain\User\Services\UpdatedMasterPassException */ public function setViewForBlank(int $actionId): void { @@ -492,6 +519,7 @@ final class AccountHelper extends HelperBase $accountPermission = $itemPresetPermission->hydrate(AccountPermission::class) ?: $accountPermission; } + // FIXME: Use IoC $selectUsers = SelectItemAdapter::factory(UserService::getItemsBasic()); $selectUserGroups = SelectItemAdapter::factory(UserGroupService::getItemsBasic()); $selectTags = SelectItemAdapter::factory(TagService::getItemsBasic()); @@ -548,11 +576,10 @@ final class AccountHelper extends HelperBase $this->view->assign('gotData', false); $this->view->assign( 'accountActions', - $this->dic->get(AccountActionsHelper::class) - ->getActionsForAccount( - $this->accountAcl, - new AccountActionsDto($this->accountId) - ) + $this->accountActionsHelper->getActionsForAccount( + $this->accountAcl, + new AccountActionsDto($this->accountId) + ) ); $this->setViewCommon(); @@ -565,12 +592,10 @@ final class AccountHelper extends HelperBase * @param int $actionId * * @return bool - * @throws NoSuchItemException - * @throws UnauthorizedPageException - * @throws UpdatedMasterPassException - * @throws DependencyException - * @throws NotFoundException - * @throws ServiceException + * @throws \SP\Core\Acl\UnauthorizedPageException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \SP\Domain\User\Services\UpdatedMasterPassException */ public function setViewForRequest( AccountDetailsResponse $accountDetailsResponse, @@ -595,15 +620,14 @@ final class AccountHelper extends HelperBase $this->view->assign( 'accountActions', - $this->dic->get(AccountActionsHelper::class) - ->getActionsForAccount( - $this->accountAcl, - new AccountActionsDto( - $this->accountId, - null, - $accountData->getParentId() - ) + $this->accountActionsHelper->getActionsForAccount( + $this->accountAcl, + new AccountActionsDto( + $this->accountId, + null, + $accountData->getParentId() ) + ) ); return true; @@ -616,21 +640,4 @@ final class AccountHelper extends HelperBase { $this->isView = $isView; } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->acl = $this->dic->get(Acl::class); - $this->accountService = $this->dic->get(AccountService::class); - $this->accountHistoryService = $this->dic->get(AccountHistoryService::class); - $this->publicLinkService = $this->dic->get(PublicLinkService::class); - $this->itemPresetService = $this->dic->get(ItemPresetService::class); - - $this->view->assign('changesHash'); - $this->view->assign('chkUserEdit', false); - $this->view->assign('chkGroupEdit', false); - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php index 7ec712b9..8b6ba243 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php @@ -24,29 +24,25 @@ namespace SP\Modules\Web\Controllers\Helpers\Account; -use DI\DependencyException; -use DI\NotFoundException; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; use SP\Core\Acl\AccountPermissionException; use SP\Core\Acl\Acl; use SP\Core\Acl\UnauthorizedPageException; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\AccountHistoryData; use SP\DataModel\Dto\AccountAclDto; +use SP\Domain\Account\AccountAclServiceInterface; +use SP\Domain\Account\Services\AccountAcl; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Client\Services\ClientService; +use SP\Domain\Crypt\MasterPassServiceInterface; +use SP\Domain\User\Services\UpdatedMasterPassException; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\HelperBase; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountAcl; -use SP\Services\Account\AccountAclService; -use SP\Services\Account\AccountHistoryService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Crypt\MasterPassService; -use SP\Services\ServiceException; -use SP\Services\User\UpdatedMasterPassException; +use SP\Mvc\View\TemplateInterface; /** * Class AccountHistoryHelper @@ -55,34 +51,54 @@ use SP\Services\User\UpdatedMasterPassException; */ final class AccountHistoryHelper extends HelperBase { - protected ?Acl $acl = null; - protected ?AccountHistoryService $accountHistoryService = null; - protected ?int $accountId = null; - protected ?int $actionId = null; - protected ?int $accountHistoryId = null; - protected ?AccountAcl $accountAcl = null; + private Acl $acl; + private \SP\Domain\Account\AccountHistoryServiceInterface $accountHistoryService; + private AccountActionsHelper $accountActionsHelper; + private MasterPassServiceInterface $masterPassService; + private AccountAclServiceInterface $accountAclService; + private ?int $accountId = null; + private ?int $actionId = null; + private ?AccountAcl $accountAcl = null; + + public function __construct( + Application $application, + TemplateInterface $template, + RequestInterface $request, + Acl $acl, + \SP\Domain\Account\AccountHistoryServiceInterface $accountHistoryService, + AccountActionsHelper $accountActionsHelper, + MasterPassServiceInterface $masterPassService, + AccountAclServiceInterface $accountAclService + ) { + $this->acl = $acl; + $this->accountHistoryService = $accountHistoryService; + $this->accountActionsHelper = $accountActionsHelper; + $this->masterPassService = $masterPassService; + $this->accountAclService = $accountAclService; + + parent::__construct($application, $template, $request); + } + /** - * @param AccountHistoryData $accountHistoryData - * @param int $actionId + * @param AccountHistoryData $accountHistoryData + * @param int $actionId * - * @throws AccountPermissionException - * @throws UnauthorizedPageException - * @throws UpdatedMasterPassException - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException - * @throws NoSuchItemException - * @throws ServiceException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + * @throws \SP\Core\Acl\AccountPermissionException + * @throws \SP\Core\Acl\UnauthorizedPageException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \SP\Domain\User\Services\UpdatedMasterPassException */ public function setView( AccountHistoryData $accountHistoryData, - int $actionId - ): void - { + int $actionId + ): void { $this->actionId = $actionId; - $this->accountHistoryId = $accountHistoryData->getId(); $this->accountId = $accountHistoryData->getAccountId(); $this->checkActionAccess(); @@ -98,7 +114,8 @@ final class AccountHistoryHelper extends HelperBase $this->view->assign( 'historyData', SelectItemAdapter::factory($this->accountHistoryService->getHistoryForAccount($this->accountId)) - ->getItemsFromArraySelected([$this->accountHistoryId])); + ->getItemsFromArraySelected([$accountHistoryData->getId()]) + ); $this->view->assign( 'accountPassDate', @@ -110,11 +127,13 @@ final class AccountHistoryHelper extends HelperBase ); $this->view->assign( 'categories', + // FIXME: use IoC SelectItemAdapter::factory(CategoryService::getItemsBasic()) ->getItemsFromModelSelected([$accountHistoryData->getCategoryId()]) ); $this->view->assign( 'clients', + // FIXME: use IoC SelectItemAdapter::factory(ClientService::getItemsBasic()) ->getItemsFromModelSelected([$accountHistoryData->getClientId()]) ); @@ -123,31 +142,27 @@ final class AccountHistoryHelper extends HelperBase strtotime($accountHistoryData->getDateEdit()) !== false ); - $accountActionsHelper = $this->dic->get(AccountActionsHelper::class); - $accountActionsDto = new AccountActionsDto( $this->accountId, - $this->accountHistoryId, + $accountHistoryData->getId(), 0 ); $this->view->assign( 'accountActions', - $accountActionsHelper->getActionsForAccount($this->accountAcl, $accountActionsDto) + $this->accountActionsHelper->getActionsForAccount($this->accountAcl, $accountActionsDto) ); $this->view->assign( 'accountActionsMenu', - $accountActionsHelper->getActionsGrouppedForAccount($this->accountAcl, $accountActionsDto) + $this->accountActionsHelper->getActionsGrouppedForAccount($this->accountAcl, $accountActionsDto) ); } /** - * @throws UnauthorizedPageException - * @throws UpdatedMasterPassException - * @throws DependencyException - * @throws NotFoundException - * @throws NoSuchItemException - * @throws ServiceException + * @throws \SP\Core\Acl\UnauthorizedPageException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \SP\Domain\User\Services\UpdatedMasterPassException */ protected function checkActionAccess(): void { @@ -155,9 +170,7 @@ final class AccountHistoryHelper extends HelperBase throw new UnauthorizedPageException(SPException::INFO); } - if (!$this->dic->get(MasterPassService::class) - ->checkUserUpdateMPass($this->context->getUserData()->getLastUpdateMPass()) - ) { + if (!$this->masterPassService->checkUserUpdateMPass($this->context->getUserData()->getLastUpdateMPass())) { throw new UpdatedMasterPassException(SPException::INFO); } } @@ -165,11 +178,9 @@ final class AccountHistoryHelper extends HelperBase /** * Comprobar si el usuario dispone de acceso al módulo * - * @param AccountHistoryData $accountHistoryData + * @param AccountHistoryData $accountHistoryData * * @throws AccountPermissionException - * @throws DependencyException - * @throws NotFoundException * @throws ConstraintException * @throws QueryException */ @@ -181,25 +192,10 @@ final class AccountHistoryHelper extends HelperBase $this->accountHistoryService->getUserGroupsByAccountId($this->accountId) ); - $this->accountAcl = $this->dic->get(AccountAclService::class) - ->getAcl($this->actionId, $acccountAclDto, true); + $this->accountAcl = $this->accountAclService->getAcl($this->actionId, $acccountAclDto, true); - if ($this->accountAcl === null - || $this->accountAcl->checkAccountAccess($this->actionId) === false - ) { + if ($this->accountAcl->checkAccountAccess($this->actionId) === false) { throw new AccountPermissionException(SPException::INFO); } } - - /** - * Initialize class - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->acl = $this->dic->get(Acl::class); - $this->accountHistoryService = $this->dic->get(AccountHistoryService::class); - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php index 45db46ef..0e4001b6 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountPasswordHelper.php @@ -24,20 +24,17 @@ namespace SP\Modules\Web\Controllers\Helpers\Account; -use Defuse\Crypto\Exception\CryptoException; -use DI\DependencyException; -use DI\NotFoundException; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Session as CryptSession; -use SP\Core\Exceptions\FileNotFoundException; use SP\DataModel\AccountPassData; +use SP\Domain\Crypt\MasterPassServiceInterface; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\HelperBase; use SP\Modules\Web\Controllers\Helpers\HelperException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Crypt\MasterPassService; -use SP\Services\ServiceException; +use SP\Mvc\View\TemplateInterface; use SP\Util\ImageUtil; /** @@ -47,27 +44,44 @@ use SP\Util\ImageUtil; */ final class AccountPasswordHelper extends HelperBase { - private ?Acl $acl = null; + private Acl $acl; + private ImageUtil $imageUtil; + private MasterPassServiceInterface $masterPassService; + + public function __construct( + Application $application, + TemplateInterface $template, + RequestInterface $request, + Acl $acl, + ImageUtil $imageUtil, + MasterPassServiceInterface $masterPassService + ) { + parent::__construct($application, $template, $request); + + $this->acl = $acl; + $this->imageUtil = $imageUtil; + $this->masterPassService = $masterPassService; + } /** - * @param AccountPassData $accountData + * @param AccountPassData $accountData * - * @param bool $useImage + * @param bool $useImage * * @return array - * @throws HelperException - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws FileNotFoundException - * @throws NoSuchItemException - * @throws ServiceException + * @throws \Defuse\Crypto\Exception\BadFormatException + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException + * @throws \SP\Core\Exceptions\FileNotFoundException + * @throws \SP\Modules\Web\Controllers\Helpers\HelperException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException */ public function getPasswordView( AccountPassData $accountData, - bool $useImage - ): array - { + bool $useImage + ): array { $this->checkActionAccess(); $this->view->addTemplate('viewpass'); @@ -78,15 +92,13 @@ final class AccountPasswordHelper extends HelperBase $pass = $this->getPasswordClear($accountData); if ($useImage) { - $imageUtil = $this->dic->get(ImageUtil::class); - $this->view->assign( 'login', - $imageUtil->convertText($accountData->getLogin()) + $this->imageUtil->convertText($accountData->getLogin()) ); $this->view->assign( 'pass', - $imageUtil->convertText($pass) + $this->imageUtil->convertText($pass) ); } else { $this->view->assign('login', $accountData->getLogin()); @@ -98,7 +110,7 @@ final class AccountPasswordHelper extends HelperBase return [ 'useimage' => $useImage, - 'html' => $this->view->render() + 'html' => $this->view->render(), ]; } @@ -115,25 +127,26 @@ final class AccountPasswordHelper extends HelperBase /** * Returns account's password * - * @param AccountPassData $accountData + * @param AccountPassData $accountData * * @return string - * @throws HelperException - * @throws DependencyException - * @throws NotFoundException - * @throws CryptoException - * @throws NoSuchItemException - * @throws ServiceException + * @throws \Defuse\Crypto\Exception\BadFormatException + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException + * @throws \SP\Modules\Web\Controllers\Helpers\HelperException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException */ public function getPasswordClear(AccountPassData $accountData): string { $this->checkActionAccess(); - if (!$this->dic->get(MasterPassService::class)->checkUserUpdateMPass($this->context->getUserData()->getLastUpdateMPass())) { + if (!$this->masterPassService->checkUserUpdateMPass($this->context->getUserData()->getLastUpdateMPass())) { throw new HelperException( __('Master password updated') - . '
' - . __('Please, restart the session for update it') + .'
' + .__('Please, restart the session for update it') ); } @@ -145,13 +158,4 @@ final class AccountPasswordHelper extends HelperBase ) ); } - - /** - * @throws DependencyException - * @throws NotFoundException - */ - protected function initialize(): void - { - $this->acl = $this->dic->get(Acl::class); - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/Helpers/Account/AccountSearchHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountSearchHelper.php index 6662ed33..b86e0049 100644 --- a/app/modules/web/Controllers/Helpers/Account/AccountSearchHelper.php +++ b/app/modules/web/Controllers/Helpers/Account/AccountSearchHelper.php @@ -28,9 +28,17 @@ use DI\DependencyException; use DI\NotFoundException; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; +use SP\DataModel\ProfileData; +use SP\DataModel\UserPreferencesData; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Domain\Account\Services\AccountSearchItem; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Client\ClientServiceInterface; +use SP\Domain\Tag\Services\TagService; use SP\Html\DataGrid\Action\DataGridAction; use SP\Html\DataGrid\Action\DataGridActionSearch; use SP\Html\DataGrid\DataGrid; @@ -38,14 +46,10 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridSort; use SP\Html\DataGrid\Layout\DataGridHeaderSort; use SP\Html\DataGrid\Layout\DataGridPager; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\HelperBase; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Services\Account\AccountSearchFilter; -use SP\Services\Account\AccountSearchItem; -use SP\Services\Account\AccountSearchService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Tag\TagService; +use SP\Mvc\View\TemplateInterface; /** * Class AccountSearch @@ -57,19 +61,35 @@ final class AccountSearchHelper extends HelperBase /** * @var bool Indica si el filtrado de cuentas está activo */ - private bool $filterOn = false; - private int $queryTimeStart = 0; - private bool $isAjax = false; - private bool $isIndex = false; - private ?AccountSearchFilter $accountSearchFilter = null; + private bool $filterOn = false; + private int $queryTimeStart = 0; + private bool $isAjax = false; + private bool $isIndex = false; + private ?AccountSearchFilter $accountSearchFilter = null; + private ClientServiceInterface $clientService; + private \SP\Domain\Account\AccountSearchServiceInterface $accountSearchService; + private AccountActionsHelper $accountActionsHelper; + + public function __construct( + Application $application, + TemplateInterface $template, + RequestInterface $request, + ClientServiceInterface $clientService, + \SP\Domain\Account\AccountSearchServiceInterface $accountSearchService, + AccountActionsHelper $accountActionsHelper + ) { + parent::__construct($application, $template, $request); + + $this->clientService = $clientService; + $this->accountSearchService = $accountSearchService; + $this->accountActionsHelper = $accountActionsHelper; + } /** * Obtener los datos para la caja de búsqueda * - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ public function getSearchBox(): void { @@ -77,20 +97,19 @@ final class AccountSearchHelper extends HelperBase $this->view->assign( 'clients', - SelectItemAdapter::factory( - $this->dic->get(ClientService::class) - ->getAllForUser())->getItemsFromModelSelected([$this->accountSearchFilter->getClientId()]) + SelectItemAdapter::factory($this->clientService->getAllForUser()) + ->getItemsFromModelSelected( + [$this->accountSearchFilter->getClientId()] + ) ); $this->view->assign( 'categories', - SelectItemAdapter::factory( - CategoryService::getItemsBasic()) + SelectItemAdapter::factory(CategoryService::getItemsBasic()) ->getItemsFromModelSelected([$this->accountSearchFilter->getCategoryId()]) ); $this->view->assign( 'tags', - SelectItemAdapter::factory( - TagService::getItemsBasic()) + SelectItemAdapter::factory(TagService::getItemsBasic()) ->getItemsFromModelSelected($this->accountSearchFilter->getTagsId()) ); } @@ -111,14 +130,14 @@ final class AccountSearchHelper extends HelperBase $this->view->assign('isAjax', $this->isAjax); $this->filterOn = ($this->accountSearchFilter->getSortKey() > 1 - || $this->accountSearchFilter->getClientId() - || $this->accountSearchFilter->getCategoryId() - || $this->accountSearchFilter->getTagsId() - || $this->accountSearchFilter->getTxtSearch() - || $this->accountSearchFilter->isSearchFavorites() - || $this->accountSearchFilter->isSortViews()); + || $this->accountSearchFilter->getClientId() + || $this->accountSearchFilter->getCategoryId() + || $this->accountSearchFilter->getTagsId() + || $this->accountSearchFilter->getTxtSearch() + || $this->accountSearchFilter->isSearchFavorites() + || $this->accountSearchFilter->isSortViews()); - $userPreferences = $this->context->getUserData()->getPreferences(); + $userPreferences = $this->context->getUserData()->getPreferences() ?? new UserPreferencesData(); AccountSearchItem::$accountLink = $userPreferences->isAccountLink(); AccountSearchItem::$topNavbar = $userPreferences->isTopNavbar(); @@ -147,15 +166,11 @@ final class AccountSearchHelper extends HelperBase ); } - $accountSearchService = $this->dic->get(AccountSearchService::class); - $dataGrid = $this->getGrid(); - $dataGrid->getData() - ->setData($accountSearchService->processSearchResults($this->accountSearchFilter)); + $dataGrid->getData()->setData($this->accountSearchService->processSearchResults($this->accountSearchFilter)); $dataGrid->updatePager(); $dataGrid->setTime(round(getElapsedTime($this->queryTimeStart), 5)); - // Establecer el filtro de búsqueda en la sesión como un objeto $this->context->setSearchFilters($this->accountSearchFilter); @@ -197,13 +212,11 @@ final class AccountSearchHelper extends HelperBase $gridPager->setFilterOn($this->filterOn); $gridPager->setSourceAction(new DataGridActionSearch(ActionsInterface::ACCOUNT_SEARCH)); - $userPreferences = $this->context->getUserData()->getPreferences(); + $userPreferences = $this->context->getUserData()->getPreferences() ?? new UserPreferencesData(); $showOptionalActions = $userPreferences->isOptionalActions() - || $userPreferences->isResultsAsCards() - || ($userPreferences->getUserId() === 0 - && $this->configData->isResultsAsCards()); - - $actions = $this->dic->get(AccountActionsHelper::class); + || $userPreferences->isResultsAsCards() + || ($userPreferences->getUserId() === 0 + && $this->configData->isResultsAsCards()); $dataGrid = new DataGrid($this->view->getTheme()); $dataGrid->setId('gridSearch'); @@ -217,22 +230,22 @@ final class AccountSearchHelper extends HelperBase 'grid' ); $dataGrid->setHeader($this->getHeaderSort()); - $dataGrid->addDataAction($actions->getViewAction()); - $dataGrid->addDataAction($actions->getViewPassAction()); - $dataGrid->addDataAction($actions->getCopyPassAction()); + $dataGrid->addDataAction($this->accountActionsHelper->getViewAction()); + $dataGrid->addDataAction($this->accountActionsHelper->getViewPassAction()); + $dataGrid->addDataAction($this->accountActionsHelper->getCopyPassAction()); $dataGrid->addDataAction( - $actions->getEditAction(), + $this->accountActionsHelper->getEditAction(), !$showOptionalActions ); $dataGrid->addDataAction( - $actions->getCopyAction(), + $this->accountActionsHelper->getCopyAction(), !$showOptionalActions ); $dataGrid->addDataAction( - $actions->getDeleteAction(), + $this->accountActionsHelper->getDeleteAction(), !$showOptionalActions ); - $dataGrid->addDataAction($actions->getRequestAction()); + $dataGrid->addDataAction($this->accountActionsHelper->getRequestAction()); $dataGrid->setPager($gridPager); $dataGrid->setData(new DataGridData()); @@ -306,59 +319,31 @@ final class AccountSearchHelper extends HelperBase /** * Establecer las variables necesarias para las plantillas */ - private function setVars() + private function setVars(): void { $userData = $this->context->getUserData(); - $this->view->assign('isAdmin', - $userData->getIsAdminApp() - || $userData->getIsAdminAcc()); - $this->view->assign('showGlobalSearch', - $this->configData->isGlobalSearch() - && $this->context->getUserProfile()->isAccGlobalSearch()); + $this->view->assign('isAdmin', $userData->getIsAdminApp() || $userData->getIsAdminAcc()); + + $profileData = $this->context->getUserProfile() ?? new ProfileData(); + + $this->view->assign( + 'showGlobalSearch', + $this->configData->isGlobalSearch() && $profileData->isAccGlobalSearch() + ); $this->accountSearchFilter = $this->getFilters(); - $this->view->assign( - 'searchCustomer', - $this->accountSearchFilter->getClientId() - ); - $this->view->assign( - 'searchCategory', - $this->accountSearchFilter->getCategoryId() - ); - $this->view->assign( - 'searchTags', - $this->accountSearchFilter->getTagsId() - ); - $this->view->assign( - 'searchTxt', - $this->accountSearchFilter->getTxtSearch() - ); - $this->view->assign( - 'searchGlobal', - $this->accountSearchFilter->getGlobalSearch() - ); - $this->view->assign( - 'searchFavorites', - $this->accountSearchFilter->isSearchFavorites() - ); - $this->view->assign( - 'searchRoute', - Acl::getActionRoute(ActionsInterface::ACCOUNT_SEARCH) - ); - $this->view->assign( - 'favoriteRouteOn', - Acl::getActionRoute(ActionsInterface::ACCOUNT_FAVORITE_ADD) - ); - $this->view->assign( - 'favoriteRouteOff', - Acl::getActionRoute(ActionsInterface::ACCOUNT_FAVORITE_DELETE) - ); - $this->view->assign( - 'viewAccountRoute', - Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW) - ); + $this->view->assign('searchCustomer', $this->accountSearchFilter->getClientId()); + $this->view->assign('searchCategory', $this->accountSearchFilter->getCategoryId()); + $this->view->assign('searchTags', $this->accountSearchFilter->getTagsId()); + $this->view->assign('searchTxt', $this->accountSearchFilter->getTxtSearch()); + $this->view->assign('searchGlobal', $this->accountSearchFilter->getGlobalSearch()); + $this->view->assign('searchFavorites', $this->accountSearchFilter->isSearchFavorites()); + $this->view->assign('searchRoute', Acl::getActionRoute(ActionsInterface::ACCOUNT_SEARCH)); + $this->view->assign('favoriteRouteOn', Acl::getActionRoute(ActionsInterface::ACCOUNT_FAVORITE_ADD)); + $this->view->assign('favoriteRouteOff', Acl::getActionRoute(ActionsInterface::ACCOUNT_FAVORITE_DELETE)); + $this->view->assign('viewAccountRoute', Acl::getActionRoute(ActionsInterface::ACCOUNT_VIEW)); } /** @@ -375,7 +360,7 @@ final class AccountSearchHelper extends HelperBase return $accountSearchFilter; } - $userPreferences = $this->context->getUserData()->getPreferences(); + $userPreferences = $this->context->getUserData()->getPreferences() ?? new UserPreferencesData(); $limitCount = $userPreferences->getResultsPerPage() > 0 ? $userPreferences->getResultsPerPage() : $this->configData->getAccountCount(); diff --git a/app/modules/web/Controllers/Helpers/Grid/AccountGrid.php b/app/modules/web/Controllers/Helpers/Grid/AccountGrid.php index b38ebbcf..08fac702 100644 --- a/app/modules/web/Controllers/Helpers/Grid/AccountGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/AccountGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/AccountHistoryGrid.php b/app/modules/web/Controllers/Helpers/Grid/AccountHistoryGrid.php index 76830c54..67011041 100644 --- a/app/modules/web/Controllers/Helpers/Grid/AccountHistoryGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/AccountHistoryGrid.php @@ -33,7 +33,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountHistoryGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/AuthTokenGrid.php b/app/modules/web/Controllers/Helpers/Grid/AuthTokenGrid.php index 9f15e761..39a87f52 100644 --- a/app/modules/web/Controllers/Helpers/Grid/AuthTokenGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/AuthTokenGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class AuthTokenGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/CategoryGrid.php b/app/modules/web/Controllers/Helpers/Grid/CategoryGrid.php index 1f7652cb..71988f90 100644 --- a/app/modules/web/Controllers/Helpers/Grid/CategoryGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/CategoryGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class CategoryGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/ClientGrid.php b/app/modules/web/Controllers/Helpers/Grid/ClientGrid.php index e01b6659..72d2c130 100644 --- a/app/modules/web/Controllers/Helpers/Grid/ClientGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/ClientGrid.php @@ -33,7 +33,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class ClientGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/CustomFieldGrid.php b/app/modules/web/Controllers/Helpers/Grid/CustomFieldGrid.php index b82269c1..3651011c 100644 --- a/app/modules/web/Controllers/Helpers/Grid/CustomFieldGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/CustomFieldGrid.php @@ -26,6 +26,7 @@ namespace SP\Modules\Web\Controllers\Helpers\Grid; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Domain\CustomField\Services\CustomFieldDefService; use SP\Html\DataGrid\Action\DataGridAction; use SP\Html\DataGrid\Action\DataGridActionSearch; use SP\Html\DataGrid\Action\DataGridActionType; @@ -33,8 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Services\CustomField\CustomFieldDefService; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class CustomFieldGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/EventlogGrid.php b/app/modules/web/Controllers/Helpers/Grid/EventlogGrid.php index 405bd7d3..2540f142 100644 --- a/app/modules/web/Controllers/Helpers/Grid/EventlogGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/EventlogGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class EventlogGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/FileGrid.php b/app/modules/web/Controllers/Helpers/Grid/FileGrid.php index fc78540c..81ce525c 100644 --- a/app/modules/web/Controllers/Helpers/Grid/FileGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/FileGrid.php @@ -33,7 +33,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class FileGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/GridInterface.php b/app/modules/web/Controllers/Helpers/Grid/GridInterface.php index affc4c9b..2eeed70f 100644 --- a/app/modules/web/Controllers/Helpers/Grid/GridInterface.php +++ b/app/modules/web/Controllers/Helpers/Grid/GridInterface.php @@ -25,7 +25,7 @@ namespace SP\Modules\Web\Controllers\Helpers\Grid; use SP\Html\DataGrid\DataGridInterface; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** diff --git a/app/modules/web/Controllers/Helpers/Grid/ItemPresetGrid.php b/app/modules/web/Controllers/Helpers/Grid/ItemPresetGrid.php index f0c4e1f2..01982df5 100644 --- a/app/modules/web/Controllers/Helpers/Grid/ItemPresetGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/ItemPresetGrid.php @@ -26,6 +26,7 @@ namespace SP\Modules\Web\Controllers\Helpers\Grid; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Domain\ItemPreset\ItemPresetInterface; use SP\Html\DataGrid\Action\DataGridAction; use SP\Html\DataGrid\Action\DataGridActionSearch; use SP\Html\DataGrid\Action\DataGridActionType; @@ -33,8 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Services\ItemPreset\ItemPresetInterface; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountDefaultPermissionGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/NotificationGrid.php b/app/modules/web/Controllers/Helpers/Grid/NotificationGrid.php index ac7eeb93..c8dc85fa 100644 --- a/app/modules/web/Controllers/Helpers/Grid/NotificationGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/NotificationGrid.php @@ -36,7 +36,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\Layout\DataGridHeader; use SP\Html\Html; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; use SP\Util\DateUtil; /** diff --git a/app/modules/web/Controllers/Helpers/Grid/PluginGrid.php b/app/modules/web/Controllers/Helpers/Grid/PluginGrid.php index 6656393d..af93c127 100644 --- a/app/modules/web/Controllers/Helpers/Grid/PluginGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/PluginGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class PluginGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/PublicLinkGrid.php b/app/modules/web/Controllers/Helpers/Grid/PublicLinkGrid.php index 0a99c43d..b12ed6c8 100644 --- a/app/modules/web/Controllers/Helpers/Grid/PublicLinkGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/PublicLinkGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class PublicLinkGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/TagGrid.php b/app/modules/web/Controllers/Helpers/Grid/TagGrid.php index a2d46e2c..95c6d068 100644 --- a/app/modules/web/Controllers/Helpers/Grid/TagGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/TagGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class TagGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/TrackGrid.php b/app/modules/web/Controllers/Helpers/Grid/TrackGrid.php index 9b736efa..b343e09e 100644 --- a/app/modules/web/Controllers/Helpers/Grid/TrackGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/TrackGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; use SP\Http\Address; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class TrackGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/UserGrid.php b/app/modules/web/Controllers/Helpers/Grid/UserGrid.php index 4e29033a..89af2144 100644 --- a/app/modules/web/Controllers/Helpers/Grid/UserGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/UserGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class UserGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/UserGroupGrid.php b/app/modules/web/Controllers/Helpers/Grid/UserGroupGrid.php index 0fd9bdde..d2697b11 100644 --- a/app/modules/web/Controllers/Helpers/Grid/UserGroupGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/UserGroupGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class UserGroupGrid diff --git a/app/modules/web/Controllers/Helpers/Grid/UserProfileGrid.php b/app/modules/web/Controllers/Helpers/Grid/UserProfileGrid.php index b16890bf..30efa33e 100644 --- a/app/modules/web/Controllers/Helpers/Grid/UserProfileGrid.php +++ b/app/modules/web/Controllers/Helpers/Grid/UserProfileGrid.php @@ -34,7 +34,7 @@ use SP\Html\DataGrid\DataGridData; use SP\Html\DataGrid\DataGridInterface; use SP\Html\DataGrid\DataGridTab; use SP\Html\DataGrid\Layout\DataGridHeader; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Class UserProfileGrid diff --git a/app/modules/web/Controllers/Helpers/HelperBase.php b/app/modules/web/Controllers/Helpers/HelperBase.php index 62a54821..7a8596b6 100644 --- a/app/modules/web/Controllers/Helpers/HelperBase.php +++ b/app/modules/web/Controllers/Helpers/HelperBase.php @@ -24,16 +24,14 @@ namespace SP\Modules\Web\Controllers\Helpers; -use DI\Container; -use DI\DependencyException; -use DI\NotFoundException; -use Psr\Container\ContainerInterface; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; +use SP\Core\Application; use SP\Core\Context\ContextInterface; use SP\Core\Events\EventDispatcher; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigFileService; use SP\Http\Request; -use SP\Mvc\View\Template; +use SP\Http\RequestInterface; +use SP\Mvc\View\TemplateInterface; /** * Class HelperBase @@ -42,34 +40,31 @@ use SP\Mvc\View\Template; */ abstract class HelperBase { - protected Template $view; + protected TemplateInterface $view; protected ConfigDataInterface $configData; - protected ContextInterface $context; - protected EventDispatcher $eventDispatcher; - protected Config $config; - protected ContainerInterface $dic; - protected Request $request; + protected ContextInterface $context; + protected EventDispatcher $eventDispatcher; + protected ConfigFileService $config; + protected Request $request; /** * Constructor * - * @throws DependencyException - * @throws NotFoundException + * @param \SP\Core\Application $application + * @param \SP\Mvc\View\TemplateInterface $template + * @param \SP\Http\RequestInterface $request */ - final public function __construct( - Template $template, - Config $config, - ContextInterface $context, - EventDispatcher $eventDispatcher, - Container $container) - { - $this->dic = $container; - $this->request = $this->dic->get(Request::class); + public function __construct( + Application $application, + TemplateInterface $template, + RequestInterface $request + ) { + $this->config = $application->getConfig(); + $this->context = $application->getContext(); + $this->eventDispatcher = $application->getEventDispatcher(); + $this->request = $request; + $this->configData = $this->config->getConfigData(); $this->view = $template; - $this->config = $config; - $this->configData = $config->getConfigData(); - $this->context = $context; - $this->eventDispatcher = $eventDispatcher; if (method_exists($this, 'initialize')) { $this->initialize(); diff --git a/app/modules/web/Controllers/Helpers/ItemPresetHelper.php b/app/modules/web/Controllers/Helpers/ItemPresetHelper.php index a96ba4ae..72f8ee5a 100644 --- a/app/modules/web/Controllers/Helpers/ItemPresetHelper.php +++ b/app/modules/web/Controllers/Helpers/ItemPresetHelper.php @@ -31,10 +31,10 @@ use SP\DataModel\ItemPreset\AccountPrivate; use SP\DataModel\ItemPreset\Password; use SP\DataModel\ItemPreset\SessionTimeout; use SP\DataModel\ItemPresetData; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserProfileService; +use SP\Domain\User\Services\UserService; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserProfile\UserProfileService; /** * Class ItemPresetHelper diff --git a/app/modules/web/Controllers/Helpers/LayoutHelper.php b/app/modules/web/Controllers/Helpers/LayoutHelper.php index bf9d7a51..25e029a3 100644 --- a/app/modules/web/Controllers/Helpers/LayoutHelper.php +++ b/app/modules/web/Controllers/Helpers/LayoutHelper.php @@ -24,20 +24,21 @@ namespace SP\Modules\Web\Controllers\Helpers; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; use SP\Core\AppInfoInterface; +use SP\Core\Application; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Crypt\CryptPKI; use SP\Core\Exceptions\SPException; use SP\Core\Language; use SP\Core\UI\ThemeInterface; +use SP\Domain\Install\Services\Installer; use SP\Html\DataGrid\Action\DataGridAction; +use SP\Http\RequestInterface; use SP\Http\Uri; +use SP\Mvc\View\TemplateInterface; use SP\Plugin\PluginManager; -use SP\Services\Install\Installer; use SP\Util\VersionUtil; /** @@ -47,8 +48,29 @@ use SP\Util\VersionUtil; */ final class LayoutHelper extends HelperBase { - protected ?bool $loggedIn = null; - protected ?ThemeInterface $theme = null; + private ThemeInterface $theme; + private CryptPKI $cryptPKI; + private PluginManager $pluginManager; + private bool $loggedIn; + + public function __construct( + Application $application, + TemplateInterface $template, + RequestInterface $request, + ThemeInterface $theme, + CryptPKI $cryptPKI, + PluginManager $pluginManager + ) { + parent::__construct($application, $template, $request); + + $this->theme = $theme; + $this->cryptPKI = $cryptPKI; + $this->pluginManager = $pluginManager; + $this->loggedIn = $this->context->isLoggedIn(); + + $this->view->assign('loggedIn', $this->loggedIn); + } + /** * Sets a full layout page @@ -113,7 +135,7 @@ final class LayoutHelper extends HelperBase try { // Cargar la clave pública en la sesión - $this->context->setPublicKey($this->dic->get(CryptPKI::class)->getPublicKey()); + $this->context->setPublicKey($this->cryptPKI->getPublicKey()); } catch (SPException $e) { processException($e); } @@ -199,7 +221,7 @@ final class LayoutHelper extends HelperBase } // Cargar los recursos de los plugins - $loadedPlugins = $this->dic->get(PluginManager::class)->getLoadedPlugins(); + $loadedPlugins = $this->pluginManager->getLoadedPlugins(); foreach ($loadedPlugins as $plugin) { $base = str_replace(APP_ROOT, '', $plugin->getBase()); @@ -418,10 +440,8 @@ final class LayoutHelper extends HelperBase * * @return LayoutHelper */ - public function getCustomLayout( - string $template, - string $page = '' - ): LayoutHelper { + public function getCustomLayout(string $template, string $page = ''): LayoutHelper + { $this->view->addTemplate('main', '_layouts'); $this->view->addContentTemplate($template); @@ -430,17 +450,4 @@ final class LayoutHelper extends HelperBase return $this; } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->theme = $this->dic->get(ThemeInterface::class); - - $this->loggedIn = $this->context->isLoggedIn(); - - $this->view->assign('loggedIn', $this->loggedIn); - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/IndexController.php b/app/modules/web/Controllers/Index/IndexController.php similarity index 67% rename from app/modules/web/Controllers/IndexController.php rename to app/modules/web/Controllers/Index/IndexController.php index 0cce608b..d1ff0518 100644 --- a/app/modules/web/Controllers/IndexController.php +++ b/app/modules/web/Controllers/Index/IndexController.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,11 +22,11 @@ * along with sysPass. If not, see . */ -namespace SP\Modules\Web\Controllers; +namespace SP\Modules\Web\Controllers\Index; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; -use SP\Modules\Web\Controllers\Helpers\LayoutHelper; +use SP\Modules\Web\Controllers\ControllerBase; /** * Class IndexController @@ -43,24 +43,13 @@ final class IndexController extends ControllerBase */ public function indexAction(): void { - if ($this->session->isLoggedIn() === false - || $this->session->getAuthCompleted() === false + if ($this->session->isLoggedIn() === false || $this->session->getAuthCompleted() === false ) { - $this->router->response() - ->redirect('index.php?r=login'); + $this->router->response()->redirect('index.php?r=login'); } else { - $this->dic->get(LayoutHelper::class) - ->getFullLayout('main', $this->acl); + $this->layoutHelper->getFullLayout('main', $this->acl); $this->view(); } } - - /** - * @return void - */ - protected function initialize(): void - { - // TODO: Implement initialize() method. - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/InstallController.php b/app/modules/web/Controllers/InstallController.php index 5d5ba442..f147ed54 100644 --- a/app/modules/web/Controllers/InstallController.php +++ b/app/modules/web/Controllers/InstallController.php @@ -32,15 +32,16 @@ use SP\Core\Exceptions\SPException; use SP\Core\Language; use SP\Core\PhpExtensionChecker; use SP\Core\UI\ThemeInterface; +use SP\Domain\Install\InstallerInterface; +use SP\Domain\Install\Services\InstallData; +use SP\Domain\Install\Services\Installer; use SP\Http\JsonResponse; -use SP\Http\Request; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Mvc\View\Template; -use SP\Providers\Auth\Browser\Browser; -use SP\Services\Install\InstallData; -use SP\Services\Install\Installer; +use SP\Mvc\View\TemplateInterface; +use SP\Providers\Auth\Browser\BrowserAuthInterface; /** * Class InstallController @@ -58,12 +59,12 @@ final class InstallController extends ControllerBase ThemeInterface $theme, Klein $router, Acl $acl, - Request $request, + RequestInterface $request, PhpExtensionChecker $extensionChecker, - Template $template, - Browser $browser, + TemplateInterface $template, + BrowserAuthInterface $browser, LayoutHelper $layoutHelper, - Installer $installer + InstallerInterface $installer ) { parent::__construct( $application, diff --git a/app/modules/web/Controllers/ItemManagerController.php b/app/modules/web/Controllers/ItemManagerController.php index 3b2dd095..f120b92f 100644 --- a/app/modules/web/Controllers/ItemManagerController.php +++ b/app/modules/web/Controllers/ItemManagerController.php @@ -24,16 +24,26 @@ namespace SP\Modules\Web\Controllers; -use DI\DependencyException; -use DI\NotFoundException; +use Klein\Klein; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Core\Exceptions\SessionTimeout; +use SP\Core\PhpExtensionChecker; +use SP\Core\UI\ThemeInterface; use SP\DataModel\ItemSearchData; +use SP\Domain\Account\AccountFileServiceInterface; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Category\CategoryServiceInterface; +use SP\Domain\Client\ClientServiceInterface; +use SP\Domain\CustomField\CustomFieldDefServiceInterface; +use SP\Domain\ItemPreset\ItemPresetServiceInterface; +use SP\Domain\Tag\TagServiceInterface; use SP\Html\DataGrid\DataGridTab; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Helpers\Grid\AccountGrid; use SP\Modules\Web\Controllers\Helpers\Grid\AccountHistoryGrid; use SP\Modules\Web\Controllers\Helpers\Grid\CategoryGrid; @@ -42,16 +52,10 @@ use SP\Modules\Web\Controllers\Helpers\Grid\CustomFieldGrid; use SP\Modules\Web\Controllers\Helpers\Grid\FileGrid; use SP\Modules\Web\Controllers\Helpers\Grid\ItemPresetGrid; use SP\Modules\Web\Controllers\Helpers\Grid\TagGrid; +use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Helpers\TabsGridHelper; -use SP\Services\Account\AccountFileService; -use SP\Services\Account\AccountHistoryService; -use SP\Services\Account\AccountService; -use SP\Services\Auth\AuthException; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\CustomField\CustomFieldDefService; -use SP\Services\ItemPreset\ItemPresetService; -use SP\Services\Tag\TagService; +use SP\Mvc\View\TemplateInterface; +use SP\Providers\Auth\Browser\BrowserAuthInterface; /** * Class ItemManagerController @@ -60,12 +64,87 @@ use SP\Services\Tag\TagService; */ final class ItemManagerController extends ControllerBase { - protected ?ItemSearchData $itemSearchData = null; - protected ?TabsGridHelper $tabsGridHelper = null; + protected ?ItemSearchData $itemSearchData = null; + private TabsGridHelper $tabsGridHelper; + private CategoryServiceInterface $categoryService; + private TagServiceInterface $tagService; + private ClientServiceInterface $clientService; + private CustomFieldDefServiceInterface $customFieldDefService; + private AccountFileServiceInterface $accountFileService; + private AccountServiceInterface $accountService; + private AccountHistoryServiceInterface $accountHistoryService; + private ItemPresetServiceInterface $itemPresetService; + private CategoryGrid $categoryGrid; + private TagGrid $tagGrid; + private ClientGrid $clientGrid; + private CustomFieldGrid $customFieldGrid; + private FileGrid $fileGrid; + private AccountGrid $accountGrid; + private AccountHistoryGrid $accountHistoryGrid; + private ItemPresetGrid $itemPresetGrid; + + public function __construct( + Application $application, + ThemeInterface $theme, + Klein $router, + Acl $acl, + RequestInterface $request, + PhpExtensionChecker $extensionChecker, + TemplateInterface $template, + BrowserAuthInterface $browser, + LayoutHelper $layoutHelper, + Helpers\TabsGridHelper $tabsGridHelper, + CategoryServiceInterface $categoryService, + TagServiceInterface $tagService, + ClientServiceInterface $clientService, + CustomFieldDefServiceInterface $customFieldDefService, + AccountFileServiceInterface $accountFileService, + AccountServiceInterface $accountService, + AccountHistoryServiceInterface $accountHistoryService, + ItemPresetServiceInterface $itemPresetService, + Helpers\Grid\CategoryGrid $categoryGrid, + Helpers\Grid\TagGrid $tagGrid, + Helpers\Grid\ClientGrid $clientGrid, + Helpers\Grid\CustomFieldGrid $customFieldGrid, + Helpers\Grid\FileGrid $fileGrid, + Helpers\Grid\AccountGrid $accountGrid, + Helpers\Grid\AccountHistoryGrid $accountHistoryGrid, + Helpers\Grid\ItemPresetGrid $itemPresetGrid + ) { + $this->tabsGridHelper = $tabsGridHelper; + $this->categoryService = $categoryService; + $this->tagService = $tagService; + $this->clientService = $clientService; + $this->customFieldDefService = $customFieldDefService; + $this->accountFileService = $accountFileService; + $this->accountService = $accountService; + $this->accountHistoryService = $accountHistoryService; + $this->itemPresetService = $itemPresetService; + $this->categoryGrid = $categoryGrid; + $this->tagGrid = $tagGrid; + $this->clientGrid = $clientGrid; + $this->customFieldGrid = $customFieldGrid; + $this->fileGrid = $fileGrid; + $this->accountGrid = $accountGrid; + $this->accountHistoryGrid = $accountHistoryGrid; + $this->itemPresetGrid = $itemPresetGrid; + + parent::__construct( + $application, + $theme, + $router, + $acl, + $request, + $extensionChecker, + $template, + $browser, + $layoutHelper + ); + + $this->checkLoggedIn(); + } /** - * @throws DependencyException - * @throws NotFoundException * @throws ConstraintException * @throws QueryException */ @@ -77,18 +156,14 @@ final class ItemManagerController extends ControllerBase /** * Returns a tabbed grid with items * - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ protected function getGridTabs(): void { $this->itemSearchData = new ItemSearchData(); $this->itemSearchData->setLimitCount($this->configData->getAccountCount()); - $this->tabsGridHelper = $this->dic->get(TabsGridHelper::class); - if ($this->checkAccess(ActionsInterface::CATEGORY)) { $this->tabsGridHelper->addTab($this->getCategoriesList()); } @@ -138,68 +213,49 @@ final class ItemManagerController extends ControllerBase /** * Returns categories' data tab * - * @return DataGridTab - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException + * @return \SP\Html\DataGrid\DataGridTab + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ protected function getCategoriesList(): DataGridTab { - return $this->dic->get(CategoryGrid::class) - ->getGrid($this->dic->get(CategoryService::class) - ->search($this->itemSearchData)) - ->updatePager(); + return $this->categoryGrid->getGrid($this->categoryService->search($this->itemSearchData))->updatePager(); } /** * Returns tags' data tab * * @return DataGridTab - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ protected function getTagsList(): DataGridTab { - return $this->dic->get(TagGrid::class) - ->getGrid($this->dic->get(TagService::class) - ->search($this->itemSearchData)) - ->updatePager(); + return $this->tagGrid->getGrid($this->tagService->search($this->itemSearchData))->updatePager(); } /** * Returns clients' data tab * * @return DataGridTab - * @throws DependencyException - * @throws NotFoundException * @throws ConstraintException * @throws QueryException */ protected function getClientsList(): DataGridTab { - return $this->dic->get(ClientGrid::class) - ->getGrid($this->dic->get(ClientService::class) - ->search($this->itemSearchData)) - ->updatePager(); + return $this->clientGrid->getGrid($this->clientService->search($this->itemSearchData))->updatePager(); } /** * Returns custom fields' data tab * * @return DataGridTab - * @throws DependencyException - * @throws NotFoundException * @throws ConstraintException * @throws QueryException */ protected function getCustomFieldsList(): DataGridTab { - return $this->dic->get(CustomFieldGrid::class) - ->getGrid($this->dic->get(CustomFieldDefService::class) - ->search($this->itemSearchData)) + return $this->customFieldGrid->getGrid($this->customFieldDefService->search($this->itemSearchData)) ->updatePager(); } @@ -207,50 +263,36 @@ final class ItemManagerController extends ControllerBase * Returns account files' data tab * * @return DataGridTab - * @throws DependencyException - * @throws NotFoundException * @throws ConstraintException * @throws QueryException */ protected function getAccountFilesList(): DataGridTab { - return $this->dic->get(FileGrid::class) - ->getGrid($this->dic->get(AccountFileService::class) - ->search($this->itemSearchData)) - ->updatePager(); + return $this->fileGrid->getGrid($this->accountFileService->search($this->itemSearchData))->updatePager(); } /** * Returns accounts' data tab * * @return DataGridTab - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ protected function getAccountsList(): DataGridTab { - return $this->dic->get(AccountGrid::class) - ->getGrid($this->dic->get(AccountService::class) - ->search($this->itemSearchData)) - ->updatePager(); + return $this->accountGrid->getGrid($this->accountService->search($this->itemSearchData))->updatePager(); } /** * Returns accounts' history data tab * * @return DataGridTab - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ protected function getAccountsHistoryList(): DataGridTab { - return $this->dic->get(AccountHistoryGrid::class) - ->getGrid($this->dic->get(AccountHistoryService::class) - ->search($this->itemSearchData)) + return $this->accountHistoryGrid->getGrid($this->accountHistoryService->search($this->itemSearchData)) ->updatePager(); } @@ -258,17 +300,12 @@ final class ItemManagerController extends ControllerBase * Returns API tokens data tab * * @return DataGridTab - * @throws DependencyException - * @throws NotFoundException - * @throws ConstraintException - * @throws QueryException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException */ protected function getItemPresetList(): DataGridTab { - return $this->dic->get(ItemPresetGrid::class) - ->getGrid($this->dic->get(ItemPresetService::class) - ->search($this->itemSearchData)) - ->updatePager(); + return $this->itemPresetGrid->getGrid($this->itemPresetService->search($this->itemSearchData))->updatePager(); } /** @@ -278,15 +315,4 @@ final class ItemManagerController extends ControllerBase { return $this->tabsGridHelper; } - - /** - * @throws AuthException - * @throws DependencyException - * @throws NotFoundException - * @throws SessionTimeout - */ - protected function initialize(): void - { - $this->checkLoggedIn(); - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/ItemPresetController.php b/app/modules/web/Controllers/ItemPresetController.php index d9a25420..9d8aa1b0 100644 --- a/app/modules/web/Controllers/ItemPresetController.php +++ b/app/modules/web/Controllers/ItemPresetController.php @@ -39,18 +39,18 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\ItemPresetData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\ItemPreset\ItemPresetInterface; +use SP\Domain\ItemPreset\Services\ItemPresetService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\Grid\ItemPresetGrid; use SP\Modules\Web\Controllers\Helpers\ItemPresetHelper; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\ItemsPresetForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; -use SP\Repositories\NoSuchItemException; -use SP\Services\Auth\AuthException; -use SP\Services\ItemPreset\ItemPresetInterface; -use SP\Services\ItemPreset\ItemPresetService; use SP\Util\Filter; /** diff --git a/app/modules/web/Controllers/ItemsController.php b/app/modules/web/Controllers/ItemsController.php index cf35c2c9..0265b36d 100644 --- a/app/modules/web/Controllers/ItemsController.php +++ b/app/modules/web/Controllers/ItemsController.php @@ -32,15 +32,15 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\DataModel\DataModelInterface; use SP\DataModel\NotificationData; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Client\Services\ClientService; +use SP\Domain\Notification\Services\NotificationService; +use SP\Domain\Tag\Services\TagService; use SP\Html\Html; use SP\Http\Json; use SP\Http\JsonResponse; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Services\Account\AccountService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Notification\NotificationService; -use SP\Services\Tag\TagService; use stdClass; /** diff --git a/app/modules/web/Controllers/Login/IndexController.php b/app/modules/web/Controllers/Login/IndexController.php new file mode 100644 index 00000000..866256f8 --- /dev/null +++ b/app/modules/web/Controllers/Login/IndexController.php @@ -0,0 +1,47 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Login; + +use SP\Core\SessionUtil; +use SP\Modules\Web\Controllers\ControllerBase; + +final class IndexController extends ControllerBase +{ + /** + * Index action + */ + public function indexAction(): void + { + SessionUtil::cleanSession(); + + $this->layoutHelper->getCustomLayout('index', 'login'); + + $this->view->assign('mailEnabled', $this->configData->isMailEnabled()); + + $this->prepareSignedUriOnView(); + + $this->view(); + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Login/LoginController.php b/app/modules/web/Controllers/Login/LoginController.php new file mode 100644 index 00000000..1094c082 --- /dev/null +++ b/app/modules/web/Controllers/Login/LoginController.php @@ -0,0 +1,129 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Login; + +use Exception; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; +use SP\Core\Bootstrap\BootstrapBase; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Domain\Auth\LoginServiceInterface; +use SP\Domain\Auth\Services\LoginService; +use SP\Http\Uri; +use SP\Modules\Web\Controllers\ControllerBase; +use SP\Modules\Web\Controllers\Traits\JsonTrait; +use SP\Mvc\Controller\WebControllerHelper; + +/** + * Class LoginController + * + * @package SP\Modules\Web\Controllers + */ +final class LoginController extends ControllerBase +{ + use JsonTrait; + + private LoginService $loginService; + + public function __construct( + Application $application, + WebControllerHelper $webControllerHelper, + LoginServiceInterface $loginService + ) { + parent::__construct($application, $webControllerHelper); + + $this->loginService = $loginService; + } + + + /** + * Login action + * + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws \JsonException + */ + public function loginAction(): bool + { + try { + $from = $this->getSignedUriFromRequest($this->request); + $this->loginService->setFrom($from); + + $loginResponse = $this->loginService->doLogin(); + + $this->checkForwarded(); + + $redirector = function ($route) use ($from) { + $uri = new Uri(ltrim(BootstrapBase::$SUBURI, '/')); + $uri->addParam('r', $route); + + if ($from !== null) { + return $uri->addParam('from', $from)->getUriSigned($this->configData->getPasswordSalt()); + } + + return $uri->getUri(); + }; + + $this->eventDispatcher->notifyEvent( + 'login.finish', + new Event($this, EventMessage::factory()->addExtra('redirect', $redirector)) + ); + + return $this->returnJsonResponseData([ + 'url' => $this->session->getTrasientKey('redirect') ?: $loginResponse->getRedirect(), + ]); + } catch (Exception $e) { + processException($e); + + $this->eventDispatcher->notifyEvent('exception', new Event($e)); + + return $this->returnJsonResponse($e->getCode(), $e->getMessage()); + } + } + + /** + * checkForwarded + */ + private function checkForwarded(): void + { + $forward = $this->request->getForwardedFor(); + + if ($forward !== null) { + $this->eventDispatcher->notifyEvent( + 'login.info', + new Event( + $this, + EventMessage::factory() + ->addDetail( + 'Forwarded', + $this->configData->isDemoEnabled() ? '***' : implode(',', $forward) + ) + ) + ); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/Login/LogoutController.php b/app/modules/web/Controllers/Login/LogoutController.php new file mode 100644 index 00000000..3dbcf315 --- /dev/null +++ b/app/modules/web/Controllers/Login/LogoutController.php @@ -0,0 +1,72 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Login; + +use SP\Core\Context\ContextBase; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Core\SessionUtil; +use SP\Modules\Web\Controllers\ControllerBase; + +/** + * Class LoginController + * + * @package SP\Modules\Web\Controllers + */ +final class LogoutController extends ControllerBase +{ + /** + * Logout action + */ + public function logoutAction(): void + { + if ($this->session->isLoggedIn() === true) { + $inactiveTime = abs(round((time() - $this->session->getLastActivity()) / 60, 2)); + $totalTime = abs(round((time() - $this->session->getStartActivity()) / 60, 2)); + + $this->eventDispatcher->notifyEvent( + 'logout', + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Logout session')) + ->addDetail(__u('User'), $this->session->getUserData()->getLogin()) + ->addDetail(__u('Inactive time'), $inactiveTime.' min.') + ->addDetail(__u('Total time'), $totalTime.' min.') + ) + ); + + SessionUtil::cleanSession(); + + $this->session->setAppStatus(ContextBase::APP_STATUS_LOGGEDOUT); + + $this->layoutHelper->getCustomLayout('logout', 'logout'); + + $this->view(); + } else { + $this->router->response()->redirect('index.php?r=login'); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/LoginController.php b/app/modules/web/Controllers/LoginController.php deleted file mode 100644 index 64e8a1e3..00000000 --- a/app/modules/web/Controllers/LoginController.php +++ /dev/null @@ -1,210 +0,0 @@ -. - */ - -namespace SP\Modules\Web\Controllers; - -use Exception; -use Klein\Klein; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Core\Acl\Acl; -use SP\Core\Application; -use SP\Core\Context\ContextBase; -use SP\Core\Events\Event; -use SP\Core\Events\EventMessage; -use SP\Core\PhpExtensionChecker; -use SP\Core\SessionUtil; -use SP\Core\UI\ThemeInterface; -use SP\Http\Request; -use SP\Http\Uri; -use SP\Modules\Web\Controllers\Helpers\LayoutHelper; -use SP\Modules\Web\Controllers\Traits\JsonTrait; -use SP\Mvc\View\Template; -use SP\Providers\Auth\Browser\Browser; -use SP\Services\Auth\LoginService; - -/** - * Class LoginController - * - * @package SP\Modules\Web\Controllers - */ -final class LoginController extends ControllerBase -{ - use JsonTrait; - - private LoginService $loginService; - - public function __construct( - Application $application, - ThemeInterface $theme, - Klein $router, - Acl $acl, - Request $request, - PhpExtensionChecker $extensionChecker, - Template $template, - Browser $browser, - LayoutHelper $layoutHelper, - LoginService $loginService - ) { - parent::__construct( - $application, - $theme, - $router, - $acl, - $request, - $extensionChecker, - $template, - $browser, - $layoutHelper - ); - - $this->loginService = $loginService; - } - - - /** - * Login action - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws \JsonException - */ - public function loginAction(): bool - { - try { - $from = $this->getSignedUriFromRequest($this->request); - $this->loginService->setFrom($from); - - $loginResponse = $this->loginService->doLogin(); - - $this->checkForwarded(); - - $redirector = function ($route) use ($from) { - $uri = new Uri(ltrim(Bootstrap::$SUBURI, '/')); - $uri->addParam('r', $route); - - if ($from !== null) { - return $uri->addParam('from', $from) - ->getUriSigned($this->configData->getPasswordSalt()); - } - - return $uri->getUri(); - }; - - $this->eventDispatcher->notifyEvent( - 'login.finish', - new Event( - $this, - EventMessage::factory() - ->addExtra('redirect', $redirector) - ) - ); - - return $this->returnJsonResponseData([ - 'url' => $this->session->getTrasientKey('redirect') - ?: $loginResponse->getRedirect(), - ]); - } catch (Exception $e) { - processException($e); - - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); - - return $this->returnJsonResponse($e->getCode(), $e->getMessage()); - } - } - - /** - * checkForwarded - */ - private function checkForwarded(): void - { - $forward = $this->request->getForwardedFor(); - - if ($forward !== null) { - $this->eventDispatcher->notifyEvent( - 'login.info', - new Event( - $this, - EventMessage::factory() - ->addDetail('Forwarded', $this->configData->isDemoEnabled() ? '***' : implode(',', $forward)) - ) - ); - } - } - - /** - * Logout action - */ - public function logoutAction(): void - { - if ($this->session->isLoggedIn() === true) { - $inactiveTime = abs(round((time() - $this->session->getLastActivity()) / 60, 2)); - $totalTime = abs(round((time() - $this->session->getStartActivity()) / 60, 2)); - - $this->eventDispatcher->notifyEvent( - 'logout', - new Event( - $this, - EventMessage::factory() - ->addDescription(__u('Logout session')) - ->addDetail(__u('User'), $this->session->getUserData()->getLogin()) - ->addDetail(__u('Inactive time'), $inactiveTime.' min.') - ->addDetail(__u('Total time'), $totalTime.' min.') - ) - ); - - SessionUtil::cleanSession(); - - $this->session->setAppStatus(ContextBase::APP_STATUS_LOGGEDOUT); - - $this->layoutHelper->getCustomLayout('logout', 'logout'); - - $this->view(); - } else { - $this->router->response()->redirect('index.php?r=login'); - } - } - - /** - * Index action - */ - public function indexAction(): void - { - SessionUtil::cleanSession(); - - $this->layoutHelper->getCustomLayout('index', 'login'); - - $this->view->assign( - 'mailEnabled', - $this->configData->isMailEnabled() - ); - - $this->prepareSignedUriOnView(); - - $this->view(); - } -} \ No newline at end of file diff --git a/app/modules/web/Controllers/NotificationController.php b/app/modules/web/Controllers/NotificationController.php index 0d61a9fe..dc53ab8b 100644 --- a/app/modules/web/Controllers/NotificationController.php +++ b/app/modules/web/Controllers/NotificationController.php @@ -36,18 +36,18 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\DataModel\NotificationData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Notification\Services\NotificationService; +use SP\Domain\User\Services\UserService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\Grid\NotificationGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\NotificationForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Repositories\NoSuchItemException; -use SP\Services\Auth\AuthException; -use SP\Services\Notification\NotificationService; -use SP\Services\User\UserService; /** * Class NotificationController diff --git a/app/modules/web/Controllers/PluginController.php b/app/modules/web/Controllers/PluginController.php index 2e2e2ab0..b01453ca 100644 --- a/app/modules/web/Controllers/PluginController.php +++ b/app/modules/web/Controllers/PluginController.php @@ -35,17 +35,17 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Plugin\Services\PluginDataService; +use SP\Domain\Plugin\Services\PluginService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Plugin\Repositories\PluginModel; use SP\Modules\Web\Controllers\Helpers\Grid\PluginGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Mvc\Controller\ItemTrait; use SP\Plugin\PluginManager; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Plugin\PluginModel; -use SP\Services\Auth\AuthException; -use SP\Services\Plugin\PluginDataService; -use SP\Services\Plugin\PluginService; /** * Class PluginController diff --git a/app/modules/web/Controllers/PublicLinkController.php b/app/modules/web/Controllers/PublicLinkController.php index 966df554..8260da9b 100644 --- a/app/modules/web/Controllers/PublicLinkController.php +++ b/app/modules/web/Controllers/PublicLinkController.php @@ -40,6 +40,9 @@ use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\PublicLinkData; use SP\DataModel\PublicLinkListData; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Account\Services\PublicLinkService; +use SP\Domain\Auth\Services\AuthException; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Helpers\Grid\PublicLinkGrid; @@ -48,9 +51,6 @@ use SP\Modules\Web\Forms\PublicLinkForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Services\Account\AccountService; -use SP\Services\Auth\AuthException; -use SP\Services\PublicLink\PublicLinkService; use SP\Util\PasswordUtil; /** diff --git a/app/modules/web/Controllers/Resource/CssController.php b/app/modules/web/Controllers/Resource/CssController.php new file mode 100644 index 00000000..c73c3d0d --- /dev/null +++ b/app/modules/web/Controllers/Resource/CssController.php @@ -0,0 +1,92 @@ +. + */ + +namespace SP\Modules\Web\Controllers\Resource; + +use Klein\Klein; +use SP\Core\Acl\Acl; +use SP\Core\Application; +use SP\Core\PhpExtensionChecker; +use SP\Core\UI\ThemeInterface; +use SP\Html\Minify; +use SP\Http\RequestInterface; +use SP\Modules\Web\Controllers\SimpleControllerBase; + +/** + * Class ResourceController + * + * @package SP\Modules\Web\Controllers + */ +final class CssController extends SimpleControllerBase +{ + private const CSS_MIN_FILES = [ + 'reset.min.css', + 'jquery-ui.min.css', + 'jquery-ui.structure.min.css', + 'material-icons.min.css', + 'toastr.min.css', + 'magnific-popup.min.css', + ]; + + private Minify $minify; + + public function __construct( + Application $application, + ThemeInterface $theme, + Klein $router, + Acl $acl, + RequestInterface $request, + PhpExtensionChecker $extensionChecker, + Minify $minify + ) { + parent::__construct($application, $theme, $router, $acl, $request, $extensionChecker); + + $this->minify = $minify; + + $this->request->verifySignature($this->configData->getPasswordSalt()); + } + + /** + * Returns CSS resources + */ + public function cssAction(): void + { + $file = $this->request->analyzeString('f'); + $base = $this->request->analyzeString('b'); + + if ($file && $base) { + $this->minify + ->setType(Minify::FILETYPE_CSS) + ->setBase(urldecode($base), true) + ->addFilesFromString(urldecode($file)) + ->getMinified(); + } else { + $this->minify->setType(Minify::FILETYPE_CSS) + ->setBase(PUBLIC_PATH.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'css') + ->addFiles(self::CSS_MIN_FILES, false) + ->addFile('fonts.min.css', false, PUBLIC_PATH.DIRECTORY_SEPARATOR.'css') + ->getMinified(); + } + } +} \ No newline at end of file diff --git a/app/modules/web/Controllers/ResourceController.php b/app/modules/web/Controllers/Resource/JsController.php similarity index 57% rename from app/modules/web/Controllers/ResourceController.php rename to app/modules/web/Controllers/Resource/JsController.php index 6439283b..34bf1ca5 100644 --- a/app/modules/web/Controllers/ResourceController.php +++ b/app/modules/web/Controllers/Resource/JsController.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,29 +22,26 @@ * along with sysPass. If not, see . */ -namespace SP\Modules\Web\Controllers; +namespace SP\Modules\Web\Controllers\Resource; -use DI\DependencyException; -use DI\NotFoundException; -use SP\Core\Exceptions\SPException; +use Klein\Klein; +use SP\Core\Acl\Acl; +use SP\Core\Application; +use SP\Core\PhpExtensionChecker; +use SP\Core\UI\ThemeInterface; use SP\Html\Minify; +use SP\Http\RequestInterface; +use SP\Modules\Web\Controllers\SimpleControllerBase; /** * Class ResourceController * * @package SP\Modules\Web\Controllers */ -final class ResourceController extends SimpleControllerBase +final class JsController extends SimpleControllerBase { - private const CSS_MIN_FILES = [ - 'reset.min.css', - 'jquery-ui.min.css', - 'jquery-ui.structure.min.css', - 'material-icons.min.css', - 'toastr.min.css', - 'magnific-popup.min.css' - ]; - private const JS_MIN_FILES = [ + + private const JS_MIN_FILES = [ 'jquery-3.3.1.min.js', 'jquery.fileDownload.min.js', 'clipboard.min.js', @@ -57,7 +54,8 @@ final class ResourceController extends SimpleControllerBase 'moment-timezone.min.js', 'toastr.min.js', 'jquery.magnific-popup.min.js', - 'eventsource.min.js']; + 'eventsource.min.js', + ]; private const JS_APP_MIN_FILES = [ 'app.min.js', 'app-config.min.js', @@ -65,31 +63,25 @@ final class ResourceController extends SimpleControllerBase 'app-actions.min.js', 'app-requests.min.js', 'app-util.min.js', - 'app-main.min.js']; + 'app-main.min.js', + ]; - private ?Minify $minify = null; + private Minify $minify; - /** - * Returns CSS resources - */ - public function cssAction(): void - { - $file = $this->request->analyzeString('f'); - $base = $this->request->analyzeString('b'); + public function __construct( + Application $application, + ThemeInterface $theme, + Klein $router, + Acl $acl, + RequestInterface $request, + PhpExtensionChecker $extensionChecker, + Minify $minify + ) { + parent::__construct($application, $theme, $router, $acl, $request, $extensionChecker); - if ($file && $base) { - $this->minify - ->setType(Minify::FILETYPE_CSS) - ->setBase(urldecode($base), true) - ->addFilesFromString(urldecode($file)) - ->getMinified(); - } else { - $this->minify->setType(Minify::FILETYPE_CSS) - ->setBase(PUBLIC_PATH . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'css') - ->addFiles(self::CSS_MIN_FILES, false) - ->addFile('fonts.min.css', false, PUBLIC_PATH . DIRECTORY_SEPARATOR . 'css') - ->getMinified(); - } + $this->minify = $minify; + + $this->request->verifySignature($this->configData->getPasswordSalt()); } /** @@ -111,12 +103,12 @@ final class ResourceController extends SimpleControllerBase if ($group === 0) { $this->minify->setType(Minify::FILETYPE_JS) - ->setBase(PUBLIC_PATH . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'js'); + ->setBase(PUBLIC_PATH.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'js'); $this->minify->addFiles(self::JS_MIN_FILES, false); } elseif ($group === 1) { $this->minify->setType(Minify::FILETYPE_JS) - ->setBase(PUBLIC_PATH . DIRECTORY_SEPARATOR . 'js'); + ->setBase(PUBLIC_PATH.DIRECTORY_SEPARATOR.'js'); $this->minify->addFiles(self::JS_APP_MIN_FILES, false); } @@ -124,16 +116,4 @@ final class ResourceController extends SimpleControllerBase $this->minify->getMinified(); } } - - /** - * @throws SPException - * @throws DependencyException - * @throws NotFoundException - */ - protected function initialize(): void - { - $this->request->verifySignature($this->configData->getPasswordSalt()); - - $this->minify = $this->dic->get(Minify::class); - } } \ No newline at end of file diff --git a/app/modules/web/Controllers/SecurityManagerController.php b/app/modules/web/Controllers/SecurityManagerController.php index 5553cf9b..40895aec 100644 --- a/app/modules/web/Controllers/SecurityManagerController.php +++ b/app/modules/web/Controllers/SecurityManagerController.php @@ -33,13 +33,13 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SessionTimeout; use SP\DataModel\ItemSearchData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Security\Services\EventlogService; +use SP\Domain\Security\Services\TrackService; use SP\Html\DataGrid\DataGridTab; use SP\Modules\Web\Controllers\Helpers\Grid\EventlogGrid; use SP\Modules\Web\Controllers\Helpers\Grid\TrackGrid; use SP\Modules\Web\Controllers\Helpers\TabsGridHelper; -use SP\Services\Auth\AuthException; -use SP\Services\EventLog\EventlogService; -use SP\Services\Track\TrackService; /** * Class SecurityManagerController diff --git a/app/modules/web/Controllers/SimpleControllerBase.php b/app/modules/web/Controllers/SimpleControllerBase.php index 815893ea..483b9a11 100644 --- a/app/modules/web/Controllers/SimpleControllerBase.php +++ b/app/modules/web/Controllers/SimpleControllerBase.php @@ -26,7 +26,6 @@ namespace SP\Modules\Web\Controllers; use Klein\Klein; use Psr\Container\ContainerInterface; -use SP\Config\Config; use SP\Core\Acl\Acl; use SP\Core\Acl\UnauthorizedPageException; use SP\Core\Application; @@ -37,7 +36,9 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\PhpExtensionChecker; use SP\Core\UI\ThemeInterface; +use SP\Domain\Config\Services\ConfigFileService; use SP\Http\Request; +use SP\Http\RequestInterface; use SP\Modules\Web\Controllers\Traits\WebControllerTrait; /** @@ -52,9 +53,9 @@ abstract class SimpleControllerBase // TODO: remove when controllers are ready protected ContainerInterface $dic; - protected EventDispatcher $eventDispatcher; - protected Config $config; - protected ContextInterface $session; + protected EventDispatcher $eventDispatcher; + protected ConfigFileService $config; + protected ContextInterface $session; protected ThemeInterface $theme; protected Klein $router; protected Acl $acl; @@ -70,7 +71,7 @@ abstract class SimpleControllerBase ThemeInterface $theme, Klein $router, Acl $acl, - Request $request, + RequestInterface $request, PhpExtensionChecker $extensionChecker ) { // TODO: remove when controllers are ready diff --git a/app/modules/web/Controllers/TagController.php b/app/modules/web/Controllers/TagController.php index d145118f..4ef33738 100644 --- a/app/modules/web/Controllers/TagController.php +++ b/app/modules/web/Controllers/TagController.php @@ -36,16 +36,16 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\TagData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Tag\Services\TagService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\Grid\TagGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\TagForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; -use SP\Repositories\NoSuchItemException; -use SP\Services\Auth\AuthException; -use SP\Services\Tag\TagService; /** * Class TagController diff --git a/app/modules/web/Controllers/TaskController.php b/app/modules/web/Controllers/TaskController.php index b0581971..fcc7cb2d 100644 --- a/app/modules/web/Controllers/TaskController.php +++ b/app/modules/web/Controllers/TaskController.php @@ -26,10 +26,11 @@ namespace SP\Modules\Web\Controllers; use Klein\Klein; use Psr\Container\ContainerInterface; -use SP\Services\ServiceException; -use SP\Services\Task\TaskFactory; -use SP\Services\Task\TaskService; -use SP\Storage\File\FileException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Task\Services\TaskFactory; +use SP\Domain\Task\Services\TaskService; +use SP\Domain\Task\TaskServiceInterface; +use SP\Infrastructure\File\FileException; /** * Class TaskController @@ -39,7 +40,7 @@ use SP\Storage\File\FileException; final class TaskController { /** - * @var TaskService + * @var TaskServiceInterface */ private $taskService; /** diff --git a/app/modules/web/Controllers/TrackController.php b/app/modules/web/Controllers/TrackController.php index 95f09995..7231fc0f 100644 --- a/app/modules/web/Controllers/TrackController.php +++ b/app/modules/web/Controllers/TrackController.php @@ -34,13 +34,13 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Security\Services\TrackService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Helpers\Grid\TrackGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Mvc\Controller\ItemTrait; -use SP\Services\Auth\AuthException; -use SP\Services\Track\TrackService; /** * Class TrackController diff --git a/app/modules/web/Controllers/Traits/ConfigTrait.php b/app/modules/web/Controllers/Traits/ConfigTrait.php index 095a487c..9c586a75 100644 --- a/app/modules/web/Controllers/Traits/ConfigTrait.php +++ b/app/modules/web/Controllers/Traits/ConfigTrait.php @@ -25,9 +25,9 @@ namespace SP\Modules\Web\Controllers\Traits; use Exception; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; use SP\Core\Bootstrap\BootstrapBase; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Http\JsonResponse; use SP\Util\Util; @@ -49,7 +49,7 @@ trait ConfigTrait */ protected function saveConfig( ConfigDataInterface $configData, - Config $config, + ConfigInterface $config, callable $onSuccess = null ): bool { try { diff --git a/app/modules/web/Controllers/Traits/WebControllerTrait.php b/app/modules/web/Controllers/Traits/WebControllerTrait.php index 69789bb1..e26097e8 100644 --- a/app/modules/web/Controllers/Traits/WebControllerTrait.php +++ b/app/modules/web/Controllers/Traits/WebControllerTrait.php @@ -28,6 +28,7 @@ use Closure; use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Http\Request; +use SP\Http\RequestInterface; use SP\Mvc\Controller\ControllerTrait; /** @@ -43,7 +44,7 @@ trait WebControllerTrait * Returns the signed URI component after validating its signature. * This component is used for deep linking */ - final protected function getSignedUriFromRequest(Request $request): ?string + final protected function getSignedUriFromRequest(RequestInterface $request): ?string { if (!$this->setup) { return null; diff --git a/app/modules/web/Controllers/UpgradeController.php b/app/modules/web/Controllers/UpgradeController.php index 75d45e93..dc0c911d 100644 --- a/app/modules/web/Controllers/UpgradeController.php +++ b/app/modules/web/Controllers/UpgradeController.php @@ -28,12 +28,12 @@ use DI\DependencyException; use DI\NotFoundException; use Exception; use SP\Core\Acl\Actions; +use SP\Domain\Upgrade\Services\UpgradeAppService; +use SP\Domain\Upgrade\Services\UpgradeDatabaseService; use SP\Http\JsonResponse; +use SP\Infrastructure\File\FileException; use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Traits\JsonTrait; -use SP\Services\Upgrade\UpgradeAppService; -use SP\Services\Upgrade\UpgradeDatabaseService; -use SP\Storage\File\FileException; /** * Class UpgradeController diff --git a/app/modules/web/Controllers/UserController.php b/app/modules/web/Controllers/UserController.php index 8ad5dba7..98916ed4 100644 --- a/app/modules/web/Controllers/UserController.php +++ b/app/modules/web/Controllers/UserController.php @@ -38,6 +38,12 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\UserData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Notification\Services\MailService; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserPassRecoverService; +use SP\Domain\User\Services\UserProfileService; +use SP\Domain\User\Services\UserService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Helpers\Grid\UserGrid; @@ -46,12 +52,6 @@ use SP\Modules\Web\Forms\UserForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Services\Auth\AuthException; -use SP\Services\Mail\MailService; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserPassRecover\UserPassRecoverService; -use SP\Services\UserProfile\UserProfileService; /** * Class UserController @@ -485,7 +485,7 @@ final class UserController extends ControllerBase implements CrudControllerInter * @throws \PHPMailer\PHPMailer\Exception * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ protected function checkChangeUserPass(int $userId, UserData $userData): void { diff --git a/app/modules/web/Controllers/UserGroupController.php b/app/modules/web/Controllers/UserGroupController.php index abf6af6b..666f2b06 100644 --- a/app/modules/web/Controllers/UserGroupController.php +++ b/app/modules/web/Controllers/UserGroupController.php @@ -37,19 +37,19 @@ use SP\Core\Exceptions\SessionTimeout; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\UserGroupData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\Grid\UserGroupGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\UserGroupForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Repositories\NoSuchItemException; -use SP\Services\Auth\AuthException; -use SP\Services\ServiceException; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; /** * Class GroupController diff --git a/app/modules/web/Controllers/UserPassResetController.php b/app/modules/web/Controllers/UserPassResetController.php index 7aa0ae11..737118ab 100644 --- a/app/modules/web/Controllers/UserPassResetController.php +++ b/app/modules/web/Controllers/UserPassResetController.php @@ -34,14 +34,14 @@ use SP\Core\Events\EventMessage; use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; +use SP\Domain\Notification\Services\MailService; +use SP\Domain\Security\Services\TrackService; +use SP\Domain\User\Services\UserPassRecoverService; +use SP\Domain\User\Services\UserService; use SP\Http\JsonResponse; +use SP\Infrastructure\Security\Repositories\TrackRequest; use SP\Modules\Web\Controllers\Helpers\LayoutHelper; use SP\Modules\Web\Controllers\Traits\JsonTrait; -use SP\Repositories\Track\TrackRequest; -use SP\Services\Mail\MailService; -use SP\Services\Track\TrackService; -use SP\Services\User\UserService; -use SP\Services\UserPassRecover\UserPassRecoverService; use SP\Util\ErrorUtil; /** @@ -65,7 +65,7 @@ final class UserPassResetController extends ControllerBase public function indexAction(): void { $this->dic->get(LayoutHelper::class) - ->getCustomLayout('request', strtolower($this->controllerName)); + ->getCustomLayout('request', strtolower($this->getViewBaseName())); if (!$this->configData->isMailEnabled()) { ErrorUtil::showErrorInView( @@ -173,7 +173,7 @@ final class UserPassResetController extends ControllerBase } /** - * @param string|null $hash + * @param string|null $hash * * @throws DependencyException * @throws NotFoundException @@ -181,7 +181,7 @@ final class UserPassResetController extends ControllerBase public function resetAction(?string $hash = null): void { $this->dic->get(LayoutHelper::class) - ->getCustomLayout('reset', strtolower($this->controllerName)); + ->getCustomLayout('reset', strtolower($this->getViewBaseName())); if ($hash && $this->configData->isMailEnabled()) { $this->view->assign('hash', $hash); @@ -268,6 +268,6 @@ final class UserPassResetController extends ControllerBase protected function initialize(): void { $this->trackService = $this->dic->get(TrackService::class); - $this->trackRequest = $this->trackService->getTrackRequest($this->controllerName); + $this->trackRequest = $this->trackService->getTrackRequest($this->getViewBaseName()); } } \ No newline at end of file diff --git a/app/modules/web/Controllers/UserProfileController.php b/app/modules/web/Controllers/UserProfileController.php index 70a4e773..cab6f265 100644 --- a/app/modules/web/Controllers/UserProfileController.php +++ b/app/modules/web/Controllers/UserProfileController.php @@ -38,17 +38,17 @@ use SP\Core\Exceptions\SPException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\ProfileData; use SP\DataModel\UserProfileData; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\User\Services\UserProfileService; use SP\Html\DataGrid\DataGridInterface; use SP\Http\JsonResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Modules\Web\Controllers\Helpers\Grid\UserProfileGrid; use SP\Modules\Web\Controllers\Traits\JsonTrait; use SP\Modules\Web\Forms\UserProfileForm; use SP\Mvc\Controller\CrudControllerInterface; use SP\Mvc\Controller\ItemTrait; -use SP\Repositories\NoSuchItemException; -use SP\Services\Auth\AuthException; -use SP\Services\ServiceException; -use SP\Services\UserProfile\UserProfileService; /** * Class UserProfileController diff --git a/app/modules/web/Controllers/UserSettingsGeneralController.php b/app/modules/web/Controllers/UserSettingsGeneralController.php index fd0d7025..72d71d5d 100644 --- a/app/modules/web/Controllers/UserSettingsGeneralController.php +++ b/app/modules/web/Controllers/UserSettingsGeneralController.php @@ -29,9 +29,9 @@ use DI\NotFoundException; use Exception; use SP\Core\Events\Event; use SP\Core\Exceptions\SessionTimeout; +use SP\Domain\User\Services\UserService; use SP\Http\JsonResponse; use SP\Modules\Web\Controllers\Traits\JsonTrait; -use SP\Services\User\UserService; /** * Class UserSettingsGeneralController diff --git a/app/modules/web/Controllers/UserSettingsManagerController.php b/app/modules/web/Controllers/UserSettingsManagerController.php index 467ef098..18c61819 100644 --- a/app/modules/web/Controllers/UserSettingsManagerController.php +++ b/app/modules/web/Controllers/UserSettingsManagerController.php @@ -32,12 +32,12 @@ use SP\Core\Events\Event; use SP\Core\Events\EventDispatcherInterface; use SP\Core\Exceptions\SessionTimeout; use SP\Core\Language; +use SP\Domain\Auth\Services\AuthException; use SP\Modules\Web\Controllers\Helpers\TabsHelper; use SP\Mvc\Controller\ExtensibleTabControllerInterface; use SP\Mvc\View\Components\DataTab; use SP\Mvc\View\Components\SelectItemAdapter; -use SP\Mvc\View\Template; -use SP\Services\Auth\AuthException; +use SP\Mvc\View\TemplateInterface; /** * Class UserSettingsManagerController @@ -119,9 +119,9 @@ final class UserSettingsManagerController extends ControllerBase implements Exte } /** - * @return Template + * @return TemplateInterface */ - public function getView(): Template + public function getView(): TemplateInterface { return $this->view; } diff --git a/app/modules/web/Forms/AccountForm.php b/app/modules/web/Forms/AccountForm.php index a172e919..1f0f6eb6 100644 --- a/app/modules/web/Forms/AccountForm.php +++ b/app/modules/web/Forms/AccountForm.php @@ -24,14 +24,15 @@ namespace SP\Modules\Web\Forms; -use Psr\Container\ContainerInterface; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\ValidationException; -use SP\Services\Account\AccountPresetService; -use SP\Services\Account\AccountRequest; +use SP\Domain\Account\AccountPresetServiceInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Http\RequestInterface; /** * Class AccountForm @@ -40,13 +41,25 @@ use SP\Services\Account\AccountRequest; */ final class AccountForm extends FormBase implements FormInterface { - protected ?AccountRequest $accountRequest = null; - private ?AccountPresetService $accountPresetService = null; + private AccountPresetServiceInterface $accountPresetService; + private AccountRequest $accountRequest; + + public function __construct( + Application $application, + RequestInterface $request, + AccountPresetServiceInterface $accountPresetService, + ?int $itemId = null + ) { + parent::__construct($application, $request, $itemId); + + $this->accountPresetService = $accountPresetService; + $this->accountRequest = new AccountRequest(); + } /** * Validar el formulario * - * @param int $action + * @param int $action * * @return AccountForm|FormInterface * @throws ValidationException @@ -191,14 +204,8 @@ final class AccountForm extends FormBase implements FormInterface } } - public function getItemData(): ?AccountRequest + public function getItemData(): AccountRequest { return $this->accountRequest; } - - protected function initialize(ContainerInterface $dic): void - { - $this->accountPresetService = $dic->get(AccountPresetService::class); - $this->accountRequest = new AccountRequest(); - } } \ No newline at end of file diff --git a/app/modules/web/Forms/AuthTokenForm.php b/app/modules/web/Forms/AuthTokenForm.php index cbe88961..cf4439f7 100644 --- a/app/modules/web/Forms/AuthTokenForm.php +++ b/app/modules/web/Forms/AuthTokenForm.php @@ -27,7 +27,7 @@ namespace SP\Modules\Web\Forms; use SP\Core\Acl\ActionsInterface; use SP\Core\Exceptions\ValidationException; use SP\DataModel\AuthTokenData; -use SP\Services\AuthToken\AuthTokenService; +use SP\Domain\Auth\Services\AuthTokenService; /** * Class ApiTokenForm diff --git a/app/modules/web/Forms/FormBase.php b/app/modules/web/Forms/FormBase.php index 2abf6283..69425cf4 100644 --- a/app/modules/web/Forms/FormBase.php +++ b/app/modules/web/Forms/FormBase.php @@ -24,11 +24,12 @@ namespace SP\Modules\Web\Forms; -use Psr\Container\ContainerInterface; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; +use SP\Core\Application; use SP\Core\Context\ContextInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigFileService; use SP\Http\Request; +use SP\Http\RequestInterface; /** * Class FormBase @@ -37,33 +38,37 @@ use SP\Http\Request; */ abstract class FormBase { - protected ?int $itemId; - protected Config $config; + protected ?int $itemId; + protected ConfigFileService $config; protected ConfigDataInterface $configData; - protected ContextInterface $context; - protected Request $request; + protected ContextInterface $context; + protected Request $request; /** * FormBase constructor. * - * @param ContainerInterface $container - * @param int|null $itemId + * @param \SP\Core\Application $application + * @param \SP\Http\RequestInterface $request + * @param int|null $itemId */ public function __construct( - ContainerInterface $container, - ?int $itemId = null - ) - { - $this->config = $container->get(Config::class); + Application $application, + RequestInterface $request, + ?int $itemId = null + ) { + $this->config = $application->getConfig(); $this->configData = $this->config->getConfigData(); - $this->context = $container->get(ContextInterface::class); - $this->request = $container->get(Request::class); - + $this->context = $application->getContext(); + $this->request = $request; $this->itemId = $itemId; + } - if (method_exists($this, 'initialize')) { - $this->initialize($container); - } + /** + * @param int $itemId + */ + public function setItemId(int $itemId): void + { + $this->itemId = $itemId; } /** diff --git a/app/modules/web/Forms/ItemsPresetForm.php b/app/modules/web/Forms/ItemsPresetForm.php index 3bb39599..5963da03 100644 --- a/app/modules/web/Forms/ItemsPresetForm.php +++ b/app/modules/web/Forms/ItemsPresetForm.php @@ -32,9 +32,9 @@ use SP\DataModel\ItemPreset\AccountPrivate; use SP\DataModel\ItemPreset\Password; use SP\DataModel\ItemPreset\SessionTimeout; use SP\DataModel\ItemPresetData; +use SP\Domain\ItemPreset\ItemPresetInterface; +use SP\Domain\ItemPreset\Services\ItemPresetRequest; use SP\Mvc\Controller\Validators\Validator; -use SP\Services\ItemPreset\ItemPresetInterface; -use SP\Services\ItemPreset\ItemPresetRequest; /** * Class ItemsPresetForm diff --git a/app/modules/web/Forms/PublicLinkForm.php b/app/modules/web/Forms/PublicLinkForm.php index ee1c739a..b39032fe 100644 --- a/app/modules/web/Forms/PublicLinkForm.php +++ b/app/modules/web/Forms/PublicLinkForm.php @@ -27,7 +27,7 @@ namespace SP\Modules\Web\Forms; use SP\Core\Acl\ActionsInterface; use SP\Core\Exceptions\ValidationException; use SP\DataModel\PublicLinkData; -use SP\Services\PublicLink\PublicLinkService; +use SP\Domain\Account\Services\PublicLinkService; /** * Class PublicLinkForm diff --git a/app/modules/web/Init.php b/app/modules/web/Init.php index 7cc951cb..6ce7d33d 100644 --- a/app/modules/web/Init.php +++ b/app/modules/web/Init.php @@ -42,21 +42,24 @@ use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; use SP\Core\HttpModuleBase; use SP\Core\Language; +use SP\Core\LanguageInterface; use SP\Core\ProvidersHelper; use SP\Core\UI\ThemeInterface; use SP\DataModel\ItemPreset\SessionTimeout; +use SP\Domain\Crypt\SecureSessionServiceInterface; +use SP\Domain\Crypt\Services\SecureSessionService; +use SP\Domain\ItemPreset\ItemPresetInterface; +use SP\Domain\ItemPreset\Services\ItemPresetService; +use SP\Domain\Upgrade\Services\UpgradeAppService; +use SP\Domain\Upgrade\Services\UpgradeDatabaseService; +use SP\Domain\Upgrade\Services\UpgradeUtil; +use SP\Domain\User\Services\UserProfileService; +use SP\Domain\User\UserProfileServiceInterface; use SP\Http\Address; -use SP\Http\Request; +use SP\Http\RequestInterface; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\File\FileException; use SP\Plugin\PluginManager; -use SP\Services\Crypt\SecureSessionService; -use SP\Services\ItemPreset\ItemPresetInterface; -use SP\Services\ItemPreset\ItemPresetService; -use SP\Services\Upgrade\UpgradeAppService; -use SP\Services\Upgrade\UpgradeDatabaseService; -use SP\Services\Upgrade\UpgradeUtil; -use SP\Services\UserProfile\UserProfileService; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\File\FileException; use SP\Util\HttpUtil; /** @@ -94,16 +97,16 @@ final class Init extends HttpModuleBase public function __construct( Application $application, ProvidersHelper $providersHelper, - Request $request, + RequestInterface $request, Klein $router, CSRF $csrf, ThemeInterface $theme, - Language $language, - SecureSessionService $secureSessionService, + LanguageInterface $language, + SecureSessionServiceInterface $secureSessionService, PluginManager $pluginManager, ItemPresetService $itemPresetService, DatabaseUtil $databaseUtil, - UserProfileService $userProfileService + UserProfileServiceInterface $userProfileService ) { parent::__construct( $application, @@ -133,8 +136,8 @@ final class Init extends HttpModuleBase * @throws \SP\Core\Exceptions\InitializationException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Repositories\NoSuchItemException - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\File\FileException * @throws \Exception */ public function initialize(string $controller): void diff --git a/app/modules/web/themes/material-blue/views/_layouts/main.inc b/app/modules/web/themes/material-blue/views/_layouts/main.inc index e0936bf1..7ec155e4 100644 --- a/app/modules/web/themes/material-blue/views/_layouts/main.inc +++ b/app/modules/web/themes/material-blue/views/_layouts/main.inc @@ -1,7 +1,7 @@
- diff --git a/app/modules/web/themes/material-blue/views/account/account-request.inc b/app/modules/web/themes/material-blue/views/account/account-request.inc index 01d2e018..180731fd 100644 --- a/app/modules/web/themes/material-blue/views/account/account-request.inc +++ b/app/modules/web/themes/material-blue/views/account/account-request.inc @@ -4,12 +4,12 @@ * @var ThemeIcons $icons * @var AccountExtData $accountData * @var AccountAcl $accountAcl - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData */ use SP\Core\UI\ThemeIcons; use SP\DataModel\AccountExtData; -use SP\Services\Account\AccountAcl; +use SP\Domain\Account\Services\AccountAcl; /** @var AccountExtData $accountData */ $accountData = $_getvar('accountData'); diff --git a/app/modules/web/themes/material-blue/views/account/account.inc b/app/modules/web/themes/material-blue/views/account/account.inc index 1038ae6f..06650793 100644 --- a/app/modules/web/themes/material-blue/views/account/account.inc +++ b/app/modules/web/themes/material-blue/views/account/account.inc @@ -4,13 +4,13 @@ * @var ThemeIcons $icons * @var AccountExtData $accountData * @var AccountAcl $accountAcl - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData */ use SP\Core\UI\ThemeIcons; use SP\DataModel\AccountExtData; +use SP\Domain\Account\Services\AccountAcl; use SP\Mvc\View\Components\SelectItem; -use SP\Services\Account\AccountAcl; $accountData = $_getvar('accountData'); $accountAcl = $_getvar('accountAcl'); diff --git a/app/modules/web/themes/material-blue/views/account/actions.inc b/app/modules/web/themes/material-blue/views/account/actions.inc index 68589f38..b89208ca 100644 --- a/app/modules/web/themes/material-blue/views/account/actions.inc +++ b/app/modules/web/themes/material-blue/views/account/actions.inc @@ -4,13 +4,13 @@ * @var callable $_getvar * @var AccountExtData $accountData * @var AccountAcl $accountAcl - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData */ use SP\Core\UI\ThemeIcons; use SP\DataModel\AccountExtData; +use SP\Domain\Account\Services\AccountAcl; use SP\Html\DataGrid\Action\DataGridActionInterface; -use SP\Services\Account\AccountAcl; ?> diff --git a/app/modules/web/themes/material-blue/views/account/details.inc b/app/modules/web/themes/material-blue/views/account/details.inc index df7a5833..74db973a 100644 --- a/app/modules/web/themes/material-blue/views/account/details.inc +++ b/app/modules/web/themes/material-blue/views/account/details.inc @@ -4,12 +4,12 @@ * @var callable $_getvar * @var AccountExtData $accountData * @var AccountAcl $accountAcl - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData */ use SP\Core\UI\ThemeIcons; use SP\DataModel\AccountExtData; -use SP\Services\Account\AccountAcl; +use SP\Domain\Account\Services\AccountAcl; ?> diff --git a/app/modules/web/themes/material-blue/views/account/files-list.inc b/app/modules/web/themes/material-blue/views/account/files-list.inc index c0eb5db5..d0b808d5 100644 --- a/app/modules/web/themes/material-blue/views/account/files-list.inc +++ b/app/modules/web/themes/material-blue/views/account/files-list.inc @@ -2,7 +2,7 @@ /** * @var ThemeIcons $icons * @var callable $_getvar - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData * @var FileData $file */ diff --git a/app/modules/web/themes/material-blue/views/account/files.inc b/app/modules/web/themes/material-blue/views/account/files.inc index b7ea2480..8cbfc97c 100644 --- a/app/modules/web/themes/material-blue/views/account/files.inc +++ b/app/modules/web/themes/material-blue/views/account/files.inc @@ -4,12 +4,12 @@ * @var callable $_getvar * @var AccountExtData $accountData * @var AccountAcl $accountAcl - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData */ use SP\Core\UI\ThemeIcons; use SP\DataModel\AccountExtData; -use SP\Services\Account\AccountAcl; +use SP\Domain\Account\Services\AccountAcl; ?> diff --git a/app/modules/web/themes/material-blue/views/account/linkedAccounts.inc b/app/modules/web/themes/material-blue/views/account/linkedAccounts.inc index ee404424..64aaceb6 100644 --- a/app/modules/web/themes/material-blue/views/account/linkedAccounts.inc +++ b/app/modules/web/themes/material-blue/views/account/linkedAccounts.inc @@ -2,7 +2,7 @@ /** * @var ThemeIcons $icons * @var callable $_getvar - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData */ use SP\Core\UI\ThemeIcons; diff --git a/app/modules/web/themes/material-blue/views/account/search-header.inc b/app/modules/web/themes/material-blue/views/account/search-header.inc index 5580cb8e..25cdc018 100644 --- a/app/modules/web/themes/material-blue/views/account/search-header.inc +++ b/app/modules/web/themes/material-blue/views/account/search-header.inc @@ -2,14 +2,14 @@ /** * @var ThemeIcons $icons * @var callable $_getvar - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData * @var AccountSearchItem $account * @var DataGridTab $data */ use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\Services\AccountSearchItem; use SP\Html\DataGrid\DataGridTab; -use SP\Services\Account\AccountSearchItem; if (!isset($data)) { $data = $_getvar('data'); diff --git a/app/modules/web/themes/material-blue/views/account/search-index.inc b/app/modules/web/themes/material-blue/views/account/search-index.inc index 86f96a09..3e4c5e36 100644 --- a/app/modules/web/themes/material-blue/views/account/search-index.inc +++ b/app/modules/web/themes/material-blue/views/account/search-index.inc @@ -2,14 +2,14 @@ /** * @var ThemeIcons $icons * @var callable $_getvar - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData * @var AccountSearchItem $account * @var DataGrid $data */ use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\Services\AccountSearchItem; use SP\Html\DataGrid\DataGrid; -use SP\Services\Account\AccountSearchItem; if (!isset($data)) { $data = $_getvar('data'); diff --git a/app/modules/web/themes/material-blue/views/account/search-rows.inc b/app/modules/web/themes/material-blue/views/account/search-rows.inc index f6804778..133f3a0c 100644 --- a/app/modules/web/themes/material-blue/views/account/search-rows.inc +++ b/app/modules/web/themes/material-blue/views/account/search-rows.inc @@ -2,7 +2,7 @@ /** * @var ThemeIcons $icons * @var callable $_getvar - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData * @var AccountSearchItem $account * @var DataGridTab $data * @var DataGridActionBase $actionMenu @@ -12,9 +12,9 @@ use SP\Core\Acl\ActionsInterface; use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\Services\AccountSearchItem; use SP\Html\DataGrid\Action\DataGridActionBase; use SP\Html\DataGrid\DataGridTab; -use SP\Services\Account\AccountSearchItem; use SP\Util\DateUtil; if (!isset($data)) { diff --git a/app/modules/web/themes/material-blue/views/account/search-searchbox.inc b/app/modules/web/themes/material-blue/views/account/search-searchbox.inc index 06ddfa27..43777145 100644 --- a/app/modules/web/themes/material-blue/views/account/search-searchbox.inc +++ b/app/modules/web/themes/material-blue/views/account/search-searchbox.inc @@ -2,15 +2,15 @@ /** * @var ThemeIcons $icons * @var callable $_getvar - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData * @var AccountSearchItem $account * @var DataGrid $data */ use SP\Core\UI\ThemeIcons; +use SP\Domain\Account\Services\AccountSearchItem; use SP\Html\DataGrid\DataGrid; use SP\Mvc\View\Components\SelectItem; -use SP\Services\Account\AccountSearchItem; if (!isset($data)) { $data = $_getvar('data'); diff --git a/app/modules/web/themes/material-blue/views/account/viewpass.inc b/app/modules/web/themes/material-blue/views/account/viewpass.inc index b248e85a..389627b0 100644 --- a/app/modules/web/themes/material-blue/views/account/viewpass.inc +++ b/app/modules/web/themes/material-blue/views/account/viewpass.inc @@ -4,12 +4,12 @@ * @var ThemeIcons $icons * @var AccountExtData $accountData * @var AccountAcl $accountAcl - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData */ use SP\Core\UI\ThemeIcons; use SP\DataModel\AccountExtData; -use SP\Services\Account\AccountAcl; +use SP\Domain\Account\Services\AccountAcl; ?>
diff --git a/app/modules/web/themes/material-blue/views/common/aux-customfields.inc b/app/modules/web/themes/material-blue/views/common/aux-customfields.inc index 5b45f7ab..f5156231 100644 --- a/app/modules/web/themes/material-blue/views/common/aux-customfields.inc +++ b/app/modules/web/themes/material-blue/views/common/aux-customfields.inc @@ -1,14 +1,13 @@ diff --git a/app/modules/web/themes/material-blue/views/config/backup.inc b/app/modules/web/themes/material-blue/views/config/backup.inc index ff7d7c89..9d184bae 100644 --- a/app/modules/web/themes/material-blue/views/config/backup.inc +++ b/app/modules/web/themes/material-blue/views/config/backup.inc @@ -1,14 +1,13 @@ diff --git a/app/modules/web/themes/material-blue/views/config/encryption.inc b/app/modules/web/themes/material-blue/views/config/encryption.inc index 0eb67ca6..a49b3025 100644 --- a/app/modules/web/themes/material-blue/views/config/encryption.inc +++ b/app/modules/web/themes/material-blue/views/config/encryption.inc @@ -1,14 +1,13 @@ isMaintenance() ? '' : 'disabled'; ?> diff --git a/app/modules/web/themes/material-blue/views/config/general-auth.inc b/app/modules/web/themes/material-blue/views/config/general-auth.inc index 7838755c..0fd3b82d 100644 --- a/app/modules/web/themes/material-blue/views/config/general-auth.inc +++ b/app/modules/web/themes/material-blue/views/config/general-auth.inc @@ -1,14 +1,13 @@ diff --git a/app/modules/web/themes/material-blue/views/config/general-events.inc b/app/modules/web/themes/material-blue/views/config/general-events.inc index bea9ae04..09e4801c 100644 --- a/app/modules/web/themes/material-blue/views/config/general-events.inc +++ b/app/modules/web/themes/material-blue/views/config/general-events.inc @@ -1,14 +1,13 @@ diff --git a/app/modules/web/themes/material-blue/views/config/general-proxy.inc b/app/modules/web/themes/material-blue/views/config/general-proxy.inc index 50b326f0..2a1125fe 100644 --- a/app/modules/web/themes/material-blue/views/config/general-proxy.inc +++ b/app/modules/web/themes/material-blue/views/config/general-proxy.inc @@ -1,13 +1,12 @@ diff --git a/app/modules/web/themes/material-blue/views/config/general-site.inc b/app/modules/web/themes/material-blue/views/config/general-site.inc index c894578b..dc06ae8d 100644 --- a/app/modules/web/themes/material-blue/views/config/general-site.inc +++ b/app/modules/web/themes/material-blue/views/config/general-site.inc @@ -1,14 +1,13 @@ diff --git a/app/modules/web/themes/material-blue/views/config/general.inc b/app/modules/web/themes/material-blue/views/config/general.inc index 28ed6dee..70939fd1 100644 --- a/app/modules/web/themes/material-blue/views/config/general.inc +++ b/app/modules/web/themes/material-blue/views/config/general.inc @@ -1,13 +1,12 @@
diff --git a/app/modules/web/themes/material-blue/views/config/info.inc b/app/modules/web/themes/material-blue/views/config/info.inc index a1a13c03..3b54d6f4 100644 --- a/app/modules/web/themes/material-blue/views/config/info.inc +++ b/app/modules/web/themes/material-blue/views/config/info.inc @@ -1,19 +1,18 @@
info diff --git a/app/modules/web/themes/material-blue/views/config/ldap.inc b/app/modules/web/themes/material-blue/views/config/ldap.inc index a90c4a4e..3d65af33 100644 --- a/app/modules/web/themes/material-blue/views/config/ldap.inc +++ b/app/modules/web/themes/material-blue/views/config/ldap.inc @@ -1,14 +1,13 @@ diff --git a/app/modules/web/themes/material-blue/views/config/mail.inc b/app/modules/web/themes/material-blue/views/config/mail.inc index 1fe50fef..ac49f8be 100644 --- a/app/modules/web/themes/material-blue/views/config/mail.inc +++ b/app/modules/web/themes/material-blue/views/config/mail.inc @@ -1,14 +1,13 @@ diff --git a/app/modules/web/themes/material-blue/views/config/wiki-dokuwiki.inc b/app/modules/web/themes/material-blue/views/config/wiki-dokuwiki.inc index 075b40c2..63f1162a 100644 --- a/app/modules/web/themes/material-blue/views/config/wiki-dokuwiki.inc +++ b/app/modules/web/themes/material-blue/views/config/wiki-dokuwiki.inc @@ -1,13 +1,12 @@ diff --git a/app/modules/web/themes/material-blue/views/config/wiki.inc b/app/modules/web/themes/material-blue/views/config/wiki.inc index d44f9d16..07fb833f 100644 --- a/app/modules/web/themes/material-blue/views/config/wiki.inc +++ b/app/modules/web/themes/material-blue/views/config/wiki.inc @@ -1,13 +1,12 @@ diff --git a/app/modules/web/themes/material-blue/views/error/error-database.inc b/app/modules/web/themes/material-blue/views/error/error-database.inc index 32e9c435..8c454fee 100644 --- a/app/modules/web/themes/material-blue/views/error/error-database.inc +++ b/app/modules/web/themes/material-blue/views/error/error-database.inc @@ -1,7 +1,7 @@ diff --git a/app/modules/web/themes/material-blue/views/eventlog/index.inc b/app/modules/web/themes/material-blue/views/eventlog/index.inc index a309e546..d0f4e785 100644 --- a/app/modules/web/themes/material-blue/views/eventlog/index.inc +++ b/app/modules/web/themes/material-blue/views/eventlog/index.inc @@ -2,5 +2,5 @@ echo __('Event Log'); ?> includeTemplate('datagrid-grid', 'grid'); \ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/grid/datagrid-grid.inc b/app/modules/web/themes/material-blue/views/grid/datagrid-grid.inc index c5eb56f4..fb82a4fd 100644 --- a/app/modules/web/themes/material-blue/views/grid/datagrid-grid.inc +++ b/app/modules/web/themes/material-blue/views/grid/datagrid-grid.inc @@ -1,18 +1,17 @@ diff --git a/app/modules/web/themes/material-blue/views/install/index.inc b/app/modules/web/themes/material-blue/views/install/index.inc index bbde0a6b..c23ee40c 100644 --- a/app/modules/web/themes/material-blue/views/install/index.inc +++ b/app/modules/web/themes/material-blue/views/install/index.inc @@ -1,14 +1,13 @@
diff --git a/app/modules/web/themes/material-blue/views/itemshow/account_bulkedit.inc b/app/modules/web/themes/material-blue/views/itemshow/account_bulkedit.inc index a4bfc97b..2f41ba57 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/account_bulkedit.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/account_bulkedit.inc @@ -1,19 +1,18 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/auth_token.inc b/app/modules/web/themes/material-blue/views/itemshow/auth_token.inc index b38e1443..3f4b608b 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/auth_token.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/auth_token.inc @@ -1,16 +1,15 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/category.inc b/app/modules/web/themes/material-blue/views/itemshow/category.inc index 8ded44fb..e09135d5 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/category.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/category.inc @@ -1,15 +1,14 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/client.inc b/app/modules/web/themes/material-blue/views/itemshow/client.inc index 21f3ea08..bb3b9a4d 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/client.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/client.inc @@ -1,15 +1,14 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/custom_field.inc b/app/modules/web/themes/material-blue/views/itemshow/custom_field.inc index 61cf0a1c..28506f2c 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/custom_field.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/custom_field.inc @@ -1,16 +1,15 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/file.inc b/app/modules/web/themes/material-blue/views/itemshow/file.inc index 78b439da..52397b33 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/file.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/file.inc @@ -1,15 +1,14 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/item_preset-password.inc b/app/modules/web/themes/material-blue/views/itemshow/item_preset-password.inc index f8fd3337..11113fd6 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/item_preset-password.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/item_preset-password.inc @@ -1,15 +1,14 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/item_preset-permission.inc b/app/modules/web/themes/material-blue/views/itemshow/item_preset-permission.inc index 17a351d2..db26ff40 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/item_preset-permission.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/item_preset-permission.inc @@ -1,14 +1,13 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/item_preset-private.inc b/app/modules/web/themes/material-blue/views/itemshow/item_preset-private.inc index 6c1e35a1..e0f0a91a 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/item_preset-private.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/item_preset-private.inc @@ -1,15 +1,14 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/item_preset-session_timeout.inc b/app/modules/web/themes/material-blue/views/itemshow/item_preset-session_timeout.inc index 980110e9..9305a9aa 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/item_preset-session_timeout.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/item_preset-session_timeout.inc @@ -1,15 +1,14 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/item_preset.inc b/app/modules/web/themes/material-blue/views/itemshow/item_preset.inc index d1bed86f..515a4998 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/item_preset.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/item_preset.inc @@ -1,16 +1,15 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/public_link.inc b/app/modules/web/themes/material-blue/views/itemshow/public_link.inc index 72b685d6..d4b4a7bf 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/public_link.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/public_link.inc @@ -1,16 +1,15 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/results.inc b/app/modules/web/themes/material-blue/views/itemshow/results.inc index b23ff527..9215091a 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/results.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/results.inc @@ -1,13 +1,12 @@
diff --git a/app/modules/web/themes/material-blue/views/itemshow/tag.inc b/app/modules/web/themes/material-blue/views/itemshow/tag.inc index ada5ccf8..d9a004f9 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/tag.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/tag.inc @@ -1,15 +1,14 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/user.inc b/app/modules/web/themes/material-blue/views/itemshow/user.inc index 9f7584fb..d7be6ac5 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/user.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/user.inc @@ -1,16 +1,15 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/user_group.inc b/app/modules/web/themes/material-blue/views/itemshow/user_group.inc index 89d24ddb..186930b2 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/user_group.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/user_group.inc @@ -1,18 +1,17 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/user_pass.inc b/app/modules/web/themes/material-blue/views/itemshow/user_pass.inc index 66fc0aa5..151ca0a3 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/user_pass.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/user_pass.inc @@ -1,15 +1,14 @@ diff --git a/app/modules/web/themes/material-blue/views/itemshow/user_profile.inc b/app/modules/web/themes/material-blue/views/itemshow/user_profile.inc index c2a62db4..90cd3201 100644 --- a/app/modules/web/themes/material-blue/views/itemshow/user_profile.inc +++ b/app/modules/web/themes/material-blue/views/itemshow/user_profile.inc @@ -1,17 +1,16 @@ diff --git a/app/modules/web/themes/material-blue/views/main/update.inc b/app/modules/web/themes/material-blue/views/main/update.inc index 2897c696..e2a7f8e1 100644 --- a/app/modules/web/themes/material-blue/views/main/update.inc +++ b/app/modules/web/themes/material-blue/views/main/update.inc @@ -1,13 +1,12 @@ diff --git a/app/modules/web/themes/material-blue/views/main/upgrade.inc b/app/modules/web/themes/material-blue/views/main/upgrade.inc index 682b408f..33f89063 100644 --- a/app/modules/web/themes/material-blue/views/main/upgrade.inc +++ b/app/modules/web/themes/material-blue/views/main/upgrade.inc @@ -1,16 +1,15 @@

diff --git a/app/modules/web/themes/material-blue/views/notification/index.inc b/app/modules/web/themes/material-blue/views/notification/index.inc index b188e3e8..1407c3be 100644 --- a/app/modules/web/themes/material-blue/views/notification/index.inc +++ b/app/modules/web/themes/material-blue/views/notification/index.inc @@ -2,5 +2,5 @@ echo __('Notifications'); ?> includeTemplate('datagrid-grid', 'grid'); \ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/notification/notification.inc b/app/modules/web/themes/material-blue/views/notification/notification.inc index 87a4697b..edd42cef 100644 --- a/app/modules/web/themes/material-blue/views/notification/notification.inc +++ b/app/modules/web/themes/material-blue/views/notification/notification.inc @@ -2,15 +2,14 @@ /** * @var NotificationData $notification * @var ThemeIcons $icons - * @var \SP\Config\ConfigDataInterface $configData + * @var \SP\Domain\Config\In\ConfigDataInterface $configData * @var callable $_getvar - * @var Template $this + * @var \SP\Mvc\View\TemplateInterface $this */ use SP\Core\UI\ThemeIcons; use SP\DataModel\NotificationData; use SP\Mvc\View\Components\SelectItem; -use SP\Mvc\View\Template; use SP\Util\DateUtil; $notification = $_getvar('notification'); diff --git a/app/modules/web/themes/material-blue/views/plugin/index.inc b/app/modules/web/themes/material-blue/views/plugin/index.inc index 49c701fb..bf250b73 100644 --- a/app/modules/web/themes/material-blue/views/plugin/index.inc +++ b/app/modules/web/themes/material-blue/views/plugin/index.inc @@ -2,5 +2,5 @@ echo __('Plugins'); ?> includeTemplate('datagrid-grid', 'grid'); \ No newline at end of file diff --git a/app/modules/web/themes/material-blue/views/plugin/plugin.inc b/app/modules/web/themes/material-blue/views/plugin/plugin.inc index 1d120955..06176008 100644 --- a/app/modules/web/themes/material-blue/views/plugin/plugin.inc +++ b/app/modules/web/themes/material-blue/views/plugin/plugin.inc @@ -1,17 +1,16 @@ diff --git a/app/modules/web/themes/material-blue/views/usersettings/general.inc b/app/modules/web/themes/material-blue/views/usersettings/general.inc index be6bacab..d66c2a79 100644 --- a/app/modules/web/themes/material-blue/views/usersettings/general.inc +++ b/app/modules/web/themes/material-blue/views/usersettings/general.inc @@ -1,16 +1,15 @@ diff --git a/app/modules/web/themes/material-blue/views/wiki/wikipage.inc b/app/modules/web/themes/material-blue/views/wiki/wikipage.inc index 49bb7250..bb7fde55 100644 --- a/app/modules/web/themes/material-blue/views/wiki/wikipage.inc +++ b/app/modules/web/themes/material-blue/views/wiki/wikipage.inc @@ -1,13 +1,12 @@ =2,<=2.5.24", "ezsystems/ezplatform-admin-ui": ">=1.3,<1.3.5|>=1.4,<1.4.6|>=1.5,<1.5.27", "ezsystems/ezplatform-admin-ui-assets": ">=4,<4.2.1|>=5,<5.0.1|>=5.1,<5.1.1", - "ezsystems/ezplatform-kernel": "<=1.2.5|>=1.3,<1.3.17", + "ezsystems/ezplatform-kernel": "<=1.2.5|>=1.3,<1.3.19", "ezsystems/ezplatform-rest": ">=1.2,<=1.2.2|>=1.3,<1.3.8", "ezsystems/ezplatform-richtext": ">=2.3,<=2.3.7", "ezsystems/ezplatform-user": ">=1,<1.0.1", - "ezsystems/ezpublish-kernel": "<=6.13.8.1|>=7,<7.5.28", + "ezsystems/ezpublish-kernel": "<=6.13.8.1|>=7,<7.5.29", "ezsystems/ezpublish-legacy": "<=2017.12.7.3|>=2018.6,<=2019.3.5.1", "ezsystems/platform-ui-assets-bundle": ">=4.2,<4.2.3", "ezsystems/repository-forms": ">=2.3,<2.3.2.1", @@ -5087,12 +5087,12 @@ "grumpydictator/firefly-iii": "<5.6.5", "guzzlehttp/guzzle": "<6.5.6|>=7,<7.4.3", "guzzlehttp/psr7": "<1.8.4|>=2,<2.1.1", - "helloxz/imgurl": "<=2.31", + "helloxz/imgurl": "= 2.31|<=2.31", "hillelcoren/invoice-ninja": "<5.3.35", "hjue/justwriting": "<=1", "hov/jobfair": "<1.0.13|>=2,<2.0.2", "hyn/multi-tenant": ">=5.6,<5.7.2", - "ibexa/core": ">=4,<4.0.5|>=4.1,<4.1.2", + "ibexa/core": ">=4,<4.0.7|>=4.1,<4.1.4", "ibexa/post-install": "<=1.0.4", "icecoder/icecoder": "<=8.1", "illuminate/auth": ">=4,<4.0.99|>=4.1,<=4.1.31|>=4.2,<=4.2.22|>=5,<=5.0.35|>=5.1,<=5.1.46|>=5.2,<=5.2.45|>=5.3,<=5.3.31|>=5.4,<=5.4.36|>=5.5,<5.5.10", @@ -5131,7 +5131,7 @@ "league/commonmark": "<0.18.3", "league/flysystem": "<1.1.4|>=2,<2.1.1", "lexik/jwt-authentication-bundle": "<2.10.7|>=2.11,<2.11.3", - "librenms/librenms": "<22.2.2", + "librenms/librenms": "<22.4", "limesurvey/limesurvey": "<3.27.19", "livehelperchat/livehelperchat": "<=3.91", "livewire/livewire": ">2.2.4,<2.2.6", @@ -5150,8 +5150,9 @@ "miniorange/miniorange-saml": "<1.4.3", "mittwald/typo3_forum": "<1.2.1", "modx/revolution": "<= 2.8.3-pl|<2.8", + "mojo42/jirafeau": "<4.4", "monolog/monolog": ">=1.8,<1.12", - "moodle/moodle": "<3.9.13|>=3.10-beta,<3.10.10|>=3.11,<3.11.6", + "moodle/moodle": "<4.0.1", "mustache/mustache": ">=2,<2.14.1", "namshi/jose": "<2.2", "neoan3-apps/template": "<1.1.1", @@ -5429,7 +5430,7 @@ "type": "tidelift" } ], - "time": "2022-05-25T23:04:15+00:00" + "time": "2022-06-03T23:04:18+00:00" }, { "name": "sebastian/cli-parser", diff --git a/lib/Base.php b/lib/Base.php index 7d9f8213..5b27c2ac 100644 --- a/lib/Base.php +++ b/lib/Base.php @@ -49,7 +49,7 @@ $dotenv = Dotenv::createImmutable(APP_ROOT); $dotenv->load(); defined('APP_MODULE') || define('APP_MODULE', 'web'); -define('DEBUG', getenv('DEBUG')); +define('DEBUG', (bool)getenv('DEBUG')); define( 'IS_TESTING', getenv('IS_TESTING') @@ -108,12 +108,15 @@ define( try { $moduleDefinitions = initModule(APP_MODULE); - return (new ContainerBuilder) - ->writeProxiesToFile(true, CACHE_PATH.DS.'proxies') - ->addDefinitions( - BASE_PATH.DS.'Definitions.php', - $moduleDefinitions - ) + $containerBuilder = new ContainerBuilder; + + if (!DEBUG) { + $containerBuilder->enableCompilation(CACHE_PATH); + $containerBuilder->writeProxiesToFile(true, CACHE_PATH.DS.'proxies'); + } + + return $containerBuilder + ->addDefinitions(BASE_PATH.DS.'Definitions.php', $moduleDefinitions) ->build(); } catch (Exception $e) { processException($e); diff --git a/lib/BaseFunctions.php b/lib/BaseFunctions.php index 9e63a72c..7d5d2ec1 100644 --- a/lib/BaseFunctions.php +++ b/lib/BaseFunctions.php @@ -31,7 +31,7 @@ const LOG_FORMAT = "[%s] [%s] %s"; /** * [timestamp] [type] [caller] data */ -const LOG_FORMAT_OWN = '[%s] syspass.%s: logger {"message":"%s","caller":"%s"}' . PHP_EOL; +const LOG_FORMAT_OWN = '[%s] syspass.%s: logger {"message":"%s","caller":"%s"}'.PHP_EOL; /** * Basic logger to handle some debugging and exception messages. @@ -42,10 +42,10 @@ const LOG_FORMAT_OWN = '[%s] syspass.%s: logger {"message":"%s","caller":"%s"}' * * A more advanced event logging should be handled through EventDispatcher * - * @param mixed $data - * @param string|null $type + * @param mixed $data + * @param string $type */ -function logger($data, ?string $type = 'DEBUG') +function logger($data, string $type = 'DEBUG') { if (!DEBUG && $type === 'DEBUG') { return; @@ -62,7 +62,7 @@ function logger($data, ?string $type = 'DEBUG') ); $useOwn = (!defined('LOG_FILE') - || !@error_log($line, 3, LOG_FILE) + || !@error_log($line, 3, LOG_FILE) ); if ($useOwn === false) { @@ -93,7 +93,7 @@ function getLastCaller(int $skip = 2): string $callers = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5); if (isset($callers[$skip]['class'], $callers[$skip]['function'])) { - return $callers[$skip]['class'] . '::' . $callers[$skip]['function']; + return $callers[$skip]['class'].'::'.$callers[$skip]['function']; } return 'N/A'; @@ -153,22 +153,28 @@ function formatStackTrace(Throwable $e): string /** * Process an exception and log into the error log * - * @param \Exception $exception + * @param \Exception $exception */ function processException(Exception $exception) { - logger(sprintf( - "%s\n%s", - __($exception->getMessage()), - formatStackTrace($exception)), - 'EXCEPTION'); + logger( + sprintf( + "%s\n%s", + __($exception->getMessage()), + formatStackTrace($exception) + ), + 'EXCEPTION' + ); if (($previous = $exception->getPrevious()) !== null) { - logger(sprintf( - "(P) %s\n%s", - __($previous->getMessage()), - $previous->getTraceAsString()), - 'EXCEPTION'); + logger( + sprintf( + "(P) %s\n%s", + __($previous->getMessage()), + $previous->getTraceAsString() + ), + 'EXCEPTION' + ); } } @@ -199,14 +205,14 @@ function formatTrace(array $trace): string /** * Alias gettext function * - * @param string $message - * @param bool $translate Si es necesario traducir + * @param string $message + * @param bool $translate Si es necesario traducir */ function __(string $message, bool $translate = true): string { return $translate === true - && $message !== '' - && mb_strlen($message) < 4096 + && $message !== '' + && mb_strlen($message) < 4096 ? gettext($message) : $message; } @@ -226,8 +232,8 @@ function __u(string $message): string function _t(string $domain, string $message, bool $translate = true): string { return $translate === true - && $message !== '' - && mb_strlen($message) < 4096 + && $message !== '' + && mb_strlen($message) < 4096 ? dgettext($domain, $message) : $message; } @@ -264,7 +270,7 @@ function initModule(string $module): array { logger(sprintf('Initializing module: %s', $module)); - $moduleFile = MODULES_PATH . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'module.php'; + $moduleFile = MODULES_PATH.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.'module.php'; if (is_dir(MODULES_PATH) && file_exists($moduleFile)) { $definitions = require $moduleFile; @@ -287,9 +293,9 @@ function initModule(string $module): array function nDirname($dir, $levels) { if (version_compare(PHP_VERSION, '7.0') === -1) { - logger(realpath(dirname($dir) . str_repeat('../', $levels))); + logger(realpath(dirname($dir).str_repeat('../', $levels))); - return realpath(dirname($dir) . str_repeat('../', $levels)); + return realpath(dirname($dir).str_repeat('../', $levels)); } return dirname($dir, $levels); diff --git a/lib/Definitions.php b/lib/Definitions.php index aa90b2e3..b25f21c2 100644 --- a/lib/Definitions.php +++ b/lib/Definitions.php @@ -24,76 +24,166 @@ use Monolog\Logger; use PHPMailer\PHPMailer\PHPMailer; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; +use Psr\Container\ContainerInterface; use SP\Core\Acl\Acl; use SP\Core\Acl\Actions; +use SP\Core\Application; use SP\Core\Context\ContextFactory; use SP\Core\Context\ContextInterface; use SP\Core\Crypt\CSRF; +use SP\Core\Language; +use SP\Core\LanguageInterface; use SP\Core\MimeTypes; +use SP\Core\MimeTypesInterface; use SP\Core\UI\Theme; use SP\Core\UI\ThemeInterface; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigBackupService; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\Providers\MailerInterface; +use SP\Domain\Providers\MailProviderInterface; use SP\Http\Client; use SP\Http\Request; -use SP\Services\Account\AccountAclService; -use SP\Services\Config\ConfigBackupService; -use SP\Storage\Database\DatabaseConnectionData; -use SP\Storage\Database\DBStorageInterface; -use SP\Storage\Database\MySQLHandler; -use SP\Storage\File\FileCache; -use SP\Storage\File\FileHandler; -use SP\Storage\File\XmlHandler; +use SP\Http\RequestInterface; +use SP\Infrastructure\Database\Database; +use SP\Infrastructure\Database\DatabaseConnectionData; +use SP\Infrastructure\Database\DatabaseInterface; +use SP\Infrastructure\Database\DBStorageInterface; +use SP\Infrastructure\Database\MySQLHandler; +use SP\Infrastructure\File\FileCache; +use SP\Infrastructure\File\FileHandler; +use SP\Infrastructure\File\XmlHandler; +use SP\Mvc\View\Template; +use SP\Mvc\View\TemplateInterface; +use SP\Providers\Auth\AuthProvider; +use SP\Providers\Auth\AuthProviderInterface; +use SP\Providers\Auth\Browser\BrowserAuth; +use SP\Providers\Auth\Browser\BrowserAuthInterface; +use SP\Providers\Auth\Database\DatabaseAuth; +use SP\Providers\Auth\Database\DatabaseAuthInterface; +use SP\Providers\Auth\Ldap\Ldap; +use SP\Providers\Auth\Ldap\LdapAuth; +use SP\Providers\Auth\Ldap\LdapAuthInterface; +use SP\Providers\Auth\Ldap\LdapParams; +use SP\Providers\Mail\MailProvider; +use SP\Providers\Mail\PhpMailerWrapper; use function DI\autowire; use function DI\create; use function DI\factory; use function DI\get; return [ - Request::class => create(Request::class) + RequestInterface::class => create(Request::class) ->constructor(\Klein\Request::createFromGlobals()), - ContextInterface::class => + ContextInterface::class => static fn() => ContextFactory::getForModule(APP_MODULE), - Config::class => create(Config::class) + ConfigInterface::class => create(ConfigFileService::class) ->constructor( - new XmlHandler(new FileHandler(CONFIG_FILE)), - new FileCache(Config::CONFIG_CACHE_FILE), + create(XmlHandler::class) + ->constructor(create(FileHandler::class)->constructor(CONFIG_FILE)), + create(FileCache::class)->constructor(ConfigFileService::CONFIG_CACHE_FILE), get(ContextInterface::class), autowire(ConfigBackupService::class)->lazy() ), - ConfigDataInterface::class => - static fn(Config $config) => $config->getConfigData(), - DBStorageInterface::class => create(MySQLHandler::class) - ->constructor( - factory([DatabaseConnectionData::class, 'getFromConfig']) - ), - Actions::class => + ConfigDataInterface::class => + static fn(ConfigInterface $config) => $config->getConfigData(), + DBStorageInterface::class => create(MySQLHandler::class) + ->constructor(factory([DatabaseConnectionData::class, 'getFromConfig'])), + Actions::class => static fn() => new Actions( new FileCache(Actions::ACTIONS_CACHE_FILE), new XmlHandler(new FileHandler(ACTIONS_FILE)) ), - MimeTypes::class => + MimeTypesInterface::class => static fn() => new MimeTypes( new FileCache(MimeTypes::MIME_CACHE_FILE), new XmlHandler(new FileHandler(MIMETYPES_FILE)) ), - Acl::class => autowire(Acl::class) + Acl::class => autowire(Acl::class) ->constructorParameter( 'action', get(Actions::class) ), - ThemeInterface::class => autowire(Theme::class) + ThemeInterface::class => autowire(Theme::class) ->constructorParameter('module', APP_MODULE) ->constructorParameter( 'fileCache', - new FileCache(Theme::ICONS_CACHE_FILE) + create(FileCache::class)->constructor(Theme::ICONS_CACHE_FILE) ), - PHPMailer::class => create(PHPMailer::class) - ->constructor(true), - Logger::class => create(Logger::class) + TemplateInterface::class => autowire(Template::class), + DatabaseAuthInterface::class => autowire(DatabaseAuth::class), + BrowserAuthInterface::class => autowire(BrowserAuth::class), + LdapAuthInterface::class => autowire(LdapAuth::class) + ->constructorParameter( + 'ldap', + factory([Ldap::class, 'factory']) + ->parameter('ldapParams', factory([LdapParams::class, 'getFrom'])) + ), + AuthProviderInterface::class => static function ( + ContainerInterface $c, + ConfigDataInterface $configData + ) { + $provider = new AuthProvider($c->get(Application::class), $c->get(DatabaseAuthInterface::class)); + + if ($configData->isLdapEnabled()) { + $provider->withLdapAuth($c->get(LdapAuthInterface::class)); + } + + if ($configData->isAuthBasicEnabled()) { + $provider->withBrowserAuth($c->get(BrowserAuthInterface::class)); + } + + return $provider; + }, + Logger::class => create(Logger::class) ->constructor('syspass'), - AccountAclService::class => autowire(AccountAclService::class), - \GuzzleHttp\Client::class => create(GuzzleHttp\Client::class) + \GuzzleHttp\Client::class => create(GuzzleHttp\Client::class) ->constructor(factory([Client::class, 'getOptions'])), - CSRF::class => autowire(CSRF::class), + CSRF::class => autowire(CSRF::class), + LanguageInterface::class => autowire(Language::class), + DatabaseInterface::class => autowire(Database::class), + MailProviderInterface::class => autowire(MailProvider::class), + MailerInterface::class => autowire(PhpMailerWrapper::class)->constructor( + create(PHPMailer::class)->constructor(true) + ), + 'SP\Domain\Account\*ServiceInterface' => autowire('SP\Domain\Account\Services\*Service'), + 'SP\Domain\Account\In\*RepositoryInterface' => autowire('SP\Infrastructure\Account\Repositories\*Repository'), + 'SP\Domain\Category\*ServiceInterface' => autowire('SP\Domain\Category\Services\*Service'), + 'SP\Domain\Category\In\*RepositoryInterface' => autowire('SP\Infrastructure\Category\Repositories\*Repository'), + 'SP\Domain\Client\*ServiceInterface' => autowire('SP\Domain\Client\Services\*Service'), + 'SP\Domain\Client\In\*RepositoryInterface' => autowire('SP\Infrastructure\Client\Repositories\*Repository'), + 'SP\Domain\Tag\*ServiceInterface' => autowire('SP\Domain\Tag\Services\*Service'), + 'SP\Domain\Tag\In\*RepositoryInterface' => autowire('SP\Infrastructure\Tag\Repositories\*Repository'), + 'SP\Domain\User\*ServiceInterface' => autowire('SP\Domain\User\Services\*Service'), + 'SP\Domain\User\In\*RepositoryInterface' => autowire('SP\Infrastructure\User\Repositories\*Repository'), + 'SP\Domain\Auth\*ServiceInterface' => autowire('SP\Domain\Auth\Services\*Service'), + 'SP\Domain\Auth\In\*RepositoryInterface' => autowire('SP\Infrastructure\Auth\Repositories\*Repository'), + 'SP\Domain\CustomField\*ServiceInterface' => autowire('SP\Domain\CustomField\Services\*Service'), + 'SP\Domain\CustomField\In\*RepositoryInterface' => autowire( + 'SP\Infrastructure\CustomField\Repositories\*Repository' + ), + 'SP\Domain\Export\*ServiceInterface' => autowire('SP\Domain\Export\Services\*Service'), + 'SP\Domain\Import\*ServiceInterface' => autowire('SP\Domain\Import\Services\*Service'), + 'SP\Domain\Crypt\*ServiceInterface' => autowire('SP\Domain\Crypt\Services\*Service'), + 'SP\Domain\Plugin\*ServiceInterface' => autowire('SP\Domain\Plugin\Services\*Service'), + 'SP\Domain\ItemPreset\*ServiceInterface' => autowire('SP\Domain\ItemPreset\Services\*Service'), + 'SP\Domain\ItemPreset\In\*RepositoryInterface' => autowire( + 'SP\Infrastructure\ItemPreset\Repositories\*Repository' + ), + 'SP\Domain\Notification\*ServiceInterface' => autowire('SP\Domain\Notification\Services\*Service'), + 'SP\Domain\Notification\In\*RepositoryInterface' => autowire( + 'SP\Infrastructure\Notification\Repositories\*Repository' + ), + 'SP\Domain\Security\*ServiceInterface' => autowire('SP\Domain\Security\Services\*Service'), + 'SP\Domain\Security\In\*RepositoryInterface' => autowire( + 'SP\Infrastructure\Security\Repositories\*Repository' + ), + 'SP\Domain\Config\*ServiceInterface' => autowire('SP\Domain\Config\Services\*Service'), + 'SP\Domain\Config\In\*RepositoryInterface' => autowire( + 'SP\Infrastructure\Config\Repositories\*Repository' + ), + 'SP\Domain\Plugin\In\*RepositoryInterface' => autowire( + 'SP\Infrastructure\Plugin\Repositories\*Repository' + ), ]; \ No newline at end of file diff --git a/lib/SP/Adapters/AccountAdapter.php b/lib/SP/Adapters/AccountAdapter.php index a4e996d9..148aeaa8 100644 --- a/lib/SP/Adapters/AccountAdapter.php +++ b/lib/SP/Adapters/AccountAdapter.php @@ -48,7 +48,7 @@ final class AccountAdapter extends AdapterBase * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function includeCustomFields(AccountDetailsResponse $data): Collection { diff --git a/lib/SP/Adapters/AdapterBase.php b/lib/SP/Adapters/AdapterBase.php index 35b1a328..1c02c4e6 100644 --- a/lib/SP/Adapters/AdapterBase.php +++ b/lib/SP/Adapters/AdapterBase.php @@ -26,7 +26,7 @@ namespace SP\Adapters; use League\Fractal\TransformerAbstract; -use SP\Config\ConfigDataInterface; +use SP\Domain\Config\In\ConfigDataInterface; /** * Class AdapterBase diff --git a/lib/SP/Adapters/CategoryAdapter.php b/lib/SP/Adapters/CategoryAdapter.php index af0d702a..03db94cd 100644 --- a/lib/SP/Adapters/CategoryAdapter.php +++ b/lib/SP/Adapters/CategoryAdapter.php @@ -47,7 +47,7 @@ final class CategoryAdapter extends AdapterBase * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function includeCustomFields(CategoryData $data): Collection { diff --git a/lib/SP/Adapters/ClientAdapter.php b/lib/SP/Adapters/ClientAdapter.php index 62c30127..cae3c795 100644 --- a/lib/SP/Adapters/ClientAdapter.php +++ b/lib/SP/Adapters/ClientAdapter.php @@ -47,7 +47,7 @@ final class ClientAdapter extends AdapterBase * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function includeCustomFields(ClientData $data): Collection { diff --git a/lib/SP/Adapters/CustomFieldAdapter.php b/lib/SP/Adapters/CustomFieldAdapter.php index 7e5dfbc6..9b0898f9 100644 --- a/lib/SP/Adapters/CustomFieldAdapter.php +++ b/lib/SP/Adapters/CustomFieldAdapter.php @@ -25,7 +25,7 @@ namespace SP\Adapters; -use SP\Services\CustomField\CustomFieldItem; +use SP\Domain\CustomField\Services\CustomFieldItem; /** * Class CustomFieldAdapter diff --git a/lib/SP/Core/Acl/Acl.php b/lib/SP/Core/Acl/Acl.php index f1de53b7..cf453990 100644 --- a/lib/SP/Core/Acl/Acl.php +++ b/lib/SP/Core/Acl/Acl.php @@ -35,7 +35,7 @@ defined('APP_ROOT') || die(); /** * Esta clase es la encargada de calcular las access lists de acceso a usuarios. */ -final class Acl implements ActionsInterface +class Acl implements ActionsInterface { protected static ?Actions $action; private ContextInterface $context; diff --git a/lib/SP/Core/Acl/Actions.php b/lib/SP/Core/Acl/Actions.php index c3422283..63a1fc34 100644 --- a/lib/SP/Core/Acl/Actions.php +++ b/lib/SP/Core/Acl/Actions.php @@ -26,16 +26,16 @@ namespace SP\Core\Acl; use RuntimeException; use SP\DataModel\ActionData; -use SP\Storage\File\FileCacheInterface; -use SP\Storage\File\FileException; -use SP\Storage\File\XmlFileStorageInterface; +use SP\Infrastructure\File\FileCacheInterface; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\XmlFileStorageInterface; /** * Class Actions * * @package SP\Core\Acl */ -final class Actions +class Actions { /** * Cache file name diff --git a/lib/SP/Core/Application.php b/lib/SP/Core/Application.php index 17ce413e..204fd99c 100644 --- a/lib/SP/Core/Application.php +++ b/lib/SP/Core/Application.php @@ -25,28 +25,28 @@ namespace SP\Core; -use SP\Config\Config; use SP\Core\Context\ContextInterface; use SP\Core\Events\EventDispatcher; +use SP\Domain\Config\ConfigInterface; /** * The Application helper class. It holds all the needed dependencies for the application */ final class Application { - private Config $config; + private ConfigInterface $config; private EventDispatcher $eventDispatcher; private ContextInterface $context; /** * Module constructor. * - * @param \SP\Config\Config $config - * @param \SP\Core\Events\EventDispatcher $eventDispatcher - * @param \SP\Core\Context\ContextInterface $context + * @param ConfigInterface $config + * @param EventDispatcher $eventDispatcher + * @param ContextInterface $context */ public function __construct( - Config $config, + ConfigInterface $config, EventDispatcher $eventDispatcher, ContextInterface $context ) { @@ -55,25 +55,16 @@ final class Application $this->context = $context; } - /** - * @return \SP\Config\Config - */ - public function getConfig(): Config + public function getConfig(): ConfigInterface { return $this->config; } - /** - * @return \SP\Core\Events\EventDispatcher - */ public function getEventDispatcher(): EventDispatcher { return $this->eventDispatcher; } - /** - * @return \SP\Core\Context\ContextInterface - */ public function getContext(): ContextInterface { return $this->context; diff --git a/lib/SP/Core/Bootstrap/BootstrapApi.php b/lib/SP/Core/Bootstrap/BootstrapApi.php index 45294d7d..7dc39c40 100644 --- a/lib/SP/Core/Bootstrap/BootstrapApi.php +++ b/lib/SP/Core/Bootstrap/BootstrapApi.php @@ -30,9 +30,9 @@ use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use SP\Core\HttpModuleBase; +use SP\Domain\Api\Services\ApiRequest; +use SP\Domain\Api\Services\JsonRpcResponse; use SP\Modules\Api\Init as InitApi; -use SP\Services\Api\ApiRequest; -use SP\Services\Api\JsonRpcResponse; /** * Bootstrap API interface diff --git a/lib/SP/Core/Bootstrap/BootstrapBase.php b/lib/SP/Core/Bootstrap/BootstrapBase.php index 1a94fc8d..64f7ae84 100644 --- a/lib/SP/Core/Bootstrap/BootstrapBase.php +++ b/lib/SP/Core/Bootstrap/BootstrapBase.php @@ -29,13 +29,13 @@ use Klein\Klein; use Klein\Response; use PHPMailer\PHPMailer\Exception; use Psr\Container\ContainerInterface; -use SP\Config\ConfigDataInterface; -use SP\Config\ConfigUtil; use SP\Core\Exceptions\InitializationException; use SP\Core\Exceptions\SPException; use SP\Core\Language; use SP\Core\PhpExtensionChecker; -use SP\Http\Request; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigUtil; +use SP\Http\RequestInterface; use SP\Plugin\PluginManager; use SP\Util\Checks; use Symfony\Component\Debug\Debug; @@ -67,7 +67,7 @@ abstract class BootstrapBase public static bool $checkPhpVersion = false; protected static ContainerInterface $container; protected Klein $router; - protected Request $request; + protected RequestInterface $request; protected ConfigDataInterface $configData; private UpgradeConfigChecker $upgradeConfigChecker; @@ -77,7 +77,7 @@ abstract class BootstrapBase final public function __construct( ConfigDataInterface $configData, Klein $router, - Request $request, + RequestInterface $request, UpgradeConfigChecker $upgradeConfigChecker ) { // Set the default language @@ -145,8 +145,17 @@ abstract class BootstrapBase return self::$container; } - final protected static function getClassFor(string $controllerName): string + final protected static function getClassFor(string $controllerName, ?string $actionName): string { + if ($actionName !== null) { + return sprintf( + 'SP\Modules\%s\Controllers\%s\%sController', + ucfirst(APP_MODULE), + ucfirst($controllerName), + ucfirst($actionName) + ); + } + return sprintf( 'SP\Modules\%s\Controllers\%sController', ucfirst(APP_MODULE), @@ -170,7 +179,7 @@ abstract class BootstrapBase * @throws \SP\Core\Exceptions\CheckException * @throws \SP\Core\Exceptions\ConfigException * @throws \SP\Core\Exceptions\InitializationException - * @throws \SP\Services\Upgrade\UpgradeException + * @throws \SP\Domain\Upgrade\Services\UpgradeException */ final protected function initializeCommon(): void { @@ -245,15 +254,7 @@ abstract class BootstrapBase */ private function initPHPVars(): void { - if (defined('DEBUG') && DEBUG) { - /** @noinspection ForgottenDebugOutputInspection */ - Debug::enable(); - } elseif (!defined('DEBUG') - && ($this->router->request()->cookies()->get('XDEBUG_SESSION') - || $this->configData->isDebug()) - ) { - define('DEBUG', true); - + if (DEBUG) { /** @noinspection ForgottenDebugOutputInspection */ Debug::enable(); } else { @@ -306,7 +307,7 @@ abstract class BootstrapBase * Cargar la configuración * * @throws \SP\Core\Exceptions\ConfigException - * @throws \SP\Services\Upgrade\UpgradeException + * @throws \SP\Domain\Upgrade\Services\UpgradeException */ private function initConfig(): void { diff --git a/lib/SP/Core/Bootstrap/BootstrapWeb.php b/lib/SP/Core/Bootstrap/BootstrapWeb.php index fd1bc11c..8e9e6146 100644 --- a/lib/SP/Core/Bootstrap/BootstrapWeb.php +++ b/lib/SP/Core/Bootstrap/BootstrapWeb.php @@ -104,9 +104,8 @@ final class BootstrapWeb extends BootstrapBase } $controllerName = $matches['controller'][0]; - $methodName = empty($matches['action'][0]) - ? 'indexAction' - : $matches['action'][0].'Action'; + $actionName = empty($matches['action'][0]) ? 'index' : $matches['action'][0]; + $methodName = sprintf('%sAction', $actionName); $methodParams = empty($matches['params'][0]) ? [] : Filter::getArray( @@ -119,7 +118,7 @@ final class BootstrapWeb extends BootstrapBase ) ); - $controllerClass = self::getClassFor($controllerName); + $controllerClass = self::getClassFor($controllerName, $actionName); $this->initializePluginClasses(); @@ -162,7 +161,11 @@ final class BootstrapWeb extends BootstrapBase $response->code(503); } - return __($e->getMessage()); + echo __($e->getMessage()); + + if (DEBUG) { + echo $e->getTraceAsString(); + } } }; } diff --git a/lib/SP/Core/Bootstrap/UpgradeConfigChecker.php b/lib/SP/Core/Bootstrap/UpgradeConfigChecker.php index 2493f67e..2f88b870 100644 --- a/lib/SP/Core/Bootstrap/UpgradeConfigChecker.php +++ b/lib/SP/Core/Bootstrap/UpgradeConfigChecker.php @@ -25,20 +25,21 @@ namespace SP\Core\Bootstrap; -use SP\Config\ConfigDataInterface; -use SP\Services\Upgrade\UpgradeConfigService; -use SP\Services\Upgrade\UpgradeUtil; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\UpgradeConfigService; +use SP\Domain\Config\UpgradeConfigServiceInterface; +use SP\Domain\Upgrade\Services\UpgradeUtil; use SP\Util\VersionUtil; /** * Upgrade the config whenever is needed */ -final class UpgradeConfigChecker +class UpgradeConfigChecker { private UpgradeConfigService $upgradeConfigService; private ConfigDataInterface $configData; - public function __construct(UpgradeConfigService $upgradeConfigService, ConfigDataInterface $configData) + public function __construct(UpgradeConfigServiceInterface $upgradeConfigService, ConfigDataInterface $configData) { $this->upgradeConfigService = $upgradeConfigService; $this->configData = $configData; @@ -47,7 +48,7 @@ final class UpgradeConfigChecker /** * Comprobar la versión de configuración y actualizarla * - * @throws \SP\Services\Upgrade\UpgradeException + * @throws \SP\Domain\Upgrade\Services\UpgradeException */ public function checkConfigVersion(): void { diff --git a/lib/SP/Core/Context/ContextInterface.php b/lib/SP/Core/Context/ContextInterface.php index 8b7921a4..406ba70c 100644 --- a/lib/SP/Core/Context/ContextInterface.php +++ b/lib/SP/Core/Context/ContextInterface.php @@ -26,7 +26,7 @@ namespace SP\Core\Context; use SP\DataModel\Dto\AccountCache; use SP\DataModel\ProfileData; -use SP\Services\User\UserLoginResponse; +use SP\Domain\User\Services\UserLoginResponse; /** * Class ContextInterface diff --git a/lib/SP/Core/Context/SessionContext.php b/lib/SP/Core/Context/SessionContext.php index f004bdc7..4117f7ee 100644 --- a/lib/SP/Core/Context/SessionContext.php +++ b/lib/SP/Core/Context/SessionContext.php @@ -27,15 +27,15 @@ namespace SP\Core\Context; use SP\Core\Crypt\Vault; use SP\DataModel\Dto\AccountCache; use SP\DataModel\ProfileData; -use SP\Services\Account\AccountSearchFilter; -use SP\Services\User\UserLoginResponse; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Domain\User\Services\UserLoginResponse; /** * Class Session * * @package SP\Core\Session */ -final class SessionContext extends ContextBase +class SessionContext extends ContextBase { public const MAX_SID_TIME = 120; diff --git a/lib/SP/Core/Context/StatelessContext.php b/lib/SP/Core/Context/StatelessContext.php index 03c21567..2cb250a8 100644 --- a/lib/SP/Core/Context/StatelessContext.php +++ b/lib/SP/Core/Context/StatelessContext.php @@ -25,14 +25,14 @@ namespace SP\Core\Context; use SP\DataModel\ProfileData; -use SP\Services\User\UserLoginResponse; +use SP\Domain\User\Services\UserLoginResponse; /** * Class ApiContext * * @package SP\Core\Context */ -final class StatelessContext extends ContextBase +class StatelessContext extends ContextBase { /** * Establece los datos del usuario en la sesión. diff --git a/lib/SP/Core/Crypt/CSRF.php b/lib/SP/Core/Crypt/CSRF.php index 628d6dde..87bb646e 100644 --- a/lib/SP/Core/Crypt/CSRF.php +++ b/lib/SP/Core/Crypt/CSRF.php @@ -25,16 +25,17 @@ namespace SP\Core\Crypt; -use SP\Config\ConfigDataInterface; use SP\Core\Context\ContextInterface; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Http\Request; +use SP\Http\RequestInterface; /** * Class CSRF * * @package SP\Core\Crypt */ -final class CSRF +class CSRF { private ContextInterface $context; private Request $request; @@ -43,13 +44,13 @@ final class CSRF /** * CSRF constructor. * - * @param ContextInterface $context - * @param Request $request - * @param ConfigDataInterface $configData + * @param ContextInterface $context + * @param RequestInterface $request + * @param \SP\Domain\Config\In\ConfigDataInterface $configData */ public function __construct( ContextInterface $context, - Request $request, + RequestInterface $request, ConfigDataInterface $configData ) { diff --git a/lib/SP/Core/Crypt/Cookie.php b/lib/SP/Core/Crypt/Cookie.php index f2615d36..81b16e0b 100644 --- a/lib/SP/Core/Crypt/Cookie.php +++ b/lib/SP/Core/Crypt/Cookie.php @@ -26,6 +26,7 @@ namespace SP\Core\Crypt; use SP\Core\Bootstrap\BootstrapBase; use SP\Http\Request; +use SP\Http\RequestInterface; /** * Class Cookie @@ -40,10 +41,10 @@ abstract class Cookie /** * Cookie constructor. * - * @param string $cookieName - * @param Request $request + * @param string $cookieName + * @param RequestInterface $request */ - protected function __construct(string $cookieName, Request $request) + protected function __construct(string $cookieName, RequestInterface $request) { $this->cookieName = $cookieName; $this->request = $request; diff --git a/lib/SP/Core/Crypt/Crypt.php b/lib/SP/Core/Crypt/Crypt.php index d479eb10..da055171 100644 --- a/lib/SP/Core/Crypt/Crypt.php +++ b/lib/SP/Core/Crypt/Crypt.php @@ -34,7 +34,7 @@ use Defuse\Crypto\KeyProtectedByPassword; * * @package SP\Core\Crypt */ -final class Crypt +class Crypt { /** * Encriptar datos con una clave segura diff --git a/lib/SP/Core/Crypt/CryptPKI.php b/lib/SP/Core/Crypt/CryptPKI.php index 12393a02..01de6175 100644 --- a/lib/SP/Core/Crypt/CryptPKI.php +++ b/lib/SP/Core/Crypt/CryptPKI.php @@ -28,15 +28,15 @@ defined('APP_ROOT') || die(); use phpseclib\Crypt\RSA; use SP\Core\Exceptions\SPException; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; /** * Class CryptPKI para el manejo de las funciones para PKI * * @package SP */ -final class CryptPKI +class CryptPKI { public const KEY_SIZE = 1024; public const PUBLIC_KEY_FILE = CONFIG_PATH . DIRECTORY_SEPARATOR . 'pubkey.pem'; diff --git a/lib/SP/Core/Crypt/CryptSessionHandler.php b/lib/SP/Core/Crypt/CryptSessionHandler.php index 7b084a6b..85fbf1ef 100644 --- a/lib/SP/Core/Crypt/CryptSessionHandler.php +++ b/lib/SP/Core/Crypt/CryptSessionHandler.php @@ -33,7 +33,7 @@ use SessionHandler; * * @package SP\Core\Crypt */ -final class CryptSessionHandler extends SessionHandler +class CryptSessionHandler extends SessionHandler { /** * @var bool Indica si la sesión está encriptada diff --git a/lib/SP/Core/Crypt/OldCrypt.php b/lib/SP/Core/Crypt/OldCrypt.php index a15e5d15..f2df047b 100644 --- a/lib/SP/Core/Crypt/OldCrypt.php +++ b/lib/SP/Core/Crypt/OldCrypt.php @@ -24,9 +24,9 @@ namespace SP\Core\Crypt; -use SP\Config\ConfigDataInterface; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Exceptions\SPException; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Util\Checks; defined('APP_ROOT') || die(); @@ -66,7 +66,7 @@ final class OldCrypt */ public static function makeHashSalt($salt = null, $random = true) { - /** @var ConfigDataInterface $ConfigData */ + /** @var \SP\Domain\Config\In\ConfigDataInterface $ConfigData */ $ConfigData = BootstrapBase::getContainer()['configData']; if ($random === true) { diff --git a/lib/SP/Core/Crypt/SecureKeyCookie.php b/lib/SP/Core/Crypt/SecureKeyCookie.php index 8634869d..143cb3b5 100644 --- a/lib/SP/Core/Crypt/SecureKeyCookie.php +++ b/lib/SP/Core/Crypt/SecureKeyCookie.php @@ -28,13 +28,14 @@ use Defuse\Crypto\Exception\CryptoException; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use Defuse\Crypto\Key; use SP\Http\Request; +use SP\Http\RequestInterface; /** * Class SecureKeyCookie * * @package SP\Core\Crypt */ -final class SecureKeyCookie extends Cookie +class SecureKeyCookie extends Cookie { /** * Nombre de la cookie @@ -46,7 +47,7 @@ final class SecureKeyCookie extends Cookie private ?Key $securedKey = null; private ?string $cypher = null; - public static function factory(Request $request): SecureKeyCookie + public static function factory(RequestInterface $request): SecureKeyCookie { $self = new self(self::COOKIE_NAME, $request); $self->cypher = $self->getCypher(); diff --git a/lib/SP/Core/Crypt/Session.php b/lib/SP/Core/Crypt/Session.php index a261e47a..b0421e8e 100644 --- a/lib/SP/Core/Crypt/Session.php +++ b/lib/SP/Core/Crypt/Session.php @@ -32,7 +32,7 @@ use SP\Core\Context\SessionContext; * * @package SP\Core\Crypt */ -final class Session +class Session { /** * Devolver la clave maestra de la sesión diff --git a/lib/SP/Core/Crypt/UUIDCookie.php b/lib/SP/Core/Crypt/UUIDCookie.php index 77e519cb..518f2cbb 100644 --- a/lib/SP/Core/Crypt/UUIDCookie.php +++ b/lib/SP/Core/Crypt/UUIDCookie.php @@ -25,6 +25,7 @@ namespace SP\Core\Crypt; use SP\Http\Request; +use SP\Http\RequestInterface; /** * Class SecureCookie @@ -38,7 +39,7 @@ class UUIDCookie extends Cookie */ public const COOKIE_NAME = 'SYSPASS_UUID'; - public static function factory(Request $request): UUIDCookie + public static function factory(RequestInterface $request): UUIDCookie { return new self(self::COOKIE_NAME, $request); } diff --git a/lib/SP/Core/Events/Event.php b/lib/SP/Core/Events/Event.php index 48cfed65..68d7107e 100644 --- a/lib/SP/Core/Events/Event.php +++ b/lib/SP/Core/Events/Event.php @@ -32,7 +32,7 @@ use SP\Core\Exceptions\SPException; * * @package SP\Core\Events */ -final class Event +class Event { private object $source; private ?EventMessage $eventMessage; diff --git a/lib/SP/Core/HttpModuleBase.php b/lib/SP/Core/HttpModuleBase.php index 0d77c861..815ce4d4 100644 --- a/lib/SP/Core/HttpModuleBase.php +++ b/lib/SP/Core/HttpModuleBase.php @@ -27,6 +27,7 @@ namespace SP\Core; use Klein\Klein; use SP\Core\Bootstrap\BootstrapBase; use SP\Http\Request; +use SP\Http\RequestInterface; use SP\Util\Util; /** @@ -40,7 +41,7 @@ abstract class HttpModuleBase extends ModuleBase public function __construct( Application $application, ProvidersHelper $providersHelper, - Request $request, + RequestInterface $request, Klein $router ) { $this->request = $request; diff --git a/lib/SP/Core/Language.php b/lib/SP/Core/Language.php index 18a39364..47f84289 100644 --- a/lib/SP/Core/Language.php +++ b/lib/SP/Core/Language.php @@ -24,10 +24,11 @@ namespace SP\Core; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; use SP\Core\Context\ContextInterface; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Http\Request; +use SP\Http\RequestInterface; defined('APP_ROOT') || die(); @@ -36,7 +37,7 @@ defined('APP_ROOT') || die(); * * @package SP */ -final class Language +final class Language implements LanguageInterface { /** * Lenguaje del usuario @@ -59,7 +60,7 @@ final class Language /** * Available languages */ - private static array $langs = [ + private static array $langs = [ 'es_ES' => 'Español', 'ca_ES' => 'Catalá', 'en_US' => 'English', @@ -71,18 +72,18 @@ final class Language 'nl_NL' => 'Nederlands', 'pt_BR' => 'Português', 'it_IT' => 'Italiano', - 'da' => 'Dansk', - 'fo' => 'Føroyskt mál', + 'da' => 'Dansk', + 'fo' => 'Føroyskt mál', 'ja_JP' => '日本語', ]; protected ConfigDataInterface $configData; - protected ContextInterface $context; - private Request $request; + protected ContextInterface $context; + private Request $request; /** * Language constructor. */ - public function __construct(ContextInterface $session, Config $config, Request $request) + public function __construct(ContextInterface $session, ConfigInterface $config, RequestInterface $request) { $this->context = $session; $this->configData = $config->getConfigData(); @@ -102,7 +103,7 @@ final class Language /** * Establecer el lenguaje a utilizar * - * @param bool $force Forzar la detección del lenguaje para los inicios de sesión + * @param bool $force Forzar la detección del lenguaje para los inicios de sesión */ public function setLanguage(bool $force = false): void { @@ -162,16 +163,16 @@ final class Language self::$localeStatus = setlocale(LC_MESSAGES, $lang); - putenv('LANG=' . $lang); - putenv('LANGUAGE=' . $lang); + putenv('LANG='.$lang); + putenv('LANGUAGE='.$lang); $locale = setlocale(LC_ALL, $lang); if ($locale === false) { logger('Could not set locale', 'ERROR'); - logger('Domain path: ' . LOCALES_PATH); + logger('Domain path: '.LOCALES_PATH); } else { - logger('Locale set to: ' . $locale); + logger('Locale set to: '.$locale); } bindtextdomain('messages', LOCALES_PATH); @@ -206,12 +207,4 @@ final class Language self::$appSet = false; } } - - /** - * Comprobar si el archivo de lenguaje existe - */ - private function checkLangFile(string $lang): bool - { - return file_exists(LOCALES_PATH . DIRECTORY_SEPARATOR . $lang); - } } diff --git a/lib/SP/Core/LanguageInterface.php b/lib/SP/Core/LanguageInterface.php new file mode 100644 index 00000000..12814159 --- /dev/null +++ b/lib/SP/Core/LanguageInterface.php @@ -0,0 +1,61 @@ +. + */ + +namespace SP\Core; + + +/** + * Class Language para el manejo del lenguaje utilizado por la aplicación + * + * @package SP + */ +interface LanguageInterface +{ + /** + * Devolver los lenguajes disponibles + */ + public static function getAvailableLanguages(): array; + + /** + * Establecer el lenguaje a utilizar + * + * @param bool $force Forzar la detección del lenguaje para los inicios de sesión + */ + public function setLanguage(bool $force = false): void; + + /** + * Establecer las locales de gettext + */ + public static function setLocales(string $lang): void; + + /** + * Establecer el lenguaje global para las traducciones + */ + public function setAppLocales(): void; + + /** + * Restablecer el lenguaje global para las traducciones + */ + public function unsetAppLocales(): void; +} \ No newline at end of file diff --git a/lib/SP/Core/MimeTypes.php b/lib/SP/Core/MimeTypes.php index 72fcac7a..a88a0243 100644 --- a/lib/SP/Core/MimeTypes.php +++ b/lib/SP/Core/MimeTypes.php @@ -24,16 +24,16 @@ namespace SP\Core; -use SP\Storage\File\FileCacheInterface; -use SP\Storage\File\FileException; -use SP\Storage\File\XmlFileStorageInterface; +use SP\Infrastructure\File\FileCacheInterface; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\XmlFileStorageInterface; /** * Class Mime * * @package SP\Core */ -final class MimeTypes +final class MimeTypes implements MimeTypesInterface { /** * Cache file name diff --git a/lib/SP/Core/MimeTypesInterface.php b/lib/SP/Core/MimeTypesInterface.php new file mode 100644 index 00000000..a0695fa2 --- /dev/null +++ b/lib/SP/Core/MimeTypesInterface.php @@ -0,0 +1,43 @@ +. + */ + +namespace SP\Core; + + +use SP\Infrastructure\File\FileException; + +/** + * Class Mime + * + * @package SP\Core + */ +interface MimeTypesInterface +{ + /** + * @throws FileException + */ + public function reset(): void; + + public function getMimeTypes(): ?array; +} \ No newline at end of file diff --git a/lib/SP/Core/ModuleBase.php b/lib/SP/Core/ModuleBase.php index 68026679..c00a2a99 100644 --- a/lib/SP/Core/ModuleBase.php +++ b/lib/SP/Core/ModuleBase.php @@ -24,10 +24,10 @@ namespace SP\Core; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; use SP\Core\Context\ContextInterface; use SP\Core\Events\EventDispatcher; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigFileService; /** * Class ModuleBase @@ -36,7 +36,7 @@ use SP\Core\Events\EventDispatcher; */ abstract class ModuleBase { - protected Config $config; + protected ConfigFileService $config; protected ConfigDataInterface $configData; protected ContextInterface $context; private EventDispatcher $eventDispatcher; diff --git a/lib/SP/Core/UI/Theme.php b/lib/SP/Core/UI/Theme.php index c39e1b29..134b005e 100644 --- a/lib/SP/Core/UI/Theme.php +++ b/lib/SP/Core/UI/Theme.php @@ -24,14 +24,14 @@ namespace SP\Core\UI; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Context\ContextBase; use SP\Core\Context\ContextInterface; use SP\Core\Exceptions\InvalidClassException; -use SP\Storage\File\FileCacheInterface; -use SP\Storage\File\FileException; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Infrastructure\File\FileCacheInterface; +use SP\Infrastructure\File\FileException; defined('APP_ROOT') || die(); @@ -62,13 +62,13 @@ final class Theme implements ThemeInterface * Theme constructor. * * @param string $module - * @param Config $config + * @param ConfigInterface $config * @param ContextInterface $context * @param FileCacheInterface $fileCache */ public function __construct( string $module, - Config $config, + ConfigInterface $config, ContextInterface $context, FileCacheInterface $fileCache ) { diff --git a/lib/SP/DataModel/UserLoginData.php b/lib/SP/DataModel/UserLoginData.php index 04fb9181..5ab01134 100644 --- a/lib/SP/DataModel/UserLoginData.php +++ b/lib/SP/DataModel/UserLoginData.php @@ -24,7 +24,7 @@ namespace SP\DataModel; -use SP\Services\User\UserLoginResponse; +use SP\Domain\User\Services\UserLoginResponse; /** * Class UserLoginData diff --git a/lib/SP/Domain/Account/AccountAclServiceInterface.php b/lib/SP/Domain/Account/AccountAclServiceInterface.php new file mode 100644 index 00000000..b8363b7a --- /dev/null +++ b/lib/SP/Domain/Account/AccountAclServiceInterface.php @@ -0,0 +1,92 @@ +. + */ + +namespace SP\Domain\Account; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\Dto\AccountAclDto; +use SP\DataModel\ProfileData; +use SP\Domain\Account\Services\AccountAcl; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Infrastructure\File\FileCacheInterface; + +/** + * Class AccountAclService + * + * @package SP\Domain\Account\Services + */ +interface AccountAclServiceInterface +{ + /** + * Sets grants which don't need the account's data + * + * @param UserLoginResponse $userData + * @param ProfileData $profileData + * + * @return bool + */ + public static function getShowPermission(UserLoginResponse $userData, ProfileData $profileData): bool; + + /** + * Obtener la ACL de una cuenta + * + * @param int $actionId + * @param AccountAclDto|null $accountAclDto + * @param bool $isHistory + * + * @return AccountAcl + * @throws ConstraintException + * @throws QueryException + */ + public function getAcl(int $actionId, ?AccountAclDto $accountAclDto = null, bool $isHistory = false): AccountAcl; + + /** + * Resturns an stored ACL + * + * @param int $accountId + * @param int $actionId + * + * @return AccountAcl + */ + public function getAclFromCache(int $accountId, int $actionId): ?AccountAcl; + + /** + * @param int $accountId + * @param int $actionId + * + * @return string + */ + public function getCacheFileForAcl(int $accountId, int $actionId): string; + + /** + * Saves the ACL + * + * @param AccountAcl $accountAcl + * + * @return null|FileCacheInterface + */ + public function saveAclInCache(AccountAcl $accountAcl): ?FileCacheInterface; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/AccountCryptServiceInterface.php b/lib/SP/Domain/Account/AccountCryptServiceInterface.php new file mode 100644 index 00000000..c400a422 --- /dev/null +++ b/lib/SP/Domain/Account/AccountCryptServiceInterface.php @@ -0,0 +1,51 @@ +. + */ + +namespace SP\Domain\Account; + + +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; + +/** + * Class AccountCryptService + * + * @package SP\Domain\Account\Services + */ +interface AccountCryptServiceInterface +{ + /** + * Actualiza las claves de todas las cuentas con la nueva clave maestra. + * + * @throws ServiceException + */ + public function updateMasterPassword(UpdateMasterPassRequest $updateMasterPassRequest): void; + + /** + * Actualiza las claves de todas las cuentas con la nueva clave maestra. + * + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function updateHistoryMasterPassword(UpdateMasterPassRequest $updateMasterPassRequest): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/AccountFileServiceInterface.php b/lib/SP/Domain/Account/AccountFileServiceInterface.php new file mode 100644 index 00000000..ba0bd698 --- /dev/null +++ b/lib/SP/Domain/Account/AccountFileServiceInterface.php @@ -0,0 +1,123 @@ +. + */ + +namespace SP\Domain\Account; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\InvalidImageException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\FileData; +use SP\DataModel\FileExtData; +use SP\DataModel\ItemSearchData; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountFileService + * + * @package SP\Domain\Account\Services + */ +interface AccountFileServiceInterface +{ + /** + * Creates an item + * + * @throws InvalidImageException + * @throws ConstraintException + * @throws QueryException + */ + public function create(FileData $itemData): int; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getInfoById(int $id): ?FileExtData; + + /** + * Returns the item for given id + * + * @return mixed|null + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getById(int $id); + + /** + * Returns all the items + * + * @return FileExtData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): array; + + /** + * Returns all the items for given ids + * + * @param int[] $ids + * + * @return FileExtData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getByIdBatch(array $ids): array; + + /** + * Deletes all the items for given ids + * + * @param int[] $ids + * + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * Deletes an item + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): AccountFileServiceInterface; + + /** + * Searches for items by a given filter + * + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $searchData): QueryResult; + + /** + * Returns the item for given id + * + * @return FileData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getByAccountId(int $id): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/AccountHistoryServiceInterface.php b/lib/SP/Domain/Account/AccountHistoryServiceInterface.php new file mode 100644 index 00000000..93ab4e2c --- /dev/null +++ b/lib/SP/Domain/Account/AccountHistoryServiceInterface.php @@ -0,0 +1,141 @@ +. + */ + +namespace SP\Domain\Account; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\AccountHistoryData; +use SP\DataModel\Dto\AccountHistoryCreateDto; +use SP\DataModel\ItemData; +use SP\DataModel\ItemSearchData; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountHistoryService + * + * @package SP\Domain\Account\Services + */ +interface AccountHistoryServiceInterface +{ + /** + * Returns the item for given id + * + * @throws SPException + * @throws SPException + */ + public function getById(int $id): AccountHistoryData; + + /** + * Obtiene el listado del histórico de una cuenta. + * + * @return array Con los registros con id como clave y fecha - usuario como valor + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getHistoryForAccount(int $id): array; + + /** + * @return ItemData[] + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getUsersByAccountId(int $id): array; + + /** + * @return ItemData[] + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getUserGroupsByAccountId(int $id): array; + + /** + * @throws QueryException + * @throws ConstraintException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * Crea una nueva cuenta en la BBDD + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function create(AccountHistoryCreateDto $dto): int; + + /** + * @throws QueryException + * @throws ConstraintException + */ + public function getAccountsPassData(): array; + + /** + * Elimina los datos de una cuenta en la BBDD. + * + * @throws QueryException + * @throws ServiceException + * @throws ConstraintException + */ + public function delete(int $id): void; + + /** + * Deletes all the items for given ids + * + * @param int[] $ids + * + * @return int + * @throws QueryException + * @throws ConstraintException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * Deletes all the items for given accounts id + * + * @param int[] $ids + * + * @return int + * @throws QueryException + * @throws ConstraintException + */ + public function deleteByAccountIdBatch(array $ids): int; + + /** + * @throws SPException + * @throws ConstraintException + */ + public function updatePasswordMasterPass(AccountPasswordRequest $accountRequest): void; + + /** + * Returns all the items + * + * @throws QueryException + * @throws ConstraintException + */ + public function getAll(): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/AccountPresetServiceInterface.php b/lib/SP/Domain/Account/AccountPresetServiceInterface.php new file mode 100644 index 00000000..ada51407 --- /dev/null +++ b/lib/SP/Domain/Account/AccountPresetServiceInterface.php @@ -0,0 +1,48 @@ +. + */ + +namespace SP\Domain\Account; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\NoSuchPropertyException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\ValidationException; +use SP\Domain\Account\Services\AccountRequest; + +/** + * Class AccountPreset + * + * @package SP\Domain\Account\Services + */ +interface AccountPresetServiceInterface +{ + /** + * @throws ValidationException + * @throws ConstraintException + * @throws NoSuchPropertyException + * @throws QueryException + */ + public function checkPasswordPreset(AccountRequest $accountRequest): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/AccountSearchServiceInterface.php b/lib/SP/Domain/Account/AccountSearchServiceInterface.php new file mode 100644 index 00000000..f4a0fc11 --- /dev/null +++ b/lib/SP/Domain/Account/AccountSearchServiceInterface.php @@ -0,0 +1,57 @@ +. + */ + +namespace SP\Domain\Account; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Infrastructure\Database\QueryResult; +use SP\Mvc\Model\QueryCondition; + +/** + * Class AccountSearchService para la gestión de búsquedas de cuentas + */ +interface AccountSearchServiceInterface +{ + /** + * Procesar los resultados de la búsqueda y crear la variable que contiene los datos de cada cuenta + * a mostrar. + * + * @throws ConstraintException + * @throws QueryException + * @throws SPException + */ + public function processSearchResults(AccountSearchFilter $accountSearchFilter): QueryResult; + + /** + * Analizar la cadena de consulta por eqituetas especiales y devolver un objeto + * QueryCondition con los filtros + */ + public function analyzeQueryFilters(string $string): QueryCondition; + + public function getCleanString(): ?string; +} \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountServiceInterface.php b/lib/SP/Domain/Account/AccountServiceInterface.php similarity index 87% rename from lib/SP/Services/Account/AccountServiceInterface.php rename to lib/SP/Domain/Account/AccountServiceInterface.php index 27c453b1..f1d84b2a 100644 --- a/lib/SP/Services/Account/AccountServiceInterface.php +++ b/lib/SP/Domain/Account/AccountServiceInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account; use SP\Core\Exceptions\SPException; use SP\DataModel\Dto\AccountDetailsResponse; @@ -30,12 +30,12 @@ use SP\DataModel\Dto\AccountDetailsResponse; /** * Interface AccountServiceInterface * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ interface AccountServiceInterface { /** - * @param int $id + * @param int $id * * @return AccountDetailsResponse * @throws SPException diff --git a/lib/SP/Domain/Account/AccountToFavoriteServiceInterface.php b/lib/SP/Domain/Account/AccountToFavoriteServiceInterface.php new file mode 100644 index 00000000..db35d470 --- /dev/null +++ b/lib/SP/Domain/Account/AccountToFavoriteServiceInterface.php @@ -0,0 +1,61 @@ +. + */ + +namespace SP\Domain\Account; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; + +/** + * Class AccountFavoriteService + * + * @package SP\Domain\Account\Services + */ +interface AccountToFavoriteServiceInterface +{ + /** + * Obtener un array con los Ids de cuentas favoritas + * + * @throws ConstraintException + * @throws QueryException + */ + public function getForUserId(int $id): array; + + /** + * Añadir una cuenta a la lista de favoritos + * + * @throws ConstraintException + * @throws QueryException + */ + public function add(int $accountId, int $userId): int; + + /** + * Eliminar una cuenta de la lista de favoritos + * + * @throws ConstraintException + * @throws QueryException + */ + public function delete(int $accountId, int $userId): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/AccountToTagServiceInterface.php b/lib/SP/Domain/Account/AccountToTagServiceInterface.php new file mode 100644 index 00000000..771d5338 --- /dev/null +++ b/lib/SP/Domain/Account/AccountToTagServiceInterface.php @@ -0,0 +1,43 @@ +. + */ + +namespace SP\Domain\Account; + + +use SP\DataModel\ItemData; + +/** + * Class AccountToTagService + * + * @package SP\Domain\Account\Services + */ +interface AccountToTagServiceInterface +{ + /** + * @return ItemData[] + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getTagsByAccountId(int $id): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/In/AccountFileRepositoryInterface.php b/lib/SP/Domain/Account/In/AccountFileRepositoryInterface.php new file mode 100644 index 00000000..a6e7dd31 --- /dev/null +++ b/lib/SP/Domain/Account/In/AccountFileRepositoryInterface.php @@ -0,0 +1,59 @@ +. + */ + +namespace SP\Domain\Account\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountFileRepository + * + * @package SP\Infrastructure\Account\Repositories + */ +interface AccountFileRepositoryInterface extends RepositoryInterface +{ + /** + * @param int $id + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getInfoById(int $id): QueryResult; + + /** + * Returns the item for given id + * + * @param int $id + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByAccountId(int $id): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/In/AccountHistoryRepositoryInterface.php b/lib/SP/Domain/Account/In/AccountHistoryRepositoryInterface.php new file mode 100644 index 00000000..53c93566 --- /dev/null +++ b/lib/SP/Domain/Account/In/AccountHistoryRepositoryInterface.php @@ -0,0 +1,82 @@ +. + */ + +namespace SP\Domain\Account\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountHistoryRepository + * + * @package Services + */ +interface AccountHistoryRepositoryInterface extends RepositoryInterface +{ + /** + * Obtiene el listado del histórico de una cuenta. + * + * @param $id + * + * @return QueryResult + * @throws QueryException + * @throws ConstraintException + */ + public function getHistoryForAccount($id): QueryResult; + + /** + * Deletes all the items for given accounts id + * + * @param array $ids + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByAccountIdBatch(array $ids): int; + + /** + * Obtener los datos relativos a la clave de todas las cuentas. + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getAccountsPassData(): QueryResult; + + /** + * Actualiza la clave de una cuenta en la BBDD. + * + * @param AccountPasswordRequest $request + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function updatePassword(AccountPasswordRequest $request): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/In/AccountRepositoryInterface.php b/lib/SP/Domain/Account/In/AccountRepositoryInterface.php new file mode 100644 index 00000000..4f2a4a7a --- /dev/null +++ b/lib/SP/Domain/Account/In/AccountRepositoryInterface.php @@ -0,0 +1,190 @@ +. + */ + +namespace SP\Domain\Account\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; +use SP\Mvc\Model\QueryCondition; +use stdClass; + +/** + * Class AccountRepository + * + * @package Services + */ +interface AccountRepositoryInterface extends RepositoryInterface +{ + /** + * Devolver el número total de cuentas + * + * @return stdClass + * @throws QueryException + * @throws ConstraintException + */ + public function getTotalNumAccounts(): stdClass; + + /** + * @param int $id + * @param QueryCondition $queryCondition + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getPasswordForId(int $id, QueryCondition $queryCondition): QueryResult; + + /** + * @param QueryCondition $queryCondition + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getPasswordHistoryForId(QueryCondition $queryCondition): QueryResult; + + /** + * Incrementa el contador de vista de clave de una cuenta en la BBDD + * + * @param int $id + * + * @return bool + * @throws ConstraintException + * @throws QueryException + */ + public function incrementDecryptCounter(int $id): bool; + + /** + * Actualiza la clave de una cuenta en la BBDD. + * + * @param AccountRequest $accountRequest + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function editPassword(AccountRequest $accountRequest): int; + + /** + * Actualiza la clave de una cuenta en la BBDD. + * + * @param AccountPasswordRequest $request + * + * @return bool + * @throws ConstraintException + * @throws QueryException + */ + public function updatePassword(AccountPasswordRequest $request): bool; + + /** + * Restaurar una cuenta desde el histórico. + * + * @param int $historyId El Id del registro en el histórico + * @param int $userId User's Id + * + * @return bool + * @throws ConstraintException + * @throws QueryException + */ + public function editRestore(int $historyId, int $userId): bool; + + /** + * Updates an item for bulk action + * + * @param AccountRequest $itemData + * + * @return int + * @throws SPException + */ + public function updateBulk(AccountRequest $itemData): int; + + /** + * Incrementa el contador de visitas de una cuenta en la BBDD + * + * @param int $id + * + * @return bool + * @throws ConstraintException + * @throws QueryException + */ + public function incrementViewCounter(int $id): bool; + + /** + * Obtener los datos de una cuenta. + * + * @param int $id + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getDataForLink(int $id): QueryResult; + + /** + * Obtener las cuentas de una búsqueda. + * + * @param AccountSearchFilter $accountSearchFilter + * @param QueryCondition $queryFilterUser + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + * @throws SPException + */ + public function getByFilter(AccountSearchFilter $accountSearchFilter, QueryCondition $queryFilterUser): QueryResult; + + /** + * @param QueryCondition $queryFilter + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getForUser(QueryCondition $queryFilter): QueryResult; + + /** + * @param QueryCondition $queryFilter + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getLinked(QueryCondition $queryFilter): QueryResult; + + /** + * Obtener los datos relativos a la clave de todas las cuentas. + * + * @return \SP\Infrastructure\Database\QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getAccountsPassData(): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/In/AccountToFavoriteRepositoryInterface.php b/lib/SP/Domain/Account/In/AccountToFavoriteRepositoryInterface.php new file mode 100644 index 00000000..13b6d499 --- /dev/null +++ b/lib/SP/Domain/Account/In/AccountToFavoriteRepositoryInterface.php @@ -0,0 +1,73 @@ +. + */ + +namespace SP\Domain\Account\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountFavoriteRepository + * + * @package SP\Infrastructure\Account\Repositories + */ +interface AccountToFavoriteRepositoryInterface +{ + /** + * Obtener un array con los Ids de cuentas favoritas + * + * @param $id int El Id de usuario + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getForUserId(int $id): QueryResult; + + /** + * Añadir una cuenta a la lista de favoritos + * + * @param $accountId int El Id de la cuenta + * @param $userId int El Id del usuario + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function add(int $accountId, int $userId): int; + + /** + * Eliminar una cuenta de la lista de favoritos + * + * @param $accountId int El Id de la cuenta + * @param $userId int El Id del usuario + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function delete(int $accountId, int $userId): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/In/AccountToTagRepositoryInterface.php b/lib/SP/Domain/Account/In/AccountToTagRepositoryInterface.php new file mode 100644 index 00000000..25bb539b --- /dev/null +++ b/lib/SP/Domain/Account/In/AccountToTagRepositoryInterface.php @@ -0,0 +1,80 @@ +. + */ + +namespace SP\Domain\Account\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountToTagRepository + * + * @package SP\Infrastructure\Account\Repositories + */ +interface AccountToTagRepositoryInterface +{ + /** + * Devolver las etiquetas de una cuenta + * + * @param int $id + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getTagsByAccountId(int $id): QueryResult; + + /** + * @param AccountRequest $accountRequest + * + * @throws ConstraintException + * @throws QueryException + */ + public function update(AccountRequest $accountRequest): void; + + /** + * Eliminar las etiquetas de una cuenta + * + * @param int $id + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByAccountId(int $id): int; + + /** + * Actualizar las etiquetas de una cuenta + * + * @param AccountRequest $accountRequest + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function add(AccountRequest $accountRequest): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/In/AccountToUserGroupRepositoryInterface.php b/lib/SP/Domain/Account/In/AccountToUserGroupRepositoryInterface.php new file mode 100644 index 00000000..813c840f --- /dev/null +++ b/lib/SP/Domain/Account/In/AccountToUserGroupRepositoryInterface.php @@ -0,0 +1,109 @@ +. + */ + +namespace SP\Domain\Account\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountToUserGroupRepository + * + * @package SP\Infrastructure\Account\Repositories + */ +interface AccountToUserGroupRepositoryInterface +{ + /** + * Obtiene el listado con el nombre de los grupos de una cuenta. + * + * @param int $id con el Id de la cuenta + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getUserGroupsByAccountId(int $id): QueryResult; + + /** + * Obtiene el listado con el nombre de los grupos de una cuenta. + * + * @param int $id + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getUserGroupsByUserGroupId(int $id): QueryResult; + + /** + * @param $id int + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByUserGroupId(int $id): int; + + /** + * @param AccountRequest $accountRequest + * @param bool $isEdit + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function updateByType(AccountRequest $accountRequest, bool $isEdit): int; + + /** + * @param int $id + * @param bool $isEdit + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteTypeByAccountId(int $id, bool $isEdit): int; + + /** + * @param AccountRequest $accountRequest + * @param bool $isEdit + * + * @return int Last ID inserted + * @throws ConstraintException + * @throws QueryException + */ + public function addByType(AccountRequest $accountRequest, bool $isEdit): int; + + /** + * @param $id int + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByAccountId(int $id): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/In/AccountToUserRepositoryInterface.php b/lib/SP/Domain/Account/In/AccountToUserRepositoryInterface.php new file mode 100644 index 00000000..3d3b1033 --- /dev/null +++ b/lib/SP/Domain/Account/In/AccountToUserRepositoryInterface.php @@ -0,0 +1,98 @@ +. + */ + +namespace SP\Domain\Account\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountToUserRepository + * + * @package SP\Infrastructure\Account\Repositories + */ +interface AccountToUserRepositoryInterface +{ + /** + * Actualizar la asociación de grupos con cuentas. + * + * @param AccountRequest $accountRequest + * + * @param bool $isEdit + * + * @return void + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function updateByType(AccountRequest $accountRequest, bool $isEdit): void; + + /** + * Eliminar la asociación de grupos con cuentas. + * + * @param int $id con el Id de la cuenta + * @param bool $isEdit + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteTypeByAccountId(int $id, bool $isEdit): int; + + /** + * Crear asociación de usuarios con cuentas. + * + * @param AccountRequest $accountRequest + * @param bool $isEdit + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function addByType(AccountRequest $accountRequest, bool $isEdit): int; + + /** + * Eliminar la asociación de grupos con cuentas. + * + * @param int $id con el Id de la cuenta + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByAccountId(int $id): int; + + /** + * Obtiene el listado de usuarios de una cuenta. + * + * @param int $id con el id de la cuenta + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getUsersByAccountId(int $id): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/Account/PublicLinkServiceInterface.php b/lib/SP/Domain/Account/PublicLinkServiceInterface.php new file mode 100644 index 00000000..d089b6c7 --- /dev/null +++ b/lib/SP/Domain/Account/PublicLinkServiceInterface.php @@ -0,0 +1,146 @@ +. + */ + +namespace SP\Domain\Account; + + +use Defuse\Crypto\Exception\CryptoException; +use Defuse\Crypto\Exception\EnvironmentIsBrokenException; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\ItemSearchData; +use SP\DataModel\PublicLinkData; +use SP\DataModel\PublicLinkListData; +use SP\Domain\Account\Services\PublicLinkKey; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class PublicLinkService + * + * @package SP\Domain\Common\Services\PublicLink + */ +interface PublicLinkServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id): PublicLinkListData; + + /** + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\SPException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function refresh(int $id): bool; + + /** + * @throws EnvironmentIsBrokenException + */ + public function getPublicLinkKey(?string $hash = null): PublicLinkKey; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): PublicLinkServiceInterface; + + /** + * Deletes all the items for given ids + * + * @param int[] $ids + * + * @throws ConstraintException + * @throws QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * @throws SPException + * @throws CryptoException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws ConstraintException + * @throws QueryException + */ + public function create(PublicLinkData $itemData): int; + + /** + * Get all items from the service's repository + * + * @return PublicLinkListData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; + + /** + * Incrementar el contador de visitas de un enlace + * + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function addLinkView(PublicLinkData $publicLinkData): void; + + /** + * @throws SPException + */ + public function getByHash(string $hash): PublicLinkData; + + /** + * Devolver el hash asociado a un elemento + * + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function getHashForItem(int $itemId): PublicLinkData; + + /** + * Updates an item + * + * @throws SPException + * @throws ConstraintException + * @throws QueryException + */ + public function update(PublicLinkData $itemData): int; +} \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountAcl.php b/lib/SP/Domain/Account/Services/AccountAcl.php similarity index 70% rename from lib/SP/Services/Account/AccountAcl.php rename to lib/SP/Domain/Account/Services/AccountAcl.php index 1769c8fb..6059d4b7 100644 --- a/lib/SP/Services/Account/AccountAcl.php +++ b/lib/SP/Domain/Account/Services/AccountAcl.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,41 +22,41 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; use SP\Core\Acl\ActionsInterface; /** * Class AccountAcl * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ final class AccountAcl { - private bool $userInGroups = false; - private bool $userInUsers = false; - private bool $resultView = false; - private bool $resultEdit = false; - private bool $modified = false; - private bool $showView = false; - private bool $showHistory = false; - private bool $showDetails = false; - private bool $showPass = false; - private bool $showFiles = false; - private bool $showViewPass = false; - private bool $showSave = false; - private bool $showEdit = false; - private bool $showEditPass = false; - private bool $showDelete = false; - private bool $showRestore = false; - private bool $showLink = false; - private bool $showCopy = false; - private bool $showPermission = false; + private bool $userInGroups = false; + private bool $userInUsers = false; + private bool $resultView = false; + private bool $resultEdit = false; + private bool $modified = false; + private bool $showView = false; + private bool $showHistory = false; + private bool $showDetails = false; + private bool $showPass = false; + private bool $showFiles = false; + private bool $showViewPass = false; + private bool $showSave = false; + private bool $showEdit = false; + private bool $showEditPass = false; + private bool $showDelete = false; + private bool $showRestore = false; + private bool $showLink = false; + private bool $showCopy = false; + private bool $showPermission = false; private bool $compiledAccountAccess = false; - private bool $compiledShowAccess = false; - private ?int $accountId = null; - private int $actionId; - private int $time = 0; + private bool $compiledShowAccess = false; + private ?int $accountId = null; + private int $actionId; + private int $time = 0; private bool $isHistory; public function __construct(int $actionId, bool $isHistory = false) @@ -116,9 +116,9 @@ final class AccountAcl public function isShowDetails(): bool { return $this->resultView - && ($this->actionId === ActionsInterface::ACCOUNT_VIEW - || $this->actionId === ActionsInterface::ACCOUNT_HISTORY_VIEW - || $this->actionId === ActionsInterface::ACCOUNT_DELETE); + && ($this->actionId === ActionsInterface::ACCOUNT_VIEW + || $this->actionId === ActionsInterface::ACCOUNT_HISTORY_VIEW + || $this->actionId === ActionsInterface::ACCOUNT_DELETE); } public function setShowDetails(bool $showDetails): AccountAcl @@ -131,7 +131,7 @@ final class AccountAcl public function isShowPass(): bool { return ($this->actionId === ActionsInterface::ACCOUNT_CREATE - || $this->actionId === ActionsInterface::ACCOUNT_COPY); + || $this->actionId === ActionsInterface::ACCOUNT_COPY); } public function setShowPass(bool $showPass): AccountAcl @@ -144,9 +144,9 @@ final class AccountAcl public function isShowFiles(): bool { return $this->showFiles - && ($this->actionId === ActionsInterface::ACCOUNT_EDIT - || $this->actionId === ActionsInterface::ACCOUNT_VIEW - || $this->actionId === ActionsInterface::ACCOUNT_HISTORY_VIEW); + && ($this->actionId === ActionsInterface::ACCOUNT_EDIT + || $this->actionId === ActionsInterface::ACCOUNT_VIEW + || $this->actionId === ActionsInterface::ACCOUNT_HISTORY_VIEW); } public function setShowFiles(bool $showFiles): AccountAcl @@ -159,11 +159,11 @@ final class AccountAcl public function isShowViewPass(): bool { return $this->showViewPass - && ($this->actionId === ActionsInterface::ACCOUNT_SEARCH - || $this->actionId === ActionsInterface::ACCOUNT_VIEW - || $this->actionId === ActionsInterface::ACCOUNT_VIEW_PASS - || $this->actionId === ActionsInterface::ACCOUNT_HISTORY_VIEW - || $this->actionId === ActionsInterface::ACCOUNT_EDIT); + && ($this->actionId === ActionsInterface::ACCOUNT_SEARCH + || $this->actionId === ActionsInterface::ACCOUNT_VIEW + || $this->actionId === ActionsInterface::ACCOUNT_VIEW_PASS + || $this->actionId === ActionsInterface::ACCOUNT_HISTORY_VIEW + || $this->actionId === ActionsInterface::ACCOUNT_EDIT); } public function setShowViewPass(bool $showViewPass): AccountAcl @@ -176,8 +176,8 @@ final class AccountAcl public function isShowSave(): bool { return $this->actionId === ActionsInterface::ACCOUNT_EDIT - || $this->actionId === ActionsInterface::ACCOUNT_CREATE - || $this->actionId === ActionsInterface::ACCOUNT_COPY; + || $this->actionId === ActionsInterface::ACCOUNT_CREATE + || $this->actionId === ActionsInterface::ACCOUNT_COPY; } public function setShowSave(bool $showSave): AccountAcl @@ -190,8 +190,8 @@ final class AccountAcl public function isShowEdit(): bool { return $this->showEdit - && ($this->actionId === ActionsInterface::ACCOUNT_SEARCH - || $this->actionId === ActionsInterface::ACCOUNT_VIEW); + && ($this->actionId === ActionsInterface::ACCOUNT_SEARCH + || $this->actionId === ActionsInterface::ACCOUNT_VIEW); } public function setShowEdit(bool $showEdit): AccountAcl @@ -204,8 +204,8 @@ final class AccountAcl public function isShowEditPass(): bool { return $this->showEditPass - && ($this->actionId === ActionsInterface::ACCOUNT_EDIT - || $this->actionId === ActionsInterface::ACCOUNT_VIEW); + && ($this->actionId === ActionsInterface::ACCOUNT_EDIT + || $this->actionId === ActionsInterface::ACCOUNT_VIEW); } public function setShowEditPass(bool $showEditPass): AccountAcl @@ -218,9 +218,9 @@ final class AccountAcl public function isShowDelete(): bool { return $this->showDelete - && ($this->actionId === ActionsInterface::ACCOUNT_SEARCH - || $this->actionId === ActionsInterface::ACCOUNT_DELETE - || $this->actionId === ActionsInterface::ACCOUNT_EDIT); + && ($this->actionId === ActionsInterface::ACCOUNT_SEARCH + || $this->actionId === ActionsInterface::ACCOUNT_DELETE + || $this->actionId === ActionsInterface::ACCOUNT_EDIT); } public function setShowDelete(bool $showDelete): AccountAcl @@ -257,8 +257,8 @@ final class AccountAcl public function isShowHistory(): bool { return $this->showHistory - && ($this->actionId === ActionsInterface::ACCOUNT_VIEW - || $this->actionId === ActionsInterface::ACCOUNT_HISTORY_VIEW); + && ($this->actionId === ActionsInterface::ACCOUNT_VIEW + || $this->actionId === ActionsInterface::ACCOUNT_HISTORY_VIEW); } public function setShowHistory(bool $showHistory): AccountAcl @@ -308,15 +308,15 @@ final class AccountAcl switch ($actionId) { case ActionsInterface::ACCOUNT_VIEW - || ActionsInterface::ACCOUNT_SEARCH - || ActionsInterface::ACCOUNT_VIEW_PASS - || ActionsInterface::ACCOUNT_HISTORY_VIEW - || ActionsInterface::ACCOUNT_COPY: + || ActionsInterface::ACCOUNT_SEARCH + || ActionsInterface::ACCOUNT_VIEW_PASS + || ActionsInterface::ACCOUNT_HISTORY_VIEW + || ActionsInterface::ACCOUNT_COPY: return $this->resultView; case ActionsInterface::ACCOUNT_EDIT - || ActionsInterface::ACCOUNT_DELETE - || ActionsInterface::ACCOUNT_EDIT_PASS - || ActionsInterface::ACCOUNT_EDIT_RESTORE: + || ActionsInterface::ACCOUNT_DELETE + || ActionsInterface::ACCOUNT_EDIT_PASS + || ActionsInterface::ACCOUNT_EDIT_RESTORE: return $this->resultEdit; default: return false; @@ -350,9 +350,9 @@ final class AccountAcl public function isShowCopy(): bool { return $this->showCopy - && ($this->actionId === ActionsInterface::ACCOUNT_SEARCH - || $this->actionId === ActionsInterface::ACCOUNT_VIEW - || $this->actionId === ActionsInterface::ACCOUNT_EDIT); + && ($this->actionId === ActionsInterface::ACCOUNT_SEARCH + || $this->actionId === ActionsInterface::ACCOUNT_VIEW + || $this->actionId === ActionsInterface::ACCOUNT_EDIT); } public function setShowCopy(bool $showCopy): AccountAcl diff --git a/lib/SP/Services/Account/AccountAclService.php b/lib/SP/Domain/Account/Services/AccountAclService.php similarity index 70% rename from lib/SP/Services/Account/AccountAclService.php rename to lib/SP/Domain/Account/Services/AccountAclService.php index 41bf8672..7899a4d4 100644 --- a/lib/SP/Services/Account/AccountAclService.php +++ b/lib/SP/Domain/Account/Services/AccountAclService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,39 +22,52 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\FileNotFoundException; use SP\Core\Exceptions\QueryException; use SP\DataModel\Dto\AccountAclDto; use SP\DataModel\ProfileData; -use SP\Services\Service; -use SP\Services\User\UserLoginResponse; -use SP\Services\UserGroup\UserToUserGroupService; -use SP\Storage\File\FileCache; -use SP\Storage\File\FileCacheInterface; -use SP\Storage\File\FileException; +use SP\Domain\Account\AccountAclServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Domain\User\UserToUserGroupServiceInterface; +use SP\Infrastructure\File\FileCache; +use SP\Infrastructure\File\FileCacheInterface; +use SP\Infrastructure\File\FileException; use SP\Util\FileUtil; /** * Class AccountAclService * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ -final class AccountAclService extends Service +final class AccountAclService extends Service implements AccountAclServiceInterface { /** * ACL's file base path */ - public const ACL_PATH = CACHE_PATH . DIRECTORY_SEPARATOR . 'accountAcl' . DIRECTORY_SEPARATOR; - public static bool $useCache = true; - private ?AccountAclDto $accountAclDto = null; - private ?AccountAcl $accountAcl = null; - private ?Acl $acl = null; - private ?UserLoginResponse $userData = null; + public const ACL_PATH = CACHE_PATH.DIRECTORY_SEPARATOR.'accountAcl'.DIRECTORY_SEPARATOR; + public static bool $useCache = true; + private ?AccountAclDto $accountAclDto = null; + private ?AccountAcl $accountAcl = null; + private Acl $acl; + private UserToUserGroupServiceInterface $userToUserGroupService; + private UserLoginResponse $userData; + + public function __construct(Application $application, Acl $acl, UserToUserGroupServiceInterface $userGroupService) + { + parent::__construct($application); + + $this->acl = $acl; + $this->userToUserGroupService = $userGroupService; + $this->userData = $this->context->getUserData(); + } + /** * @param $userId @@ -66,8 +79,8 @@ final class AccountAclService extends Service logger(sprintf('Clearing ACL for user ID: %d', $userId)); try { - if (FileUtil::rmdir_recursive(self::ACL_PATH . $userId) === false) { - logger(sprintf('Unable to delete %s directory', self::ACL_PATH . $userId)); + if (FileUtil::rmdir_recursive(self::ACL_PATH.$userId) === false) { + logger(sprintf('Unable to delete %s directory', self::ACL_PATH.$userId)); return false; } @@ -83,24 +96,19 @@ final class AccountAclService extends Service /** * Obtener la ACL de una cuenta * - * @param int $actionId - * @param AccountAclDto|null $accountAclDto - * @param bool $isHistory + * @param int $actionId + * @param AccountAclDto|null $accountAclDto + * @param bool $isHistory * * @return AccountAcl * @throws ConstraintException * @throws QueryException */ - public function getAcl( - int $actionId, - ?AccountAclDto $accountAclDto = null, - bool $isHistory = false - ): AccountAcl + public function getAcl(int $actionId, ?AccountAclDto $accountAclDto = null, bool $isHistory = false): AccountAcl { $this->accountAcl = new AccountAcl($actionId, $isHistory); $this->accountAcl->setShowPermission( - self::getShowPermission($this->context->getUserData(), - $this->context->getUserProfile()) + self::getShowPermission($this->context->getUserData(), $this->context->getUserProfile()) ); if ($accountAclDto !== null) { @@ -109,10 +117,12 @@ final class AccountAclService extends Service $accountAcl = $this->getAclFromCache($accountAclDto->getAccountId(), $actionId); if (self::$useCache && null !== $accountAcl) { - $this->accountAcl->setModified(( - $accountAclDto->getDateEdit() > $accountAcl->getTime() - || $this->userData->getLastUpdate() > $accountAcl->getTime() - )); + $this->accountAcl->setModified( + ( + $accountAclDto->getDateEdit() > $accountAcl->getTime() + || $this->userData->getLastUpdate() > $accountAcl->getTime() + ) + ); if (!$this->accountAcl->isModified()) { logger('Account ACL HIT'); @@ -134,34 +144,30 @@ final class AccountAclService extends Service /** * Sets grants which don't need the account's data * - * @param UserLoginResponse $userData - * @param ProfileData $profileData + * @param UserLoginResponse $userData + * @param ProfileData $profileData * * @return bool */ - public static function getShowPermission( - UserLoginResponse $userData, - ProfileData $profileData - ): bool + public static function getShowPermission(UserLoginResponse $userData, ProfileData $profileData): bool { return $userData->getIsAdminApp() - || $userData->getIsAdminAcc() - || $profileData->isAccPermission(); + || $userData->getIsAdminAcc() + || $profileData->isAccPermission(); } /** * Resturns an stored ACL * - * @param int $accountId - * @param int $actionId + * @param int $accountId + * @param int $actionId * * @return AccountAcl */ public function getAclFromCache(int $accountId, int $actionId): ?AccountAcl { try { - $acl = FileCache::factory($this->getCacheFileForAcl($accountId, $actionId)) - ->load(); + $acl = FileCache::factory($this->getCacheFileForAcl($accountId, $actionId))->load(); if ($acl instanceof AccountAcl) { return $acl; @@ -174,21 +180,22 @@ final class AccountAclService extends Service } /** - * @param int $accountId - * @param int $actionId + * @param int $accountId + * @param int $actionId * * @return string */ public function getCacheFileForAcl(int $accountId, int $actionId): string { $userId = $this->context->getUserData()->getId(); + return self::ACL_PATH - . $userId - . DIRECTORY_SEPARATOR - . $accountId - . DIRECTORY_SEPARATOR - . md5($userId . $accountId . $actionId) - . '.cache'; + .$userId + .DIRECTORY_SEPARATOR + .$accountId + .DIRECTORY_SEPARATOR + .md5($userId.$accountId.$actionId) + .'.cache'; } /** @@ -269,14 +276,10 @@ final class AccountAclService extends Service } // Analyze user's groups - $userToUserGroupService = $this->dic->get(UserToUserGroupService::class); - - // Groups in whinch the user is listed in + // Groups in which the user is listed in $userGroups = array_map( - static function ($value) { - return (int)$value->userGroupId; - }, - $userToUserGroupService->getGroupsForUser($this->userData->getId()) + static fn($value) => (int)$value->userGroupId, + $this->userToUserGroupService->getGroupsForUser($this->userData->getId()) ); // Check out if user groups match with account's main group @@ -306,24 +309,26 @@ final class AccountAclService extends Service /** * Checks if the user is listed in the account users * - * @param int $userId + * @param int $userId * * @return array */ private function getUserInSecondaryUsers(int $userId): array { - return array_values(array_filter( - $this->accountAclDto->getUsersId(), - static function ($value) use ($userId) { - return (int)$value->id === $userId; - } - )); + return array_values( + array_filter( + $this->accountAclDto->getUsersId(), + static function ($value) use ($userId) { + return (int)$value->id === $userId; + } + ) + ); } /** * Comprobar si los grupos del usuario está vinculado desde el grupo principal de la cuenta * - * @param array $userGroups + * @param array $userGroups * * @return bool */ @@ -337,8 +342,8 @@ final class AccountAclService extends Service * Comprobar si el usuario o el grupo del usuario se encuentran los grupos asociados a la * cuenta. * - * @param array $userGroups - * @param int $userGroupId + * @param array $userGroups + * @param int $userGroupId * * @return array */ @@ -347,16 +352,18 @@ final class AccountAclService extends Service $isAccountFullGroupAccess = $this->config->getConfigData()->isAccountFullGroupAccess(); // Comprobar si el grupo del usuario está vinculado desde los grupos secundarios de la cuenta - return array_values(array_filter( - $this->accountAclDto->getUserGroupsId(), - static function ($value) use ($userGroupId, $isAccountFullGroupAccess, $userGroups) { - return (int)$value->id === $userGroupId - // o... permitir los grupos que no sean el principal del usuario? - || ($isAccountFullGroupAccess - // Comprobar si el usuario está vinculado desde los grupos secundarios de la cuenta - && in_array((int)$value->id, $userGroups, true)); - } - )); + return array_values( + array_filter( + $this->accountAclDto->getUserGroupsId(), + static function ($value) use ($userGroupId, $isAccountFullGroupAccess, $userGroups) { + return (int)$value->id === $userGroupId + // o... permitir los grupos que no sean el principal del usuario? + || ($isAccountFullGroupAccess + // Comprobar si el usuario está vinculado desde los grupos secundarios de la cuenta + && in_array((int)$value->id, $userGroups, true)); + } + ) + ); } /** @@ -398,23 +405,18 @@ final class AccountAclService extends Service /** * Saves the ACL * - * @param AccountAcl $accountAcl + * @param AccountAcl $accountAcl * * @return null|FileCacheInterface */ public function saveAclInCache(AccountAcl $accountAcl): ?FileCacheInterface { try { - return FileCache::factory($this->getCacheFileForAcl($accountAcl->getAccountId(), $accountAcl->getActionId())) - ->save($accountAcl); + return FileCache::factory( + $this->getCacheFileForAcl($accountAcl->getAccountId(), $accountAcl->getActionId()) + )->save($accountAcl); } catch (FileException $e) { return null; } } - - protected function initialize(): void - { - $this->acl = $this->dic->get(Acl::class); - $this->userData = $this->context->getUserData(); - } } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountBulkRequest.php b/lib/SP/Domain/Account/Services/AccountBulkRequest.php similarity index 85% rename from lib/SP/Services/Account/AccountBulkRequest.php rename to lib/SP/Domain/Account/Services/AccountBulkRequest.php index f4275dcf..3b5b0ece 100644 --- a/lib/SP/Services/Account/AccountBulkRequest.php +++ b/lib/SP/Domain/Account/Services/AccountBulkRequest.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,25 +22,25 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; /** * Class AccountBulkRequest * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ final class AccountBulkRequest { - private array $itemsId; + private array $itemsId; private AccountRequest $accountRequest; - private bool $deleteHistory = false; + private bool $deleteHistory = false; /** * AccountBulkRequest constructor. * - * @param int[] $itemsId - * @param AccountRequest $accountRequest + * @param int[] $itemsId + * @param AccountRequest $accountRequest */ public function __construct(array $itemsId, AccountRequest $accountRequest) { diff --git a/lib/SP/Services/Account/AccountCryptService.php b/lib/SP/Domain/Account/Services/AccountCryptService.php similarity index 78% rename from lib/SP/Services/Account/AccountCryptService.php rename to lib/SP/Domain/Account/Services/AccountCryptService.php index fe4719a2..dbd77a49 100644 --- a/lib/SP/Services/Account/AccountCryptService.php +++ b/lib/SP/Domain/Account/Services/AccountCryptService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,33 +22,45 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; use Defuse\Crypto\Exception\CryptoException; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SPException; -use SP\Services\Crypt\UpdateMasterPassRequest; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\Task\TaskFactory; +use SP\Domain\Account\AccountCryptServiceInterface; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; +use SP\Domain\Task\Services\TaskFactory; use SP\Util\Util; /** * Class AccountCryptService * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ -final class AccountCryptService extends Service +final class AccountCryptService extends Service implements AccountCryptServiceInterface { - private ?AccountService $accountService = null; - private ?AccountHistoryService $accountHistoryService = null; + private AccountService $accountService; + private AccountHistoryService $accountHistoryService; private ?UpdateMasterPassRequest $request = null; + public function __construct( + Application $application, + AccountService $accountService, + AccountHistoryServiceInterface $accountHistoryService + ) { + parent::__construct($application); + + $this->accountService = $accountService; + $this->accountHistoryService = $accountHistoryService; + } + /** * Actualiza las claves de todas las cuentas con la nueva clave maestra. * @@ -61,7 +73,8 @@ final class AccountCryptService extends Service try { $this->eventDispatcher->notifyEvent( 'update.masterPassword.accounts.start', - new Event($this, + new Event( + $this, EventMessage::factory() ->addDescription(__u('Update Master Password')) ) @@ -70,9 +83,12 @@ final class AccountCryptService extends Service if ($this->request->useTask()) { $task = $this->request->getTask(); - TaskFactory::update($task, - TaskFactory::createMessage($task->getTaskId(), - __u('Update Master Password')) + TaskFactory::update( + $task, + TaskFactory::createMessage( + $task->getTaskId(), + __u('Update Master Password') + ) ); } @@ -95,15 +111,15 @@ final class AccountCryptService extends Service SPException::ERROR, null, $e->getCode(), - $e); + $e + ); } } private function processAccounts( - array $accounts, + array $accounts, callable $passUpdater - ): EventMessage - { + ): EventMessage { set_time_limit(0); $accountsOk = []; @@ -152,11 +168,14 @@ final class AccountCryptService extends Service logger($taskMessage->composeText()); } else { logger( - sprintf(__('Updated accounts: %d / %d - %d%% - ETA: %ds (%.2f/s)'), + sprintf( + __('Updated accounts: %d / %d - %d%% - ETA: %ds (%.2f/s)'), $counter, $numAccounts, round(($counter * 100) / $numAccounts, 2), - $eta[0], $eta[1]) + $eta[0], + $eta[1] + ) ); } } @@ -184,7 +203,7 @@ final class AccountCryptService extends Service $accountsOk[] = $account->id; $counter++; - } catch (SPException | CryptoException $e) { + } catch (SPException|CryptoException $e) { $errorCount++; $eventMessage->addDescription(__u('Error while updating the account\'s password')); @@ -205,14 +224,14 @@ final class AccountCryptService extends Service */ public function updateHistoryMasterPassword( UpdateMasterPassRequest $updateMasterPassRequest - ): void - { + ): void { $this->request = $updateMasterPassRequest; try { $this->eventDispatcher->notifyEvent( 'update.masterPassword.accountsHistory.start', - new Event($this, + new Event( + $this, EventMessage::factory() ->addDescription(__u('Update Master Password (H)')) ) @@ -221,9 +240,12 @@ final class AccountCryptService extends Service if ($this->request->useTask()) { $task = $this->request->getTask(); - TaskFactory::update($task, - TaskFactory::createMessage($task->getTaskId(), - __u('Update Master Password (H)')) + TaskFactory::update( + $task, + TaskFactory::createMessage( + $task->getTaskId(), + __u('Update Master Password (H)') + ) ); } @@ -233,7 +255,8 @@ final class AccountCryptService extends Service $request->hash = $this->request->getHash(); $this->accountHistoryService->updatePasswordMasterPass($request); - }); + } + ); $this->eventDispatcher->notifyEvent( 'update.masterPassword.accountsHistory.end', @@ -247,17 +270,8 @@ final class AccountCryptService extends Service SPException::ERROR, null, $e->getCode(), - $e); + $e + ); } } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->accountService = $this->dic->get(AccountService::class); - $this->accountHistoryService = $this->dic->get(AccountHistoryService::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountFileService.php b/lib/SP/Domain/Account/Services/AccountFileService.php similarity index 69% rename from lib/SP/Services/Account/AccountFileService.php rename to lib/SP/Domain/Account/Services/AccountFileService.php index 91153f15..4bbc2272 100644 --- a/lib/SP/Services/Account/AccountFileService.php +++ b/lib/SP/Domain/Account/Services/AccountFileService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,48 +22,59 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\CheckException; use SP\Core\Exceptions\ConstraintException; -use SP\Core\Exceptions\InvalidImageException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\FileData; use SP\DataModel\FileExtData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Account\AccountFileRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\AccountFileServiceInterface; +use SP\Domain\Account\In\AccountFileRepositoryInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; use SP\Util\FileUtil; use SP\Util\ImageUtil; /** * Class AccountFileService * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ -final class AccountFileService extends Service +final class AccountFileService extends Service implements AccountFileServiceInterface { - protected ?AccountFileRepository $accountFileRepository = null; + private AccountFileRepositoryInterface $accountFileRepository; + private ImageUtil $imageUtil; + + public function __construct( + Application $application, + AccountFileRepositoryInterface $accountFileRepository, + ImageUtil $imageUtil + ) { + $this->accountFileRepository = $accountFileRepository; + $this->imageUtil = $imageUtil; + + parent::__construct($application); + } /** * Creates an item * - * @throws InvalidImageException - * @throws ConstraintException - * @throws QueryException + * @param \SP\DataModel\FileData $itemData + * + * @return int + * @throws \SP\Core\Exceptions\InvalidImageException */ public function create(FileData $itemData): int { if (FileUtil::isImage($itemData)) { try { - $imageUtil = $this->dic->get(ImageUtil::class); - $itemData->setThumb($imageUtil->createThumbnail($itemData->getContent())); + $itemData->setThumb($this->imageUtil->createThumbnail($itemData->getContent())); } catch (CheckException $e) { processException($e); @@ -112,11 +123,9 @@ final class AccountFileService extends Service /** * Returns all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @return FileExtData[] - * @throws ConstraintException - * @throws QueryException */ public function getByIdBatch(array $ids): array { @@ -126,11 +135,10 @@ final class AccountFileService extends Service /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * - * @throws ServiceException - * @throws ConstraintException - * @throws QueryException + * @return int + * @throws \SP\Domain\Common\Services\ServiceException */ public function deleteByIdBatch(array $ids): int { @@ -149,11 +157,12 @@ final class AccountFileService extends Service /** * Deletes an item * - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @param int $id + * + * @return \SP\Domain\Account\AccountFileServiceInterface + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function delete(int $id): AccountFileService + public function delete(int $id): AccountFileServiceInterface { if ($this->accountFileRepository->delete($id) === 0) { throw new NoSuchItemException(__u('File not found')); @@ -165,8 +174,9 @@ final class AccountFileService extends Service /** * Searches for items by a given filter * - * @throws ConstraintException - * @throws QueryException + * @param \SP\DataModel\ItemSearchData $searchData + * + * @return \SP\Infrastructure\Database\QueryResult */ public function search(ItemSearchData $searchData): QueryResult { @@ -184,13 +194,4 @@ final class AccountFileService extends Service { return $this->accountFileRepository->getByAccountId($id)->getDataAsArray(); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->accountFileRepository = $this->dic->get(AccountFileRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountFilterUser.php b/lib/SP/Domain/Account/Services/AccountFilterUser.php similarity index 81% rename from lib/SP/Services/Account/AccountFilterUser.php rename to lib/SP/Domain/Account/Services/AccountFilterUser.php index f3902892..e46d4f43 100644 --- a/lib/SP/Services/Account/AccountFilterUser.php +++ b/lib/SP/Domain/Account/Services/AccountFilterUser.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,13 +22,13 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; -use SP\Config\ConfigDataInterface; use SP\Core\Context\ContextInterface; use SP\DataModel\ProfileData; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\User\Services\UserLoginResponse; use SP\Mvc\Model\QueryCondition; -use SP\Services\User\UserLoginResponse; defined('APP_ROOT') || die(); @@ -37,16 +37,15 @@ defined('APP_ROOT') || die(); */ final class AccountFilterUser { - private ?ProfileData $userProfile = null; private ConfigDataInterface $configData; - private ?UserLoginResponse $userData = null; - private ContextInterface $context; + private ContextInterface $context; + private ?ProfileData $userProfile = null; + private ?UserLoginResponse $userData = null; public function __construct( - ContextInterface $context, + ContextInterface $context, ConfigDataInterface $configData - ) - { + ) { $this->context = $context; $this->configData = $configData; } @@ -70,15 +69,18 @@ final class AccountFilterUser OR AccountHistory.accountId IN (SELECT accountId AS accountId FROM AccountToUser WHERE accountId = AccountHistory.accountId AND userId = ? UNION ALL SELECT accountId FROM AccountToUserGroup WHERE accountId = AccountHistory.accountId AND userGroupId = ?) OR AccountHistory.userGroupId IN (SELECT userGroupId FROM UserToUserGroup WHERE userGroupId = AccountHistory.userGroupId AND userId = ?))'; - $params = [$this->userData->getId(), + $params = [ + $this->userData->getId(), $this->userData->getUserGroupId(), $this->userData->getId(), $this->userData->getUserGroupId(), - $this->userData->getId()]; + $this->userData->getId(), + ]; if ($this->configData->isAccountFullGroupAccess()) { // Filtro de grupos secundarios en grupos que incluyen al usuario - $filter .= PHP_EOL . 'OR AccountHistory.accountId = (SELECT accountId FROM AccountToUserGroup aug INNER JOIN UserToUserGroup uug ON uug.userGroupId = aug.userGroupId WHERE aug.accountId = AccountHistory.accountId AND uug.userId = ? LIMIT 1)'; + $filter .= PHP_EOL + .'OR AccountHistory.accountId = (SELECT accountId FROM AccountToUserGroup aug INNER JOIN UserToUserGroup uug ON uug.userGroupId = aug.userGroupId WHERE aug.accountId = AccountHistory.accountId AND uug.userId = ? LIMIT 1)'; $params[] = $this->userData->getId(); } @@ -121,15 +123,18 @@ final class AccountFilterUser OR Account.id IN (SELECT accountId AS accountId FROM AccountToUser WHERE accountId = Account.id AND userId = ? UNION ALL SELECT accountId FROM AccountToUserGroup WHERE accountId = Account.id AND userGroupId = ?) OR Account.userGroupId IN (SELECT userGroupId FROM UserToUserGroup WHERE userGroupId = Account.userGroupId AND userId = ?))'; - $params = [$this->userData->getId(), + $params = [ + $this->userData->getId(), $this->userData->getUserGroupId(), $this->userData->getId(), $this->userData->getUserGroupId(), - $this->userData->getId()]; + $this->userData->getId(), + ]; if ($this->configData->isAccountFullGroupAccess()) { // Filtro de grupos secundarios en grupos que incluyen al usuario - $filter .= PHP_EOL . 'OR Account.id = (SELECT accountId FROM AccountToUserGroup aug INNER JOIN UserToUserGroup uug ON uug.userGroupId = aug.userGroupId WHERE aug.accountId = Account.id AND uug.userId = ? LIMIT 1)'; + $filter .= PHP_EOL + .'OR Account.id = (SELECT accountId FROM AccountToUserGroup aug INNER JOIN UserToUserGroup uug ON uug.userGroupId = aug.userGroupId WHERE aug.accountId = Account.id AND uug.userId = ? LIMIT 1)'; $params[] = $this->userData->getId(); } diff --git a/lib/SP/Services/Account/AccountHistoryService.php b/lib/SP/Domain/Account/Services/AccountHistoryService.php similarity index 70% rename from lib/SP/Services/Account/AccountHistoryService.php rename to lib/SP/Domain/Account/Services/AccountHistoryService.php index b71647bc..86e84c78 100644 --- a/lib/SP/Services/Account/AccountHistoryService.php +++ b/lib/SP/Domain/Account/Services/AccountHistoryService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,10 +22,9 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; @@ -33,24 +32,38 @@ use SP\DataModel\AccountHistoryData; use SP\DataModel\Dto\AccountHistoryCreateDto; use SP\DataModel\ItemData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Account\AccountHistoryRepository; -use SP\Repositories\Account\AccountToUserGroupRepository; -use SP\Repositories\Account\AccountToUserRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Account\In\AccountHistoryRepositoryInterface; +use SP\Domain\Account\In\AccountToUserGroupRepositoryInterface; +use SP\Domain\Account\In\AccountToUserRepositoryInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountHistoryService * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ -final class AccountHistoryService extends Service +final class AccountHistoryService extends Service implements AccountHistoryServiceInterface { - protected ?AccountHistoryRepository $accountHistoryRepository = null; - protected ?AccountToUserGroupRepository $accountToUserGroupRepository = null; - protected ?AccountToUserRepository $accountToUserRepository = null; + private AccountHistoryRepositoryInterface $accountHistoryRepository; + private AccountToUserGroupRepositoryInterface $accountToUserGroupRepository; + private AccountToUserRepositoryInterface $accountToUserRepository; + + public function __construct( + Application $application, + AccountHistoryRepositoryInterface $accountHistoryRepository, + AccountToUserGroupRepositoryInterface $accountToUserGroupRepository, + AccountToUserRepositoryInterface $accountToUserRepository + ) { + $this->accountHistoryRepository = $accountHistoryRepository; + $this->accountToUserGroupRepository = $accountToUserGroupRepository; + $this->accountToUserRepository = $accountToUserRepository; + + parent::__construct($application); + } /** * Returns the item for given id @@ -78,7 +91,9 @@ final class AccountHistoryService extends Service */ public function getHistoryForAccount(int $id): array { - return self::mapHistoryForDateSelect($this->accountHistoryRepository->getHistoryForAccount($id)->getDataAsArray()); + return self::mapHistoryForDateSelect( + $this->accountHistoryRepository->getHistoryForAccount($id)->getDataAsArray() + ); } /** @@ -91,9 +106,9 @@ final class AccountHistoryService extends Service foreach ($history as $item) { // Comprobamos si la entrada en el historial es la primera (no tiene editor ni fecha de edición) if (empty($item->dateEdit) || $item->dateEdit === '0000-00-00 00:00:00') { - $date = $item->dateAdd . ' - ' . $item->userAdd; + $date = $item->dateAdd.' - '.$item->userAdd; } else { - $date = $item->dateEdit . ' - ' . $item->userEdit; + $date = $item->dateEdit.' - '.$item->userEdit; } $items[$item->id] = $date; @@ -123,8 +138,9 @@ final class AccountHistoryService extends Service } /** - * @throws QueryException - * @throws ConstraintException + * @param \SP\DataModel\ItemSearchData $itemSearchData + * + * @return \SP\Infrastructure\Database\QueryResult */ public function search(ItemSearchData $itemSearchData): QueryResult { @@ -134,8 +150,9 @@ final class AccountHistoryService extends Service /** * Crea una nueva cuenta en la BBDD * - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException + * @param \SP\DataModel\Dto\AccountHistoryCreateDto $dto + * + * @return int */ public function create(AccountHistoryCreateDto $dto): int { @@ -154,9 +171,9 @@ final class AccountHistoryService extends Service /** * Elimina los datos de una cuenta en la BBDD. * - * @throws QueryException - * @throws ServiceException - * @throws ConstraintException + * @param int $id + * + * @throws \SP\Domain\Common\Services\ServiceException */ public function delete(int $id): void { @@ -168,11 +185,9 @@ final class AccountHistoryService extends Service /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @return int - * @throws QueryException - * @throws ConstraintException */ public function deleteByIdBatch(array $ids): int { @@ -182,7 +197,7 @@ final class AccountHistoryService extends Service /** * Deletes all the items for given accounts id * - * @param int[] $ids + * @param int[] $ids * * @return int * @throws QueryException @@ -199,8 +214,7 @@ final class AccountHistoryService extends Service */ public function updatePasswordMasterPass( AccountPasswordRequest $accountRequest - ): void - { + ): void { if ($this->accountHistoryRepository->updatePassword($accountRequest) !== 1) { throw new ServiceException(__u('Error while updating the password')); } @@ -216,15 +230,4 @@ final class AccountHistoryService extends Service { return $this->accountHistoryRepository->getAll()->getDataAsArray(); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->accountHistoryRepository = $this->dic->get(AccountHistoryRepository::class); - $this->accountToUserRepository = $this->dic->get(AccountToUserRepository::class); - $this->accountToUserGroupRepository = $this->dic->get(AccountToUserGroupRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountPasswordRequest.php b/lib/SP/Domain/Account/Services/AccountPasswordRequest.php similarity index 81% rename from lib/SP/Services/Account/AccountPasswordRequest.php rename to lib/SP/Domain/Account/Services/AccountPasswordRequest.php index c390f8f9..733e94d5 100644 --- a/lib/SP/Services/Account/AccountPasswordRequest.php +++ b/lib/SP/Domain/Account/Services/AccountPasswordRequest.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,17 +22,17 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; /** * Class AccountPasswordRequest * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ final class AccountPasswordRequest { - public ?int $id = null; + public ?int $id = null; public ?string $pass = null; - public ?string $key = null; + public ?string $key = null; public ?string $hash = null; } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountPresetService.php b/lib/SP/Domain/Account/Services/AccountPresetService.php similarity index 79% rename from lib/SP/Services/Account/AccountPresetService.php rename to lib/SP/Domain/Account/Services/AccountPresetService.php index a5d74c0e..742e2ef7 100644 --- a/lib/SP/Services/Account/AccountPresetService.php +++ b/lib/SP/Domain/Account/Services/AccountPresetService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,34 +22,34 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; -use SP\Config\ConfigDataInterface; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\ValidationException; use SP\DataModel\ItemPreset\Password; +use SP\Domain\Account\AccountPresetServiceInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\ItemPreset\ItemPresetInterface; +use SP\Domain\ItemPreset\ItemPresetServiceInterface; use SP\Mvc\Controller\Validators\PasswordValidator; -use SP\Services\ItemPreset\ItemPresetInterface; -use SP\Services\ItemPreset\ItemPresetService; /** * Class AccountPreset * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ -final class AccountPresetService +final class AccountPresetService implements AccountPresetServiceInterface { - private ItemPresetService $itemPresetService; - private ConfigDataInterface $configData; + private ItemPresetServiceInterface $itemPresetService; + private ConfigDataInterface $configData; public function __construct( - ItemPresetService $itemPresetService, + ItemPresetServiceInterface $itemPresetService, ConfigDataInterface $configData - ) - { + ) { $this->itemPresetService = $itemPresetService; $this->configData = $configData; } diff --git a/lib/SP/Domain/Account/Services/AccountRequest.php b/lib/SP/Domain/Account/Services/AccountRequest.php new file mode 100644 index 00000000..1a792c06 --- /dev/null +++ b/lib/SP/Domain/Account/Services/AccountRequest.php @@ -0,0 +1,61 @@ +. + */ + +namespace SP\Domain\Account\Services; + +/** + * Class AccountRequest + * + * @package SP\Account + */ +final class AccountRequest +{ + public ?int $id = null; + public ?string $name = null; + public ?int $clientId = null; + public ?int $categoryId = null; + public ?string $login = null; + public ?string $url = null; + public ?string $notes = null; + public ?int $userId = null; + public ?int $userGroupId = null; + public ?int $userEditId = null; + public ?int $otherUserEdit = null; + public ?int $otherUserGroupEdit = null; + public ?string $pass = null; + public ?string $key = null; + public ?int $isPrivate = null; + public ?int $isPrivateGroup = null; + public ?int $passDateChange = null; + public ?int $parentId = null; + public ?array $usersView = null; + public ?array $usersEdit = null; + public ?array $userGroupsView = null; + public ?array $userGroupsEdit = null; + public ?array $tags = null; + public ?bool $changeOwner = false; + public ?bool $changeUserGroup = false; + public ?bool $changePermissions = false; + public ?bool $updateTags = false; +} \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountSearchFilter.php b/lib/SP/Domain/Account/Services/AccountSearchFilter.php similarity index 85% rename from lib/SP/Services/Account/AccountSearchFilter.php rename to lib/SP/Domain/Account/Services/AccountSearchFilter.php index 161721ca..20306bf8 100644 --- a/lib/SP/Services/Account/AccountSearchFilter.php +++ b/lib/SP/Domain/Account/Services/AccountSearchFilter.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; use SP\Mvc\Model\QueryCondition; @@ -37,36 +37,36 @@ final class AccountSearchFilter /** * Constantes de ordenación */ - public const SORT_DIR_ASC = 0; + public const SORT_DIR_ASC = 0; public const SORT_DIR_DESC = 1; - public const SORT_LOGIN = 3; - public const SORT_URL = 4; + public const SORT_LOGIN = 3; + public const SORT_URL = 4; public const SORT_CATEGORY = 2; - public const SORT_CLIENT = 5; - public const SORT_NAME = 1; - public const SORT_DEFAULT = 0; + public const SORT_CLIENT = 5; + public const SORT_NAME = 1; + public const SORT_DEFAULT = 0; /** * @var int|null El número de registros de la última consulta */ public static ?int $queryNumRows; - private bool $globalSearch = false; - private ?string $txtSearch = null; + private bool $globalSearch = false; + private ?string $txtSearch = null; /** * @var string|null Search string without special filters */ - private ?string $cleanTxtSearch = null; - private ?int $clientId = null; - private ?int $categoryId = null; - private ?array $tagsId = null; - private int $sortOrder = self::SORT_DEFAULT; - private int $sortKey = self::SORT_DIR_ASC; - private int $limitStart = 0; - private ?int $limitCount = null; - private ?bool $sortViews = null; - private bool $searchFavorites = false; - private ?QueryCondition $stringFilters = null; - private ?string $filterOperator = null; + private ?string $cleanTxtSearch = null; + private ?int $clientId = null; + private ?int $categoryId = null; + private ?array $tagsId = null; + private int $sortOrder = self::SORT_DEFAULT; + private int $sortKey = self::SORT_DIR_ASC; + private int $limitStart = 0; + private ?int $limitCount = null; + private ?bool $sortViews = null; + private bool $searchFavorites = false; + private ?QueryCondition $stringFilters = null; + private ?string $filterOperator = null; public function isSearchFavorites(): bool { diff --git a/lib/SP/Services/Account/AccountSearchItem.php b/lib/SP/Domain/Account/Services/AccountSearchItem.php similarity index 97% rename from lib/SP/Services/Account/AccountSearchItem.php rename to lib/SP/Domain/Account/Services/AccountSearchItem.php index 2bf13bb6..3c31ecfc 100644 --- a/lib/SP/Services/Account/AccountSearchItem.php +++ b/lib/SP/Domain/Account/Services/AccountSearchItem.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,16 +22,15 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; defined('APP_ROOT') || die(); -use SP\Config\ConfigDataInterface; use SP\Core\Bootstrap\BootstrapBase; use SP\DataModel\AccountSearchVData; use SP\DataModel\ItemData; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Html\Html; -use SP\Services\PublicLink\PublicLinkService; /** * Class AccountSearchItem para contener los datos de cada cuenta en la búsqueda diff --git a/lib/SP/Services/Account/AccountSearchService.php b/lib/SP/Domain/Account/Services/AccountSearchService.php similarity index 71% rename from lib/SP/Services/Account/AccountSearchService.php rename to lib/SP/Domain/Account/Services/AccountSearchService.php index 2d7ba328..19b6f1a9 100644 --- a/lib/SP/Services/Account/AccountSearchService.php +++ b/lib/SP/Domain/Account/Services/AccountSearchService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,31 +22,33 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Config\ConfigDataInterface; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\AccountSearchVData; use SP\DataModel\Dto\AccountAclDto; use SP\DataModel\Dto\AccountCache; +use SP\Domain\Account\AccountAclServiceInterface; +use SP\Domain\Account\AccountSearchServiceInterface; +use SP\Domain\Account\AccountToFavoriteServiceInterface; +use SP\Domain\Account\In\AccountRepositoryInterface; +use SP\Domain\Account\In\AccountToTagRepositoryInterface; +use SP\Domain\Account\In\AccountToUserGroupRepositoryInterface; +use SP\Domain\Account\In\AccountToUserRepositoryInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\User\UserGroupServiceInterface; +use SP\Domain\User\UserServiceInterface; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\File\FileCache; +use SP\Infrastructure\File\FileCacheInterface; +use SP\Infrastructure\File\FileException; use SP\Mvc\Model\QueryCondition; -use SP\Repositories\Account\AccountRepository; -use SP\Repositories\Account\AccountToTagRepository; -use SP\Repositories\Account\AccountToUserGroupRepository; -use SP\Repositories\Account\AccountToUserRepository; -use SP\Services\Service; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Storage\Database\QueryResult; -use SP\Storage\File\FileCache; -use SP\Storage\File\FileCacheInterface; -use SP\Storage\File\FileException; use SP\Util\Filter; defined('APP_ROOT') || die(); @@ -54,27 +56,27 @@ defined('APP_ROOT') || die(); /** * Class AccountSearchService para la gestión de búsquedas de cuentas */ -final class AccountSearchService extends Service +final class AccountSearchService extends Service implements AccountSearchServiceInterface { /** * Regex filters for special searching */ private const FILTERS = [ 'condition' => [ - 'subject' => ['is', 'not'], - 'condition' => ['expired', 'private'] + 'subject' => ['is', 'not'], + 'condition' => ['expired', 'private'], ], - 'items' => [ - 'subject' => ['id', 'user', 'group', 'file', 'owner', 'maingroup', 'client', 'category', 'name_regex'], - 'condition' => null + 'items' => [ + 'subject' => ['id', 'user', 'group', 'file', 'owner', 'maingroup', 'client', 'category', 'name_regex'], + 'condition' => null, + ], + 'operator' => [ + 'subject' => ['op'], + 'condition' => ['and', 'or'], ], - 'operator' => [ - 'subject' => ['op'], - 'condition' => ['and', 'or'] - ] ]; - private const COLORS_CACHE_FILE = CACHE_PATH . DIRECTORY_SEPARATOR . 'colors.cache'; + private const COLORS_CACHE_FILE = CACHE_PATH.DIRECTORY_SEPARATOR.'colors.cache'; /** * Colores para resaltar las cuentas @@ -98,17 +100,65 @@ final class AccountSearchService extends Service '673AB7', '3F51B5', ]; - private ?AccountFilterUser $accountFilterUser = null; - private ?AccountAclService $accountAclService = null; - private ?ConfigDataInterface $configData = null; - private ?AccountToTagRepository $accountToTagRepository = null; - private ?AccountToUserRepository $accountToUserRepository = null; - private ?AccountToUserGroupRepository $accountToUserGroupRepository = null; - private ?FileCacheInterface $colorCache = null; - private ?array $accountColor = null; - private ?AccountRepository $accountRepository = null; - private ?string $cleanString = null; - private ?string $filterOperator = null; + private AccountFilterUser $accountFilterUser; + private AccountAclServiceInterface $accountAclService; + private ConfigDataInterface $configData; + private AccountToTagRepositoryInterface $accountToTagRepository; + private AccountToUserRepositoryInterface $accountToUserRepository; + private AccountToUserGroupRepositoryInterface $accountToUserGroupRepository; + private AccountToFavoriteServiceInterface $accountToFavoriteService; + private UserServiceInterface $userService; + private UserGroupServiceInterface $userGroupService; + private FileCacheInterface $colorCache; + private AccountRepositoryInterface $accountRepository; + private ?array $accountColor = null; + private ?string $cleanString = null; + private ?string $filterOperator = null; + + public function __construct( + Application $application, + AccountAclServiceInterface $accountAclService, + AccountToTagRepositoryInterface $accountToTagRepository, + AccountToUserRepositoryInterface $accountToUserRepository, + AccountToUserGroupRepositoryInterface $accountToUserGroupRepository, + AccountToFavoriteServiceInterface $accountToFavoriteService, + UserServiceInterface $userService, + UserGroupServiceInterface $userGroupService, + AccountRepositoryInterface $accountRepository, + AccountFilterUser $accountFilterUser + ) { + parent::__construct($application); + $this->accountAclService = $accountAclService; + $this->userService = $userService; + $this->userGroupService = $userGroupService; + $this->accountToFavoriteService = $accountToFavoriteService; + $this->accountToTagRepository = $accountToTagRepository; + $this->accountToUserRepository = $accountToUserRepository; + $this->accountToUserGroupRepository = $accountToUserGroupRepository; + $this->accountRepository = $accountRepository; + $this->accountFilterUser = $accountFilterUser; + + // TODO: use IoC + $this->colorCache = new FileCache(self::COLORS_CACHE_FILE); + $this->configData = $this->config->getConfigData(); + + $this->loadColors(); + + } + + /** + * Load colors from cache + */ + private function loadColors(): void + { + try { + $this->accountColor = $this->colorCache->load(); + + logger('Loaded accounts color cache'); + } catch (FileException $e) { + processException($e); + } + } /** * Procesar los resultados de la búsqueda y crear la variable que contiene los datos de cada cuenta @@ -120,8 +170,7 @@ final class AccountSearchService extends Service */ public function processSearchResults( AccountSearchFilter $accountSearchFilter - ): QueryResult - { + ): QueryResult { if (!empty($accountSearchFilter->getTxtSearch())) { $accountSearchFilter->setStringFilters($this->analyzeQueryFilters($accountSearchFilter->getTxtSearch())); } @@ -144,11 +193,9 @@ final class AccountSearchService extends Service // Variables de configuración $maxTextLength = $this->configData->isResultsAsCards() ? 40 : 60; - $accountLinkEnabled = $this->context->getUserData() - ->getPreferences() - ->isAccountLink() || $this->configData->isAccountLink(); - $favorites = $this->dic->get(AccountToFavoriteService::class) - ->getForUserId($this->context->getUserData()->getId()); + $accountLinkEnabled = $this->context->getUserData()->getPreferences()->isAccountLink() + || $this->configData->isAccountLink(); + $favorites = $this->accountToFavoriteService->getForUserId($this->context->getUserData()->getId()); $accountsData = []; @@ -232,7 +279,7 @@ final class AccountSearchService extends Service $filtersAndValues, static function ($value, $key) { return in_array($key, self::FILTERS['items']['subject'], true) - && $value !== ''; + && $value !== ''; }, ARRAY_FILTER_USE_BOTH ); @@ -245,7 +292,7 @@ final class AccountSearchService extends Service $filtersAndValues, static function ($value, $key) { return in_array($key, self::FILTERS['operator']['subject'], true) - && in_array($value, self::FILTERS['operator']['condition'], true); + && in_array($value, self::FILTERS['operator']['condition'], true); }, ARRAY_FILTER_USE_BOTH ); @@ -260,7 +307,7 @@ final class AccountSearchService extends Service if (in_array($subject, self::FILTERS['condition']['subject'], true) && in_array($condition, self::FILTERS['condition']['condition'], true) ) { - return $subject . ':' . $condition; + return $subject.':'.$condition; } return null; @@ -280,52 +327,57 @@ final class AccountSearchService extends Service } private function processFilterItems( - array $filters, + array $filters, QueryCondition $queryCondition - ): void - { + ): void { foreach ($filters as $filter => $text) { try { switch ($filter) { case 'user': - $userData = $this->dic->get(UserService::class) - ->getByLogin(Filter::safeSearchString($text)); + $userData = $this->userService->getByLogin(Filter::safeSearchString($text)); - if (is_object($userData)) { + if (null !== $userData) { $queryCondition->addFilter( 'Account.userId = ? OR Account.userGroupId = ? OR Account.id IN (SELECT AccountToUser.accountId FROM AccountToUser WHERE AccountToUser.accountId = Account.id AND AccountToUser.userId = ? UNION SELECT AccountToUserGroup.accountId FROM AccountToUserGroup WHERE AccountToUserGroup.accountId = Account.id AND AccountToUserGroup.userGroupId = ?)', - [$userData->getId(), $userData->getUserGroupId(), $userData->getId(), $userData->getUserGroupId()]); + [ + $userData->getId(), + $userData->getUserGroupId(), + $userData->getId(), + $userData->getUserGroupId(), + ] + ); } break; case 'owner': - $text = '%' . Filter::safeSearchString($text) . '%'; + $text = '%'.Filter::safeSearchString($text).'%'; $queryCondition->addFilter( 'Account.userLogin LIKE ? OR Account.userName LIKE ?', - [$text, $text]); + [$text, $text] + ); break; case 'group': - $userGroupData = $this->dic->get(UserGroupService::class) - ->getByName(Filter::safeSearchString($text)); + $userGroupData = $this->userGroupService->getByName(Filter::safeSearchString($text)); if (is_object($userGroupData)) { $queryCondition->addFilter( 'Account.userGroupId = ? OR Account.id IN (SELECT AccountToUserGroup.accountId FROM AccountToUserGroup WHERE AccountToUserGroup.accountId = id AND AccountToUserGroup.userGroupId = ?)', - [$userGroupData->getId(), $userGroupData->getId()]); + [$userGroupData->getId(), $userGroupData->getId()] + ); } break; case 'maingroup': $queryCondition->addFilter( 'Account.userGroupName LIKE ?', - ['%' . Filter::safeSearchString($text) . '%'] + ['%'.Filter::safeSearchString($text).'%'] ); break; case 'file': $queryCondition->addFilter( 'Account.id IN (SELECT AccountFile.accountId FROM AccountFile WHERE AccountFile.name LIKE ?)', - ['%' . $text . '%'] + ['%'.$text.'%'] ); break; case 'id': @@ -337,13 +389,13 @@ final class AccountSearchService extends Service case 'client': $queryCondition->addFilter( 'Account.clientName LIKE ?', - ['%' . Filter::safeSearchString($text) . '%'] + ['%'.Filter::safeSearchString($text).'%'] ); break; case 'category': $queryCondition->addFilter( 'Account.categoryName LIKE ?', - ['%' . Filter::safeSearchString($text) . '%'] + ['%'.Filter::safeSearchString($text).'%'] ); break; case 'name_regex': @@ -372,30 +424,33 @@ final class AccountSearchService extends Service } private function processFilterIs( - array $filters, + array $filters, QueryCondition $queryCondition - ): void - { + ): void { foreach ($filters as $filter) { switch ($filter) { case 'is:expired': $queryCondition->addFilter( 'Account.passDateChange > 0 AND UNIX_TIMESTAMP() > Account.passDateChange', - []); + [] + ); break; case 'not:expired': $queryCondition->addFilter( 'Account.passDateChange = 0 OR Account.passDateChange IS NULL OR UNIX_TIMESTAMP() < Account.passDateChange', - []); + [] + ); break; case 'is:private': $queryCondition->addFilter( '(Account.isPrivate = 1 AND Account.userId = ?) OR (Account.isPrivateGroup = 1 AND Account.userGroupId = ?)', - [$this->context->getUserData()->getId(), $this->context->getUserData()->getUserGroupId()]); + [$this->context->getUserData()->getId(), $this->context->getUserData()->getUserGroupId()] + ); break; case 'not:private': $queryCondition->addFilter( - '(Account.isPrivate = 0 OR Account.isPrivate IS NULL) AND (Account.isPrivateGroup = 0 OR Account.isPrivateGroup IS NULL)'); + '(Account.isPrivate = 0 OR Account.isPrivate IS NULL) AND (Account.isPrivateGroup = 0 OR Account.isPrivateGroup IS NULL)' + ); break; } } @@ -409,8 +464,7 @@ final class AccountSearchService extends Service */ protected function getCacheForAccount( AccountSearchVData $accountSearchData - ): AccountCache - { + ): AccountCache { $accountId = $accountSearchData->getId(); /** @var AccountCache[] $cache */ @@ -425,7 +479,8 @@ final class AccountSearchService extends Service $cache[$accountId] = new AccountCache( $accountId, $this->accountToUserRepository->getUsersByAccountId($accountId)->getDataAsArray(), - $this->accountToUserGroupRepository->getUserGroupsByAccountId($accountId)->getDataAsArray()); + $this->accountToUserGroupRepository->getUserGroupsByAccountId($accountId)->getDataAsArray() + ); if ($hasCache) { $this->context->setAccountsCache($cache); @@ -438,7 +493,7 @@ final class AccountSearchService extends Service /** * Seleccionar un color para la cuenta * - * @param int $id El id del elemento a asignar + * @param int $id El id del elemento a asignar */ private function pickAccountColor(int $id): string { @@ -448,7 +503,7 @@ final class AccountSearchService extends Service } // Se asigna el color de forma aleatoria a cada id - $this->accountColor[$id] = '#' . self::COLORS[array_rand(self::COLORS)]; + $this->accountColor[$id] = '#'.self::COLORS[array_rand(self::COLORS)]; try { $this->colorCache->save($this->accountColor); @@ -467,36 +522,4 @@ final class AccountSearchService extends Service { return $this->cleanString; } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->accountRepository = $this->dic->get(AccountRepository::class); - $this->accountToTagRepository = $this->dic->get(AccountToTagRepository::class); - $this->accountToUserRepository = $this->dic->get(AccountToUserRepository::class); - $this->accountToUserGroupRepository = $this->dic->get(AccountToUserGroupRepository::class); - $this->colorCache = new FileCache(self::COLORS_CACHE_FILE); - $this->accountAclService = $this->dic->get(AccountAclService::class); - $this->accountFilterUser = $this->dic->get(AccountFilterUser::class); - $this->configData = $this->config->getConfigData(); - - $this->loadColors(); - } - - /** - * Load colors from cache - */ - private function loadColors(): void - { - try { - $this->accountColor = $this->colorCache->load(); - - logger('Loaded accounts color cache'); - } catch (FileException $e) { - processException($e); - } - } } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountService.php b/lib/SP/Domain/Account/Services/AccountService.php similarity index 77% rename from lib/SP/Services/Account/AccountService.php rename to lib/SP/Domain/Account/Services/AccountService.php index 8e7e8165..95dfd4d2 100644 --- a/lib/SP/Services/Account/AccountService.php +++ b/lib/SP/Domain/Account/Services/AccountService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,12 +22,10 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; use Defuse\Crypto\Exception\CryptoException; -use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; @@ -43,33 +41,61 @@ use SP\DataModel\ItemPreset\AccountPermission; use SP\DataModel\ItemPreset\AccountPrivate; use SP\DataModel\ItemSearchData; use SP\DataModel\ProfileData; -use SP\Repositories\Account\AccountRepository; -use SP\Repositories\Account\AccountToTagRepository; -use SP\Repositories\Account\AccountToUserGroupRepository; -use SP\Repositories\Account\AccountToUserRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Config\ConfigService; -use SP\Services\ItemPreset\ItemPresetInterface; -use SP\Services\ItemPreset\ItemPresetService; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Account\In\AccountRepositoryInterface; +use SP\Domain\Account\In\AccountToTagRepositoryInterface; +use SP\Domain\Account\In\AccountToUserGroupRepositoryInterface; +use SP\Domain\Account\In\AccountToUserRepositoryInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\ItemPreset\ItemPresetInterface; +use SP\Domain\ItemPreset\ItemPresetServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountService * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ final class AccountService extends Service implements AccountServiceInterface { use ServiceItemTrait; - protected ?AccountRepository $accountRepository = null; - protected ?AccountToUserGroupRepository $accountToUserGroupRepository = null; - protected ?AccountToUserRepository $accountToUserRepository = null; - protected ?AccountToTagRepository $accountToTagRepository = null; - protected ?ItemPresetService $itemPresetService = null; + private AccountRepositoryInterface $accountRepository; + private AccountToUserGroupRepositoryInterface $accountToUserGroupRepository; + private AccountToUserRepositoryInterface $accountToUserRepository; + private AccountToTagRepositoryInterface $accountToTagRepository; + private ItemPresetServiceInterface $itemPresetService; + private AccountHistoryServiceInterface $accountHistoryService; + private ConfigServiceInterface $configService; + private AccountFilterUser $accountFilterUser; + + public function __construct( + Application $application, + AccountRepositoryInterface $accountRepository, + AccountToUserGroupRepositoryInterface $accountToUserGroupRepository, + AccountToUserRepositoryInterface $accountToUserRepository, + AccountToTagRepositoryInterface $accountToTagRepository, + ItemPresetServiceInterface $itemPresetService, + AccountHistoryServiceInterface $accountHistoryService, + ConfigServiceInterface $configService, + AccountFilterUser $accountFilterUser + ) { + $this->accountRepository = $accountRepository; + $this->accountToUserGroupRepository = $accountToUserGroupRepository; + $this->accountToUserRepository = $accountToUserRepository; + $this->accountToTagRepository = $accountToTagRepository; + $this->itemPresetService = $itemPresetService; + $this->accountHistoryService = $accountHistoryService; + $this->configService = $configService; + $this->accountFilterUser = $accountFilterUser; + + parent::__construct($application); + } /** * @throws QueryException @@ -134,11 +160,11 @@ final class AccountService extends Service implements AccountServiceInterface /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function getPasswordForId(int $id): AccountPassData { - $queryFilter = $this->dic->get(AccountFilterUser::class)->getFilter(); + $queryFilter = $this->accountFilterUser->getFilter(); $result = $this->accountRepository->getPasswordForId($id, $queryFilter); @@ -149,6 +175,32 @@ final class AccountService extends Service implements AccountServiceInterface return $result->getData(); } + /** + * @param \SP\DataModel\AccountHistoryData $data + * + * @return int + */ + public function createFromHistory(AccountHistoryData $data): int + { + $accountRequest = new AccountRequest(); + $accountRequest->name = $data->getName(); + $accountRequest->categoryId = $data->getCategoryId(); + $accountRequest->clientId = $data->getClientId(); + $accountRequest->url = $data->getUrl(); + $accountRequest->login = $data->getLogin(); + $accountRequest->pass = $data->getPass(); + $accountRequest->key = $data->getKey(); + $accountRequest->notes = $data->getNotes(); + $accountRequest->userId = $data->getUserId(); + $accountRequest->userGroupId = $data->getUserGroupId(); + $accountRequest->passDateChange = $data->getPassDateChange(); + $accountRequest->parentId = $data->getParentId(); + $accountRequest->isPrivate = $data->getIsPrivate(); + $accountRequest->isPrivateGroup = $data->getIsPrivateGroup(); + + return $this->accountRepository->create($accountRequest); + } + /** * @throws QueryException * @throws SPException @@ -161,7 +213,8 @@ final class AccountService extends Service implements AccountServiceInterface $accountRequest->changePermissions = AccountAclService::getShowPermission( $userData, - $this->context->getUserProfile()); + $this->context->getUserProfile() + ); if (empty($accountRequest->userGroupId) || !$accountRequest->changePermissions @@ -196,7 +249,7 @@ final class AccountService extends Service implements AccountServiceInterface /** * Devolver los datos de la clave encriptados * - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function getPasswordEncrypted(string $pass, ?string $masterPass = null): array { @@ -320,7 +373,8 @@ final class AccountService extends Service implements AccountServiceInterface */ private function addPresetPermissions(int $accountId): void { - $itemPresetData = $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PERMISSION); + $itemPresetData = + $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PERMISSION); if ($itemPresetData !== null && $itemPresetData->getFixed() @@ -332,8 +386,10 @@ final class AccountService extends Service implements AccountServiceInterface $accountRequest->id = $accountId; $accountRequest->usersView = array_diff($accountPermission->getUsersView(), [$userData->getId()]); $accountRequest->usersEdit = array_diff($accountPermission->getUsersEdit(), [$userData->getId()]); - $accountRequest->userGroupsView = array_diff($accountPermission->getUserGroupsView(), [$userData->getUserGroupId()]); - $accountRequest->userGroupsEdit = array_diff($accountPermission->getUserGroupsEdit(), [$userData->getUserGroupId()]); + $accountRequest->userGroupsView = + array_diff($accountPermission->getUserGroupsView(), [$userData->getUserGroupId()]); + $accountRequest->userGroupsEdit = + array_diff($accountPermission->getUserGroupsEdit(), [$userData->getUserGroupId()]); if (!empty($accountRequest->usersView)) { $this->accountToUserRepository->addByType($accountRequest, false); @@ -353,35 +409,12 @@ final class AccountService extends Service implements AccountServiceInterface } } - /** - * @throws QueryException - * @throws ConstraintException - */ - public function createFromHistory(AccountHistoryData $data): int - { - $accountRequest = new AccountRequest(); - $accountRequest->name = $data->getName(); - $accountRequest->categoryId = $data->getCategoryId(); - $accountRequest->clientId = $data->getClientId(); - $accountRequest->url = $data->getUrl(); - $accountRequest->login = $data->getLogin(); - $accountRequest->pass = $data->getPass(); - $accountRequest->key = $data->getKey(); - $accountRequest->notes = $data->getNotes(); - $accountRequest->userId = $data->getUserId(); - $accountRequest->userGroupId = $data->getUserGroupId(); - $accountRequest->passDateChange = $data->getPassDateChange(); - $accountRequest->parentId = $data->getParentId(); - $accountRequest->isPrivate = $data->getIsPrivate(); - $accountRequest->isPrivateGroup = $data->getIsPrivateGroup(); - - return $this->accountRepository->create($accountRequest); - } - /** * Updates external items for the account * - * @throws Exception + * @param \SP\Domain\Account\Services\AccountRequest $accountRequest + * + * @throws \SP\Domain\Common\Services\ServiceException */ public function update(AccountRequest $accountRequest): void { @@ -397,17 +430,18 @@ final class AccountService extends Service implements AccountServiceInterface $account = $this->getById($accountRequest->id)->getAccountVData(); $accountRequest->changeOwner = $accountRequest->userId > 0 - && ($userData->getIsAdminApp() - || $userData->getIsAdminAcc() - || ($userProfile->isAccPermission() - && $userData->getId() === $account->getUserId())); + && ($userData->getIsAdminApp() + || $userData->getIsAdminAcc() + || ($userProfile->isAccPermission() + && $userData->getId() === $account->getUserId())); $accountRequest->changeUserGroup = $accountRequest->userGroupId > 0 - && ($userData->getIsAdminApp() - || $userData->getIsAdminAcc() - || (($userProfile->isAccPermission() - && ($userData->getUserGroupId() === $account->getUserGroupId())) - || $userData->getId() === $account->getUserId())); + && ($userData->getIsAdminApp() + || $userData->getIsAdminAcc() + || (($userProfile->isAccPermission() + && ($userData->getUserGroupId() + === $account->getUserGroupId())) + || $userData->getId() === $account->getUserId())); } $this->addHistory($accountRequest->id); @@ -431,15 +465,13 @@ final class AccountService extends Service implements AccountServiceInterface */ private function addHistory(int $accountId, bool $isDelete = false): int { - $accountHistoryRepository = $this->dic->get(AccountHistoryService::class); - $configService = $this->dic->get(ConfigService::class); - - return $accountHistoryRepository->create( + return $this->accountHistoryService->create( new AccountHistoryCreateDto( $accountId, !$isDelete, $isDelete, - $configService->getByParam('masterPwd')) + $this->configService->getByParam('masterPwd') + ) ); } @@ -497,7 +529,9 @@ final class AccountService extends Service implements AccountServiceInterface /** * Update accounts in bulk mode * - * @throws ServiceException + * @param \SP\Domain\Account\Services\AccountBulkRequest $request + * + * @throws \SP\Domain\Common\Services\ServiceException */ public function updateBulk(AccountBulkRequest $request): void { @@ -517,7 +551,9 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @throws Exception + * @param \SP\Domain\Account\Services\AccountRequest $accountRequest + * + * @throws \SP\Domain\Common\Services\ServiceException */ public function editPassword(AccountRequest $accountRequest): void { @@ -545,10 +581,10 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @param int $historyId - * @param int $accountId + * @param int $historyId + * @param int $accountId * - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function editRestore(int $historyId, int $accountId): void { @@ -564,7 +600,7 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function delete(int $id): AccountService { @@ -580,7 +616,7 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @param int[] $ids + * @param int[] $ids * * @throws SPException * @throws ServiceException @@ -600,10 +636,13 @@ final class AccountService extends Service implements AccountServiceInterface */ public function getForUser(int $accountId = null): array { - $queryFilter = $this->dic->get(AccountFilterUser::class)->getFilter(); + $queryFilter = $this->accountFilterUser->getFilter(); if (null !== $accountId) { - $queryFilter->addFilter('Account.id <> ? AND (Account.parentId = 0 OR Account.parentId IS NULL)', [$accountId]); + $queryFilter->addFilter( + 'Account.id <> ? AND (Account.parentId = 0 OR Account.parentId IS NULL)', + [$accountId] + ); } return $this->accountRepository->getForUser($queryFilter)->getDataAsArray(); @@ -615,7 +654,7 @@ final class AccountService extends Service implements AccountServiceInterface */ public function getLinked(int $accountId): array { - $queryFilter = $this->dic->get(AccountFilterUser::class)->getFilter(); + $queryFilter = $this->accountFilterUser->getFilter(); $queryFilter->addFilter('Account.parentId = ?', [$accountId]); @@ -629,7 +668,7 @@ final class AccountService extends Service implements AccountServiceInterface */ public function getPasswordHistoryForId(int $id): AccountPassData { - $queryFilter = $this->dic->get(AccountFilterUser::class)->getFilterHistory(); + $queryFilter = $this->accountFilterUser->getFilterHistory(); $queryFilter->addFilter('AccountHistory.id = ?', [$id]); $result = $this->accountRepository->getPasswordHistoryForId($queryFilter); @@ -652,8 +691,9 @@ final class AccountService extends Service implements AccountServiceInterface } /** - * @throws QueryException - * @throws ConstraintException + * @param \SP\DataModel\ItemSearchData $itemSearchData + * + * @return \SP\Infrastructure\Database\QueryResult */ public function search(ItemSearchData $itemSearchData): QueryResult { @@ -676,7 +716,7 @@ final class AccountService extends Service implements AccountServiceInterface * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function getDataForLink(int $id): AccountExtData { @@ -703,30 +743,18 @@ final class AccountService extends Service implements AccountServiceInterface /** * Obtener las cuentas de una búsqueda. * - * @throws QueryException - * @throws SPException - * @throws ConstraintException + * @param \SP\Domain\Account\Services\AccountSearchFilter $accountSearchFilter + * + * @return \SP\Infrastructure\Database\QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\SPException */ public function getByFilter(AccountSearchFilter $accountSearchFilter): QueryResult { - $accountFilterUser = $this->dic->get(AccountFilterUser::class); - return $this->accountRepository->getByFilter( $accountSearchFilter, - $accountFilterUser->getFilter($accountSearchFilter->getGlobalSearch()) + $this->accountFilterUser->getFilter($accountSearchFilter->getGlobalSearch()) ); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->accountRepository = $this->dic->get(AccountRepository::class); - $this->accountToUserRepository = $this->dic->get(AccountToUserRepository::class); - $this->accountToUserGroupRepository = $this->dic->get(AccountToUserGroupRepository::class); - $this->accountToTagRepository = $this->dic->get(AccountToTagRepository::class); - $this->itemPresetService = $this->dic->get(ItemPresetService::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountToFavoriteService.php b/lib/SP/Domain/Account/Services/AccountToFavoriteService.php similarity index 70% rename from lib/SP/Services/Account/AccountToFavoriteService.php rename to lib/SP/Domain/Account/Services/AccountToFavoriteService.php index 6c718230..d2b341ea 100644 --- a/lib/SP/Services/Account/AccountToFavoriteService.php +++ b/lib/SP/Domain/Account/Services/AccountToFavoriteService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,23 +22,32 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\Account\AccountToFavoriteRepository; -use SP\Services\Service; +use SP\Domain\Account\AccountToFavoriteServiceInterface; +use SP\Domain\Account\In\AccountToFavoriteRepositoryInterface; +use SP\Domain\Common\Services\Service; /** * Class AccountFavoriteService * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ -final class AccountToFavoriteService extends Service +final class AccountToFavoriteService extends Service implements AccountToFavoriteServiceInterface { - protected ?AccountToFavoriteRepository $accountFavoriteRepository = null; + private AccountToFavoriteRepositoryInterface $accountFavoriteRepository; + + public function __construct( + Application $application, + AccountToFavoriteRepositoryInterface $accountFavoriteRepository + ) { + $this->accountFavoriteRepository = $accountFavoriteRepository; + + parent::__construct($application); + } /** * Obtener un array con los Ids de cuentas favoritas @@ -74,13 +83,4 @@ final class AccountToFavoriteService extends Service { return $this->accountFavoriteRepository->delete($accountId, $userId); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->accountFavoriteRepository = $this->dic->get(AccountToFavoriteRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Account/AccountToTagService.php b/lib/SP/Domain/Account/Services/AccountToTagService.php similarity index 61% rename from lib/SP/Services/Account/AccountToTagService.php rename to lib/SP/Domain/Account/Services/AccountToTagService.php index d61c1e02..53d0c170 100644 --- a/lib/SP/Services/Account/AccountToTagService.php +++ b/lib/SP/Domain/Account/Services/AccountToTagService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,22 +22,31 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Account; +namespace SP\Domain\Account\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\DataModel\ItemData; -use SP\Repositories\Account\AccountToTagRepository; -use SP\Services\Service; +use SP\Domain\Account\AccountToTagServiceInterface; +use SP\Domain\Account\In\AccountToTagRepositoryInterface; +use SP\Domain\Common\Services\Service; /** * Class AccountToTagService * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ -final class AccountToTagService extends Service +final class AccountToTagService extends Service implements AccountToTagServiceInterface { - protected ?AccountToTagRepository $accountToTagRepository = null; + private AccountToTagRepositoryInterface $accountToTagRepository; + + public function __construct( + Application $application, + AccountToTagRepositoryInterface $accountToTagRepository + ) { + $this->accountToTagRepository = $accountToTagRepository; + + parent::__construct($application); + } /** * @return ItemData[] @@ -50,14 +59,4 @@ final class AccountToTagService extends Service ->getTagsByAccountId($id) ->getDataAsArray(); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->accountToTagRepository = $this->dic->get(AccountToTagRepository::class); - } - } \ No newline at end of file diff --git a/lib/SP/Services/PublicLink/PublicLinkKey.php b/lib/SP/Domain/Account/Services/PublicLinkKey.php similarity index 88% rename from lib/SP/Services/PublicLink/PublicLinkKey.php rename to lib/SP/Domain/Account/Services/PublicLinkKey.php index 9e5bf852..38651f20 100644 --- a/lib/SP/Services/PublicLink/PublicLinkKey.php +++ b/lib/SP/Domain/Account/Services/PublicLinkKey.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\PublicLink; +namespace SP\Domain\Account\Services; use SP\Util\PasswordUtil; /** * Class PublicLinkKey * - * @package SP\Services\PublicLink + * @package SP\Domain\Common\Services\PublicLink */ final class PublicLinkKey { @@ -54,7 +54,7 @@ final class PublicLinkKey public function getKey(): string { - return sha1($this->salt . $this->hash); + return sha1($this->salt.$this->hash); } public function getHash(): string diff --git a/lib/SP/Services/PublicLink/PublicLinkService.php b/lib/SP/Domain/Account/Services/PublicLinkService.php similarity index 74% rename from lib/SP/Services/PublicLink/PublicLinkService.php rename to lib/SP/Domain/Account/Services/PublicLinkService.php index 6df48c21..bb03e4e9 100644 --- a/lib/SP/Services/PublicLink/PublicLinkService.php +++ b/lib/SP/Domain/Account/Services/PublicLinkService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,13 +22,11 @@ * along with sysPass. If not, see . */ -namespace SP\Services\PublicLink; +namespace SP\Domain\Account\Services; use Defuse\Crypto\Exception\CryptoException; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Config\Config; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Vault; use SP\Core\Exceptions\ConstraintException; @@ -37,22 +35,24 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\PublicLinkData; use SP\DataModel\PublicLinkListData; -use SP\Http\Request; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Account\PublicLinkServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\Config\ConfigInterface; +use SP\Http\RequestInterface; use SP\Http\Uri; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\PublicLink\PublicLinkRepository; -use SP\Services\Account\AccountService; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Account\Repositories\PublicLinkRepository; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; /** * Class PublicLinkService * - * @package SP\Services\PublicLink + * @package SP\Domain\Common\Services\PublicLink */ -final class PublicLinkService extends Service +final class PublicLinkService extends Service implements PublicLinkServiceInterface { use ServiceItemTrait; @@ -61,17 +61,30 @@ final class PublicLinkService extends Service */ public const TYPE_ACCOUNT = 1; - protected ?PublicLinkRepository $publicLinkRepository = null; - protected ?Request $request = null; + private PublicLinkRepository $publicLinkRepository; + private RequestInterface $request; + private AccountServiceInterface $accountService; + + public function __construct( + Application $application, + PublicLinkRepository $publicLinkRepository, + RequestInterface $request, + AccountServiceInterface $accountService + ) { + parent::__construct($application); + + $this->publicLinkRepository = $publicLinkRepository; + $this->request = $request; + $this->accountService = $accountService; + } + /** * Returns an HTTP URL for given hash */ public static function getLinkForHash(string $baseUrl, string $hash): string { - return (new Uri($baseUrl)) - ->addParam('r', 'account/viewLink/' . $hash) - ->getUri(); + return (new Uri($baseUrl))->addParam('r', 'account/viewLink/'.$hash)->getUri(); } /** @@ -82,12 +95,9 @@ final class PublicLinkService extends Service return hash('sha256', uniqid('sysPassPublicLink', true)); } - public static function getKeyForHash( - string $salt, - PublicLinkData $publicLinkData - ): string + public static function getKeyForHash(string $salt, PublicLinkData $publicLinkData): string { - return sha1($salt . $publicLinkData->getHash()); + return sha1($salt.$publicLinkData->getHash()); } /** @@ -99,30 +109,14 @@ final class PublicLinkService extends Service return $this->publicLinkRepository->search($itemSearchData); } - /** - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException - */ - public function getById(int $id): PublicLinkListData - { - $result = $this->publicLinkRepository->getById($id); - - if ($result->getNumRows() === 0) { - throw new NoSuchItemException(__u('Link not found')); - } - - return $result->getData(); - } - /** * @throws \Defuse\Crypto\Exception\CryptoException * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Repositories\NoSuchItemException - * @throws \SP\Services\ServiceException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException */ public function refresh(int $id): bool { @@ -144,6 +138,22 @@ final class PublicLinkService extends Service return $this->publicLinkRepository->refresh($publicLinkData); } + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id): PublicLinkListData + { + $result = $this->publicLinkRepository->getById($id); + + if ($result->getNumRows() === 0) { + throw new NoSuchItemException(__u('Link not found')); + } + + return $result->getData(); + } + /** * @throws EnvironmentIsBrokenException */ @@ -161,19 +171,17 @@ final class PublicLinkService extends Service * @throws \Defuse\Crypto\Exception\CryptoException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException - * @throws \SP\Services\ServiceException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException */ private function getSecuredLinkData(int $itemId, PublicLinkKey $key): string { // Obtener los datos de la cuenta - $accountData = $this->dic->get(AccountService::class)->getDataForLink($itemId); + $accountData = $this->accountService->getDataForLink($itemId); // Desencriptar la clave de la cuenta - $accountData->setPass(Crypt::decrypt( - $accountData->getPass(), - $accountData->getKey(), - $this->getMasterKeyFromContext()) + $accountData->setPass( + Crypt::decrypt($accountData->getPass(), $accountData->getKey(), $this->getMasterKeyFromContext()) ); $accountData->setKey(null); @@ -183,7 +191,7 @@ final class PublicLinkService extends Service /** * Devolver el tiempo de caducidad del enlace */ - public static function calcDateExpire(Config $config): int + public static function calcDateExpire(ConfigInterface $config): int { return time() + $config->getConfigData()->getPublinksMaxTime(); } @@ -191,15 +199,12 @@ final class PublicLinkService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function delete(int $id): PublicLinkService + public function delete(int $id): PublicLinkServiceInterface { if ($this->publicLinkRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Link not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Link not found'), SPException::INFO); } return $this; @@ -208,7 +213,7 @@ final class PublicLinkService extends Service /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @throws ConstraintException * @throws QueryException @@ -219,10 +224,7 @@ final class PublicLinkService extends Service $count = $this->publicLinkRepository->deleteByIdBatch($ids); if ($count !== count($ids)) { - throw new ServiceException( - __u('Error while removing the links'), - SPException::WARNING - ); + throw new ServiceException(__u('Error while removing the links'), SPException::WARNING); } return $count; @@ -231,8 +233,6 @@ final class PublicLinkService extends Service /** * @throws SPException * @throws CryptoException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface * @throws ConstraintException * @throws QueryException */ @@ -283,14 +283,14 @@ final class PublicLinkService extends Service /** * Actualizar la información de uso */ - public static function getUseInfo(string $hash, Request $request): array + public static function getUseInfo(string $hash, RequestInterface $request): array { return [ - 'who' => $request->getClientAddress(true), - 'time' => time(), - 'hash' => $hash, + 'who' => $request->getClientAddress(true), + 'time' => time(), + 'hash' => $hash, 'agent' => $request->getHeader('User-Agent'), - 'https' => $request->isHttps() + 'https' => $request->isHttps(), ]; } @@ -337,14 +337,4 @@ final class PublicLinkService extends Service { return $this->publicLinkRepository->update($itemData); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->publicLinkRepository = $this->dic->get(PublicLinkRepository::class); - $this->request = $this->dic->get(Request::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Upgrade/UpgradePublicLink.php b/lib/SP/Domain/Account/Services/UpgradePublicLinkService.php similarity index 59% rename from lib/SP/Services/Upgrade/UpgradePublicLink.php rename to lib/SP/Domain/Account/Services/UpgradePublicLinkService.php index 9c693e03..fdda88d7 100644 --- a/lib/SP/Services/Upgrade/UpgradePublicLink.php +++ b/lib/SP/Domain/Account/Services/UpgradePublicLinkService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,27 +22,41 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\Account\Services; use Exception; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\DataModel\PublickLinkOldData; use SP\DataModel\PublicLinkData; -use SP\Services\PublicLink\PublicLinkService; -use SP\Services\Service; -use SP\Storage\Database\Database; -use SP\Storage\Database\QueryData; +use SP\Domain\Account\PublicLinkServiceInterface; +use SP\Domain\Account\UpgradePublicLinkServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Infrastructure\Database\DatabaseInterface; +use SP\Infrastructure\Database\QueryData; use SP\Util\Util; /** * Class UpgradePublicLink * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ -final class UpgradePublicLink extends Service +final class UpgradePublicLinkService extends Service implements UpgradePublicLinkServiceInterface { - private ?Database $db = null; + protected PublicLinkServiceInterface $publicLinkService; + protected DatabaseInterface $database; + + public function __construct( + Application $application, + PublicLinkServiceInterface $publicLinkService, + DatabaseInterface $database + ) { + parent::__construct($application); + + $this->publicLinkService = $publicLinkService; + $this->database = $database; + } /** * upgrade_300_18010101 @@ -51,20 +65,21 @@ final class UpgradePublicLink extends Service { $this->eventDispatcher->notifyEvent( 'upgrade.publicLink.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('Public links update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Public links update')) + ->addDescription(__FUNCTION__) + ) ); try { $this->transactionAware( function () { - $publicLinkService = $this->dic->get(PublicLinkService::class); - $queryData = new QueryData(); $queryData->setQuery('SELECT id, `data` FROM PublicLink'); - foreach ($this->db->doSelect($queryData)->getDataAsArray() as $item) { + foreach ($this->database->doSelect($queryData)->getDataAsArray() as $item) { /** @var PublickLinkOldData $data */ $data = Util::unserialize( PublickLinkOldData::class, @@ -86,36 +101,35 @@ final class UpgradePublicLink extends Service $itemData->setUseInfo($data->getUseInfo()); $itemData->setData($data->getData()); - $publicLinkService->update($itemData); + $this->publicLinkService->update($itemData); $this->eventDispatcher->notifyEvent( 'upgrade.publicLink.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Link updated')) - ->addDetail(__u('Link'), $item->id)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Link updated')) + ->addDetail(__u('Link'), $item->id) + ) ); } - } + }, + $this->database ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); } $this->eventDispatcher->notifyEvent( 'upgrade.publicLink.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('Public links update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Public links update')) + ->addDescription(__FUNCTION__) + ) ); } - - protected function initialize(): void - { - $this->db = $this->dic->get(Database::class); - } } \ No newline at end of file diff --git a/lib/SP/Domain/Account/UpgradePublicLinkServiceInterface.php b/lib/SP/Domain/Account/UpgradePublicLinkServiceInterface.php new file mode 100644 index 00000000..14f06311 --- /dev/null +++ b/lib/SP/Domain/Account/UpgradePublicLinkServiceInterface.php @@ -0,0 +1,39 @@ +. + */ + +namespace SP\Domain\Account; + + +/** + * Class UpgradePublicLink + * + * @package SP\Domain\Upgrade\Services + */ +interface UpgradePublicLinkServiceInterface +{ + /** + * upgrade_300_18010101 + */ + public function upgrade_300_18010101(): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Api/ApiServiceInterface.php b/lib/SP/Domain/Api/ApiServiceInterface.php new file mode 100644 index 00000000..935ec764 --- /dev/null +++ b/lib/SP/Domain/Api/ApiServiceInterface.php @@ -0,0 +1,113 @@ +. + */ + +namespace SP\Domain\Api; + + +use Exception; +use SP\Core\Context\ContextException; +use SP\Core\Exceptions\InvalidClassException; +use SP\Core\Exceptions\SPException; +use SP\Domain\Api\Services\ApiRequest; +use SP\Domain\Common\Services\ServiceException; + +/** + * Class ApiService + * + * @package SP\Domain\Common\Services\ApiService + */ +interface ApiServiceInterface +{ + /** + * Sets up API + * + * @throws ServiceException + * @throws SPException + * @throws Exception + */ + public function setup(int $actionId): void; + + /** + * Devolver el valor de un parámetro + * + * @param string $param + * @param bool $required Si es requerido + * @param mixed $default Valor por defecto + * + * @return mixed + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function getParam(string $param, bool $required = false, $default = null); + + /** + * Devuelve la ayuda para una acción + * + * @param string $action + * + * @return array + */ + public function getHelp(string $action): array; + + /** + * @throws ServiceException + * @throws ContextException + */ + public function requireMasterPass(): void; + + /** + * @throws ServiceException + */ + public function getParamInt(string $param, bool $required = false, $default = null): ?int; + + /** + * @throws ServiceException + */ + public function getParamString(string $param, bool $required = false, $default = null): ?string; + + /** + * @throws ServiceException + */ + public function getParamArray(string $param, bool $required = false, $default = null): ?array; + + /** + * @throws ServiceException + */ + public function getParamRaw(string $param, bool $required = false, $default = null): ?string; + + /** + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function getMasterPass(): string; + + public function setApiRequest(ApiRequest $apiRequest): ApiServiceInterface; + + public function getRequestId(): int; + + public function isInitialized(): bool; + + /** + * @throws InvalidClassException + */ + public function setHelpClass(string $helpClass): void; +} \ No newline at end of file diff --git a/lib/SP/Services/Api/ApiRequest.php b/lib/SP/Domain/Api/Services/ApiRequest.php similarity index 86% rename from lib/SP/Services/Api/ApiRequest.php rename to lib/SP/Domain/Api/Services/ApiRequest.php index b1cc625c..8be4be3f 100644 --- a/lib/SP/Services/Api/ApiRequest.php +++ b/lib/SP/Domain/Api/Services/ApiRequest.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Api; +namespace SP\Domain\Api\Services; use JsonException; use SP\Core\Exceptions\SPException; @@ -30,18 +30,18 @@ use SP\Core\Exceptions\SPException; /** * Class ApiRequest * - * @package SP\Services\Api + * @package SP\Domain\Api\Services */ final class ApiRequest { - protected ?string $method = null; - protected ?int $id = null; - protected ?ApiRequestData $data = null; + protected ?string $method = null; + protected ?int $id = null; + protected ?ApiRequestData $data = null; /** * ApiRequest constructor. * - * @throws \SP\Services\Api\ApiRequestException + * @throws \SP\Domain\Api\Services\ApiRequestException */ public function __construct(?string $request = null) { @@ -57,10 +57,10 @@ final class ApiRequest * * Comprueba que el JSON esté bien formado * - * @param string $request + * @param string $request * * @return ApiRequest - * @throws \SP\Services\Api\ApiRequestException + * @throws \SP\Domain\Api\Services\ApiRequestException */ public function requestFromJsonData(string $request): ApiRequest { @@ -84,7 +84,8 @@ final class ApiRequest $data['jsonrpc'], $data['method'], $data['id'], - $data['params']['authToken']) + $data['params']['authToken'] + ) ) { throw new ApiRequestException( __u('Invalid format'), @@ -127,8 +128,8 @@ final class ApiRequest } /** - * @param string $key - * @param mixed $default + * @param string $key + * @param mixed $default * * @return mixed */ @@ -138,7 +139,7 @@ final class ApiRequest } /** - * @param string $key + * @param string $key * * @return bool */ diff --git a/lib/SP/Services/Api/ApiRequestData.php b/lib/SP/Domain/Api/Services/ApiRequestData.php similarity index 86% rename from lib/SP/Services/Api/ApiRequestData.php rename to lib/SP/Domain/Api/Services/ApiRequestData.php index 7c410797..2fa1f3d3 100644 --- a/lib/SP/Services/Api/ApiRequestData.php +++ b/lib/SP/Domain/Api/Services/ApiRequestData.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Api; +namespace SP\Domain\Api\Services; use SP\Core\DataCollection; @@ -30,7 +30,7 @@ use SP\Core\DataCollection; /** * Class ApiData * - * @package SP\Services\Api + * @package SP\Domain\Api\Services */ final class ApiRequestData extends DataCollection { diff --git a/lib/SP/Services/Api/ApiRequestException.php b/lib/SP/Domain/Api/Services/ApiRequestException.php similarity index 86% rename from lib/SP/Services/Api/ApiRequestException.php rename to lib/SP/Domain/Api/Services/ApiRequestException.php index ab0b432e..a98aee5f 100644 --- a/lib/SP/Services/Api/ApiRequestException.php +++ b/lib/SP/Domain/Api/Services/ApiRequestException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Api; +namespace SP\Domain\Api\Services; use SP\Core\Exceptions\SPException; /** * Class ApiRequestException * - * @package SP\Services\Api + * @package SP\Domain\Api\Services */ final class ApiRequestException extends SPException { diff --git a/lib/SP/Services/Api/ApiResponse.php b/lib/SP/Domain/Api/Services/ApiResponse.php similarity index 72% rename from lib/SP/Services/Api/ApiResponse.php rename to lib/SP/Domain/Api/Services/ApiResponse.php index 0fe74b43..36ca01bf 100644 --- a/lib/SP/Services/Api/ApiResponse.php +++ b/lib/SP/Domain/Api/Services/ApiResponse.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Api; +namespace SP\Domain\Api\Services; /** * Class ApiResponse @@ -32,18 +32,18 @@ namespace SP\Services\Api; final class ApiResponse { private const RESULT_SUCCESS = 0; - private const RESULT_ERROR = 1; + private const RESULT_ERROR = 1; - private $result; - private ?int $resultCode = null; - private int $itemId; + private $result; + private ?int $resultCode = null; + private int $itemId; private ?string $resultMessage = null; /** * ApiResponse constructor. * - * @param mixed $result - * @param null $itemId + * @param mixed $result + * @param null $itemId */ public function __construct($result, $itemId = null) { @@ -52,9 +52,9 @@ final class ApiResponse } /** - * @param mixed $result - * @param int|null $itemId - * @param string|null $message + * @param mixed $result + * @param int|null $itemId + * @param string|null $message * * @return ApiResponse */ @@ -62,8 +62,7 @@ final class ApiResponse $result, ?int $itemId = null, string $message = null - ): ApiResponse - { + ): ApiResponse { $out = new self($result, $itemId); $out->resultCode = self::RESULT_SUCCESS; $out->resultMessage = $message; @@ -72,16 +71,15 @@ final class ApiResponse } /** - * @param mixed $result - * @param string|null $message + * @param mixed $result + * @param string|null $message * * @return ApiResponse */ public static function makeError( $result, ?string $message = null - ): ApiResponse - { + ): ApiResponse { $out = new self($result); $out->resultCode = self::RESULT_ERROR; $out->resultMessage = $message; @@ -95,11 +93,11 @@ final class ApiResponse public function getResponse(): array { return [ - 'itemId' => $this->itemId, - 'result' => $this->result, - 'resultCode' => $this->resultCode, + 'itemId' => $this->itemId, + 'result' => $this->result, + 'resultCode' => $this->resultCode, 'resultMessage' => $this->resultMessage, - 'count' => is_array($this->result) ? count($this->result) : null + 'count' => is_array($this->result) ? count($this->result) : null, ]; } } \ No newline at end of file diff --git a/lib/SP/Services/Api/ApiService.php b/lib/SP/Domain/Api/Services/ApiService.php similarity index 65% rename from lib/SP/Services/Api/ApiService.php rename to lib/SP/Domain/Api/Services/ApiService.php index 4fbebd0d..d81ebabe 100644 --- a/lib/SP/Services/Api/ApiService.php +++ b/lib/SP/Domain/Api/Services/ApiService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,53 +22,77 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Api; +namespace SP\Domain\Api\Services; use Defuse\Crypto\Exception\CryptoException; use Exception; +use SP\Core\Application; use SP\Core\Context\ContextException; use SP\Core\Crypt\Hash; use SP\Core\Crypt\Vault; -use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\InvalidClassException; use SP\Core\Exceptions\SPException; use SP\DataModel\AuthTokenData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Track\TrackRequest; -use SP\Services\AuthToken\AuthTokenService; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\Track\TrackService; -use SP\Services\User\UserService; -use SP\Services\UserProfile\UserProfileService; +use SP\Domain\Api\ApiServiceInterface; +use SP\Domain\Auth\AuthTokenServiceInterface; +use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Security\Services\TrackService; +use SP\Domain\Security\TrackServiceInterface; +use SP\Domain\User\Services\UserService; +use SP\Domain\User\UserProfileServiceInterface; +use SP\Domain\User\UserServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Security\Repositories\TrackRequest; use SP\Util\Filter; /** * Class ApiService * - * @package SP\Services\ApiService + * @package SP\Domain\Common\Services\ApiService */ -final class ApiService extends Service +final class ApiService extends Service implements ApiServiceInterface { - private ?AuthTokenService $authTokenService = null; - private ?TrackService $trackService = null; - private ?ApiRequest $apiRequest = null; - private ?TrackRequest $trackRequest = null; - private ?AuthTokenData $authTokenData = null; - private ?string $helpClass = null; - private $initialized = false; + private AuthTokenService $authTokenService; + private TrackService $trackService; + private UserServiceInterface $userService; + private UserProfileServiceInterface $userProfileService; + private ApiRequest $apiRequest; + private TrackRequest $trackRequest; + private ?AuthTokenData $authTokenData = null; + private ?string $helpClass = null; + private $initialized = false; + + public function __construct( + Application $application, + ApiRequest $apiRequest, + TrackServiceInterface $trackService, + AuthTokenServiceInterface $authTokenService, + UserServiceInterface $userService, + UserProfileServiceInterface $userProfileService + ) { + parent::__construct($application); + + $this->apiRequest = $apiRequest; + $this->trackService = $trackService; + $this->authTokenService = $authTokenService; + $this->userService = $userService; + $this->userProfileService = $userProfileService; + + $this->trackRequest = $this->trackService->getTrackRequest(__CLASS__); + } /** * Sets up API * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws SPException * @throws Exception */ public function setup(int $actionId): void { $this->initialized = false; - $this->apiRequest = $this->dic->get(ApiRequest::class); if ($this->trackService->checkTracking($this->trackRequest)) { $this->addTracking(); @@ -83,10 +107,7 @@ final class ApiService extends Service try { $this->authTokenData = $this->authTokenService - ->getTokenByToken( - $actionId, - $this->getParam('authToken') - ); + ->getTokenByToken($actionId, $this->getParam('authToken')); } catch (NoSuchItemException $e) { logger($e->getMessage(), 'ERROR'); @@ -115,7 +136,7 @@ final class ApiService extends Service /** * Añadir un seguimiento * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function addTracking(): void { @@ -134,21 +155,16 @@ final class ApiService extends Service /** * Devolver el valor de un parámetro * - * @param string $param - * @param bool $required Si es requerido - * @param mixed $default Valor por defecto + * @param string $param + * @param bool $required Si es requerido + * @param mixed $default Valor por defecto * * @return mixed * @throws ServiceException */ - public function getParam( - string $param, - bool $required = false, - $default = null - ) + public function getParam(string $param, bool $required = false, $default = null) { - if ($this->apiRequest === null - || ($required && !$this->apiRequest->exists($param))) { + if ($required && !$this->apiRequest->exists($param)) { throw new ServiceException( __u('Wrong parameters'), SPException::ERROR, @@ -163,7 +179,7 @@ final class ApiService extends Service /** * Devuelve la ayuda para una acción * - * @param string $action + * @param string $action * * @return array */ @@ -177,7 +193,7 @@ final class ApiService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function accessDenied(): void { @@ -199,32 +215,29 @@ final class ApiService extends Service private function setupUser(): void { $userLoginResponse = UserService::mapUserLoginResponse( - $this->dic->get(UserService::class) - ->getById($this->authTokenData->getUserId()) + $this->userService->getById($this->authTokenData->getUserId()) ); $userLoginResponse->getIsDisabled() && $this->accessDenied(); $this->context->setUserData($userLoginResponse); - $this->context->setUserProfile($this->dic->get(UserProfileService::class) - ->getById($userLoginResponse->getUserProfileId())->getProfile()); + $this->context->setUserProfile( + $this->userProfileService->getById($userLoginResponse->getUserProfileId())->getProfile() + ); } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ContextException */ public function requireMasterPass(): void { - $this->context->setTrasientKey( - '_masterpass', - $this->getMasterPassFromVault() - ); + $this->context->setTrasientKey('_masterpass', $this->getMasterPassFromVault()); } /** * Devolver la clave maestra * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function getMasterPassFromVault(): string { @@ -236,7 +249,7 @@ final class ApiService extends Service /** @var Vault $vault */ $vault = unserialize($this->authTokenData->getVault()); - if ($vault && ($pass = $vault->getData($tokenPass . $this->getParam('authToken')))) { + if ($vault && ($pass = $vault->getData($tokenPass.$this->getParam('authToken')))) { return $pass; } @@ -257,13 +270,9 @@ final class ApiService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ - public function getParamInt( - string $param, - bool $required = false, - $default = null - ): ?int + public function getParamInt(string $param, bool $required = false, $default = null): ?int { $value = $this->getParam($param, $required, $default); @@ -277,11 +286,7 @@ final class ApiService extends Service /** * @throws ServiceException */ - public function getParamString( - string $param, - bool $required = false, - $default = null - ): ?string + public function getParamString(string $param, bool $required = false, $default = null): ?string { $value = $this->getParam($param, $required, $default); @@ -293,13 +298,9 @@ final class ApiService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ - public function getParamArray( - string $param, - bool $required = false, - $default = null - ): ?array + public function getParamArray(string $param, bool $required = false, $default = null): ?array { $value = $this->getParam($param, $required, $default); @@ -313,11 +314,7 @@ final class ApiService extends Service /** * @throws ServiceException */ - public function getParamRaw( - string $param, - bool $required = false, - $default = null - ): ?string + public function getParamRaw(string $param, bool $required = false, $default = null): ?string { $value = $this->getParam($param, $required, $default); @@ -329,14 +326,14 @@ final class ApiService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function getMasterPass(): string { return $this->getMasterKeyFromContext(); } - public function setApiRequest(ApiRequest $apiRequest): ApiService + public function setApiRequest(ApiRequest $apiRequest): ApiServiceInterface { $this->apiRequest = $apiRequest; @@ -360,19 +357,10 @@ final class ApiService extends Service { if (class_exists($helpClass)) { $this->helpClass = $helpClass; + return; } throw new InvalidClassException('Invalid class for helper'); } - - /** - * @throws InvalidArgumentException - */ - protected function initialize(): void - { - $this->authTokenService = $this->dic->get(AuthTokenService::class); - $this->trackService = $this->dic->get(TrackService::class); - $this->trackRequest = $this->trackService->getTrackRequest(__CLASS__); - } } \ No newline at end of file diff --git a/lib/SP/Services/Api/JsonRpcResponse.php b/lib/SP/Domain/Api/Services/JsonRpcResponse.php similarity index 67% rename from lib/SP/Services/Api/JsonRpcResponse.php rename to lib/SP/Domain/Api/Services/JsonRpcResponse.php index d369bb12..3d7674af 100644 --- a/lib/SP/Services/Api/JsonRpcResponse.php +++ b/lib/SP/Domain/Api/Services/JsonRpcResponse.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Api; +namespace SP\Domain\Api\Services; use Exception; use SP\Core\Exceptions\SPException; @@ -35,29 +35,28 @@ use SP\Http\Json; */ final class JsonRpcResponse { - public const PARSE_ERROR = -32700; - public const INVALID_REQUEST = -32600; + public const PARSE_ERROR = -32700; + public const INVALID_REQUEST = -32600; public const METHOD_NOT_FOUND = -32601; - public const INVALID_PARAMS = -32602; - public const INTERNAL_ERROR = -32603; - public const SERVER_ERROR = -32000; + public const INVALID_PARAMS = -32602; + public const INTERNAL_ERROR = -32603; + public const SERVER_ERROR = -32000; /** - * @param ApiResponse $apiResponse - * @param int $id + * @param ApiResponse $apiResponse + * @param int $id * * @return string * @throws SPException */ public static function getResponse( ApiResponse $apiResponse, - int $id - ): string - { + int $id + ): string { return Json::getJson([ 'jsonrpc' => '2.0', - 'result' => $apiResponse->getResponse(), - 'id' => $id + 'result' => $apiResponse->getResponse(), + 'id' => $id, ], JSON_UNESCAPED_SLASHES); } @@ -69,28 +68,27 @@ final class JsonRpcResponse } /** - * @param string $message - * @param int $code - * @param int $id - * @param mixed|null $data + * @param string $message + * @param int $code + * @param int $id + * @param mixed|null $data * * @return string */ public static function getResponseError( string $message, - int $code, - int $id, - $data = null - ): string - { + int $code, + int $id, + $data = null + ): string { return json_encode([ 'jsonrpc' => '2.0', - 'error' => [ + 'error' => [ 'message' => __($message), - 'code' => $code, - 'data' => $data + 'code' => $code, + 'data' => $data, ], - 'id' => $id + 'id' => $id, ], JSON_PARTIAL_OUTPUT_ON_ERROR); } } \ No newline at end of file diff --git a/lib/SP/Domain/Auth/AuthTokenServiceInterface.php b/lib/SP/Domain/Auth/AuthTokenServiceInterface.php new file mode 100644 index 00000000..41062d4c --- /dev/null +++ b/lib/SP/Domain/Auth/AuthTokenServiceInterface.php @@ -0,0 +1,123 @@ +. + */ + +namespace SP\Domain\Auth; + + +use Defuse\Crypto\Exception\CryptoException; +use Defuse\Crypto\Exception\EnvironmentIsBrokenException; +use Exception; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\AuthTokenData; +use SP\DataModel\ItemSearchData; +use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AuthTokenService + * + * @package SP\Domain\Common\Services\AuthToken + */ +interface AuthTokenServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getById(int $id): AuthTokenData; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): AuthTokenService; + + /** + * Deletes all the items for given ids + * + * @throws ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * @throws SPException + * @throws CryptoException + * @throws EnvironmentIsBrokenException + * @throws ConstraintException + * @throws QueryException + */ + public function create(AuthTokenData $itemData): int; + + /** + * @throws Exception + */ + public function refreshAndUpdate(AuthTokenData $itemData): void; + + /** + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\DuplicatedItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function update(AuthTokenData $itemData, ?string $token = null): void; + + /** + * @throws SPException + * @throws ConstraintException + * @throws QueryException + */ + public function updateRaw(AuthTokenData $itemData): void; + + /** + * Devolver los datos de un token + * + * @throws ConstraintException + * @throws NoSuchItemException + * @throws QueryException + */ + public function getTokenByToken(int $actionId, string $token); + + /** + * @return AuthTokenData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/Auth/LdapCheckServiceInterface.php b/lib/SP/Domain/Auth/LdapCheckServiceInterface.php new file mode 100644 index 00000000..893bc7dd --- /dev/null +++ b/lib/SP/Domain/Auth/LdapCheckServiceInterface.php @@ -0,0 +1,64 @@ +. + */ + +namespace SP\Domain\Auth; + + +use SP\Providers\Auth\Ldap\LdapException; +use SP\Providers\Auth\Ldap\LdapParams; + +/** + * Class LdapCheckService + * + * @package SP\Domain\Import\Services + */ +interface LdapCheckServiceInterface +{ + /** + * @param LdapParams $ldapParams + * + * @throws LdapException + */ + public function checkConnection(LdapParams $ldapParams): void; + + /** + * @throws \SP\Providers\Auth\Ldap\LdapException + */ + public function getObjects(bool $includeGroups = true): array; + + /** + * Obtener los datos de una búsqueda de LDAP de un atributo + * + * @param array $data + * @param string[] $attributes + * + * @return array + */ + public function ldapResultsMapper(array $data, array $attributes = ['dn']): array; + + /** + * @throws \SP\Providers\Auth\Ldap\LdapException + */ + public function getObjectsByFilter(string $filter): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/Auth/LoginServiceInterface.php b/lib/SP/Domain/Auth/LoginServiceInterface.php new file mode 100644 index 00000000..94dd7058 --- /dev/null +++ b/lib/SP/Domain/Auth/LoginServiceInterface.php @@ -0,0 +1,64 @@ +. + */ + +namespace SP\Domain\Auth; + + +use Defuse\Crypto\Exception\EnvironmentIsBrokenException; +use Exception; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\Domain\Auth\Services\AuthException; +use SP\Domain\Auth\Services\LoginResponse; + +/** + * Class LoginService + * + * @package SP\Domain\Common\Services + */ +interface LoginServiceInterface +{ + /** + * Ejecutar las acciones de login + * + * @return LoginResponse + * @throws AuthException + * @throws SPException + * @throws EnvironmentIsBrokenException + * @throws ConstraintException + * @throws QueryException + * @throws Exception + * @uses LoginService::authBrowser() + * @uses LoginService::authDatabase() + * @uses LoginService::authLdap() + * + */ + public function doLogin(): LoginResponse; + + /** + * @param string|null $from + */ + public function setFrom(?string $from): void; +} \ No newline at end of file diff --git a/lib/SP/Services/Auth/AuthException.php b/lib/SP/Domain/Auth/Services/AuthException.php similarity index 86% rename from lib/SP/Services/Auth/AuthException.php rename to lib/SP/Domain/Auth/Services/AuthException.php index 7c123d77..c0f6efdb 100644 --- a/lib/SP/Services/Auth/AuthException.php +++ b/lib/SP/Domain/Auth/Services/AuthException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Auth; +namespace SP\Domain\Auth\Services; use SP\Core\Exceptions\SPException; /** * Class AuthException * - * @package SP\Services\Auth + * @package SP\Domain\Auth\Services */ final class AuthException extends SPException { diff --git a/lib/SP/Services/AuthToken/AuthTokenService.php b/lib/SP/Domain/Auth/Services/AuthTokenService.php similarity index 67% rename from lib/SP/Services/AuthToken/AuthTokenService.php rename to lib/SP/Domain/Auth/Services/AuthTokenService.php index a64b5033..c75a652b 100644 --- a/lib/SP/Services/AuthToken/AuthTokenService.php +++ b/lib/SP/Domain/Auth/Services/AuthTokenService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,15 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\AuthToken; +namespace SP\Domain\Auth\Services; use Defuse\Crypto\Exception\CryptoException; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; use SP\Core\Acl\Acl; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Crypt\Hash; use SP\Core\Crypt\Vault; use SP\Core\Exceptions\ConstraintException; @@ -38,27 +37,28 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\AuthTokenData; use SP\DataModel\ItemSearchData; -use SP\Repositories\AuthToken\AuthTokenRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Auth\AuthTokenServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Infrastructure\Auth\Repositories\AuthTokenRepository; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; use SP\Util\PasswordUtil; /** * Class AuthTokenService * - * @package SP\Services\AuthToken + * @package SP\Domain\Common\Services\AuthToken */ -final class AuthTokenService extends Service +final class AuthTokenService extends Service implements AuthTokenServiceInterface { use ServiceItemTrait; private const SECURED_ACTIONS = [ ActionsInterface::ACCOUNT_VIEW_PASS, ActionsInterface::ACCOUNT_EDIT_PASS, - ActionsInterface::ACCOUNT_CREATE + ActionsInterface::ACCOUNT_CREATE, ]; private const CAN_USE_SECURE_TOKEN_ACTIONS = [ @@ -67,7 +67,15 @@ final class AuthTokenService extends Service ActionsInterface::CLIENT_VIEW, ]; - protected ?AuthTokenRepository $authTokenRepository = null; + private AuthTokenRepository $authTokenRepository; + + public function __construct(Application $application, AuthTokenRepository $authTokenRepository) + { + parent::__construct($application); + + $this->authTokenRepository = $authTokenRepository; + } + /** * Devuelver un array de acciones posibles para los tokens @@ -77,35 +85,35 @@ final class AuthTokenService extends Service public static function getTokenActions(): array { return [ - ActionsInterface::ACCOUNT_SEARCH => Acl::getActionInfo(ActionsInterface::ACCOUNT_SEARCH), - ActionsInterface::ACCOUNT_VIEW => Acl::getActionInfo(ActionsInterface::ACCOUNT_VIEW), + ActionsInterface::ACCOUNT_SEARCH => Acl::getActionInfo(ActionsInterface::ACCOUNT_SEARCH), + ActionsInterface::ACCOUNT_VIEW => Acl::getActionInfo(ActionsInterface::ACCOUNT_VIEW), ActionsInterface::ACCOUNT_VIEW_PASS => Acl::getActionInfo(ActionsInterface::ACCOUNT_VIEW_PASS), ActionsInterface::ACCOUNT_EDIT_PASS => Acl::getActionInfo(ActionsInterface::ACCOUNT_EDIT_PASS), - ActionsInterface::ACCOUNT_DELETE => Acl::getActionInfo(ActionsInterface::ACCOUNT_DELETE), - ActionsInterface::ACCOUNT_CREATE => Acl::getActionInfo(ActionsInterface::ACCOUNT_CREATE), - ActionsInterface::ACCOUNT_EDIT => Acl::getActionInfo(ActionsInterface::ACCOUNT_EDIT), - ActionsInterface::CATEGORY_SEARCH => Acl::getActionInfo(ActionsInterface::CATEGORY_SEARCH), - ActionsInterface::CATEGORY_VIEW => Acl::getActionInfo(ActionsInterface::CATEGORY_VIEW), - ActionsInterface::CATEGORY_CREATE => Acl::getActionInfo(ActionsInterface::CATEGORY_CREATE), - ActionsInterface::CATEGORY_EDIT => Acl::getActionInfo(ActionsInterface::CATEGORY_EDIT), - ActionsInterface::CATEGORY_DELETE => Acl::getActionInfo(ActionsInterface::CATEGORY_DELETE), - ActionsInterface::CLIENT_SEARCH => Acl::getActionInfo(ActionsInterface::CLIENT_SEARCH), - ActionsInterface::CLIENT_VIEW => Acl::getActionInfo(ActionsInterface::CLIENT_VIEW), - ActionsInterface::CLIENT_CREATE => Acl::getActionInfo(ActionsInterface::CLIENT_CREATE), - ActionsInterface::CLIENT_EDIT => Acl::getActionInfo(ActionsInterface::CLIENT_EDIT), - ActionsInterface::CLIENT_DELETE => Acl::getActionInfo(ActionsInterface::CLIENT_DELETE), - ActionsInterface::TAG_SEARCH => Acl::getActionInfo(ActionsInterface::TAG_SEARCH), - ActionsInterface::TAG_VIEW => Acl::getActionInfo(ActionsInterface::TAG_VIEW), - ActionsInterface::TAG_CREATE => Acl::getActionInfo(ActionsInterface::TAG_CREATE), - ActionsInterface::TAG_EDIT => Acl::getActionInfo(ActionsInterface::TAG_EDIT), - ActionsInterface::TAG_DELETE => Acl::getActionInfo(ActionsInterface::TAG_DELETE), - ActionsInterface::GROUP_VIEW => Acl::getActionInfo(ActionsInterface::GROUP_VIEW), - ActionsInterface::GROUP_CREATE => Acl::getActionInfo(ActionsInterface::GROUP_CREATE), - ActionsInterface::GROUP_EDIT => Acl::getActionInfo(ActionsInterface::GROUP_EDIT), - ActionsInterface::GROUP_DELETE => Acl::getActionInfo(ActionsInterface::GROUP_DELETE), - ActionsInterface::GROUP_SEARCH => Acl::getActionInfo(ActionsInterface::GROUP_SEARCH), + ActionsInterface::ACCOUNT_DELETE => Acl::getActionInfo(ActionsInterface::ACCOUNT_DELETE), + ActionsInterface::ACCOUNT_CREATE => Acl::getActionInfo(ActionsInterface::ACCOUNT_CREATE), + ActionsInterface::ACCOUNT_EDIT => Acl::getActionInfo(ActionsInterface::ACCOUNT_EDIT), + ActionsInterface::CATEGORY_SEARCH => Acl::getActionInfo(ActionsInterface::CATEGORY_SEARCH), + ActionsInterface::CATEGORY_VIEW => Acl::getActionInfo(ActionsInterface::CATEGORY_VIEW), + ActionsInterface::CATEGORY_CREATE => Acl::getActionInfo(ActionsInterface::CATEGORY_CREATE), + ActionsInterface::CATEGORY_EDIT => Acl::getActionInfo(ActionsInterface::CATEGORY_EDIT), + ActionsInterface::CATEGORY_DELETE => Acl::getActionInfo(ActionsInterface::CATEGORY_DELETE), + ActionsInterface::CLIENT_SEARCH => Acl::getActionInfo(ActionsInterface::CLIENT_SEARCH), + ActionsInterface::CLIENT_VIEW => Acl::getActionInfo(ActionsInterface::CLIENT_VIEW), + ActionsInterface::CLIENT_CREATE => Acl::getActionInfo(ActionsInterface::CLIENT_CREATE), + ActionsInterface::CLIENT_EDIT => Acl::getActionInfo(ActionsInterface::CLIENT_EDIT), + ActionsInterface::CLIENT_DELETE => Acl::getActionInfo(ActionsInterface::CLIENT_DELETE), + ActionsInterface::TAG_SEARCH => Acl::getActionInfo(ActionsInterface::TAG_SEARCH), + ActionsInterface::TAG_VIEW => Acl::getActionInfo(ActionsInterface::TAG_VIEW), + ActionsInterface::TAG_CREATE => Acl::getActionInfo(ActionsInterface::TAG_CREATE), + ActionsInterface::TAG_EDIT => Acl::getActionInfo(ActionsInterface::TAG_EDIT), + ActionsInterface::TAG_DELETE => Acl::getActionInfo(ActionsInterface::TAG_DELETE), + ActionsInterface::GROUP_VIEW => Acl::getActionInfo(ActionsInterface::GROUP_VIEW), + ActionsInterface::GROUP_CREATE => Acl::getActionInfo(ActionsInterface::GROUP_CREATE), + ActionsInterface::GROUP_EDIT => Acl::getActionInfo(ActionsInterface::GROUP_EDIT), + ActionsInterface::GROUP_DELETE => Acl::getActionInfo(ActionsInterface::GROUP_DELETE), + ActionsInterface::GROUP_SEARCH => Acl::getActionInfo(ActionsInterface::GROUP_SEARCH), ActionsInterface::CONFIG_BACKUP_RUN => Acl::getActionInfo(ActionsInterface::CONFIG_BACKUP_RUN), - ActionsInterface::CONFIG_EXPORT_RUN => Acl::getActionInfo(ActionsInterface::CONFIG_EXPORT_RUN) + ActionsInterface::CONFIG_EXPORT_RUN => Acl::getActionInfo(ActionsInterface::CONFIG_EXPORT_RUN), ]; } @@ -130,7 +138,7 @@ final class AuthTokenService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function delete(int $id): AuthTokenService { @@ -183,10 +191,7 @@ final class AuthTokenService extends Service * @throws ConstraintException * @throws QueryException */ - private function injectSecureData( - AuthTokenData $authTokenData, - ?string $token = null - ): AuthTokenData + private function injectSecureData(AuthTokenData $authTokenData, ?string $token = null): AuthTokenData { if ($token === null) { $token = $this->authTokenRepository @@ -240,7 +245,7 @@ final class AuthTokenService extends Service { return (new Vault())->saveData( $this->getMasterKeyFromContext(), - $key . $token + $key.$token ); } @@ -276,9 +281,9 @@ final class AuthTokenService extends Service * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\DuplicatedItemException - * @throws \SP\Repositories\NoSuchItemException - * @throws \SP\Services\ServiceException + * @throws \SP\Infrastructure\Common\Repositories\DuplicatedItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException */ public function update(AuthTokenData $itemData, ?string $token = null): void { @@ -326,13 +331,4 @@ final class AuthTokenService extends Service { return $this->authTokenRepository->getAll()->getDataAsArray(); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->authTokenRepository = $this->dic->get(AuthTokenRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Ldap/LdapCheckService.php b/lib/SP/Domain/Auth/Services/LdapCheckService.php similarity index 77% rename from lib/SP/Services/Ldap/LdapCheckService.php rename to lib/SP/Domain/Auth/Services/LdapCheckService.php index ff8439e3..be71a6c5 100644 --- a/lib/SP/Services/Ldap/LdapCheckService.php +++ b/lib/SP/Domain/Auth/Services/LdapCheckService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,25 +22,26 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Ldap; +namespace SP\Domain\Auth\Services; +use SP\Domain\Auth\LdapCheckServiceInterface; +use SP\Domain\Common\Services\Service; use SP\Providers\Auth\Ldap\Ldap; use SP\Providers\Auth\Ldap\LdapException; use SP\Providers\Auth\Ldap\LdapInterface; use SP\Providers\Auth\Ldap\LdapParams; -use SP\Services\Service; /** * Class LdapCheckService * - * @package SP\Services\Ldap + * @package SP\Domain\Import\Services */ -final class LdapCheckService extends Service +final class LdapCheckService extends Service implements LdapCheckServiceInterface { protected ?LdapInterface $ldap = null; /** - * @param LdapParams $ldapParams + * @param LdapParams $ldapParams * * @throws LdapException */ @@ -56,66 +57,35 @@ final class LdapCheckService extends Service /** * @throws \SP\Providers\Auth\Ldap\LdapException */ - public function getObjects(bool $includeGroups = true): array + public function getObjectsByFilter(string $filter): array { - $ldapActions = $this->ldap->getLdapActions(); - - $data = ['count' => 0, 'results' => []]; - - $indirectFilterItems = $this->ldapResultsMapper( - $ldapActions->getObjects( - $this->ldap->getGroupMembershipIndirectFilter(), ['dn']) + $objects = $this->ldapResultsMapper( + $this->ldap->getLdapActions()->getObjects($filter, ['dn']) ); - $directFilterItems = $this->ldapResultsMapper( - $ldapActions->getObjects( - $this->ldap->getGroupMembershipDirectFilter(), - ['member', 'memberUid', 'uniqueMember']), - ['member', 'memberUid', 'uniqueMember'] - ); - - $userItems = array_unique(array_merge($indirectFilterItems, $directFilterItems)); - - $data['results'][] = [ - 'icon' => 'person', - 'items' => array_values($userItems) + return [ + 'count' => count($objects), + 'results' => [ + [ + 'icon' => '', + 'items' => $objects, + ], + ], ]; - - if ($includeGroups) { - $groupItems = $this->ldapResultsMapper( - $ldapActions->getObjects( - $this->ldap->getGroupObjectFilter(), ['dn']) - ); - - $data['results'][] = [ - 'icon' => 'group', - 'items' => $groupItems - ]; - } - - array_walk( - $data['results'], - static function ($value) use (&$data) { - $data['count'] += count($value['items']); - } - ); - - return $data; } /** * Obtener los datos de una búsqueda de LDAP de un atributo * - * @param array $data - * @param string[] $attributes + * @param array $data + * @param string[] $attributes * * @return array */ public function ldapResultsMapper( array $data, array $attributes = ['dn'] - ): array - { + ): array { $out = []; foreach ($data as $result) { @@ -140,20 +110,49 @@ final class LdapCheckService extends Service /** * @throws \SP\Providers\Auth\Ldap\LdapException */ - public function getObjectsByFilter(string $filter): array + public function getObjects(bool $includeGroups = true): array { - $objects = $this->ldapResultsMapper( - $this->ldap->getLdapActions()->getObjects($filter, ['dn']) + $ldapActions = $this->ldap->getLdapActions(); + + $data = ['count' => 0, 'results' => []]; + + $indirectFilterItems = $this->ldapResultsMapper( + $ldapActions->getObjects($this->ldap->getGroupMembershipIndirectFilter(), ['dn']) ); - return [ - 'count' => count($objects), - 'results' => [ - [ - 'icon' => '', - 'items' => $objects - ] - ] + $directFilterItems = $this->ldapResultsMapper( + $ldapActions->getObjects( + $this->ldap->getGroupMembershipDirectFilter(), + ['member', 'memberUid', 'uniqueMember'] + ), + ['member', 'memberUid', 'uniqueMember'] + ); + + $userItems = array_unique(array_merge($indirectFilterItems, $directFilterItems)); + + $data['results'][] = [ + 'icon' => 'person', + 'items' => array_values($userItems), ]; + + if ($includeGroups) { + $groupItems = $this->ldapResultsMapper( + $ldapActions->getObjects($this->ldap->getGroupObjectFilter(), ['dn']) + ); + + $data['results'][] = [ + 'icon' => 'group', + 'items' => $groupItems, + ]; + } + + array_walk( + $data['results'], + static function ($value) use (&$data) { + $data['count'] += count($value['items']); + } + ); + + return $data; } } \ No newline at end of file diff --git a/lib/SP/Services/Auth/LoginResponse.php b/lib/SP/Domain/Auth/Services/LoginResponse.php similarity index 84% rename from lib/SP/Services/Auth/LoginResponse.php rename to lib/SP/Domain/Auth/Services/LoginResponse.php index 42611ac2..ad2e7000 100644 --- a/lib/SP/Services/Auth/LoginResponse.php +++ b/lib/SP/Domain/Auth/Services/LoginResponse.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,23 +22,23 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Auth; +namespace SP\Domain\Auth\Services; /** * Class LoginResponse * - * @package SP\Services\Auth + * @package SP\Domain\Auth\Services */ final class LoginResponse { - private int $status; + private int $status; private ?string $redirect; /** * LoginResponse constructor. * - * @param int $status - * @param string|null $redirect + * @param int $status + * @param string|null $redirect */ public function __construct(int $status, ?string $redirect = null) { diff --git a/lib/SP/Services/Auth/LoginService.php b/lib/SP/Domain/Auth/Services/LoginService.php similarity index 68% rename from lib/SP/Services/Auth/LoginService.php rename to lib/SP/Domain/Auth/Services/LoginService.php index bf1e42cb..0ad4e1d2 100644 --- a/lib/SP/Services/Auth/LoginService.php +++ b/lib/SP/Domain/Auth/Services/LoginService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,55 +22,53 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Auth; +namespace SP\Domain\Auth\Services; defined('APP_ROOT') || die(); use Defuse\Crypto\Exception\CryptoException; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Config\ConfigDataInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; -use SP\Core\Language; +use SP\Core\LanguageInterface; use SP\Core\UI\ThemeInterface; use SP\DataModel\UserLoginData; use SP\DataModel\UserPreferencesData; -use SP\Http\Request; +use SP\Domain\Auth\LoginServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Crypt\TemporaryMasterPassServiceInterface; +use SP\Domain\Security\TrackServiceInterface; +use SP\Domain\User\Services\UserLoginRequest; +use SP\Domain\User\Services\UserPassService; +use SP\Domain\User\UserPassRecoverServiceInterface; +use SP\Domain\User\UserPassServiceInterface; +use SP\Domain\User\UserProfileServiceInterface; +use SP\Domain\User\UserServiceInterface; +use SP\Http\RequestInterface; use SP\Http\Uri; -use SP\Providers\Auth\AuthProvider; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Security\Repositories\TrackRequest; +use SP\Providers\Auth\AuthProviderInterface; use SP\Providers\Auth\Browser\BrowserAuthData; use SP\Providers\Auth\Database\DatabaseAuthData; -use SP\Providers\Auth\Ldap\LdapAuth; use SP\Providers\Auth\Ldap\LdapAuthData; +use SP\Providers\Auth\Ldap\LdapAuthInterface; use SP\Providers\Auth\Ldap\LdapCode; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Track\TrackRequest; -use SP\Services\Crypt\TemporaryMasterPassService; -use SP\Services\Service; -use SP\Services\Track\TrackService; -use SP\Services\User\UserLoginRequest; -use SP\Services\User\UserPassService; -use SP\Services\User\UserService; -use SP\Services\UserPassRecover\UserPassRecoverService; -use SP\Services\UserProfile\UserProfileService; use SP\Util\PasswordUtil; /** * Class LoginService * - * @package SP\Services + * @package SP\Domain\Common\Services */ -final class LoginService extends Service +final class LoginService extends Service implements LoginServiceInterface { - /** - * Estados - */ private const STATUS_INVALID_LOGIN = 1; private const STATUS_INVALID_MASTER_PASS = 2; private const STATUS_USER_DISABLED = 3; @@ -80,16 +78,55 @@ final class LoginService extends Service private const STATUS_PASS = 0; private const STATUS_NONE = 100; - private ?AuthProvider $authProvider = null; - private ?UserLoginData $userLoginData = null; - private ?ConfigDataInterface $configData = null; - private ?ThemeInterface $theme = null; - private ?UserService $userService = null; - private ?Language $language = null; - private ?TrackService $trackService = null; - private ?TrackRequest $trackRequest = null; - private ?string $from = null; - private ?Request $request = null; + private AuthProviderInterface $authProvider; + private UserLoginData $userLoginData; + private ConfigDataInterface $configData; + private ThemeInterface $theme; + private UserServiceInterface $userService; + private LanguageInterface $language; + private TrackServiceInterface $trackService; + private TrackRequest $trackRequest; + private RequestInterface $request; + private ?string $from = null; + private UserPassRecoverServiceInterface $userPassRecoverService; + private TemporaryMasterPassServiceInterface $temporaryMasterPassService; + private UserPassServiceInterface $userPassService; + private UserProfileServiceInterface $userProfileService; + + /** + * @throws \SP\Core\Exceptions\InvalidArgumentException + * @throws \SP\Domain\Auth\Services\AuthException + */ + public function __construct( + Application $application, + AuthProviderInterface $authProvider, + ThemeInterface $theme, + LanguageInterface $language, + TrackServiceInterface $trackService, + RequestInterface $request, + UserServiceInterface $userService, + UserPassRecoverServiceInterface $userPassRecoverService, + TemporaryMasterPassServiceInterface $temporaryMasterPassService, + UserPassServiceInterface $userPassService, + UserProfileServiceInterface $userProfileService + ) { + parent::__construct($application); + + $this->authProvider = $authProvider; + $this->theme = $theme; + $this->language = $language; + $this->trackService = $trackService; + $this->request = $request; + $this->userService = $userService; + $this->userPassRecoverService = $userPassRecoverService; + $this->temporaryMasterPassService = $temporaryMasterPassService; + $this->userPassService = $userPassService; + $this->userProfileService = $userProfileService; + $this->configData = $this->config->getConfigData(); + $this->userLoginData = new UserLoginData(); + $this->trackRequest = $this->trackService->getTrackRequest(__CLASS__); + $this->authProvider->initialize(); + } /** * Ejecutar las acciones de login @@ -98,8 +135,6 @@ final class LoginService extends Service * @throws AuthException * @throws SPException * @throws EnvironmentIsBrokenException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface * @throws ConstraintException * @throws QueryException * @throws Exception @@ -206,8 +241,6 @@ final class LoginService extends Service * * @return LoginResponse * @throws EnvironmentIsBrokenException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface * @throws ConstraintException * @throws QueryException * @throws AuthException @@ -222,9 +255,10 @@ final class LoginService extends Service $this->eventDispatcher->notifyEvent( 'login.checkUser.disabled', new Event( - $this, EventMessage::factory() - ->addDescription(__u('User disabled')) - ->addDetail(__u('User'), $userLoginResponse->getLogin()) + $this, + EventMessage::factory() + ->addDescription(__u('User disabled')) + ->addDetail(__u('User'), $userLoginResponse->getLogin()) ) ); @@ -242,24 +276,17 @@ final class LoginService extends Service if ($userLoginResponse->getIsChangePass()) { $this->eventDispatcher->notifyEvent( 'login.checkUser.changePass', - new Event( - $this, EventMessage::factory() - ->addDetail(__u('User'), $userLoginResponse->getLogin()) - ) + new Event($this, EventMessage::factory()->addDetail(__u('User'), $userLoginResponse->getLogin())) ); $hash = PasswordUtil::generateRandomBytes(16); - $this->dic->get(UserPassRecoverService::class) - ->add($userLoginResponse->getId(), $hash); + $this->userPassRecoverService->add($userLoginResponse->getId(), $hash); $uri = new Uri('index.php'); $uri->addParam('r', 'userPassReset/reset/'.$hash); - return new LoginResponse( - self::STATUS_PASS_RESET, - $uri->getUri() - ); + return new LoginResponse(self::STATUS_PASS_RESET, $uri->getUri()); } } @@ -271,42 +298,31 @@ final class LoginService extends Service * * @throws AuthException * @throws SPException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface */ private function loadMasterPass(): void { - $temporaryMasterPass = $this->dic->get(TemporaryMasterPassService::class); - $userPassService = $this->dic->get(UserPassService::class); - $masterPass = $this->request->analyzeEncrypted('mpass'); $oldPass = $this->request->analyzeEncrypted('oldpass'); try { if ($masterPass) { - if ($temporaryMasterPass->checkTempMasterPass($masterPass)) { + if ($this->temporaryMasterPassService->checkTempMasterPass($masterPass)) { $this->eventDispatcher->notifyEvent( 'login.masterPass.temporary', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Using temporary password')) - ) + new Event($this, EventMessage::factory()->addDescription(__u('Using temporary password'))) ); - $masterPass = $temporaryMasterPass->getUsingKey($masterPass); + $masterPass = $this->temporaryMasterPassService->getUsingKey($masterPass); } - if ($userPassService->updateMasterPassOnLogin( + if ($this->userPassService->updateMasterPassOnLogin( $masterPass, $this->userLoginData )->getStatus() !== UserPassService::MPASS_OK ) { $this->eventDispatcher->notifyEvent( 'login.masterPass', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Wrong master password')) - ) + new Event($this, EventMessage::factory()->addDescription(__u('Wrong master password'))) ); $this->addTracking(); @@ -321,64 +337,53 @@ final class LoginService extends Service $this->eventDispatcher->notifyEvent( 'login.masterPass', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Master password updated')) - ) + new Event($this, EventMessage::factory()->addDescription(__u('Master password updated'))) + ); + } elseif ($oldPass) { + if ($this->userPassService->updateMasterPassFromOldPass( + $oldPass, + $this->userLoginData + )->getStatus() !== UserPassService::MPASS_OK + ) { + $this->eventDispatcher->notifyEvent( + 'login.masterPass', + new Event($this, EventMessage::factory()->addDescription(__u('Wrong master password'))) + ); + + $this->addTracking(); + + throw new AuthException( + __u('Wrong master password'), + SPException::INFO, + null, + self::STATUS_INVALID_MASTER_PASS + ); + } + + $this->eventDispatcher->notifyEvent( + 'login.masterPass', + new Event($this, EventMessage::factory()->addDescription(__u('Master password updated'))) ); } else { - if ($oldPass) { - if ($userPassService->updateMasterPassFromOldPass( - $oldPass, - $this->userLoginData - )->getStatus() !== UserPassService::MPASS_OK - ) { - $this->eventDispatcher->notifyEvent( - 'login.masterPass', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Wrong master password')) - ) + switch ($this->userPassService->loadUserMPass($this->userLoginData)->getStatus()) { + case UserPassService::MPASS_CHECKOLD: + throw new AuthException( + __u('Your previous password is needed'), + SPException::INFO, + null, + self::STATUS_NEED_OLD_PASS ); - + case UserPassService::MPASS_NOTSET: + case UserPassService::MPASS_CHANGED: + case UserPassService::MPASS_WRONG: $this->addTracking(); throw new AuthException( - __u('Wrong master password'), + __u('The Master Password either is not saved or is wrong'), SPException::INFO, null, self::STATUS_INVALID_MASTER_PASS ); - } - - $this->eventDispatcher->notifyEvent( - 'login.masterPass', - new Event( - $this, EventMessage::factory() - ->addDescription(__u('Master password updated')) - ) - ); - } else { - switch ($userPassService->loadUserMPass($this->userLoginData)->getStatus()) { - case UserPassService::MPASS_CHECKOLD: - throw new AuthException( - __u('Your previous password is needed'), - SPException::INFO, - null, - self::STATUS_NEED_OLD_PASS - ); - case UserPassService::MPASS_NOTSET: - case UserPassService::MPASS_CHANGED: - case UserPassService::MPASS_WRONG: - $this->addTracking(); - - throw new AuthException( - __u('The Master Password either is not saved or is wrong'), - SPException::INFO, - null, - self::STATUS_INVALID_MASTER_PASS - ); - } } } } catch (CryptoException $e) { @@ -397,8 +402,6 @@ final class LoginService extends Service /** * Cargar la sesión del usuario * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface * @throws ConstraintException * @throws QueryException * @throws NoSuchItemException @@ -417,9 +420,7 @@ final class LoginService extends Service // Cargar las variables de ussuario en la sesión $this->context->setUserData($userLoginResponse); $this->context->setUserProfile( - $this->dic->get(UserProfileService::class) - ->getById($userLoginResponse->getUserProfileId()) - ->getProfile() + $this->userProfileService->getById($userLoginResponse->getUserProfileId())->getProfile() ); $this->context->setLocale($userLoginResponse->getPreferences()->getLang()); @@ -429,10 +430,7 @@ final class LoginService extends Service $this->eventDispatcher->notifyEvent( 'login.session.load', - new Event( - $this, EventMessage::factory() - ->addDetail(__u('User'), $userLoginResponse->getLogin()) - ) + new Event($this, EventMessage::factory()->addDetail(__u('User'), $userLoginResponse->getLogin())) ); } @@ -447,10 +445,7 @@ final class LoginService extends Service $this->context->setAuthCompleted(true); - $this->eventDispatcher->notifyEvent( - 'login.preferences.load', - new Event($this) - ); + $this->eventDispatcher->notifyEvent('login.preferences.load', new Event($this)); } /** @@ -469,27 +464,6 @@ final class LoginService extends Service $this->from = $from; } - /** - * @throws \Psr\Container\ContainerExceptionInterface - * @throws \Psr\Container\NotFoundExceptionInterface - * @throws \SP\Core\Exceptions\InvalidArgumentException - * @throws \SP\Services\Auth\AuthException - */ - protected function initialize(): void - { - $this->configData = $this->config->getConfigData(); - $this->theme = $this->dic->get(ThemeInterface::class); - $this->userService = $this->dic->get(UserService::class); - $this->language = $this->dic->get(Language::class); - $this->trackService = $this->dic->get(TrackService::class); - $this->request = $this->dic->get(Request::class); - $this->userLoginData = new UserLoginData(); - $this->trackRequest = $this->trackService->getTrackRequest(__CLASS__); - $this->authProvider = $this->dic->get(AuthProvider::class); - - $this->authProvider->initialize(); - } - /** * Autentificación LDAP * @@ -512,10 +486,7 @@ final class LoginService extends Service $this->addTracking(); - $this->eventDispatcher->notifyEvent( - 'login.auth.ldap', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.ldap', new Event($this, $eventMessage)); throw new AuthException( __u('Wrong login'), @@ -525,13 +496,10 @@ final class LoginService extends Service ); } - if ($authData->getStatusCode() === LdapAuth::ACCOUNT_EXPIRED) { + if ($authData->getStatusCode() === LdapAuthInterface::ACCOUNT_EXPIRED) { $eventMessage->addDescription(__u('Account expired')); - $this->eventDispatcher->notifyEvent( - 'login.auth.ldap', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.ldap', new Event($this, $eventMessage)); throw new AuthException( __u('Account expired'), @@ -541,13 +509,10 @@ final class LoginService extends Service ); } - if ($authData->getStatusCode() === LdapAuth::ACCOUNT_NO_GROUPS) { + if ($authData->getStatusCode() === LdapAuthInterface::ACCOUNT_NO_GROUPS) { $eventMessage->addDescription(__u('User has no associated groups')); - $this->eventDispatcher->notifyEvent( - 'login.auth.ldap', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.ldap', new Event($this, $eventMessage)); throw new AuthException( __u('User has no associated groups'), @@ -562,10 +527,7 @@ final class LoginService extends Service ) { $eventMessage->addDescription(__u('Non authoritative auth')); - $this->eventDispatcher->notifyEvent( - 'login.auth.ldap', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.ldap', new Event($this, $eventMessage)); return false; } @@ -588,9 +550,10 @@ final class LoginService extends Service $this->eventDispatcher->notifyEvent( 'login.auth.ldap', new Event( - $this, EventMessage::factory() - ->addDetail(__u('Type'), __FUNCTION__) - ->addDetail(__u('LDAP Server'), $authData->getServer()) + $this, + EventMessage::factory() + ->addDetail(__u('Type'), __FUNCTION__) + ->addDetail(__u('LDAP Server'), $authData->getServer()) ) ); @@ -650,10 +613,7 @@ final class LoginService extends Service if ($authData->isAuthoritative() === false) { $eventMessage->addDescription(__u('Non authoritative auth')); - $this->eventDispatcher->notifyEvent( - 'login.auth.database', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.database', new Event($this, $eventMessage)); return false; } @@ -662,10 +622,7 @@ final class LoginService extends Service $eventMessage->addDescription(__u('Wrong login')); - $this->eventDispatcher->notifyEvent( - 'login.auth.database', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.database', new Event($this, $eventMessage)); throw new AuthException( __u('Wrong login'), @@ -705,10 +662,7 @@ final class LoginService extends Service if ($authData->isAuthoritative() === false) { $eventMessage->addDescription(__u('Non authoritative auth')); - $this->eventDispatcher->notifyEvent( - 'login.auth.browser', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.browser', new Event($this, $eventMessage)); return false; } @@ -717,10 +671,7 @@ final class LoginService extends Service $eventMessage->addDescription(__u('Wrong login')); - $this->eventDispatcher->notifyEvent( - 'login.auth.browser', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.browser', new Event($this, $eventMessage)); throw new AuthException( __u('Wrong login'), @@ -742,10 +693,7 @@ final class LoginService extends Service $this->userService->createOnLogin($userLoginRequest); } - $this->eventDispatcher->notifyEvent( - 'login.auth.browser', - new Event($this, $eventMessage) - ); + $this->eventDispatcher->notifyEvent('login.auth.browser', new Event($this, $eventMessage)); } catch (Exception $e) { throw new AuthException( __u('Internal error'), diff --git a/lib/SP/Services/Upgrade/UpgradeAuthToken.php b/lib/SP/Domain/Auth/Services/UpgradeAuthTokenService.php similarity index 65% rename from lib/SP/Services/Upgrade/UpgradeAuthToken.php rename to lib/SP/Domain/Auth/Services/UpgradeAuthTokenService.php index 04866a2b..2b4f7f3a 100644 --- a/lib/SP/Services/Upgrade/UpgradeAuthToken.php +++ b/lib/SP/Domain/Auth/Services/UpgradeAuthTokenService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,24 +22,41 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\Auth\Services; use Exception; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Services\AuthToken\AuthTokenService; -use SP\Services\Service; +use SP\Domain\Auth\AuthTokenServiceInterface; +use SP\Domain\Auth\UpgradeAuthTokenServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Infrastructure\Database\DatabaseInterface; /** * Class UpgradeAuthToken * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ -final class UpgradeAuthToken extends Service +final class UpgradeAuthTokenService extends Service + implements UpgradeAuthTokenServiceInterface { - private ?AuthTokenService $authtokenService = null; + protected AuthTokenServiceInterface $authTokenService; + private DatabaseInterface $database; + + public function __construct( + Application $application, + AuthTokenServiceInterface $authTokenService, + DatabaseInterface $database + ) { + parent::__construct($application); + + $this->authTokenService = $authTokenService; + $this->database = $database; + } + /** * upgrade_300_18072901 @@ -50,46 +67,53 @@ final class UpgradeAuthToken extends Service { $this->eventDispatcher->notifyEvent( 'upgrade.authToken.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('API authorizations update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('API authorizations update')) + ->addDescription(__FUNCTION__) + ) ); try { $this->transactionAware( function () { - foreach ($this->authtokenService->getAllBasic() as $item) { + foreach ($this->authTokenService->getAllBasic() as $item) { $itemData = clone $item; $itemData->setActionId($this->actionMapper($item->getActionId())); - $this->authtokenService->updateRaw($itemData); + $this->authTokenService->updateRaw($itemData); $this->eventDispatcher->notifyEvent( 'upgrade.authToken.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Authorization updated')) - ->addDetail(__u('Authorization'), $item->getId())) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Authorization updated')) + ->addDetail(__u('Authorization'), $item->getId()) + ) ); } - } + }, + $this->database ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); throw $e; } $this->eventDispatcher->notifyEvent( 'upgrade.authToken.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('API authorizations update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('API authorizations update')) + ->addDescription(__FUNCTION__) + ) ); } @@ -144,9 +168,4 @@ final class UpgradeAuthToken extends Service return $moduleId; } - - protected function initialize(): void - { - $this->authtokenService = $this->dic->get(AuthTokenService::class); - } } \ No newline at end of file diff --git a/lib/SP/Domain/Auth/UpgradeAuthTokenServiceInterface.php b/lib/SP/Domain/Auth/UpgradeAuthTokenServiceInterface.php new file mode 100644 index 00000000..77ffd156 --- /dev/null +++ b/lib/SP/Domain/Auth/UpgradeAuthTokenServiceInterface.php @@ -0,0 +1,43 @@ +. + */ + +namespace SP\Domain\Auth; + + +use Exception; + +/** + * Class UpgradeAuthToken + * + * @package SP\Domain\Upgrade\Services + */ +interface UpgradeAuthTokenServiceInterface +{ + /** + * upgrade_300_18072901 + * + * @throws Exception + */ + public function upgrade_300_18072901(): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Category/CategoryServiceInterface.php b/lib/SP/Domain/Category/CategoryServiceInterface.php new file mode 100644 index 00000000..f02fe7b7 --- /dev/null +++ b/lib/SP/Domain/Category/CategoryServiceInterface.php @@ -0,0 +1,103 @@ +. + */ + +namespace SP\Domain\Category; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\CategoryData; +use SP\DataModel\ItemSearchData; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class CategoryService + * + * @package SP\Domain\Category\Services + */ +interface CategoryServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function getById(int $id): CategoryData; + + /** + * Returns the item for given id + * + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function getByName(string $name): ?CategoryData; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): CategoryServiceInterface; + + /** + * Deletes all the items for given ids + * + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * @throws SPException + * @throws DuplicatedItemException + */ + public function create(CategoryData $itemData): int; + + /** + * @throws SPException + * @throws ConstraintException + * @throws QueryException + */ + public function update(CategoryData $itemData): int; + + /** + * Get all items from the service's repository + * + * @return CategoryData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/Category/In/CategoryRepositoryInterface.php b/lib/SP/Domain/Category/In/CategoryRepositoryInterface.php new file mode 100644 index 00000000..dc10a44e --- /dev/null +++ b/lib/SP/Domain/Category/In/CategoryRepositoryInterface.php @@ -0,0 +1,50 @@ +. + */ + +namespace SP\Domain\Category\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class CategoryRepository + * + * @package SP\Infrastructure\Common\Repositories\Category + */ +interface CategoryRepositoryInterface extends RepositoryInterface +{ + /** + * Returns the item for given id + * + * @param string $name + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByName(string $name): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Services/Category/CategoryService.php b/lib/SP/Domain/Category/Services/CategoryService.php similarity index 72% rename from lib/SP/Services/Category/CategoryService.php rename to lib/SP/Domain/Category/Services/CategoryService.php index 855f63c1..bce81ce6 100644 --- a/lib/SP/Services/Category/CategoryService.php +++ b/lib/SP/Domain/Category/Services/CategoryService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,33 +22,40 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Category; +namespace SP\Domain\Category\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Category\CategoryRepository; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Category\CategoryServiceInterface; +use SP\Domain\Category\In\CategoryRepositoryInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; /** * Class CategoryService * - * @package SP\Services\Category + * @package SP\Domain\Category\Services */ -final class CategoryService extends Service +final class CategoryService extends Service implements CategoryServiceInterface { use ServiceItemTrait; - protected ?CategoryRepository $categoryRepository = null; + protected CategoryRepositoryInterface $categoryRepository; + + public function __construct(Application $application, CategoryRepositoryInterface $categoryRepository) + { + parent::__construct($application); + + $this->categoryRepository = $categoryRepository; + } /** * @throws ConstraintException @@ -96,15 +103,12 @@ final class CategoryService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function delete(int $id): CategoryService + public function delete(int $id): CategoryServiceInterface { if ($this->categoryRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Category not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Category not found'), SPException::INFO); } return $this; @@ -113,7 +117,7 @@ final class CategoryService extends Service /** * Deletes all the items for given ids * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ConstraintException * @throws QueryException */ @@ -122,10 +126,7 @@ final class CategoryService extends Service $count = $this->categoryRepository->deleteByIdBatch($ids); if ($count !== count($ids)) { - throw new ServiceException( - __u('Error while deleting categories'), - SPException::WARNING - ); + throw new ServiceException(__u('Error while deleting categories'), SPException::WARNING); } return $count; @@ -161,13 +162,4 @@ final class CategoryService extends Service { return $this->categoryRepository->getAll()->getDataAsArray(); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->categoryRepository = $this->dic->get(CategoryRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Domain/Client/ClientServiceInterface.php b/lib/SP/Domain/Client/ClientServiceInterface.php new file mode 100644 index 00000000..b1d5a8c7 --- /dev/null +++ b/lib/SP/Domain/Client/ClientServiceInterface.php @@ -0,0 +1,117 @@ +. + */ + +namespace SP\Domain\Client; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\ClientData; +use SP\DataModel\ItemData; +use SP\DataModel\ItemSearchData; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class ClientService + * + * @package SP\Domain\Client\Services + */ +interface ClientServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function getById(int $id): ClientData; + + /** + * Returns the item for given name + * + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function getByName(string $name): ?ClientData; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): ClientServiceInterface; + + /** + * @param int[] $ids + * + * @throws ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * @throws SPException + * @throws DuplicatedItemException + */ + public function create($itemData): int; + + /** + * @param ClientData $itemData + * + * @return int + * @throws SPException + * @throws ConstraintException + * @throws QueryException + */ + public function update(ClientData $itemData): int; + + /** + * Get all items from the service's repository + * + * @return ClientData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; + + /** + * Returns all clients visible for a given user + * + * @return ItemData[] + * @throws QueryException + * @throws ConstraintException + */ + public function getAllForUser(): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/Client/In/ClientRepositoryInterface.php b/lib/SP/Domain/Client/In/ClientRepositoryInterface.php new file mode 100644 index 00000000..d74b2fea --- /dev/null +++ b/lib/SP/Domain/Client/In/ClientRepositoryInterface.php @@ -0,0 +1,66 @@ +. + */ + +namespace SP\Domain\Client\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\ClientData; +use SP\DataModel\ItemSearchData; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Mvc\Model\QueryCondition; + +/** + * Class ClientRepository + * + * @package SP\Infrastructure\Common\Repositories\Client + */ +interface ClientRepositoryInterface extends RepositoryInterface +{ + /** + * Returns the item for given name + * + * @param string $name + * + * @return QueryResult + * @throws QueryException + * @throws ConstraintException + */ + public function getByName(string $name): QueryResult; + + /** + * Devolver los clientes visibles por el usuario + * + * @param QueryCondition $queryFilter + * + * @return QueryResult + * @throws QueryException + * @throws ConstraintException + */ + public function getAllForFilter(QueryCondition $queryFilter): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Services/Client/ClientService.php b/lib/SP/Domain/Client/Services/ClientService.php similarity index 67% rename from lib/SP/Services/Client/ClientService.php rename to lib/SP/Domain/Client/Services/ClientService.php index f90bae94..ff850029 100644 --- a/lib/SP/Services/Client/ClientService.php +++ b/lib/SP/Domain/Client/Services/ClientService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,35 +22,47 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Client; +namespace SP\Domain\Client\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ClientData; use SP\DataModel\ItemData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Client\ClientRepository; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountFilterUser; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\Services\AccountFilterUser; +use SP\Domain\Client\ClientServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Infrastructure\Client\Repositories\ClientRepository; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; /** * Class ClientService * - * @package SP\Services\Client + * @package SP\Domain\Client\Services */ -final class ClientService extends Service +final class ClientService extends Service implements ClientServiceInterface { use ServiceItemTrait; - protected ?ClientRepository $clientRepository = null; + private ClientRepository $clientRepository; + private AccountFilterUser $accountFilterUser; + + public function __construct( + Application $application, + ClientRepository $clientRepository, + AccountFilterUser $accountFilterUser + ) { + parent::__construct($application); + + $this->clientRepository = $clientRepository; + $this->accountFilterUser = $accountFilterUser; + } /** * @throws ConstraintException @@ -71,10 +83,7 @@ final class ClientService extends Service $result = $this->clientRepository->getById($id); if ($result->getNumRows() === 0) { - throw new NoSuchItemException - (__u('Client not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Client not found'), SPException::INFO); } return $result->getData(); @@ -92,10 +101,7 @@ final class ClientService extends Service $result = $this->clientRepository->getByName($name); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Client not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Client not found'), SPException::INFO); } return $result->getData(); @@ -104,24 +110,21 @@ final class ClientService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function delete(int $id): ClientService + public function delete(int $id): ClientServiceInterface { if ($this->clientRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Client not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Client not found'), SPException::INFO); } return $this; } /** - * @param int[] $ids + * @param int[] $ids * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ConstraintException * @throws QueryException */ @@ -149,7 +152,7 @@ final class ClientService extends Service } /** - * @param ClientData $itemData + * @param ClientData $itemData * * @return int * @throws SPException @@ -182,19 +185,6 @@ final class ClientService extends Service */ public function getAllForUser(): array { - return $this->clientRepository - ->getAllForFilter( - $this->dic->get(AccountFilterUser::class)->getFilter() - ) - ->getDataAsArray(); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->clientRepository = $this->dic->get(ClientRepository::class); + return $this->clientRepository->getAllForFilter($this->accountFilterUser->getFilter())->getDataAsArray(); } } \ No newline at end of file diff --git a/lib/SP/Repositories/RepositoryInterface.php b/lib/SP/Domain/Common/In/RepositoryInterface.php similarity index 93% rename from lib/SP/Repositories/RepositoryInterface.php rename to lib/SP/Domain/Common/In/RepositoryInterface.php index f4fb2998..ce6d3aca 100644 --- a/lib/SP/Repositories/RepositoryInterface.php +++ b/lib/SP/Domain/Common/In/RepositoryInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,15 +22,15 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories; +namespace SP\Domain\Common\In; use SP\DataModel\ItemSearchData; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; /** * Interface RepositoryItemInterface * - * @package SP\Repositories + * @package SP\Domain\Common\In */ interface RepositoryInterface { diff --git a/lib/SP/Services/Service.php b/lib/SP/Domain/Common/Services/Service.php similarity index 75% rename from lib/SP/Services/Service.php rename to lib/SP/Domain/Common/Services/Service.php index 25f89609..a8ad75c3 100644 --- a/lib/SP/Services/Service.php +++ b/lib/SP/Domain/Common/Services/Service.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,13 +22,12 @@ * along with sysPass. If not, see . */ -namespace SP\Services; +namespace SP\Domain\Common\Services; use Closure; use Defuse\Crypto\Exception\CryptoException; use Exception; -use Psr\Container\ContainerInterface; -use SP\Config\Config; +use SP\Core\Application; use SP\Core\Context\ContextException; use SP\Core\Context\ContextInterface; use SP\Core\Context\SessionContext; @@ -36,44 +35,41 @@ use SP\Core\Crypt\Session; use SP\Core\Events\Event; use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventMessage; -use SP\Storage\Database\Database; +use SP\Domain\Config\ConfigInterface; +use SP\Infrastructure\Database\DatabaseInterface; /** * Class Service * - * @package SP\Services + * @package SP\Domain\Common\Services */ abstract class Service { protected const STATUS_INTERNAL_ERROR = 1000; - protected Config $config; + protected ConfigInterface $config; protected ContextInterface $context; - protected EventDispatcher $eventDispatcher; - protected ContainerInterface $dic; + protected EventDispatcher $eventDispatcher; - public function __construct(ContainerInterface $dic) + public function __construct(Application $application) { - $this->dic = $dic; - $this->config = $dic->get(Config::class); - $this->context = $dic->get(ContextInterface::class); - $this->eventDispatcher = $dic->get(EventDispatcher::class); - - if (method_exists($this, 'initialize')) { - $this->initialize(); - } + $this->config = $application->getConfig(); + $this->context = $application->getContext(); + $this->eventDispatcher = $application->getEventDispatcher(); } /** * Bubbles a Closure in a database transaction * - * @throws ServiceException - * @throws Exception + * @param \Closure $closure + * @param \SP\Infrastructure\Database\DatabaseInterface $database + * + * @return mixed + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \Exception */ - protected function transactionAware(Closure $closure) + protected function transactionAware(Closure $closure, DatabaseInterface $database) { - $database = $this->dic->get(Database::class); - if ($database->beginTransaction()) { try { $result = $closure->call($this); @@ -88,8 +84,7 @@ abstract class Service $this->eventDispatcher->notifyEvent( 'database.rollback', - new Event($this, EventMessage::factory() - ->addDescription(__u('Rollback'))) + new Event($this, EventMessage::factory()->addDescription(__u('Rollback'))) ); throw $e; @@ -134,7 +129,7 @@ abstract class Service } else { $this->context->setTrasientKey('_masterpass', $masterPass); } - } catch (ContextException | CryptoException $e) { + } catch (ContextException|CryptoException $e) { logger($e->getMessage()); throw new ServiceException(__u('Error while setting master password in context')); diff --git a/lib/SP/Services/ServiceException.php b/lib/SP/Domain/Common/Services/ServiceException.php similarity index 86% rename from lib/SP/Services/ServiceException.php rename to lib/SP/Domain/Common/Services/ServiceException.php index 4351d3c6..97616b3c 100644 --- a/lib/SP/Services/ServiceException.php +++ b/lib/SP/Domain/Common/Services/ServiceException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services; +namespace SP\Domain\Common\Services; use SP\Core\Exceptions\SPException; @@ -30,7 +30,7 @@ use SP\Core\Exceptions\SPException; /** * Class ServiceException * - * @package SP\Services + * @package SP\Domain\Common\Services */ final class ServiceException extends SPException { diff --git a/lib/SP/Services/ServiceItemTrait.php b/lib/SP/Domain/Common/Services/ServiceItemTrait.php similarity index 89% rename from lib/SP/Services/ServiceItemTrait.php rename to lib/SP/Domain/Common/Services/ServiceItemTrait.php index a4d4170b..e05925aa 100644 --- a/lib/SP/Services/ServiceItemTrait.php +++ b/lib/SP/Domain/Common/Services/ServiceItemTrait.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services; +namespace SP\Domain\Common\Services; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; @@ -32,7 +32,7 @@ use SP\DataModel\DataModelInterface; /** * Trait ServiceItemTrait * - * @package SP\Services + * @package SP\Domain\Common\Services */ trait ServiceItemTrait { @@ -42,6 +42,8 @@ trait ServiceItemTrait * @return DataModelInterface[] * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface + * + * TODO: remove!! */ public static function getItemsBasic(): array { diff --git a/lib/SP/Config/ConfigData.php b/lib/SP/Domain/Config/Adapters/ConfigData.php similarity index 96% rename from lib/SP/Config/ConfigData.php rename to lib/SP/Domain/Config/Adapters/ConfigData.php index 9dd0ca78..8d45419f 100644 --- a/lib/SP/Config/ConfigData.php +++ b/lib/SP/Domain/Config/Adapters/ConfigData.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,28 +22,28 @@ * along with sysPass. If not, see . */ -namespace SP\Config; +namespace SP\Domain\Config\Adapters; use JsonSerializable; use SP\Core\DataCollection; +use SP\Domain\Config\In\ConfigDataInterface; /** * Class configData */ -final class ConfigData extends DataCollection - implements JsonSerializable, ConfigDataInterface +final class ConfigData extends DataCollection implements JsonSerializable, ConfigDataInterface { private const PUBLIC_LINK_MAX_VIEWS = 3; - private const PUBLIC_LINK_MAX_TIME = 600; - private const ACCOUNT_COUNT = 12; - private const DB_PORT = 3306; - private const FILES_ALLOWED_SIZE = 1024; - private const MAIL_PORT = 587; - private const SESSION_TIMEOUT = 300; - private const SITE_THEME = 'material-blue'; - private const SYSLOG_PORT = 514; - private const ACCOUNT_EXPIRE_TIME = 10368000; - private const PROXY_PORT = 8080; + private const PUBLIC_LINK_MAX_TIME = 600; + private const ACCOUNT_COUNT = 12; + private const DB_PORT = 3306; + private const FILES_ALLOWED_SIZE = 1024; + private const MAIL_PORT = 587; + private const SESSION_TIMEOUT = 300; + private const SITE_THEME = 'material-blue'; + private const SYSLOG_PORT = 514; + private const ACCOUNT_EXPIRE_TIME = 10368000; + private const PROXY_PORT = 8080; public function getAttributes(): array { @@ -1153,9 +1153,12 @@ final class ConfigData extends DataCollection public function setApplicationUrl(?string $applicationUrl): ConfigDataInterface { - $this->set('applicationUrl', $applicationUrl - ? rtrim($applicationUrl, '/') - : null); + $this->set( + 'applicationUrl', + $applicationUrl + ? rtrim($applicationUrl, '/') + : null + ); return $this; } diff --git a/lib/SP/Domain/Config/ConfigBackupServiceInterface.php b/lib/SP/Domain/Config/ConfigBackupServiceInterface.php new file mode 100644 index 00000000..64cc19e3 --- /dev/null +++ b/lib/SP/Domain/Config/ConfigBackupServiceInterface.php @@ -0,0 +1,54 @@ +. + */ + +namespace SP\Domain\Config; + + +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Infrastructure\File\FileException; + +/** + * Class ConfigBackupService + * + * @package SP\Domain\Config\Services + */ +interface ConfigBackupServiceInterface +{ + /** + * Backs up the config data into the database + */ + public function backup(ConfigDataInterface $configData): void; + + /** + * @throws FileException + * @throws ServiceException + */ + public function restore(): ConfigDataInterface; + + /** + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function getBackup(): string; +} \ No newline at end of file diff --git a/lib/SP/Domain/Config/ConfigInterface.php b/lib/SP/Domain/Config/ConfigInterface.php new file mode 100644 index 00000000..7279c4da --- /dev/null +++ b/lib/SP/Domain/Config/ConfigInterface.php @@ -0,0 +1,77 @@ +. + */ + +namespace SP\Domain\Config; + + +use Defuse\Crypto\Exception\EnvironmentIsBrokenException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Infrastructure\File\FileException; + +/** + * Esta clase es responsable de leer y escribir la configuración del archivo config.php + */ +interface ConfigInterface +{ + /** + * Cargar el archivo de configuración + * + * @throws FileException + */ + public function loadConfigFromFile(): ConfigDataInterface; + + /** + * Guardar la configuración + * + * @param \SP\Domain\Config\In\ConfigDataInterface $configData + * @param bool|null $backup + * + * @return ConfigInterface + * @throws \SP\Infrastructure\File\FileException + */ + public function saveConfig(In\ConfigDataInterface $configData, ?bool $backup = true): ConfigInterface; + + /** + * Commits a config data + */ + public function updateConfig(ConfigDataInterface $configData): ConfigInterface; + + /** + * Cargar la configuración desde el contexto + */ + public function loadConfig(?bool $reload = false): ConfigDataInterface; + + /** + * Returns a clone of the configuration data + * + * @return \SP\Domain\Config\In\ConfigDataInterface + */ + public function getConfigData(): ConfigDataInterface; + + /** + * @throws FileException + * @throws EnvironmentIsBrokenException + */ + public function generateUpgradeKey(): ConfigInterface; +} \ No newline at end of file diff --git a/lib/SP/Domain/Config/ConfigServiceInterface.php b/lib/SP/Domain/Config/ConfigServiceInterface.php new file mode 100644 index 00000000..bfb1fd70 --- /dev/null +++ b/lib/SP/Domain/Config/ConfigServiceInterface.php @@ -0,0 +1,79 @@ +. + */ + +namespace SP\Domain\Config; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ConfigData; +use SP\DataModel\Dto\ConfigRequest; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; + +/** + * Class ConfigService + * + * @package SP\Domain\Config\Services + */ +interface ConfigServiceInterface +{ + /** + * @throws NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function getByParam(string $param, $default = null); + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function create(ConfigData $configData): int; + + /** + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function saveBatch(ConfigRequest $configRequest): void; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function save(string $param, $value): bool; + + /** + * Obtener un array con la configuración almacenada en la BBDD. + * + * @return ConfigData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): array; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function deleteByParam(string $param): void; +} \ No newline at end of file diff --git a/lib/SP/Config/ConfigDataInterface.php b/lib/SP/Domain/Config/In/ConfigDataInterface.php similarity index 99% rename from lib/SP/Config/ConfigDataInterface.php rename to lib/SP/Domain/Config/In/ConfigDataInterface.php index 359e93fb..7d0c72b5 100644 --- a/lib/SP/Config/ConfigDataInterface.php +++ b/lib/SP/Domain/Config/In/ConfigDataInterface.php @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Config; +namespace SP\Domain\Config\In; /** diff --git a/lib/SP/Domain/Config/In/ConfigRepositoryInterface.php b/lib/SP/Domain/Config/In/ConfigRepositoryInterface.php new file mode 100644 index 00000000..b644cef0 --- /dev/null +++ b/lib/SP/Domain/Config/In/ConfigRepositoryInterface.php @@ -0,0 +1,93 @@ +. + */ + +namespace SP\Domain\Config\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ConfigData; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class ConfigRepository + * + * @package SP\Infrastructure\Common\Repositories\Config + */ +interface ConfigRepositoryInterface +{ + /** + * @param ConfigData $configData + * + * @return bool + * @throws ConstraintException + * @throws QueryException + */ + public function update(ConfigData $configData): bool; + + /** + * @param ConfigData $configData + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function create(ConfigData $configData): int; + + /** + * Obtener un array con la configuración almacenada en la BBDD. + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): QueryResult; + + /** + * @param string $param + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByParam(string $param): QueryResult; + + /** + * @param string $param + * + * @return bool + * @throws ConstraintException + * @throws QueryException + */ + public function has(string $param): bool; + + /** + * @param string $param + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteByParam(string $param): int; +} \ No newline at end of file diff --git a/lib/SP/Services/Config/ConfigBackupService.php b/lib/SP/Domain/Config/Services/ConfigBackupService.php similarity index 74% rename from lib/SP/Services/Config/ConfigBackupService.php rename to lib/SP/Domain/Config/Services/ConfigBackupService.php index c6e5c4ed..7071e208 100644 --- a/lib/SP/Services/Config/ConfigBackupService.php +++ b/lib/SP/Domain/Config/Services/ConfigBackupService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,32 +22,31 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Config; +namespace SP\Domain\Config\Services; use Exception; -use SP\Config\Config; -use SP\Config\ConfigData; -use SP\Config\ConfigDataInterface; use SP\Core\Exceptions\SPException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\Adapters\ConfigData; +use SP\Domain\Config\ConfigBackupServiceInterface; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Http\Json; -use SP\Repositories\NoSuchItemException; -use SP\Services\ServiceException; -use SP\Storage\File\FileException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\File\FileException; use SP\Util\Util; /** * Class ConfigBackupService * - * @package SP\Services\Config - * - * TODO: restore final?? + * @package SP\Domain\Config\Services */ -class ConfigBackupService +class ConfigBackupService implements ConfigBackupServiceInterface { - private ConfigService $configService; - private Config $config; + private ConfigService $configService; + private ConfigInterface $config; - public function __construct(ConfigService $configService, Config $config) + public function __construct(ConfigService $configService, ConfigInterface $config) { $this->configService = $configService; $this->config = $config; @@ -58,10 +57,7 @@ class ConfigBackupService */ public static function configToJson(string $configData): string { - return Json::getJson( - Util::unserialize(ConfigData::class, $configData), - JSON_PRETTY_PRINT - ); + return Json::getJson(Util::unserialize(ConfigData::class, $configData), JSON_PRETTY_PRINT); } /** @@ -70,10 +66,7 @@ class ConfigBackupService public function backup(ConfigDataInterface $configData): void { try { - $this->configService->save( - 'config_backup', - $this->packConfigData($configData) - ); + $this->configService->save('config_backup', $this->packConfigData($configData)); $this->configService->save('config_backup_date', time()); } catch (Exception $e) { processException($e); diff --git a/lib/SP/Config/Config.php b/lib/SP/Domain/Config/Services/ConfigFileService.php similarity index 84% rename from lib/SP/Config/Config.php rename to lib/SP/Domain/Config/Services/ConfigFileService.php index 58575fd5..59cfdd29 100644 --- a/lib/SP/Config/Config.php +++ b/lib/SP/Domain/Config/Services/ConfigFileService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Config; +namespace SP\Domain\Config\Services; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use Exception; @@ -30,10 +30,13 @@ use SP\Core\AppInfoInterface; use SP\Core\Context\ContextInterface; use SP\Core\Exceptions\ConfigException; use SP\Core\Exceptions\SPException; -use SP\Services\Config\ConfigBackupService; -use SP\Storage\File\FileCacheInterface; -use SP\Storage\File\FileException; -use SP\Storage\File\XmlFileStorageInterface; +use SP\Domain\Config\Adapters\ConfigData; +use SP\Domain\Config\ConfigBackupServiceInterface; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Infrastructure\File\FileCacheInterface; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\XmlFileStorageInterface; use SP\Util\PasswordUtil; defined('APP_ROOT') || die(); @@ -41,19 +44,20 @@ defined('APP_ROOT') || die(); /** * Esta clase es responsable de leer y escribir la configuración del archivo config.php */ -final class Config +class ConfigFileService implements ConfigInterface { /** * Cache file name */ public const CONFIG_CACHE_FILE = CACHE_PATH.DIRECTORY_SEPARATOR.'config.cache'; - private static int $timeUpdated; - private ContextInterface $context; - private bool $configLoaded = false; - private ?ConfigDataInterface $configData = null; - private XmlFileStorageInterface $fileStorage; - private FileCacheInterface $fileCache; - private ConfigBackupService $configBackupService; + + private static int $timeUpdated; + private bool $configLoaded = false; + private ?ConfigDataInterface $configData = null; + private ContextInterface $context; + private XmlFileStorageInterface $fileStorage; + private FileCacheInterface $fileCache; + private ConfigBackupServiceInterface $configBackupService; /** * @throws ConfigException @@ -62,7 +66,7 @@ final class Config XmlFileStorageInterface $fileStorage, FileCacheInterface $fileCache, ContextInterface $context, - ConfigBackupService $configBackupService + ConfigBackupServiceInterface $configBackupService ) { $this->fileCache = $fileCache; $this->fileStorage = $fileStorage; @@ -168,16 +172,16 @@ final class Config /** * Guardar la configuración * - * @param \SP\Config\ConfigDataInterface $configData + * @param \SP\Domain\Config\In\ConfigDataInterface $configData * @param bool|null $backup * - * @return \SP\Config\Config - * @throws \SP\Storage\File\FileException + * @return ConfigInterface + * @throws \SP\Infrastructure\File\FileException */ public function saveConfig( ConfigDataInterface $configData, ?bool $backup = true - ): Config { + ): ConfigInterface { if ($backup) { $this->configBackupService->backup($configData); } @@ -207,7 +211,7 @@ final class Config /** * Commits a config data */ - public function updateConfig(ConfigDataInterface $configData): Config + public function updateConfig(ConfigDataInterface $configData): ConfigInterface { $configData->setConfigDate(time()); $configData->setConfigSaver($this->context->getUserData()->getLogin()); @@ -249,7 +253,7 @@ final class Config /** * Returns a clone of the configuration data * - * @return \SP\Config\ConfigDataInterface + * @return \SP\Domain\Config\In\ConfigDataInterface */ public function getConfigData(): ConfigDataInterface { @@ -260,7 +264,7 @@ final class Config * @throws FileException * @throws EnvironmentIsBrokenException */ - public function generateUpgradeKey(): Config + public function generateUpgradeKey(): ConfigInterface { if (empty($this->configData->getUpgradeKey())) { logger('Generating upgrade key'); diff --git a/lib/SP/Services/Config/ConfigService.php b/lib/SP/Domain/Config/Services/ConfigService.php similarity index 78% rename from lib/SP/Services/Config/ConfigService.php rename to lib/SP/Domain/Config/Services/ConfigService.php index 548e90a3..b3dd16aa 100644 --- a/lib/SP/Services/Config/ConfigService.php +++ b/lib/SP/Domain/Config/Services/ConfigService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,33 +22,41 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Config; +namespace SP\Domain\Config\Services; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ConfigData; use SP\DataModel\Dto\ConfigRequest; -use SP\Repositories\Config\ConfigRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Config\In\ConfigRepositoryInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Config\Repositories\ConfigRepository; /** * Class ConfigService * - * @package SP\Services\Config + * @package SP\Domain\Config\Services */ -final class ConfigService extends Service +final class ConfigService extends Service implements ConfigServiceInterface { - protected ?ConfigRepository $configRepository = null; + private ConfigRepository $configRepository; + + public function __construct(Application $application, ConfigRepositoryInterface $configRepository) + { + parent::__construct($application); + + $this->configRepository = $configRepository; + } /** * @throws NoSuchItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function getByParam(string $param, $default = null) { @@ -82,16 +90,9 @@ final class ConfigService extends Service } /** - * @throws ConstraintException - * @throws QueryException - */ - public function create(ConfigData $configData): int - { - return $this->configRepository->create($configData); - } - - /** - * @throws ServiceException + * @param \SP\DataModel\Dto\ConfigRequest $configRequest + * + * @throws \SP\Domain\Common\Services\ServiceException */ public function saveBatch(ConfigRequest $configRequest): void { @@ -129,6 +130,15 @@ final class ConfigService extends Service return $this->configRepository->update(new ConfigData($param, $value)); } + /** + * @throws ConstraintException + * @throws QueryException + */ + public function create(ConfigData $configData): int + { + return $this->configRepository->create($configData); + } + /** * Obtener un array con la configuración almacenada en la BBDD. * @@ -144,7 +154,7 @@ final class ConfigService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function deleteByParam(string $param): void { @@ -154,13 +164,4 @@ final class ConfigService extends Service ); } } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->configRepository = $this->dic->get(ConfigRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Config/ConfigUtil.php b/lib/SP/Domain/Config/Services/ConfigUtil.php similarity index 96% rename from lib/SP/Config/ConfigUtil.php rename to lib/SP/Domain/Config/Services/ConfigUtil.php index 50c8a928..8943d987 100644 --- a/lib/SP/Config/ConfigUtil.php +++ b/lib/SP/Domain/Config/Services/ConfigUtil.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Config; +namespace SP\Domain\Config\Services; use SP\Core\Exceptions\ConfigException; use SP\Core\Exceptions\SPException; diff --git a/lib/SP/Services/Upgrade/UpgradeConfigService.php b/lib/SP/Domain/Config/Services/UpgradeConfigService.php similarity index 52% rename from lib/SP/Services/Upgrade/UpgradeConfigService.php rename to lib/SP/Domain/Config/Services/UpgradeConfigService.php index ed1abee9..50db009d 100644 --- a/lib/SP/Services/Upgrade/UpgradeConfigService.php +++ b/lib/SP/Domain/Config/Services/UpgradeConfigService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,25 +22,28 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\Config\Services; use Exception; -use SP\Config\ConfigDataInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Core\MimeTypes; +use SP\Core\MimeTypesInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\UpgradeConfigServiceInterface; +use SP\Domain\Upgrade\Services\UpgradeException; +use SP\Infrastructure\File\FileException; use SP\Providers\Auth\Ldap\LdapTypeInterface; use SP\Providers\Log\FileLogHandler; -use SP\Services\Service; -use SP\Storage\File\FileException; use SP\Util\VersionUtil; /** * Class UpgradeService * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ -final class UpgradeConfigService extends Service implements UpgradeInterface +final class UpgradeConfigService extends Service implements UpgradeConfigServiceInterface { /** * @var array Versiones actualizables @@ -54,6 +57,15 @@ final class UpgradeConfigService extends Service implements UpgradeInterface '320.20062801', ]; protected ?ConfigDataInterface $configData = null; + private MimeTypesInterface $mimeTypes; + + public function __construct(Application $application, FileLogHandler $fileLogHandler, MimeTypesInterface $mimeTypes) + { + parent::__construct($application); + + $this->mimeTypes = $mimeTypes; + $this->eventDispatcher->attach($fileLogHandler); + } public static function needsUpgrade(string $version): bool { @@ -63,7 +75,7 @@ final class UpgradeConfigService extends Service implements UpgradeInterface /** * Actualizar el archivo de configuración a formato XML * - * @throws \SP\Services\Upgrade\UpgradeException + * @throws \SP\Domain\Upgrade\Services\UpgradeException */ public function upgradeOldConfigFile(string $version): void { @@ -71,10 +83,7 @@ final class UpgradeConfigService extends Service implements UpgradeInterface $message = EventMessage::factory()->addDescription(__u('Update Configuration')); - $this->eventDispatcher->notifyEvent( - 'upgrade.config.old.start', - new Event($this, $message) - ); + $this->eventDispatcher->notifyEvent('upgrade.config.old.start', new Event($this, $message)); // Include the file, save the data from $CONFIG include OLD_CONFIG_FILE; @@ -95,14 +104,14 @@ final class UpgradeConfigService extends Service implements UpgradeInterface foreach ($mapFrom as $param) { $paramMapper($mapFrom, $param); } - } else if (isset($CONFIG[$mapFrom])) { + } elseif (isset($CONFIG[$mapFrom])) { $paramMapper($mapFrom, $mapTo); } } } } - $oldFile = OLD_CONFIG_FILE . '.old.' . time(); + $oldFile = OLD_CONFIG_FILE.'.old.'.time(); try { $configData->setSiteTheme('material-blue'); @@ -114,18 +123,18 @@ final class UpgradeConfigService extends Service implements UpgradeInterface $message->addDetail(__u('Version'), $version); - $this->eventDispatcher->notifyEvent( - 'upgrade.config.old.end', - new Event($this, $message) - ); + $this->eventDispatcher->notifyEvent('upgrade.config.old.end', new Event($this, $message)); } catch (Exception $e) { processException($e); $this->eventDispatcher->notifyEvent( 'exception', - new Event($this, EventMessage::factory() - ->addDescription(__u('Error while updating the configuration')) - ->addDetail(__u('File'), $oldFile)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Error while updating the configuration')) + ->addDetail(__u('File'), $oldFile) + ) ); throw new UpgradeException(__u('Error while updating the configuration')); @@ -138,58 +147,58 @@ final class UpgradeConfigService extends Service implements UpgradeInterface private static function getConfigParams(): array { return [ - 'setAccountCount' => 'account_count', - 'setAccountLink' => 'account_link', - 'setCheckUpdates' => 'checkupdates', - 'setCheckNotices' => 'checknotices', - 'setDbHost' => 'dbhost', - 'setDbName' => 'dbname', - 'setDbPass' => 'dbpass', - 'setDbUser' => 'dbuser', - 'setDebug' => 'debug', - 'setDemoEnabled' => 'demo_enabled', - 'setGlobalSearch' => 'globalsearch', - 'setInstalled' => 'installed', - 'setMaintenance' => 'maintenance', - 'setPasswordSalt' => 'passwordsalt', - 'setSessionTimeout' => 'session_timeout', - 'setSiteLang' => 'sitelang', - 'setConfigVersion' => 'version', - 'setConfigHash' => 'config_hash', - 'setProxyEnabled' => 'proxy_enabled', - 'setProxyPass' => 'proxy_pass', - 'setProxyPort' => 'proxy_port', - 'setProxyServer' => 'proxy_server', - 'setProxyUser' => 'proxy_user', - 'setResultsAsCards' => 'resultsascards', - 'setSiteTheme' => 'sitetheme', - 'setAccountPassToImage' => 'account_passtoimage', - 'setFilesAllowedExts' => ['allowed_exts', 'files_allowed_exts'], - 'setFilesAllowedSize' => ['allowed_size', 'files_allowed_size'], - 'setFilesEnabled' => ['filesenabled', 'files_enabled'], - 'setLdapBase' => ['ldapbase', 'ldap_base'], - 'setLdapBindPass' => ['ldapbindpass', 'ldap_bindpass'], - 'setLdapBindUser' => ['ldapbinduser', 'ldap_binduser'], - 'setLdapEnabled' => ['ldapenabled', 'ldap_enabled'], - 'setLdapGroup' => ['ldapgroup', 'ldap_group'], - 'setLdapServer' => ['ldapserver', 'ldap_server'], - 'setLdapAds' => 'ldap_ads', - 'setLdapDefaultGroup' => 'ldap_defaultgroup', - 'setLdapDefaultProfile' => 'ldap_defaultprofile', - 'setLogEnabled' => ['logenabled', 'log_enabled'], - 'setMailEnabled' => ['mailenabled', 'mail_enabled'], - 'setMailFrom' => ['mailfrom', 'mail_from'], - 'setMailPass' => ['mailpass', 'mail_pass'], - 'setMailPort' => ['mailport', 'mail_port'], + 'setAccountCount' => 'account_count', + 'setAccountLink' => 'account_link', + 'setCheckUpdates' => 'checkupdates', + 'setCheckNotices' => 'checknotices', + 'setDbHost' => 'dbhost', + 'setDbName' => 'dbname', + 'setDbPass' => 'dbpass', + 'setDbUser' => 'dbuser', + 'setDebug' => 'debug', + 'setDemoEnabled' => 'demo_enabled', + 'setGlobalSearch' => 'globalsearch', + 'setInstalled' => 'installed', + 'setMaintenance' => 'maintenance', + 'setPasswordSalt' => 'passwordsalt', + 'setSessionTimeout' => 'session_timeout', + 'setSiteLang' => 'sitelang', + 'setConfigVersion' => 'version', + 'setConfigHash' => 'config_hash', + 'setProxyEnabled' => 'proxy_enabled', + 'setProxyPass' => 'proxy_pass', + 'setProxyPort' => 'proxy_port', + 'setProxyServer' => 'proxy_server', + 'setProxyUser' => 'proxy_user', + 'setResultsAsCards' => 'resultsascards', + 'setSiteTheme' => 'sitetheme', + 'setAccountPassToImage' => 'account_passtoimage', + 'setFilesAllowedExts' => ['allowed_exts', 'files_allowed_exts'], + 'setFilesAllowedSize' => ['allowed_size', 'files_allowed_size'], + 'setFilesEnabled' => ['filesenabled', 'files_enabled'], + 'setLdapBase' => ['ldapbase', 'ldap_base'], + 'setLdapBindPass' => ['ldapbindpass', 'ldap_bindpass'], + 'setLdapBindUser' => ['ldapbinduser', 'ldap_binduser'], + 'setLdapEnabled' => ['ldapenabled', 'ldap_enabled'], + 'setLdapGroup' => ['ldapgroup', 'ldap_group'], + 'setLdapServer' => ['ldapserver', 'ldap_server'], + 'setLdapAds' => 'ldap_ads', + 'setLdapDefaultGroup' => 'ldap_defaultgroup', + 'setLdapDefaultProfile' => 'ldap_defaultprofile', + 'setLogEnabled' => ['logenabled', 'log_enabled'], + 'setMailEnabled' => ['mailenabled', 'mail_enabled'], + 'setMailFrom' => ['mailfrom', 'mail_from'], + 'setMailPass' => ['mailpass', 'mail_pass'], + 'setMailPort' => ['mailport', 'mail_port'], 'setMailRequestsEnabled' => ['mailrequestsenabled', 'mail_requestsenabled'], - 'setMailAuthenabled' => 'mail_authenabled', - 'setMailSecurity' => ['mailsecurity', 'mail_security'], - 'setMailServer' => ['mailserver', 'mail_server'], - 'setMailUser' => ['mailuser', 'mail_user'], - 'setWikiEnabled' => ['wikienabled', 'wiki_enabled'], - 'setWikiFilter' => ['wikifilter', 'wiki_filter'], - 'setWikiPageUrl' => ['wikipageurl' . 'wiki_pageurl'], - 'setWikiSearchUrl' => ['wikisearchurl', 'wiki_searchurl'] + 'setMailAuthenabled' => 'mail_authenabled', + 'setMailSecurity' => ['mailsecurity', 'mail_security'], + 'setMailServer' => ['mailserver', 'mail_server'], + 'setMailUser' => ['mailuser', 'mail_user'], + 'setWikiEnabled' => ['wikienabled', 'wiki_enabled'], + 'setWikiFilter' => ['wikifilter', 'wiki_filter'], + 'setWikiPageUrl' => ['wikipageurl'.'wiki_pageurl'], + 'setWikiSearchUrl' => ['wikisearchurl', 'wiki_searchurl'], ]; } @@ -200,12 +209,8 @@ final class UpgradeConfigService extends Service implements UpgradeInterface { $this->configData = $configData; - $message = EventMessage::factory() - ->addDescription(__u('Update Configuration')); - $this->eventDispatcher->notifyEvent( - 'upgrade.config.start', - new Event($this, $message) - ); + $message = EventMessage::factory()->addDescription(__u('Update Configuration')); + $this->eventDispatcher->notifyEvent('upgrade.config.start', new Event($this, $message)); foreach (self::UPGRADES as $upgradeVersion) { if (VersionUtil::checkVersion($version, $upgradeVersion)) { @@ -213,10 +218,7 @@ final class UpgradeConfigService extends Service implements UpgradeInterface } } - $this->eventDispatcher->notifyEvent( - 'upgrade.config.end', - new Event($this, $message) - ); + $this->eventDispatcher->notifyEvent('upgrade.config.end', new Event($this, $message)); } private function applyUpgrade(string $version): void @@ -238,7 +240,7 @@ final class UpgradeConfigService extends Service implements UpgradeInterface } /** - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\File\FileException */ private function upgrade_200_17011202(string $version): void { @@ -249,9 +251,12 @@ final class UpgradeConfigService extends Service implements UpgradeInterface $this->eventDispatcher->notifyEvent( 'upgrade.config.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Update Configuration')) - ->addDetail(__u('Version'), $version)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Update Configuration')) + ->addDetail(__u('Version'), $version) + ) ); } @@ -260,27 +265,26 @@ final class UpgradeConfigService extends Service implements UpgradeInterface */ private function upgrade_300_18111001(string $version): void { - $extensions = array_map( - 'strtolower', - $this->configData->getFilesAllowedExts() - ); - $mimeTypes = $this->dic->get(MimeTypes::class)->getMimeTypes(); + $extensions = array_map('strtolower', $this->configData->getFilesAllowedExts()); $configMimeTypes = []; foreach ($extensions as $extension) { $exists = false; - foreach ($mimeTypes as $mimeType) { + foreach ($this->mimeTypes->getMimeTypes() as $mimeType) { if (strtolower($mimeType['extension']) === $extension) { $configMimeTypes[] = $mimeType['type']; $exists = true; $this->eventDispatcher->notifyEvent( 'upgrade.config.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('MIME type set for this extension')) - ->addDetail(__u('MIME type'), $mimeType['type']) - ->addDetail(__u('Extension'), $extension)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('MIME type set for this extension')) + ->addDetail(__u('MIME type'), $mimeType['type']) + ->addDetail(__u('Extension'), $extension) + ) ); } } @@ -288,9 +292,12 @@ final class UpgradeConfigService extends Service implements UpgradeInterface if (!$exists) { $this->eventDispatcher->notifyEvent( 'upgrade.config.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('MIME type not found for this extension')) - ->addDetail(__u('Extension'), $extension)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('MIME type not found for this extension')) + ->addDetail(__u('Extension'), $extension) + ) ); } } @@ -302,14 +309,17 @@ final class UpgradeConfigService extends Service implements UpgradeInterface $this->eventDispatcher->notifyEvent( 'upgrade.config.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Update Configuration')) - ->addDetail(__u('Version'), $version)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Update Configuration')) + ->addDetail(__u('Version'), $version) + ) ); } /** - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\File\FileException */ private function upgrade_300_18112501(string $version): void { @@ -326,15 +336,18 @@ final class UpgradeConfigService extends Service implements UpgradeInterface $this->eventDispatcher->notifyEvent( 'upgrade.config.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Update Configuration')) - ->addDetail(__u('Version'), $version)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Update Configuration')) + ->addDetail(__u('Version'), $version) + ) ); } } /** - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\File\FileException */ private function upgrade_320_20062801(string $version): void { @@ -349,15 +362,13 @@ final class UpgradeConfigService extends Service implements UpgradeInterface $this->eventDispatcher->notifyEvent( 'upgrade.config.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Update Configuration')) - ->addDetail(__u('Version'), $version)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Update Configuration')) + ->addDetail(__u('Version'), $version) + ) ); } } - - protected function initialize(): void - { - $this->eventDispatcher->attach($this->dic->get(FileLogHandler::class)); - } } \ No newline at end of file diff --git a/lib/SP/Domain/Config/UpgradeConfigServiceInterface.php b/lib/SP/Domain/Config/UpgradeConfigServiceInterface.php new file mode 100644 index 00000000..d97d88e9 --- /dev/null +++ b/lib/SP/Domain/Config/UpgradeConfigServiceInterface.php @@ -0,0 +1,43 @@ +. + */ + +namespace SP\Domain\Config; + + +use SP\Domain\Upgrade\UpgradeInterface; + +/** + * Class UpgradeService + * + * @package SP\Domain\Upgrade\Services + */ +interface UpgradeConfigServiceInterface extends UpgradeInterface +{ + /** + * Actualizar el archivo de configuración a formato XML + * + * @throws \SP\Domain\Upgrade\Services\UpgradeException + */ + public function upgradeOldConfigFile(string $version): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Crypt/MasterPassServiceInterface.php b/lib/SP/Domain/Crypt/MasterPassServiceInterface.php new file mode 100644 index 00000000..55f4f755 --- /dev/null +++ b/lib/SP/Domain/Crypt/MasterPassServiceInterface.php @@ -0,0 +1,64 @@ +. + */ + +namespace SP\Domain\Crypt; + + +use Exception; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; + +/** + * Class MasterPassService + * + * @package SP\Domain\Crypt\Services + */ +interface MasterPassServiceInterface +{ + /** + * @throws ServiceException + * @throws NoSuchItemException + */ + public function checkUserUpdateMPass(int $userMPassTime): bool; + + /** + * @throws ServiceException + * @throws NoSuchItemException + */ + public function checkMasterPassword(string $masterPassword): bool; + + /** + * @throws Exception + */ + public function changeMasterPassword(UpdateMasterPassRequest $request): void; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function updateConfig($hash): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Crypt/SecureSessionServiceInterface.php b/lib/SP/Domain/Crypt/SecureSessionServiceInterface.php new file mode 100644 index 00000000..93cf7645 --- /dev/null +++ b/lib/SP/Domain/Crypt/SecureSessionServiceInterface.php @@ -0,0 +1,48 @@ +. + */ + +namespace SP\Domain\Crypt; + + +use Defuse\Crypto\Key; +use SP\Core\Crypt\UUIDCookie; + +/** + * Class SecureSessionService + * + * @package SP\Domain\Crypt\Services + */ +interface SecureSessionServiceInterface +{ + /** + * Returns the encryption key + * + * @param UUIDCookie $cookie + * + * @return Key|false + */ + public function getKey(UUIDCookie $cookie); + + public function getFilename(): string; +} \ No newline at end of file diff --git a/lib/SP/Services/Crypt/MasterPassService.php b/lib/SP/Domain/Crypt/Services/MasterPassService.php similarity index 64% rename from lib/SP/Services/Crypt/MasterPassService.php rename to lib/SP/Domain/Crypt/Services/MasterPassService.php index 8e90d6b2..b8bee7b8 100644 --- a/lib/SP/Services/Crypt/MasterPassService.php +++ b/lib/SP/Domain/Crypt/Services/MasterPassService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,34 +22,49 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Crypt; +namespace SP\Domain\Crypt\Services; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Crypt\Hash; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountCryptService; -use SP\Services\Config\ConfigService; -use SP\Services\CustomField\CustomFieldCryptService; -use SP\Services\Service; -use SP\Services\ServiceException; +use SP\Domain\Account\AccountCryptServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Config\Services\ConfigService; +use SP\Domain\Crypt\MasterPassServiceInterface; +use SP\Domain\CustomField\CustomFieldCryptServiceInterface; +use SP\Domain\CustomField\Services\CustomFieldCryptService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; /** * Class MasterPassService * - * @package SP\Services\Crypt + * @package SP\Domain\Crypt\Services */ -final class MasterPassService extends Service +final class MasterPassService extends Service implements MasterPassServiceInterface { public const PARAM_MASTER_PASS_TIME = 'lastupdatempass'; public const PARAM_MASTER_PASS_HASH = 'masterPwd'; - protected ?ConfigService $configService = null; - protected ?AccountCryptService $accountCryptService = null; - protected ?CustomFieldCryptService $customFieldCryptService = null; + protected ConfigService $configService; + protected AccountCryptServiceInterface $accountCryptService; + protected CustomFieldCryptService $customFieldCryptService; + + public function __construct( + Application $application, + ConfigServiceInterface $configService, + AccountCryptServiceInterface $accountCryptService, + CustomFieldCryptServiceInterface $customFieldCryptService + ) { + parent::__construct($application); + + $this->configService = $configService; + $this->accountCryptService = $accountCryptService; + $this->customFieldCryptService = $customFieldCryptService; + } /** * @throws ServiceException @@ -100,15 +115,4 @@ final class MasterPassService extends Service $this->configService->save(self::PARAM_MASTER_PASS_HASH, $hash); $this->configService->save(self::PARAM_MASTER_PASS_TIME, time()); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->configService = $this->dic->get(ConfigService::class); - $this->accountCryptService = $this->dic->get(AccountCryptService::class); - $this->customFieldCryptService = $this->dic->get(CustomFieldCryptService::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Crypt/SecureSessionService.php b/lib/SP/Domain/Crypt/Services/SecureSessionService.php similarity index 72% rename from lib/SP/Services/Crypt/SecureSessionService.php rename to lib/SP/Domain/Crypt/Services/SecureSessionService.php index 40e504c0..f066adc7 100644 --- a/lib/SP/Services/Crypt/SecureSessionService.php +++ b/lib/SP/Domain/Crypt/Services/SecureSessionService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,37 +22,48 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Crypt; +namespace SP\Domain\Crypt\Services; use Defuse\Crypto\Key; use Exception; +use SP\Core\Application; use SP\Core\Crypt\UUIDCookie; use SP\Core\Crypt\Vault; -use SP\Http\Request; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\File\FileCache; -use SP\Storage\File\FileException; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Crypt\SecureSessionServiceInterface; +use SP\Http\RequestInterface; +use SP\Infrastructure\File\FileCache; +use SP\Infrastructure\File\FileException; /** * Class SecureSessionService * - * @package SP\Services\Crypt + * @package SP\Domain\Crypt\Services */ -final class SecureSessionService extends Service +final class SecureSessionService extends Service implements SecureSessionServiceInterface { private const CACHE_EXPIRE_TIME = 86400; - private const CACHE_PATH = CACHE_PATH . DIRECTORY_SEPARATOR . 'secure_session'; + private const CACHE_PATH = CACHE_PATH.DIRECTORY_SEPARATOR.'secure_session'; + + private RequestInterface $request; + private string $seed; + private ?UUIDCookie $cookie = null; + private ?string $filename = null; + + public function __construct(Application $application, RequestInterface $request) + { + parent::__construct($application); + + $this->request = $request; + $this->seed = $this->config->getConfigData()->getPasswordSalt(); + } - protected ?string $seed = null; - protected ?Request $request = null; - protected ?UUIDCookie $cookie = null; - private ?string $filename = null; /** * Returns the encryption key * - * @param UUIDCookie $cookie + * @param UUIDCookie $cookie * * @return Key|false */ @@ -95,7 +106,7 @@ final class SecureSessionService extends Service throw new ServiceException('Unable to get UUID for filename'); } - $this->filename = self::CACHE_PATH . DIRECTORY_SEPARATOR . $uuid; + $this->filename = self::CACHE_PATH.DIRECTORY_SEPARATOR.$uuid; } return $this->filename; @@ -113,8 +124,10 @@ final class SecureSessionService extends Service FileCache::factory($this->getFileNameFromCookie()) ->save( - (new Vault())->saveData($securedKey->saveToAsciiSafeString(), - $this->getCypher()) + (new Vault())->saveData( + $securedKey->saveToAsciiSafeString(), + $this->getCypher() + ) ); logger('Saved session key'); @@ -135,7 +148,7 @@ final class SecureSessionService extends Service return hash_pbkdf2( 'sha1', sha1( - $this->request->getHeader('User-Agent') . + $this->request->getHeader('User-Agent'). $this->request->getClientAddress() ), $this->seed, @@ -148,10 +161,4 @@ final class SecureSessionService extends Service { return $this->filename; } - - protected function initialize(): void - { - $this->request = $this->dic->get(Request::class); - $this->seed = $this->config->getConfigData()->getPasswordSalt(); - } } \ No newline at end of file diff --git a/lib/SP/Services/Crypt/TemporaryMasterPassService.php b/lib/SP/Domain/Crypt/Services/TemporaryMasterPassService.php similarity index 71% rename from lib/SP/Services/Crypt/TemporaryMasterPassService.php rename to lib/SP/Domain/Crypt/Services/TemporaryMasterPassService.php index 3e7d6559..124f5b67 100644 --- a/lib/SP/Services/Crypt/TemporaryMasterPassService.php +++ b/lib/SP/Domain/Crypt/Services/TemporaryMasterPassService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,33 +22,34 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Crypt; +namespace SP\Domain\Crypt\Services; use Defuse\Crypto\Exception\CryptoException; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; use SP\Core\AppInfoInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Hash; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Messages\MailMessage; use SP\DataModel\Dto\ConfigRequest; -use SP\Repositories\NoSuchItemException; -use SP\Services\Config\ConfigService; -use SP\Services\Mail\MailService; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\User\UserService; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Crypt\TemporaryMasterPassServiceInterface; +use SP\Domain\Notification\MailServiceInterface; +use SP\Domain\User\UserServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Util\PasswordUtil; /** * Class TemporaryMasterPassService * - * @package SP\Services\Crypt + * @package SP\Domain\Crypt\Services */ final class TemporaryMasterPassService extends Service + implements TemporaryMasterPassServiceInterface { /** * Número máximo de intentos @@ -57,22 +58,39 @@ final class TemporaryMasterPassService extends Service /** * Parámetros de configuración */ - private const PARAM_PASS = 'tempmaster_pass'; - private const PARAM_KEY = 'tempmaster_passkey'; - private const PARAM_HASH = 'tempmaster_passhash'; - public const PARAM_TIME = 'tempmaster_passtime'; - public const PARAM_MAX_TIME = 'tempmaster_maxtime'; - public const PARAM_ATTEMPTS = 'tempmaster_attempts'; - protected ?ConfigService $configService = null; - protected ?int $maxTime = null; + private const PARAM_PASS = 'tempmaster_pass'; + private const PARAM_KEY = 'tempmaster_passkey'; + private const PARAM_HASH = 'tempmaster_passhash'; + public const PARAM_TIME = 'tempmaster_passtime'; + public const PARAM_MAX_TIME = 'tempmaster_maxtime'; + public const PARAM_ATTEMPTS = 'tempmaster_attempts'; + + private ConfigServiceInterface $configService; + private UserServiceInterface $userService; + private MailServiceInterface $mailService; + private ?int $maxTime = null; + + public function __construct( + Application $application, + ConfigServiceInterface $configService, + UserServiceInterface $userService, + MailServiceInterface $mailService + ) { + parent::__construct($application); + + $this->configService = $configService; + $this->userService = $userService; + $this->mailService = $mailService; + } + /** * Crea una clave temporal para encriptar la clave maestra y guardarla. * - * @param int $maxTime El tiempo máximo de validez de la clave + * @param int $maxTime El tiempo máximo de validez de la clave * * @return string - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function create(int $maxTime = 14400): string { @@ -84,7 +102,10 @@ final class TemporaryMasterPassService extends Service $secureKey = Crypt::makeSecuredKey($randomKey); $configRequest = new ConfigRequest(); - $configRequest->add(self::PARAM_PASS, Crypt::encrypt($this->getMasterKeyFromContext(), $secureKey, $randomKey)); + $configRequest->add( + self::PARAM_PASS, + Crypt::encrypt($this->getMasterKeyFromContext(), $secureKey, $randomKey) + ); $configRequest->add(self::PARAM_KEY, $secureKey); $configRequest->add(self::PARAM_HASH, Hash::hashKey($randomKey)); $configRequest->add(self::PARAM_TIME, time()); @@ -98,8 +119,10 @@ final class TemporaryMasterPassService extends Service $this->eventDispatcher->notifyEvent( 'create.tempMasterPassword', - new Event($this, EventMessage::factory() - ->addDescription(__u('Generate temporary password'))) + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Generate temporary password')) + ) ); return $randomKey; @@ -113,10 +136,10 @@ final class TemporaryMasterPassService extends Service /** * Comprueba si la clave temporal es válida * - * @param string $pass clave a comprobar + * @param string $pass clave a comprobar * * @return bool - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function checkTempMasterPass(string $pass): bool { @@ -171,7 +194,7 @@ final class TemporaryMasterPassService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ protected function expire(): void { @@ -187,15 +210,17 @@ final class TemporaryMasterPassService extends Service $this->eventDispatcher->notifyEvent( 'expire.tempMasterPassword', - new Event($this, EventMessage::factory() - ->addDescription(__u('Temporary password expired'))) + new Event( + $this, EventMessage::factory() + ->addDescription(__u('Temporary password expired')) + ) ); } /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws \PHPMailer\PHPMailer\Exception */ public function sendByEmailForGroup(int $groupId, string $key): void @@ -206,18 +231,21 @@ final class TemporaryMasterPassService extends Service static function ($value) { return $value->email; }, - $this->dic->get(UserService::class)->getUserEmailForGroup($groupId) + $this->userService->getUserEmailForGroup($groupId) ); - $this->dic->get(MailService::class) - ->sendBatch($mailMessage->getTitle(), $emails, $mailMessage); + $this->mailService->sendBatch($mailMessage->getTitle(), $emails, $mailMessage); } private function getMessageForEmail(string $key): MailMessage { $mailMessage = new MailMessage(); $mailMessage->setTitle(sprintf(__('%s Master Password'), AppInfoInterface::APP_NAME)); - $mailMessage->addDescription(__('A new sysPass master password has been generated, so next time you log into the application it will be requested.')); + $mailMessage->addDescription( + __( + 'A new sysPass master password has been generated, so next time you log into the application it will be requested.' + ) + ); $mailMessage->addDescription(sprintf(__('The new Master Password is: %s'), $key)); $mailMessage->addDescription(sprintf(__('This password will be valid until: %s'), date('r', $this->maxTime))); $mailMessage->addDescription(__('Please, don\'t forget to log in as soon as possible to save the changes.')); @@ -229,7 +257,7 @@ final class TemporaryMasterPassService extends Service * @throws \PHPMailer\PHPMailer\Exception * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function sendByEmailForAllUsers(string $key): void { @@ -239,11 +267,10 @@ final class TemporaryMasterPassService extends Service static function ($value) { return $value->email; }, - $this->dic->get(UserService::class)->getUserEmailForAll() + $this->userService->getUserEmailForAll() ); - $this->dic->get(MailService::class) - ->sendBatch($mailMessage->getTitle(), $emails, $mailMessage); + $this->mailService->sendBatch($mailMessage->getTitle(), $emails, $mailMessage); } /** @@ -253,7 +280,7 @@ final class TemporaryMasterPassService extends Service * * @return string con la clave maestra desencriptada * @throws NoSuchItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws CryptoException */ public function getUsingKey(string $key): string @@ -264,13 +291,4 @@ final class TemporaryMasterPassService extends Service $key ); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->configService = $this->dic->get(ConfigService::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Crypt/UpdateMasterPassRequest.php b/lib/SP/Domain/Crypt/Services/UpdateMasterPassRequest.php similarity index 81% rename from lib/SP/Services/Crypt/UpdateMasterPassRequest.php rename to lib/SP/Domain/Crypt/Services/UpdateMasterPassRequest.php index 5fea5004..05b5efd8 100644 --- a/lib/SP/Services/Crypt/UpdateMasterPassRequest.php +++ b/lib/SP/Domain/Crypt/Services/UpdateMasterPassRequest.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,40 +22,39 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Crypt; +namespace SP\Domain\Crypt\Services; use SP\Core\Crypt\Hash; -use SP\Services\Task\Task; +use SP\Domain\Task\Services\Task; /** * Class UpdateMasterPassRequest * - * @package SP\Services\Crypt + * @package SP\Domain\Crypt\Services */ final class UpdateMasterPassRequest { private string $currentMasterPass; private string $newMasterPass; - private ?Task $task; + private ?Task $task; private string $hash; private string $currentHash; /** * UpdateMasterPassRequest constructor. * - * @param string $currentMasterPass - * @param string $newMasterPass - * @param string $currentHash - * @param \SP\Services\Task\Task|null $task + * @param string $currentMasterPass + * @param string $newMasterPass + * @param string $currentHash + * @param \SP\Domain\Task\Services\Task|null $task */ public function __construct( string $currentMasterPass, string $newMasterPass, string $currentHash, - ?Task $task = null - ) - { + ?Task $task = null + ) { $this->currentMasterPass = $currentMasterPass; $this->newMasterPass = $newMasterPass; $this->task = $task; diff --git a/lib/SP/Domain/Crypt/TemporaryMasterPassServiceInterface.php b/lib/SP/Domain/Crypt/TemporaryMasterPassServiceInterface.php new file mode 100644 index 00000000..7063dba7 --- /dev/null +++ b/lib/SP/Domain/Crypt/TemporaryMasterPassServiceInterface.php @@ -0,0 +1,85 @@ +. + */ + +namespace SP\Domain\Crypt; + + +use Defuse\Crypto\Exception\CryptoException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; + +/** + * Class TemporaryMasterPassService + * + * @package SP\Domain\Crypt\Services + */ +interface TemporaryMasterPassServiceInterface +{ + /** + * Crea una clave temporal para encriptar la clave maestra y guardarla. + * + * @param int $maxTime El tiempo máximo de validez de la clave + * + * @return string + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function create(int $maxTime = 14400): string; + + /** + * Comprueba si la clave temporal es válida + * + * @param string $pass clave a comprobar + * + * @return bool + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function checkTempMasterPass(string $pass): bool; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \PHPMailer\PHPMailer\Exception + */ + public function sendByEmailForGroup(int $groupId, string $key): void; + + /** + * @throws \PHPMailer\PHPMailer\Exception + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function sendByEmailForAllUsers(string $key): void; + + /** + * Devuelve la clave maestra que ha sido encriptada con la clave temporal + * + * @param $key string con la clave utilizada para encriptar + * + * @return string con la clave maestra desencriptada + * @throws NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws CryptoException + */ + public function getUsingKey(string $key): string; +} \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/CustomFieldCryptServiceInterface.php b/lib/SP/Domain/CustomField/CustomFieldCryptServiceInterface.php new file mode 100644 index 00000000..f63f245c --- /dev/null +++ b/lib/SP/Domain/CustomField/CustomFieldCryptServiceInterface.php @@ -0,0 +1,46 @@ +. + */ + +namespace SP\Domain\CustomField; + + +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; + +/** + * Class CustomFieldCryptService + * + * @package SP\Mgmt\CustomFields + */ +interface CustomFieldCryptServiceInterface +{ + /** + * Actualizar los datos encriptados con una nueva clave + * + * @param UpdateMasterPassRequest $request + * + * @throws ServiceException + */ + public function updateMasterPassword(UpdateMasterPassRequest $request): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/CustomFieldDefServiceInterface.php b/lib/SP/Domain/CustomField/CustomFieldDefServiceInterface.php new file mode 100644 index 00000000..704de1f7 --- /dev/null +++ b/lib/SP/Domain/CustomField/CustomFieldDefServiceInterface.php @@ -0,0 +1,99 @@ +. + */ + +namespace SP\Domain\CustomField; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\CustomFieldDefinitionData; +use SP\DataModel\ItemSearchData; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\CustomField\Services\CustomFieldDefService; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class CustomFieldDefService + * + * @package SP\Domain\CustomField\Services + */ +interface CustomFieldDefServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function delete(int $id): CustomFieldDefService; + + /** + * Deletes all the items for given ids + * + * @param int[] $ids + * + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function deleteByIdBatch(array $ids): void; + + /** + * @param \SP\DataModel\CustomFieldDefinitionData $itemData + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function create(CustomFieldDefinitionData $itemData): int; + + /** + * @throws ServiceException + */ + public function update(CustomFieldDefinitionData $itemData); + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id): CustomFieldDefinitionData; + + /** + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function updateRaw(CustomFieldDefinitionData $itemData): void; + + /** + * Get all items from the service's repository + * + * @return CustomFieldDefinitionData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/CustomFieldServiceInterface.php b/lib/SP/Domain/CustomField/CustomFieldServiceInterface.php new file mode 100644 index 00000000..f833d19e --- /dev/null +++ b/lib/SP/Domain/CustomField/CustomFieldServiceInterface.php @@ -0,0 +1,140 @@ +. + */ + +namespace SP\Domain\CustomField; + + +use Defuse\Crypto\Exception\CryptoException; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\CustomFieldData; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; + +/** + * Class CustomFieldService + * + * @package SP\Domain\CustomField\Services + */ +interface CustomFieldServiceInterface +{ + /** + * Desencriptar y formatear los datos del campo + * + * @throws CryptoException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function decryptData(string $data, string $key): string; + + /** + * Returns the module's item for given id + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getForModuleAndItemId(int $moduleId, ?int $itemId): array; + + /** + * Updates an item + * + * @throws CryptoException + * @throws QueryException + * @throws ConstraintException + * @throws SPException + */ + public function updateOrCreateData(CustomFieldData $customFieldData): bool; + + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @throws SPException + */ + public function deleteCustomFieldData(int $itemId, int $moduleId, ?int $definitionId = null): int; + + /** + * Creates an item + * + * @throws CryptoException + * @throws QueryException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws NoSuchItemException + */ + public function create(CustomFieldData $customFieldData): bool; + + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @throws QueryException + * @throws ConstraintException + */ + public function deleteCustomFieldDefinitionData(int $definitionId): int; + + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @param int[] $ids + * @param int $moduleId + * + * @return bool + * @throws QueryException + * @throws ConstraintException + */ + public function deleteCustomFieldDataBatch(array $ids, int $moduleId): bool; + + /** + * Eliminar los datos de los elementos de una definición + * + * @param int[] $definitionIds + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteCustomFieldDefinitionDataBatch(array $definitionIds): int; + + /** + * Updates an item + * + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function updateMasterPass(CustomFieldData $customFieldData, string $masterPass): int; + + /** + * @return CustomFieldData[] + * @throws QueryException + * @throws ConstraintException + */ + public function getAll(): array; + + /** + * @return CustomFieldData[] + * @throws QueryException + * @throws ConstraintException + */ + public function getAllEncrypted(): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/CustomFieldTypeServiceInterface.php b/lib/SP/Domain/CustomField/CustomFieldTypeServiceInterface.php new file mode 100644 index 00000000..2357e1ef --- /dev/null +++ b/lib/SP/Domain/CustomField/CustomFieldTypeServiceInterface.php @@ -0,0 +1,63 @@ +. + */ + +namespace SP\Domain\CustomField; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\CustomFieldTypeData; + +/** + * Class CustomFieldTypeService + * + * @package SP\Domain\CustomField\Services + */ +interface CustomFieldTypeServiceInterface +{ + /** + * Get all items from the service's repository + * + * @return CustomFieldTypeData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; + + /** + * Returns all the items + * + * @return CustomFieldTypeData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): array; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id); +} \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/In/CustomFieldDefRepositoryInterface.php b/lib/SP/Domain/CustomField/In/CustomFieldDefRepositoryInterface.php new file mode 100644 index 00000000..fc587697 --- /dev/null +++ b/lib/SP/Domain/CustomField/In/CustomFieldDefRepositoryInterface.php @@ -0,0 +1,41 @@ +. + */ + +namespace SP\Domain\CustomField\In; + + +use SP\Domain\Common\In\RepositoryInterface; + +/** + * Class CustomFieldDefRepository + * + * @package SP\Infrastructure\CustomField\Repositories + */ +interface CustomFieldDefRepositoryInterface extends RepositoryInterface +{ + /** + * Resets the custom fields collection cache + */ + public function resetCollection(): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/In/CustomFieldRepositoryInterface.php b/lib/SP/Domain/CustomField/In/CustomFieldRepositoryInterface.php new file mode 100644 index 00000000..40035707 --- /dev/null +++ b/lib/SP/Domain/CustomField/In/CustomFieldRepositoryInterface.php @@ -0,0 +1,131 @@ +. + */ + +namespace SP\Domain\CustomField\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\CustomFieldData; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class CustomFieldRepository + * + * @package SP\Domain\Common\Services + */ +interface CustomFieldRepositoryInterface extends RepositoryInterface +{ + /** + * Comprueba si el elemento tiene campos personalizados con datos + * + * @param CustomFieldData $itemData + * + * @return bool + * @throws QueryException + * @throws ConstraintException + */ + public function checkExists(CustomFieldData $itemData): bool; + + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @param int $itemId + * @param int $moduleId + * + * @return int + * @throws QueryException + * @throws ConstraintException + */ + public function deleteCustomFieldData(int $itemId, int $moduleId): int; + + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @param int $id + * @param int $moduleId + * @param int|null $definitionId + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteCustomFieldDataForDefinition(int $id, int $moduleId, ?int $definitionId): int; + + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @param int $definitionId + * + * @return int + * @throws QueryException + * @throws ConstraintException + */ + public function deleteCustomFieldDefinitionData(int $definitionId): int; + + /** + * Eliminar los datos de los elementos de una definición + * + * @param array $definitionIds + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteCustomFieldDefinitionDataBatch(array $definitionIds): int; + + /** + * Eliminar los datos de los campos personalizados del módulo + * + * @param int[] $ids + * @param int $moduleId + * + * @return int + * @throws QueryException + * @throws ConstraintException + */ + public function deleteCustomFieldDataBatch(array $ids, int $moduleId): int; + + /** + * Returns all the items that were encryptes + * + * @return QueryResult + * @throws QueryException + * @throws ConstraintException + */ + public function getAllEncrypted(): QueryResult; + + /** + * Returns the module's item for given id + * + * @param int $moduleId + * @param int|null $itemId + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getForModuleAndItemId(int $moduleId, ?int $itemId): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/In/CustomFieldTypeRepositoryInterface.php b/lib/SP/Domain/CustomField/In/CustomFieldTypeRepositoryInterface.php new file mode 100644 index 00000000..a2d1ebcb --- /dev/null +++ b/lib/SP/Domain/CustomField/In/CustomFieldTypeRepositoryInterface.php @@ -0,0 +1,37 @@ +. + */ + +namespace SP\Domain\CustomField\In; + + +use SP\Domain\Common\In\RepositoryInterface; + +/** + * Class CustomFieldTypeRepository + * + * @package SP\Infrastructure\CustomField\Repositories + */ +interface CustomFieldTypeRepositoryInterface extends RepositoryInterface +{ +} \ No newline at end of file diff --git a/lib/SP/Services/CustomField/CustomFieldCryptService.php b/lib/SP/Domain/CustomField/Services/CustomFieldCryptService.php similarity index 67% rename from lib/SP/Services/CustomField/CustomFieldCryptService.php rename to lib/SP/Domain/CustomField/Services/CustomFieldCryptService.php index a9d5691a..40023b69 100644 --- a/lib/SP/Services/CustomField/CustomFieldCryptService.php +++ b/lib/SP/Domain/CustomField/Services/CustomFieldCryptService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,13 +22,12 @@ * along with sysPass. If not, see . */ -namespace SP\Services\CustomField; +namespace SP\Domain\CustomField\Services; defined('APP_ROOT') || die(); use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; @@ -36,25 +35,34 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldData; -use SP\Services\Crypt\UpdateMasterPassRequest; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\Task\TaskFactory; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; +use SP\Domain\CustomField\CustomFieldCryptServiceInterface; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Domain\Task\Services\TaskFactory; /** * Class CustomFieldCryptService * * @package SP\Mgmt\CustomFields */ -final class CustomFieldCryptService extends Service +final class CustomFieldCryptService extends Service implements CustomFieldCryptServiceInterface { - protected ?CustomFieldService $customFieldService = null; - protected ?UpdateMasterPassRequest $request = null; + private CustomFieldService $customFieldService; + private ?UpdateMasterPassRequest $request = null; + + public function __construct(Application $application, CustomFieldServiceInterface $customFieldService) + { + parent::__construct($application); + + $this->customFieldService = $customFieldService; + } /** * Actualizar los datos encriptados con una nueva clave * - * @param UpdateMasterPassRequest $request + * @param UpdateMasterPassRequest $request * * @throws ServiceException */ @@ -68,7 +76,8 @@ final class CustomFieldCryptService extends Service return Crypt::decrypt( $customFieldData->getData(), $customFieldData->getKey(), - $this->request->getCurrentMasterPass()); + $this->request->getCurrentMasterPass() + ); } ); } catch (Exception $e) { @@ -79,7 +88,8 @@ final class CustomFieldCryptService extends Service SPException::ERROR, null, $e->getCode(), - $e); + $e + ); } } @@ -92,28 +102,37 @@ final class CustomFieldCryptService extends Service $customFields = $this->customFieldService->getAllEncrypted(); if (count($customFields) === 0) { - $this->eventDispatcher->notifyEvent('update.masterPassword.customFields', - new Event($this, EventMessage::factory() + $this->eventDispatcher->notifyEvent( + 'update.masterPassword.customFields', + new Event( + $this, EventMessage::factory() ->addDescription(__u('Update Master Password')) - ->addDescription(__u('There aren\'t any data from custom fields'))) + ->addDescription(__u('There aren\'t any data from custom fields')) + ) ); + return; } - $this->eventDispatcher->notifyEvent('update.masterPassword.customFields.start', - new Event($this, EventMessage::factory() + $this->eventDispatcher->notifyEvent( + 'update.masterPassword.customFields.start', + new Event( + $this, EventMessage::factory() ->addDescription(__u('Update Master Password')) - ->addDescription(__u('Updating encrypted data'))) + ->addDescription(__u('Updating encrypted data')) + ) ); if ($this->request->useTask()) { $task = $this->request->getTask(); - TaskFactory::update($task, + TaskFactory::update( + $task, TaskFactory::createMessage( $task->getTaskId(), __('Update Master Password') - )->setMessage(__('Updating encrypted data'))); + )->setMessage(__('Updating encrypted data')) + ); } $errors = []; @@ -138,20 +157,14 @@ final class CustomFieldCryptService extends Service } } - $this->eventDispatcher->notifyEvent('update.masterPassword.customFields.end', - new Event($this, EventMessage::factory() + $this->eventDispatcher->notifyEvent( + 'update.masterPassword.customFields.end', + new Event( + $this, EventMessage::factory() ->addDescription(__u('Update Master Password')) ->addDetail(__u('Records updated'), implode(',', $success)) - ->addDetail(__u('Records not updated'), implode(',', $errors))) + ->addDetail(__u('Records not updated'), implode(',', $errors)) + ) ); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->customFieldService = $this->dic->get(CustomFieldService::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/CustomField/CustomFieldDefService.php b/lib/SP/Domain/CustomField/Services/CustomFieldDefService.php similarity index 65% rename from lib/SP/Services/CustomField/CustomFieldDefService.php rename to lib/SP/Domain/CustomField/Services/CustomFieldDefService.php index 29c414d1..81081f03 100644 --- a/lib/SP/Services/CustomField/CustomFieldDefService.php +++ b/lib/SP/Domain/CustomField/Services/CustomFieldDefService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,33 +22,51 @@ * along with sysPass. If not, see . */ -namespace SP\Services\CustomField; +namespace SP\Domain\CustomField\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldDefinitionData; use SP\DataModel\ItemSearchData; -use SP\Repositories\CustomField\CustomFieldDefRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\CustomField\CustomFieldDefServiceInterface; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Domain\CustomField\In\CustomFieldDefRepositoryInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\DatabaseInterface; +use SP\Infrastructure\Database\QueryResult; /** * Class CustomFieldDefService * - * @package SP\Services\CustomField + * @package SP\Domain\CustomField\Services */ -final class CustomFieldDefService extends Service +final class CustomFieldDefService extends Service implements CustomFieldDefServiceInterface { use ServiceItemTrait; - protected ?CustomFieldDefRepository $customFieldDefRepository = null; + protected CustomFieldDefRepositoryInterface $customFieldDefRepository; + protected CustomFieldServiceInterface $customFieldService; + private DatabaseInterface $database; + + public function __construct( + Application $application, + CustomFieldDefRepositoryInterface $customFieldDefRepository, + CustomFieldServiceInterface $customFieldService, + DatabaseInterface $database + ) { + parent::__construct($application); + + $this->customFieldDefRepository = $customFieldDefRepository; + $this->customFieldService = $customFieldService; + $this->database = $database; + } + /** * @param $id @@ -68,11 +86,11 @@ final class CustomFieldDefService extends Service public static function getFieldModules(): array { return [ - ActionsInterface::ACCOUNT => __('Accounts'), + ActionsInterface::ACCOUNT => __('Accounts'), ActionsInterface::CATEGORY => __('Categories'), - ActionsInterface::CLIENT => __('Clients'), - ActionsInterface::USER => __('Users'), - ActionsInterface::GROUP => __('Groups') + ActionsInterface::CLIENT => __('Clients'), + ActionsInterface::USER => __('Users'), + ActionsInterface::GROUP => __('Groups'), ]; } @@ -86,22 +104,19 @@ final class CustomFieldDefService extends Service } /** - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function delete(int $id): CustomFieldDefService { $this->transactionAware( function () use ($id) { - $this->dic->get(CustomFieldService::class) - ->deleteCustomFieldDefinitionData($id); + $this->customFieldService->deleteCustomFieldDefinitionData($id); if ($this->customFieldDefRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Field not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Field not found'), SPException::INFO); } - } + }, + $this->database ); return $this; @@ -110,7 +125,7 @@ final class CustomFieldDefService extends Service /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @throws ServiceException */ @@ -118,8 +133,7 @@ final class CustomFieldDefService extends Service { $this->transactionAware( function () use ($ids) { - $this->dic->get(CustomFieldService::class) - ->deleteCustomFieldDefinitionDataBatch($ids); + $this->customFieldService->deleteCustomFieldDefinitionDataBatch($ids); if ($this->customFieldDefRepository->deleteByIdBatch($ids) !== count($ids)) { throw new ServiceException( @@ -127,12 +141,13 @@ final class CustomFieldDefService extends Service SPException::WARNING ); } - } + }, + $this->database ); } /** - * @param \SP\DataModel\CustomFieldDefinitionData $itemData + * @param \SP\DataModel\CustomFieldDefinitionData $itemData * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -143,38 +158,6 @@ final class CustomFieldDefService extends Service return $this->customFieldDefRepository->create($itemData); } - /** - * @throws ServiceException - */ - public function update(CustomFieldDefinitionData $itemData) - { - return $this->transactionAware( - function () use ($itemData) { - $customFieldDefinitionData = $this->getById($itemData->getId()); - - // Delete the data used by the items using the previous definition - if ($customFieldDefinitionData->getModuleId() !== $itemData->moduleId) { - $this->dic->get(CustomFieldService::class) - ->deleteCustomFieldDefinitionData($customFieldDefinitionData->getId()); - } - - if ($this->customFieldDefRepository->update($itemData) !== 1) { - throw new ServiceException(__u('Error while updating the custom field')); - } - } - ); - } - - /** - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException - */ - public function getById(int $id): CustomFieldDefinitionData - { - return $this->customFieldDefRepository->getById($id); - } - /** * @throws ServiceException * @throws ConstraintException @@ -187,6 +170,38 @@ final class CustomFieldDefService extends Service } } + /** + * @throws ServiceException + */ + public function update(CustomFieldDefinitionData $itemData) + { + return $this->transactionAware( + function () use ($itemData) { + $customFieldDefinitionData = $this->getById($itemData->getId()); + + // Delete the data used by the items using the previous definition + if ($customFieldDefinitionData->getModuleId() !== $itemData->moduleId) { + $this->customFieldService->deleteCustomFieldDefinitionData($customFieldDefinitionData->getId()); + } + + if ($this->customFieldDefRepository->update($itemData) !== 1) { + throw new ServiceException(__u('Error while updating the custom field')); + } + }, + $this->database + ); + } + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id): CustomFieldDefinitionData + { + return $this->customFieldDefRepository->getById($id); + } + /** * Get all items from the service's repository * @@ -198,13 +213,4 @@ final class CustomFieldDefService extends Service { return $this->customFieldDefRepository->getAll()->getDataAsArray(); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->customFieldDefRepository = $this->dic->get(CustomFieldDefRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/CustomField/CustomFieldItem.php b/lib/SP/Domain/CustomField/Services/CustomFieldItem.php similarity index 60% rename from lib/SP/Services/CustomField/CustomFieldItem.php rename to lib/SP/Domain/CustomField/Services/CustomFieldItem.php index b4dccb82..d590f40a 100644 --- a/lib/SP/Services/CustomField/CustomFieldItem.php +++ b/lib/SP/Domain/CustomField/Services/CustomFieldItem.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,26 +22,26 @@ * along with sysPass. If not, see . */ -namespace SP\Services\CustomField; +namespace SP\Domain\CustomField\Services; use JsonSerializable; /** * Class CustomFieldItem * - * @package SP\Services\CustomField + * @package SP\Domain\CustomField\Services */ final class CustomFieldItem implements JsonSerializable { - public $required = false; - public $showInList = false; + public $required = false; + public $showInList = false; public $help; public $definitionId = 0; public $definitionName; - public $typeId = 0; + public $typeId = 0; public $typeName; public $typeText; - public $moduleId = 0; + public $moduleId = 0; public $formId; public $value; public $isEncrypted; @@ -53,16 +53,16 @@ final class CustomFieldItem implements JsonSerializable public function jsonSerialize() { return [ - 'required' => $this->required, - 'showInList' => $this->showInList, - 'help' => $this->help, - 'typeId' => $this->typeId, - 'typeName' => $this->typeName, - 'typeText' => $this->typeText, - 'moduleId' => $this->moduleId, - 'value' => $this->value, - 'isEncrypted' => $this->isEncrypted, - 'isValueEncrypted' => $this->isValueEncrypted + 'required' => $this->required, + 'showInList' => $this->showInList, + 'help' => $this->help, + 'typeId' => $this->typeId, + 'typeName' => $this->typeName, + 'typeText' => $this->typeText, + 'moduleId' => $this->moduleId, + 'value' => $this->value, + 'isEncrypted' => $this->isEncrypted, + 'isValueEncrypted' => $this->isValueEncrypted, ]; } } \ No newline at end of file diff --git a/lib/SP/Services/CustomField/CustomFieldService.php b/lib/SP/Domain/CustomField/Services/CustomFieldService.php similarity index 70% rename from lib/SP/Services/CustomField/CustomFieldService.php rename to lib/SP/Domain/CustomField/Services/CustomFieldService.php index 6a62b7dc..28697169 100644 --- a/lib/SP/Services/CustomField/CustomFieldService.php +++ b/lib/SP/Domain/CustomField/Services/CustomFieldService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,40 +22,50 @@ * along with sysPass. If not, see . */ -namespace SP\Services\CustomField; +namespace SP\Domain\CustomField\Services; use Defuse\Crypto\Exception\CryptoException; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldData; -use SP\Repositories\CustomField\CustomFieldRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Domain\CustomField\In\CustomFieldRepositoryInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\CustomField\Repositories\CustomFieldRepository; /** * Class CustomFieldService * - * @package SP\Services\CustomField + * @package SP\Domain\CustomField\Services */ -final class CustomFieldService extends Service +final class CustomFieldService extends Service implements CustomFieldServiceInterface { - protected ?CustomFieldRepository $customFieldRepository = null; - protected ?CustomFieldDefService $customFieldDefService = null; + protected CustomFieldRepository $customFieldRepository; + protected CustomFieldDefService $customFieldDefService; + + public function __construct( + Application $application, + CustomFieldRepositoryInterface $customFieldRepository, + CustomFieldDefService $customFieldDefService + ) { + parent::__construct($application); + + $this->customFieldRepository = $customFieldRepository; + $this->customFieldDefService = $customFieldDefService; + } + /** * Returns the form Id for a given name */ public static function getFormIdForName(string $name): string { - return sprintf( - 'cf_%s', - strtolower(preg_replace('/\W*/', '', $name)) - ); + return sprintf('cf_%s', strtolower(preg_replace('/\W*/', '', $name))); } /** @@ -67,10 +77,7 @@ final class CustomFieldService extends Service public function decryptData(string $data, string $key): string { if (!empty($data) && !empty($key)) { - return self::formatValue( - Crypt::decrypt($data, $key, - $this->getMasterKeyFromContext()) - ); + return self::formatValue(Crypt::decrypt($data, $key, $this->getMasterKeyFromContext())); } return ''; @@ -86,11 +93,7 @@ final class CustomFieldService extends Service public static function formatValue(string $value): string { if (preg_match('#https?://#', $value)) { - return sprintf( - '%s', - $value, - $value - ); + return sprintf('%s', $value, $value); } return $value; @@ -104,9 +107,7 @@ final class CustomFieldService extends Service */ public function getForModuleAndItemId(int $moduleId, ?int $itemId): array { - return $this->customFieldRepository - ->getForModuleAndItemId($moduleId, $itemId) - ->getDataAsArray(); + return $this->customFieldRepository->getForModuleAndItemId($moduleId, $itemId)->getDataAsArray(); } /** @@ -147,11 +148,7 @@ final class CustomFieldService extends Service * * @throws SPException */ - public function deleteCustomFieldData( - int $itemId, - int $moduleId, - ?int $definitionId = null - ): int + public function deleteCustomFieldData(int $itemId, int $moduleId, ?int $definitionId = null): int { if ($definitionId === null) { return $this->customFieldRepository->deleteCustomFieldData($itemId, $moduleId); @@ -184,28 +181,18 @@ final class CustomFieldService extends Service /** * @throws \Defuse\Crypto\Exception\CryptoException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ - protected function setSecureData( - CustomFieldData $customFieldData, - ?string $key = null - ): void + protected function setSecureData(CustomFieldData $customFieldData, ?string $key = null): void { $key = $key ?: $this->getMasterKeyFromContext(); $securedKey = Crypt::makeSecuredKey($key); if (strlen($securedKey) > 1000) { - throw new ServiceException( - __u('Internal error'), - SPException::ERROR - ); + throw new ServiceException(__u('Internal error'), SPException::ERROR); } - $customFieldData->setData(Crypt::encrypt( - $customFieldData->getData(), - $securedKey, - $key - )); + $customFieldData->setData(Crypt::encrypt($customFieldData->getData(), $securedKey, $key)); $customFieldData->setKey($securedKey); } @@ -217,15 +204,14 @@ final class CustomFieldService extends Service */ public function deleteCustomFieldDefinitionData(int $definitionId): int { - return $this->customFieldRepository - ->deleteCustomFieldDefinitionData($definitionId); + return $this->customFieldRepository->deleteCustomFieldDefinitionData($definitionId); } /** * Eliminar los datos de los campos personalizados del módulo * - * @param int[] $ids - * @param int $moduleId + * @param int[] $ids + * @param int $moduleId * * @return bool * @throws QueryException @@ -233,14 +219,13 @@ final class CustomFieldService extends Service */ public function deleteCustomFieldDataBatch(array $ids, int $moduleId): bool { - return $this->customFieldRepository - ->deleteCustomFieldDataBatch($ids, $moduleId); + return $this->customFieldRepository->deleteCustomFieldDataBatch($ids, $moduleId); } /** * Eliminar los datos de los elementos de una definición * - * @param int[] $definitionIds + * @param int[] $definitionIds * * @return int * @throws ConstraintException @@ -248,8 +233,7 @@ final class CustomFieldService extends Service */ public function deleteCustomFieldDefinitionDataBatch(array $definitionIds): int { - return $this->customFieldRepository - ->deleteCustomFieldDefinitionDataBatch($definitionIds); + return $this->customFieldRepository->deleteCustomFieldDefinitionDataBatch($definitionIds); } /** @@ -258,12 +242,9 @@ final class CustomFieldService extends Service * @throws \Defuse\Crypto\Exception\CryptoException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ - public function updateMasterPass( - CustomFieldData $customFieldData, - string $masterPass - ): int + public function updateMasterPass(CustomFieldData $customFieldData, string $masterPass): int { $this->setSecureData($customFieldData, $masterPass); @@ -289,14 +270,4 @@ final class CustomFieldService extends Service { return $this->customFieldRepository->getAllEncrypted()->getDataAsArray(); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->customFieldRepository = $this->dic->get(CustomFieldRepository::class); - $this->customFieldDefService = $this->dic->get(CustomFieldDefService::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/CustomField/CustomFieldTypeService.php b/lib/SP/Domain/CustomField/Services/CustomFieldTypeService.php similarity index 65% rename from lib/SP/Services/CustomField/CustomFieldTypeService.php rename to lib/SP/Domain/CustomField/Services/CustomFieldTypeService.php index c90c9bb2..35a6775d 100644 --- a/lib/SP/Services/CustomField/CustomFieldTypeService.php +++ b/lib/SP/Domain/CustomField/Services/CustomFieldTypeService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,26 +22,36 @@ * along with sysPass. If not, see . */ -namespace SP\Services\CustomField; +namespace SP\Domain\CustomField\Services; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\CustomFieldTypeData; -use SP\Repositories\CustomField\CustomFieldTypeRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceItemTrait; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\CustomField\CustomFieldTypeServiceInterface; +use SP\Domain\CustomField\In\CustomFieldTypeRepositoryInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\CustomField\Repositories\CustomFieldTypeRepository; /** * Class CustomFieldTypeService * - * @package SP\Services\CustomField + * @package SP\Domain\CustomField\Services */ -final class CustomFieldTypeService extends Service +final class CustomFieldTypeService extends Service implements CustomFieldTypeServiceInterface { use ServiceItemTrait; - protected ?CustomFieldTypeRepository $customFieldTypeRepository = null; + private CustomFieldTypeRepository $customFieldTypeRepository; + + public function __construct(Application $application, CustomFieldTypeRepositoryInterface $customFieldTypeRepository) + { + parent::__construct($application); + + $this->customFieldTypeRepository = $customFieldTypeRepository; + } /** * Get all items from the service's repository @@ -70,7 +80,7 @@ final class CustomFieldTypeService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function getById(int $id) { @@ -82,9 +92,4 @@ final class CustomFieldTypeService extends Service return $result->getData(); } - - protected function initialize(): void - { - $this->customFieldTypeRepository = $this->dic->get(CustomFieldTypeRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Upgrade/UpgradeCustomFieldData.php b/lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDataService.php similarity index 55% rename from lib/SP/Services/Upgrade/UpgradeCustomFieldData.php rename to lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDataService.php index 4cfbedca..cec54cc2 100644 --- a/lib/SP/Services/Upgrade/UpgradeCustomFieldData.php +++ b/lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDataService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,26 +22,41 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\CustomField\Services; use Exception; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Services\CustomField\CustomFieldService; -use SP\Services\Service; -use SP\Storage\Database\Database; -use SP\Storage\Database\QueryData; +use SP\Domain\Common\Services\Service; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Domain\CustomField\UpgradeCustomFieldDataServiceInterface; +use SP\Infrastructure\Database\DatabaseInterface; +use SP\Infrastructure\Database\QueryData; /** * Class UpgradeCustomFieldData * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ -final class UpgradeCustomFieldData extends Service +final class UpgradeCustomFieldDataService extends Service + implements UpgradeCustomFieldDataServiceInterface { - private ?Database $db = null; + private CustomFieldServiceInterface $customFieldService; + private DatabaseInterface $database; + + public function __construct( + Application $application, + CustomFieldServiceInterface $customFieldService, + DatabaseInterface $database + ) { + parent::__construct($application); + + $this->database = $database; + $this->customFieldService = $customFieldService; + } /** * upgrade_300_18072902 @@ -52,45 +67,48 @@ final class UpgradeCustomFieldData extends Service { $this->eventDispatcher->notifyEvent( 'upgrade.customField.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('Custom fields update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Custom fields update')) + ->addDescription(__FUNCTION__) + ) ); try { $this->transactionAware(function () { - $customFieldService = $this->dic->get(CustomFieldService::class); - - foreach ($customFieldService->getAll() as $item) { + foreach ($this->customFieldService->getAll() as $item) { $queryData = new QueryData(); $queryData->setQuery('UPDATE CustomFieldData SET moduleId = ? WHERE id = ? LIMIT 1'); $queryData->setParams([$this->moduleMapper($item->getModuleId()), $item->getId()]); - $this->db->doQuery($queryData); + $this->database->doQuery($queryData); $this->eventDispatcher->notifyEvent( 'upgrade.customField.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Field updated'))) + new Event( + $this, + EventMessage::factory()->addDescription(__u('Field updated')) + ) ); } - }); + }, $this->database); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); throw $e; } $this->eventDispatcher->notifyEvent( 'upgrade.customField.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('Custom fields update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Custom fields update')) + ->addDescription(__FUNCTION__) + ) ); } @@ -111,9 +129,4 @@ final class UpgradeCustomFieldData extends Service return $moduleId; } - - protected function initialize(): void - { - $this->db = $this->dic->get(Database::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Upgrade/UpgradeCustomFieldDefinition.php b/lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDefinitionService.php similarity index 57% rename from lib/SP/Services/Upgrade/UpgradeCustomFieldDefinition.php rename to lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDefinitionService.php index cbb3ff25..947a7e11 100644 --- a/lib/SP/Services/Upgrade/UpgradeCustomFieldDefinition.php +++ b/lib/SP/Domain/CustomField/Services/UpgradeCustomFieldDefinitionService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,29 +22,47 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\CustomField\Services; use Exception; use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\DataModel\CustomFieldDefDataOld; use SP\DataModel\CustomFieldDefinitionData; -use SP\Services\CustomField\CustomFieldDefService; -use SP\Services\CustomField\CustomFieldTypeService; -use SP\Services\Service; -use SP\Storage\Database\Database; -use SP\Storage\Database\QueryData; +use SP\Domain\Common\Services\Service; +use SP\Domain\CustomField\CustomFieldDefServiceInterface; +use SP\Domain\CustomField\CustomFieldTypeServiceInterface; +use SP\Domain\CustomField\UpgradeCustomFieldDefinitionServiceInterface; +use SP\Infrastructure\Database\DatabaseInterface; +use SP\Infrastructure\Database\QueryData; use SP\Util\Util; /** * Class UpgradeCustomField * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ -final class UpgradeCustomFieldDefinition extends Service +final class UpgradeCustomFieldDefinitionService extends Service + implements UpgradeCustomFieldDefinitionServiceInterface { - private ?Database $db = null; + protected CustomFieldDefServiceInterface $customFieldDefService; + protected DatabaseInterface $database; + private CustomFieldTypeServiceInterface $customFieldTypeService; + + public function __construct( + Application $application, + CustomFieldTypeServiceInterface $customFieldTypeService, + CustomFieldDefServiceInterface $customFieldDefService, + DatabaseInterface $database + ) { + parent::__construct($application); + + $this->database = $database; + $this->customFieldTypeService = $customFieldTypeService; + $this->customFieldDefService = $customFieldDefService; + } /** * upgrade_300_18010101 @@ -55,28 +73,29 @@ final class UpgradeCustomFieldDefinition extends Service { $this->eventDispatcher->notifyEvent( 'upgrade.customField.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('Custom fields update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Custom fields update')) + ->addDescription(__FUNCTION__) + ) ); try { - $customFieldTypeService = $this->dic->get(CustomFieldTypeService::class); - $customFieldType = []; - foreach ($customFieldTypeService->getAll() as $customFieldTypeData) { + foreach ($this->customFieldTypeService->getAll() as $customFieldTypeData) { $customFieldType[$customFieldTypeData->getName()] = $customFieldTypeData->getId(); } $this->transactionAware( function () use ($customFieldType) { - $customFieldDefService = $this->dic->get(CustomFieldDefService::class); - $queryData = new QueryData(); - $queryData->setQuery('SELECT id, moduleId, field FROM CustomFieldDefinition WHERE field IS NOT NULL'); + $queryData->setQuery( + 'SELECT id, moduleId, field FROM CustomFieldDefinition WHERE field IS NOT NULL' + ); - foreach ($this->db->doSelect($queryData)->getDataAsArray() as $item) { + foreach ($this->database->doSelect($queryData)->getDataAsArray() as $item) { /** @var CustomFieldDefDataOld $data */ $data = Util::unserialize( CustomFieldDefDataOld::class, @@ -93,38 +112,42 @@ final class UpgradeCustomFieldDefinition extends Service $itemData->setShowInList($data->isShowInItemsList()); $itemData->setTypeId($customFieldType[$this->typeMapper((int)$data->getType())]); - $customFieldDefService->updateRaw($itemData); + $this->customFieldDefService->updateRaw($itemData); $this->eventDispatcher->notifyEvent( 'upgrade.customField.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Field updated')) - ->addDetail(__u('Field'), $data->getName())) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Field updated')) + ->addDetail(__u('Field'), $data->getName()) + ) ); } - } + }, + $this->database ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); throw $e; } $this->eventDispatcher->notifyEvent( 'upgrade.customField.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('Custom fields update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Custom fields update')) + ->addDescription(__FUNCTION__) + ) ); } /** - * @param int $moduleId + * @param int $moduleId * * @return int */ @@ -147,7 +170,7 @@ final class UpgradeCustomFieldDefinition extends Service } /** - * @param int $typeId + * @param int $typeId * * @return string */ @@ -163,7 +186,7 @@ final class UpgradeCustomFieldDefinition extends Service 7 => 'url', 8 => 'color', 9 => 'text', - 10 => 'textarea' + 10 => 'textarea', ]; return $types[$typeId] ?? $types[1]; @@ -178,48 +201,53 @@ final class UpgradeCustomFieldDefinition extends Service { $this->eventDispatcher->notifyEvent( 'upgrade.customField.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('Custom fields update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Custom fields update')) + ->addDescription(__FUNCTION__) + ) ); try { $this->transactionAware( function () { - $customFieldDefService = $this->dic->get(CustomFieldDefService::class); - - foreach ($customFieldDefService->getAllBasic() as $item) { - + foreach ($this->customFieldDefService->getAllBasic() as $item) { $itemData = clone $item; $itemData->setModuleId($this->moduleMapper((int)$item->getModuleId())); - $customFieldDefService->updateRaw($itemData); + $this->customFieldDefService->updateRaw($itemData); $this->eventDispatcher->notifyEvent( 'upgrade.customField.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Field updated')) - ->addDetail(__u('Field'), $item->getName())) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Field updated')) + ->addDetail(__u('Field'), $item->getName()) + ) ); } } + , + $this->database ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); throw $e; } $this->eventDispatcher->notifyEvent( 'upgrade.customField.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('Custom fields update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Custom fields update')) + ->addDescription(__FUNCTION__) + ) ); } @@ -236,17 +264,18 @@ final class UpgradeCustomFieldDefinition extends Service $this->eventDispatcher->notifyEvent( 'upgrade.customField.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('Custom fields update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Custom fields update')) + ->addDescription(__FUNCTION__) + ) ); try { - $customFieldTypeService = $this->dic->get(CustomFieldTypeService::class); - $customFieldType = []; - foreach ($customFieldTypeService->getAll() as $customFieldTypeData) { + foreach ($this->customFieldTypeService->getAll() as $customFieldTypeData) { $customFieldType[$customFieldTypeData->getName()] = $customFieldTypeData->getId(); } @@ -255,7 +284,7 @@ final class UpgradeCustomFieldDefinition extends Service $queryData = new QueryData(); $queryData->setQuery('SELECT id, field FROM CustomFieldDefinition WHERE field IS NOT NULL'); - foreach ($this->db->doSelect($queryData)->getDataAsArray() as $item) { + foreach ($this->database->doSelect($queryData)->getDataAsArray() as $item) { /** @var CustomFieldDefDataOld $data */ $data = Util::unserialize( CustomFieldDefDataOld::class, @@ -269,38 +298,37 @@ final class UpgradeCustomFieldDefinition extends Service $queryData->setQuery('UPDATE CustomFieldDefinition SET typeId = ? WHERE id = ? LIMIT 1'); $queryData->setParams([$typeId, $item->id]); - $this->db->doQuery($queryData); + $this->database->doQuery($queryData); $this->eventDispatcher->notifyEvent( 'upgrade.customField.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Field updated')) - ->addDetail(__u('Field'), $data->getName())) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Field updated')) + ->addDetail(__u('Field'), $data->getName()) + ) ); } - } + }, + $this->database ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); throw $e; } $this->eventDispatcher->notifyEvent( 'upgrade.customField.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('Custom fields update')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Custom fields update')) + ->addDescription(__FUNCTION__) + ) ); } - - protected function initialize(): void - { - $this->db = $this->dic->get(Database::class); - } } \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/UpgradeCustomFieldDataServiceInterface.php b/lib/SP/Domain/CustomField/UpgradeCustomFieldDataServiceInterface.php new file mode 100644 index 00000000..665aafe2 --- /dev/null +++ b/lib/SP/Domain/CustomField/UpgradeCustomFieldDataServiceInterface.php @@ -0,0 +1,43 @@ +. + */ + +namespace SP\Domain\CustomField; + + +use Exception; + +/** + * Class UpgradeCustomFieldData + * + * @package SP\Domain\Upgrade\Services + */ +interface UpgradeCustomFieldDataServiceInterface +{ + /** + * upgrade_300_18072902 + * + * @throws Exception + */ + public function upgrade_300_18072902(): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/CustomField/UpgradeCustomFieldDefinitionServiceInterface.php b/lib/SP/Domain/CustomField/UpgradeCustomFieldDefinitionServiceInterface.php new file mode 100644 index 00000000..d902fbaf --- /dev/null +++ b/lib/SP/Domain/CustomField/UpgradeCustomFieldDefinitionServiceInterface.php @@ -0,0 +1,57 @@ +. + */ + +namespace SP\Domain\CustomField; + + +use Exception; + +/** + * Class UpgradeCustomField + * + * @package SP\Domain\Upgrade\Services + */ +interface UpgradeCustomFieldDefinitionServiceInterface +{ + /** + * upgrade_300_18010101 + * + * @throws Exception + */ + public function upgrade_300_18010101(): void; + + /** + * upgrade_300_18072901 + * + * @throws Exception + */ + public function upgrade_300_18072901(): void; + + /** + * upgrade_300_19042701 + * + * @throws Exception + */ + public function upgrade_310_19042701(): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Export/FileBackupServiceInterface.php b/lib/SP/Domain/Export/FileBackupServiceInterface.php new file mode 100644 index 00000000..55d2ab6b --- /dev/null +++ b/lib/SP/Domain/Export/FileBackupServiceInterface.php @@ -0,0 +1,43 @@ +. + */ + +namespace SP\Domain\Export; + + +use SP\Domain\Common\Services\ServiceException; + +/** + * Esta clase es la encargada de realizar la copia de sysPass. + */ +interface FileBackupServiceInterface +{ + /** + * Realizar backup de la BBDD y aplicación. + * + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function doBackup(string $backupPath = BACKUP_PATH, string $applicationPath = APP_ROOT): void; + + public function getHash(): string; +} \ No newline at end of file diff --git a/lib/SP/Services/Backup/BackupFiles.php b/lib/SP/Domain/Export/Services/BackupFiles.php similarity index 87% rename from lib/SP/Services/Backup/BackupFiles.php rename to lib/SP/Domain/Export/Services/BackupFiles.php index 58c707cd..0f787622 100644 --- a/lib/SP/Services/Backup/BackupFiles.php +++ b/lib/SP/Domain/Export/Services/BackupFiles.php @@ -22,14 +22,16 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Backup; +namespace SP\Domain\Export\Services; use SP\Core\AppInfoInterface; use SP\Core\Exceptions\CheckException; use SP\Core\PhpExtensionChecker; -use SP\Storage\File\ArchiveHandler; -use SP\Storage\File\FileHandler; +use SP\Infrastructure\File\ArchiveHandler; +use SP\Infrastructure\File\ArchiveHandlerInterface; +use SP\Infrastructure\File\FileHandler; +use SP\Infrastructure\File\FileHandlerInterface; /** * BackupFiles @@ -126,35 +128,35 @@ final class BackupFiles } /** - * @return \SP\Storage\File\FileHandler + * @return FileHandlerInterface */ - public function getAppBackupFileHandler(): FileHandler + public function getAppBackupFileHandler(): FileHandlerInterface { return new FileHandler($this->appBackupFilename); } /** - * @return \SP\Storage\File\FileHandler + * @return FileHandlerInterface */ - public function getDbBackupFileHandler(): FileHandler + public function getDbBackupFileHandler(): FileHandlerInterface { return new FileHandler($this->dbBackupFilename); } /** - * @return \SP\Storage\File\ArchiveHandler + * @return ArchiveHandlerInterface * @throws \SP\Core\Exceptions\CheckException */ - public function getDbBackupArchiveHandler(): ArchiveHandler + public function getDbBackupArchiveHandler(): ArchiveHandlerInterface { return new ArchiveHandler($this->dbBackupFilename, $this->extensionChecker); } /** - * @return \SP\Storage\File\ArchiveHandler + * @return ArchiveHandlerInterface * @throws \SP\Core\Exceptions\CheckException */ - public function getAppBackupArchiveHandler(): ArchiveHandler + public function getAppBackupArchiveHandler(): ArchiveHandlerInterface { return new ArchiveHandler($this->appBackupFilename, $this->extensionChecker); } diff --git a/lib/SP/Services/Backup/FileBackupService.php b/lib/SP/Domain/Export/Services/FileBackupService.php similarity index 90% rename from lib/SP/Services/Backup/FileBackupService.php rename to lib/SP/Domain/Export/Services/FileBackupService.php index ad8743a8..bda690b6 100644 --- a/lib/SP/Services/Backup/FileBackupService.php +++ b/lib/SP/Domain/Export/Services/FileBackupService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,12 +22,10 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Backup; +namespace SP\Domain\Export\Services; use Exception; use PDO; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; use SP\Core\AppInfoInterface; use SP\Core\Application; use SP\Core\Events\Event; @@ -35,13 +33,16 @@ use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\CheckException; use SP\Core\Exceptions\SPException; -use SP\Services\ServiceException; -use SP\Storage\Database\Database; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\Database\QueryData; -use SP\Storage\File\ArchiveHandler; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\Export\FileBackupServiceInterface; +use SP\Infrastructure\Database\Database; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\File\ArchiveHandler; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandlerInterface; use SP\Util\Checks; defined('APP_ROOT') || die(); @@ -49,7 +50,7 @@ defined('APP_ROOT') || die(); /** * Esta clase es la encargada de realizar la copia de sysPass. */ -final class FileBackupService +final class FileBackupService implements FileBackupServiceInterface { public const BACKUP_INCLUDE_REGEX = /** @lang RegExp */ '#^(?:[A-Z]:)?(?:/(?!(\.git|backup|cache|temp|vendor|tests))[^/]+)+/[^/]+\.\w+$#Di'; @@ -57,7 +58,7 @@ final class FileBackupService private Database $database; private DatabaseUtil $databaseUtil; private EventDispatcher $eventDispatcher; - private Config $config; + private ConfigFileService $config; private ConfigDataInterface $configData; private BackupFiles $backupFiles; private ?string $backupPath = null; @@ -104,7 +105,9 @@ final class FileBackupService if (!$this->backupApp($applicationPath) && !$this->backupAppLegacyLinux($applicationPath) ) { - throw new ServiceException(__u('Error while doing the backup in compatibility mode')); + throw new ServiceException( + __u('Error while doing the backup in compatibility mode') + ); } $this->configData->setBackupHash($this->backupFiles->getHash()); @@ -150,10 +153,10 @@ final class FileBackupService * @throws \SP\Core\Exceptions\CheckException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Storage\Database\DatabaseException - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\Database\DatabaseException + * @throws \SP\Infrastructure\File\FileException */ - private function backupTables(FileHandler $fileHandler): void + private function backupTables(FileHandlerInterface $fileHandler): void { $this->eventDispatcher->notifyEvent( 'run.backup.process', @@ -299,7 +302,7 @@ final class FileBackupService /** * Realizar un backup de la aplicación y comprimirlo usando aplicaciones del SO Linux. * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function backupAppLegacyLinux(string $directory): int { diff --git a/lib/SP/Services/Export/VerifyResult.php b/lib/SP/Domain/Export/Services/VerifyResult.php similarity index 86% rename from lib/SP/Services/Export/VerifyResult.php rename to lib/SP/Domain/Export/Services/VerifyResult.php index 26f91726..9ae5a856 100644 --- a/lib/SP/Services/Export/VerifyResult.php +++ b/lib/SP/Domain/Export/Services/VerifyResult.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,19 +22,19 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Export; +namespace SP\Domain\Export\Services; /** * Class VerifyResult * - * @package SP\Services\Export + * @package SP\Domain\Export\Services */ final class VerifyResult { private string $version; - private bool $encrypted; - private array $nodes; + private bool $encrypted; + private array $nodes; public function __construct(string $version, bool $encrypted, array $nodes) { diff --git a/lib/SP/Services/Export/XmlExportService.php b/lib/SP/Domain/Export/Services/XmlExportService.php similarity index 74% rename from lib/SP/Services/Export/XmlExportService.php rename to lib/SP/Domain/Export/Services/XmlExportService.php index effef94e..71fcdba6 100644 --- a/lib/SP/Services/Export/XmlExportService.php +++ b/lib/SP/Domain/Export/Services/XmlExportService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,16 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Export; +namespace SP\Domain\Export\Services; use DOMDocument; use DOMElement; use DOMXPath; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Config\ConfigDataInterface; use SP\Core\AppInfoInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Hash; use SP\Core\Events\Event; @@ -40,16 +38,18 @@ use SP\Core\Exceptions\CheckException; use SP\Core\Exceptions\SPException; use SP\Core\PhpExtensionChecker; use SP\DataModel\CategoryData; -use SP\Services\Account\AccountService; -use SP\Services\Account\AccountToTagService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\Tag\TagService; -use SP\Storage\File\ArchiveHandler; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Account\AccountToTagServiceInterface; +use SP\Domain\Category\CategoryServiceInterface; +use SP\Domain\Client\ClientServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Export\XmlExportServiceInterface; +use SP\Domain\Tag\TagServiceInterface; +use SP\Infrastructure\File\ArchiveHandler; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; use SP\Util\VersionUtil; defined('APP_ROOT') || die(); @@ -59,25 +59,52 @@ defined('APP_ROOT') || die(); * * @package SP */ -final class XmlExportService extends Service +final class XmlExportService extends Service implements XmlExportServiceInterface { - private ?ConfigDataInterface $configData = null; - private ?PhpExtensionChecker $extensionChecker = null; - private ?DOMDocument $xml = null; - private ?DOMElement $root = null; - private ?string $exportPass = null; - private bool $encrypted = false; - private ?string $exportPath = null; - private ?string $exportFile = null; + private ConfigDataInterface $configData; + private PhpExtensionChecker $extensionChecker; + private ClientServiceInterface $clientService; + private AccountServiceInterface $accountService; + private AccountToTagServiceInterface $accountToTagService; + private CategoryServiceInterface $categoryService; + private TagServiceInterface $tagService; + private ?DOMDocument $xml = null; + private ?DOMElement $root = null; + private ?string $exportPass = null; + private bool $encrypted = false; + private ?string $exportPath = null; + private ?string $exportFile = null; + + public function __construct( + Application $application, + PhpExtensionChecker $extensionChecker, + ClientServiceInterface $clientService, + AccountServiceInterface $accountService, + AccountToTagServiceInterface $accountToTagService, + CategoryServiceInterface $categoryService, + TagServiceInterface $tagService + + ) { + parent::__construct($application); + + $this->extensionChecker = $extensionChecker; + $this->clientService = $clientService; + $this->accountService = $accountService; + $this->accountToTagService = $accountToTagService; + $this->categoryService = $categoryService; + $this->tagService = $tagService; + $this->configData = $this->config->getConfigData(); + } + /** * Realiza la exportación de las cuentas a XML * - * @param string $exportPath - * @param string|null $pass La clave de exportación + * @param string $exportPath + * @param string|null $pass La clave de exportación * - * @throws \SP\Services\ServiceException - * @throws \SP\Storage\File\FileException + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \SP\Infrastructure\File\FileException */ public function doExport(string $exportPath, ?string $pass = null): void { @@ -95,7 +122,7 @@ final class XmlExportService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function setExportPath(string $exportPath): void { @@ -103,10 +130,7 @@ final class XmlExportService extends Service && !@mkdir($exportPath, 0700, true) && !is_dir($exportPath) ) { - throw new ServiceException(sprintf( - __('Unable to create the directory (%s)'), - $exportPath - )); + throw new ServiceException(sprintf(__('Unable to create the directory (%s)'), $exportPath)); } $this->exportPath = $exportPath; @@ -127,22 +151,12 @@ final class XmlExportService extends Service return self::getExportFilename($this->exportPath, $hash); } - public static function getExportFilename( - string $path, - string $hash, - bool $compressed = false - ): string + public static function getExportFilename(string $path, string $hash, bool $compressed = false): string { - $file = sprintf( - '%s%s%s_export-%s', - $path, - DIRECTORY_SEPARATOR, - AppInfoInterface::APP_NAME, - $hash - ); + $file = sprintf('%s%s%s_export-%s', $path, DIRECTORY_SEPARATOR, AppInfoInterface::APP_NAME, $hash); if ($compressed) { - return $file . ArchiveHandler::COMPRESS_EXTENSION; + return $file.ArchiveHandler::COMPRESS_EXTENSION; } return sprintf('%s.xml', $file); @@ -153,25 +167,18 @@ final class XmlExportService extends Service */ private function deleteOldExports(): void { - $path = $this->exportPath . DIRECTORY_SEPARATOR . AppInfoInterface::APP_NAME; + $path = $this->exportPath.DIRECTORY_SEPARATOR.AppInfoInterface::APP_NAME; array_map( - static function ($file) { - return @unlink($file); - }, - array_merge( - glob($path . '_export-*'), - glob($path . '*.xml') - ) + static fn($file) => @unlink($file), + array_merge(glob($path.'_export-*'), glob($path.'*.xml')) ); } /** * Crear el documento XML y guardarlo * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function makeXML(): void { @@ -200,7 +207,7 @@ final class XmlExportService extends Service /** * Crear el nodo raíz * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function createRoot(): void { @@ -208,11 +215,7 @@ final class XmlExportService extends Service $this->xml = new DOMDocument('1.0', 'UTF-8'); $this->root = $this->xml->appendChild($this->xml->createElement('Root')); } catch (Exception $e) { - throw new ServiceException( - $e->getMessage(), - SPException::ERROR, - __FUNCTION__ - ); + throw new ServiceException($e->getMessage(), SPException::ERROR, __FUNCTION__); } } @@ -243,19 +246,13 @@ final class XmlExportService extends Service $this->root->appendChild($nodeMeta); } catch (Exception $e) { - throw new ServiceException( - $e->getMessage(), - SPException::ERROR, - __FUNCTION__ - ); + throw new ServiceException($e->getMessage(), SPException::ERROR, __FUNCTION__); } } /** * Crear el nodo con los datos de las categorías * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface * @throws ServiceException */ private function createCategories(): void @@ -263,12 +260,10 @@ final class XmlExportService extends Service try { $this->eventDispatcher->notifyEvent( 'run.export.process.category', - new Event($this, EventMessage::factory() - ->addDescription(__u('Exporting categories'))) + new Event($this, EventMessage::factory()->addDescription(__u('Exporting categories'))) ); - $categoryService = $this->dic->get(CategoryService::class); - $categories = $categoryService->getAllBasic(); + $categories = $this->categoryService->getAllBasic(); // Crear el nodo de categorías $nodeCategories = $this->xml->createElement('Categories'); @@ -282,7 +277,10 @@ final class XmlExportService extends Service foreach ($categories as $category) { /** @var $category CategoryData */ $categoryName = $this->xml->createElement('name', $this->escapeChars($category->getName())); - $categoryDescription = $this->xml->createElement('description', $this->escapeChars($category->getDescription())); + $categoryDescription = $this->xml->createElement( + 'description', + $this->escapeChars($category->getDescription()) + ); // Crear el nodo de categoría $nodeCategory = $this->xml->createElement('Category'); @@ -296,20 +294,16 @@ final class XmlExportService extends Service $this->appendNode($nodeCategories); } catch (Exception $e) { - throw new ServiceException( - $e->getMessage(), - SPException::ERROR, - __FUNCTION__ - ); + throw new ServiceException($e->getMessage(), SPException::ERROR, __FUNCTION__); } } /** * Añadir un nuevo nodo al árbol raíz * - * @param DOMElement $node El nodo a añadir + * @param DOMElement $node El nodo a añadir * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function appendNode(DOMElement $node): void { @@ -351,11 +345,7 @@ final class XmlExportService extends Service $this->root->appendChild($node); } } catch (Exception $e) { - throw new ServiceException( - $e->getMessage(), - SPException::ERROR, - __FUNCTION__ - ); + throw new ServiceException($e->getMessage(), SPException::ERROR, __FUNCTION__); } } @@ -379,32 +369,30 @@ final class XmlExportService extends Service * * @throws ServiceException * @throws ServiceException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface */ private function createClients(): void { try { $this->eventDispatcher->notifyEvent( 'run.export.process.client', - new Event($this, EventMessage::factory() - ->addDescription(__u('Exporting clients'))) + new Event($this, EventMessage::factory()->addDescription(__u('Exporting clients'))) ); - $clientService = $this->dic->get(ClientService::class); - $clients = $clientService->getAllBasic(); + $clients = $this->clientService->getAllBasic(); // Crear el nodo de clientes $nodeClients = $this->xml->createElement('Clients'); if (count($clients) === 0) { $this->appendNode($nodeClients); + return; } foreach ($clients as $client) { $clientName = $this->xml->createElement('name', $this->escapeChars($client->getName())); - $clientDescription = $this->xml->createElement('description', $this->escapeChars($client->getDescription())); + $clientDescription = + $this->xml->createElement('description', $this->escapeChars($client->getDescription())); // Crear el nodo de clientes $nodeClient = $this->xml->createElement('Client'); @@ -418,38 +406,31 @@ final class XmlExportService extends Service $this->appendNode($nodeClients); } catch (Exception $e) { - throw new ServiceException( - $e->getMessage(), - SPException::ERROR, - __FUNCTION__ - ); + throw new ServiceException($e->getMessage(), SPException::ERROR, __FUNCTION__); } } /** * Crear el nodo con los datos de las etiquetas * - * @throws ServiceException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface + * @throws \SP\Domain\Common\Services\ServiceException */ private function createTags(): void { try { $this->eventDispatcher->notifyEvent( 'run.export.process.tag', - new Event($this, EventMessage::factory() - ->addDescription(__u('Exporting tags'))) + new Event($this, EventMessage::factory()->addDescription(__u('Exporting tags'))) ); - $tagService = $this->dic->get(TagService::class); - $tags = $tagService->getAllBasic(); + $tags = $this->tagService->getAllBasic(); // Crear el nodo de etiquetas $nodeTags = $this->xml->createElement('Tags'); if (count($tags) === 0) { $this->appendNode($nodeTags); + return; } @@ -467,11 +448,7 @@ final class XmlExportService extends Service $this->appendNode($nodeTags); } catch (Exception $e) { - throw new ServiceException( - $e->getMessage(), - SPException::ERROR, - __FUNCTION__ - ); + throw new ServiceException($e->getMessage(), SPException::ERROR, __FUNCTION__); } } @@ -479,27 +456,23 @@ final class XmlExportService extends Service * Crear el nodo con los datos de las cuentas * * @throws ServiceException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface */ private function createAccounts(): void { try { $this->eventDispatcher->notifyEvent( 'run.export.process.account', - new Event($this, EventMessage::factory() - ->addDescription(__u('Exporting accounts'))) + new Event($this, EventMessage::factory()->addDescription(__u('Exporting accounts'))) ); - $accountService = $this->dic->get(AccountService::class); - $accountToTagService = $this->dic->get(AccountToTagService::class); - $accounts = $accountService->getAllBasic(); + $accounts = $this->accountService->getAllBasic(); // Crear el nodo de cuentas $nodeAccounts = $this->xml->createElement('Accounts'); if (count($accounts) === 0) { $this->appendNode($nodeAccounts); + return; } @@ -514,7 +487,7 @@ final class XmlExportService extends Service $accountIV = $this->xml->createElement('key', $this->escapeChars($account->getKey())); $tags = $this->xml->createElement('tags'); - foreach ($accountToTagService->getTagsByAccountId($account->getId()) as $itemData) { + foreach ($this->accountToTagService->getTagsByAccountId($account->getId()) as $itemData) { $tag = $this->xml->createElement('tag'); $tag->setAttribute('id', $itemData->getId()); @@ -540,18 +513,14 @@ final class XmlExportService extends Service $this->appendNode($nodeAccounts); } catch (Exception $e) { - throw new ServiceException( - $e->getMessage(), - SPException::ERROR, - __FUNCTION__ - ); + throw new ServiceException($e->getMessage(), SPException::ERROR, __FUNCTION__); } } /** * Crear el hash del archivo XML e insertarlo en el árbol DOM * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function createHash(): void { @@ -592,7 +561,7 @@ final class XmlExportService extends Service /** * Generar el archivo XML * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function writeXML(): void { @@ -634,14 +603,4 @@ final class XmlExportService extends Service { return $this->encrypted; } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->extensionChecker = $this->dic->get(PhpExtensionChecker::class); - $this->configData = $this->config->getConfigData(); - } } \ No newline at end of file diff --git a/lib/SP/Services/Export/XmlVerifyService.php b/lib/SP/Domain/Export/Services/XmlVerifyService.php similarity index 83% rename from lib/SP/Services/Export/XmlVerifyService.php rename to lib/SP/Domain/Export/Services/XmlVerifyService.php index d382110e..01d76bfb 100644 --- a/lib/SP/Services/Export/XmlVerifyService.php +++ b/lib/SP/Domain/Export/Services/XmlVerifyService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Export; +namespace SP\Domain\Export\Services; use Defuse\Crypto\Exception\CryptoException; @@ -31,12 +31,13 @@ use DOMElement; use DOMXPath; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Hash; -use SP\Services\Import\FileImport; -use SP\Services\Import\ImportException; -use SP\Services\Import\XmlFileImport; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\File\FileException; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Export\XmlVerifyServiceInterface; +use SP\Domain\Import\Services\FileImport; +use SP\Domain\Import\Services\ImportException; +use SP\Domain\Import\Services\XmlFileImport; +use SP\Infrastructure\File\FileException; use SP\Util\VersionUtil; /** @@ -44,20 +45,20 @@ use SP\Util\VersionUtil; * * Verifies a sysPass exported file format * - * @package SP\Services\Export + * @package SP\Domain\Export\Services */ -final class XmlVerifyService extends Service +final class XmlVerifyService extends Service implements XmlVerifyServiceInterface { - private const NODES = ['Category', 'Client', 'Tag', 'Account']; + private const NODES = ['Category', 'Client', 'Tag', 'Account']; private const XML_MIN_VERSION = [2, 1, 0, 0]; - private ?DOMDocument $xml = null; - private ?string $xmlFile = null; - private ?string $password = null; + private ?DOMDocument $xml = null; + private ?string $xmlFile = null; + private ?string $password = null; /** * @throws FileException * @throws ImportException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function verify(string $xmlFile): VerifyResult { @@ -93,7 +94,7 @@ final class XmlVerifyService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public static function validateSchema(DOMDocument $document): void { @@ -111,7 +112,7 @@ final class XmlVerifyService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public static function checkVersion(string $version): void { @@ -130,9 +131,8 @@ final class XmlVerifyService extends Service */ public static function checkXmlHash( DOMDocument $document, - string $key - ): bool - { + string $key + ): bool { $DOMXPath = new DOMXPath($document); $hash = $DOMXPath->query('/Root/Meta/Hash'); $sign = $DOMXPath->query('/Root/Meta/Hash/@sign'); @@ -167,10 +167,7 @@ final class XmlVerifyService extends Service * @throws ImportException * @throws ServiceException */ - public function verifyEncrypted( - string $xmlFile, - string $password - ): VerifyResult + public function verifyEncrypted(string $xmlFile, string $password): VerifyResult { $this->xmlFile = $xmlFile; $this->password = $password; @@ -189,13 +186,15 @@ final class XmlVerifyService extends Service throw new ServiceException(__u('Error while checking integrity hash')); } - return new VerifyResult($this->getXmlVersion(), + return new VerifyResult( + $this->getXmlVersion(), $this->detectEncrypted(), - $this->countItemNodes($this->processEncrypted())); + $this->countItemNodes($this->processEncrypted()) + ); } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function checkPassword(): void { @@ -220,7 +219,7 @@ final class XmlVerifyService extends Service /** * Process the encrypted data and then build the unencrypted DOM * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ private function processEncrypted(): DOMDocument { diff --git a/lib/SP/Domain/Export/XmlExportServiceInterface.php b/lib/SP/Domain/Export/XmlExportServiceInterface.php new file mode 100644 index 00000000..b8dda036 --- /dev/null +++ b/lib/SP/Domain/Export/XmlExportServiceInterface.php @@ -0,0 +1,58 @@ +. + */ + +namespace SP\Domain\Export; + + +use SP\Core\Exceptions\CheckException; +use SP\Infrastructure\File\FileException; + +/** + * Clase XmlExport para realizar la exportación de las cuentas de sysPass a formato XML + * + * @package SP + */ +interface XmlExportServiceInterface +{ + /** + * Realiza la exportación de las cuentas a XML + * + * @param string $exportPath + * @param string|null $pass La clave de exportación + * + * @throws \SP\Domain\Common\Services\ServiceException + * @throws \SP\Infrastructure\File\FileException + */ + public function doExport(string $exportPath, ?string $pass = null): void; + + /** + * @throws CheckException + * @throws FileException + */ + public function createArchive(): void; + + public function getExportFile(): string; + + public function isEncrypted(): bool; +} \ No newline at end of file diff --git a/lib/SP/Domain/Export/XmlVerifyServiceInterface.php b/lib/SP/Domain/Export/XmlVerifyServiceInterface.php new file mode 100644 index 00000000..1bfd1e06 --- /dev/null +++ b/lib/SP/Domain/Export/XmlVerifyServiceInterface.php @@ -0,0 +1,55 @@ +. + */ + +namespace SP\Domain\Export; + + +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Export\Services\VerifyResult; +use SP\Domain\Import\Services\ImportException; +use SP\Infrastructure\File\FileException; + +/** + * Class XmlVerifyService + * + * Verifies a sysPass exported file format + * + * @package SP\Domain\Export\Services + */ +interface XmlVerifyServiceInterface +{ + /** + * @throws FileException + * @throws ImportException + * @throws ServiceException + */ + public function verify(string $xmlFile): VerifyResult; + + /** + * @throws FileException + * @throws ImportException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function verifyEncrypted(string $xmlFile, string $password): VerifyResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/Import/FileImportInterface.php b/lib/SP/Domain/Import/FileImportInterface.php new file mode 100644 index 00000000..15f49a7f --- /dev/null +++ b/lib/SP/Domain/Import/FileImportInterface.php @@ -0,0 +1,60 @@ +. + */ + +namespace SP\Domain\Import; + + +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandlerInterface; + +/** + * Clase FileImport encargada el leer archivos para su importación + * + * @package SP + */ +interface FileImportInterface +{ + public function getFilePath(): string; + + /** + * @throws FileException + */ + public function getFileType(): string; + + /** + * Leer los datos de un archivo subido a un array + * + * @throws FileException + */ + public function readFileToArray(): array; + + /** + * Leer los datos de un archivo subido a una cadena + * + * @throws FileException + */ + public function readFileToString(): string; + + public function getFileHandler(): FileHandlerInterface; +} \ No newline at end of file diff --git a/lib/SP/Services/Import/ImportInterface.php b/lib/SP/Domain/Import/ImportInterface.php similarity index 92% rename from lib/SP/Services/Import/ImportInterface.php rename to lib/SP/Domain/Import/ImportInterface.php index fad98834..b4af5a2a 100644 --- a/lib/SP/Services/Import/ImportInterface.php +++ b/lib/SP/Domain/Import/ImportInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import; /** * Interface ImportInterface diff --git a/lib/SP/Domain/Import/ImportServiceInterface.php b/lib/SP/Domain/Import/ImportServiceInterface.php new file mode 100644 index 00000000..b8438e0d --- /dev/null +++ b/lib/SP/Domain/Import/ImportServiceInterface.php @@ -0,0 +1,43 @@ +. + */ + +namespace SP\Domain\Import; + + +use Exception; +use SP\Domain\Import\Services\ImportParams; + +/** + * Esta clase es la encargada de importar cuentas. + */ +interface ImportServiceInterface +{ + /** + * Iniciar la importación de cuentas. + * + * @return int Returns the total number of imported items + * @throws Exception + */ + public function doImport(ImportParams $importParams, FileImportInterface $fileImport): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/Import/LdapImportServiceInterface.php b/lib/SP/Domain/Import/LdapImportServiceInterface.php new file mode 100644 index 00000000..e8801549 --- /dev/null +++ b/lib/SP/Domain/Import/LdapImportServiceInterface.php @@ -0,0 +1,56 @@ +. + */ + +namespace SP\Domain\Import; + + +use SP\Domain\Import\Services\LdapImportParams; +use SP\Providers\Auth\Ldap\LdapException; +use SP\Providers\Auth\Ldap\LdapParams; + +/** + * Class UserLdapService + * + * @package SP\Domain\User\Services + */ +interface LdapImportServiceInterface +{ + public function getTotalObjects(): int; + + public function getSyncedObjects(): int; + + public function getErrorObjects(): int; + + /** + * Sincronizar usuarios de LDAP + * + * @throws LdapException + */ + public function importGroups(LdapParams $ldapParams, LdapImportParams $ldapImportParams): void; + + /** + * @throws LdapException + */ + public function importUsers(LdapParams $ldapParams, LdapImportParams $ldapImportParams): void; +} \ No newline at end of file diff --git a/lib/SP/Services/Import/CsvImport.php b/lib/SP/Domain/Import/Services/CsvImport.php similarity index 80% rename from lib/SP/Services/Import/CsvImport.php rename to lib/SP/Domain/Import/Services/CsvImport.php index 2cb58a93..6cf32c27 100644 --- a/lib/SP/Services/Import/CsvImport.php +++ b/lib/SP/Domain/Import/Services/CsvImport.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,11 +22,12 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; -use SP\Storage\File\FileException; +use SP\Domain\Import\ImportInterface; +use SP\Infrastructure\File\FileException; defined('APP_ROOT') || die(); @@ -48,8 +49,10 @@ final class CsvImport extends CsvImportBase implements ImportInterface { $this->eventDispatcher->notifyEvent( 'run.import.csv', - new Event($this, EventMessage::factory() - ->addDescription(sprintf(__('Detected format: %s'), 'CSV'))) + new Event( + $this, + EventMessage::factory()->addDescription(sprintf(__('Detected format: %s'), 'CSV')) + ) ); $this->processAccounts(); diff --git a/lib/SP/Services/Import/CsvImportBase.php b/lib/SP/Domain/Import/Services/CsvImportBase.php similarity index 61% rename from lib/SP/Services/Import/CsvImportBase.php rename to lib/SP/Domain/Import/Services/CsvImportBase.php index 0a02e7be..e201d4bf 100644 --- a/lib/SP/Services/Import/CsvImportBase.php +++ b/lib/SP/Domain/Import/Services/CsvImportBase.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,22 +22,19 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use Exception; -use Psr\Container\ContainerInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ClientData; -use SP\Services\Account\AccountRequest; -use SP\Services\Account\AccountService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Tag\TagService; -use SP\Storage\File\FileException; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Import\FileImportInterface; +use SP\Infrastructure\File\FileException; defined('APP_ROOT') || die(); @@ -50,56 +47,25 @@ abstract class CsvImportBase { use ImportTrait; - protected int $numFields = 7; - protected array $mapFields = []; - protected FileImport $fileImport; - protected $eventDispatcher; - protected array $categories = []; - protected array $clients = []; + protected int $numFields = 7; + protected FileImportInterface $fileImport; + protected EventDispatcher $eventDispatcher; + protected array $categories = []; + protected array $clients = []; - /** - * ImportBase constructor. - * - * @param ContainerInterface $dic - * @param FileImport $fileImport - * @param ImportParams $importParams - * - */ public function __construct( - ContainerInterface $dic, - FileImport $fileImport, - ImportParams $importParams - ) - { + Application $application, + ImportHelper $importHelper, + FileImportInterface $fileImport, + ImportParams $importParams + ) { + $this->eventDispatcher = $application->getEventDispatcher(); + $this->accountService = $importHelper->getAccountService(); + $this->categoryService = $importHelper->getCategoryService(); + $this->clientService = $importHelper->getClientService(); + $this->tagService = $importHelper->getTagService(); $this->fileImport = $fileImport; $this->importParams = $importParams; - - $this->accountService = $dic->get(AccountService::class); - $this->categoryService = $dic->get(CategoryService::class); - $this->clientService = $dic->get(ClientService::class); - $this->tagService = $dic->get(TagService::class); - $this->eventDispatcher = $dic->get(EventDispatcher::class); - } - - /** - * @param int $numFields - */ - public function setNumFields(int $numFields): void - { - $this->numFields = $numFields; - } - - /** - * @param array $mapFields - */ - public function setMapFields(array $mapFields): void - { - $this->mapFields = $mapFields; - } - - public function getEventDispatcher(): EventDispatcher - { - return $this->eventDispatcher; } /** @@ -135,7 +101,7 @@ abstract class CsvImportBase $url, $login, $password, - $notes + $notes, ] = $fields; try { @@ -144,12 +110,8 @@ abstract class CsvImportBase } // Obtener los ids de cliente y categoría - $clientId = $this->addClient( - new ClientData(null, $clientName) - ); - $categoryId = $this->addCategory( - new CategoryData(null, $categoryName) - ); + $clientId = $this->addClient(new ClientData(null, $clientName)); + $categoryId = $this->addCategory(new CategoryData(null, $categoryName)); // Crear la nueva cuenta $accountRequest = new AccountRequest(); @@ -165,18 +127,24 @@ abstract class CsvImportBase $this->eventDispatcher->notifyEvent( 'run.import.csv.process.account', - new Event($this, EventMessage::factory() - ->addDetail(__u('Account imported'), $accountName) - ->addDetail(__u('Client'), $clientName)) + new Event( + $this, + EventMessage::factory() + ->addDetail(__u('Account imported'), $accountName) + ->addDetail(__u('Client'), $clientName) + ) ); } catch (Exception $e) { processException($e); $this->eventDispatcher->notifyEvent( 'exception', - new Event($e, EventMessage::factory() - ->addDetail(__u('Error while importing the account'), $accountName) - ->addDetail(__u('Error while processing line'), $line)) + new Event( + $e, + EventMessage::factory() + ->addDetail(__u('Error while importing the account'), $accountName) + ->addDetail(__u('Error while processing line'), $line) + ) ); } } diff --git a/lib/SP/Services/Import/FileImport.php b/lib/SP/Domain/Import/Services/FileImport.php similarity index 78% rename from lib/SP/Services/Import/FileImport.php rename to lib/SP/Domain/Import/Services/FileImport.php index 3ceefefc..1eb82cc4 100644 --- a/lib/SP/Services/Import/FileImport.php +++ b/lib/SP/Domain/Import/Services/FileImport.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,12 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use SP\Core\Exceptions\SPException; -use SP\Http\Request; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Domain\Import\FileImportInterface; +use SP\Http\RequestInterface; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; +use SP\Infrastructure\File\FileHandlerInterface; use SP\Util\Util; defined('APP_ROOT') || die(); @@ -37,16 +39,16 @@ defined('APP_ROOT') || die(); * * @package SP */ -final class FileImport +final class FileImport implements FileImportInterface { private FileHandler $fileHandler; /** * FileImport constructor. * - * @param FileHandler $fileHandler Datos del archivo a importar + * @param FileHandlerInterface $fileHandler Datos del archivo a importar */ - private function __construct(FileHandler $fileHandler) + private function __construct(FileHandlerInterface $fileHandler) { $this->fileHandler = $fileHandler; } @@ -55,10 +57,7 @@ final class FileImport * @throws FileException * @throws SPException */ - public static function fromRequest( - string $filename, - Request $request - ): FileImport + public static function fromRequest(string $filename, RequestInterface $request): FileImportInterface { return new self(self::checkFile($request->getFile($filename))); } @@ -66,13 +65,13 @@ final class FileImport /** * Leer los datos del archivo. * - * @param array|null $file con los datos del archivo + * @param array|null $file con los datos del archivo * - * @return FileHandler - * @throws \SP\Services\Import\ImportException - * @throws \SP\Storage\File\FileException + * @return FileHandlerInterface + * @throws \SP\Domain\Import\Services\ImportException + * @throws \SP\Infrastructure\File\FileException */ - private static function checkFile(?array $file): FileHandler + private static function checkFile(?array $file): FileHandlerInterface { if (!is_array($file)) { throw new FileException( @@ -86,9 +85,7 @@ final class FileImport $fileHandler = new FileHandler($file['tmp_name']); $fileHandler->checkFileExists(); - if (!in_array( - $fileHandler->getFileType(), - ImportService::ALLOWED_MIME)) { + if (!in_array($fileHandler->getFileType(), ImportService::ALLOWED_MIME)) { throw new ImportException( __u('File type not allowed'), SPException::ERROR, @@ -110,7 +107,15 @@ final class FileImport } } - public static function fromFilesystem(string $path): FileImport + /** + * @throws FileException + */ + public function getFileType(): string + { + return $this->fileHandler->getFileType(); + } + + public static function fromFilesystem(string $path): FileImportInterface { return new self(new FileHandler($path)); } @@ -120,14 +125,6 @@ final class FileImport return $this->fileHandler->getFile(); } - /** - * @throws FileException - */ - public function getFileType(): string - { - return $this->fileHandler->getFileType(); - } - /** * Leer los datos de un archivo subido a un array * @@ -160,7 +157,7 @@ final class FileImport return $this->fileHandler->readToString(); } - public function getFileHandler(): FileHandler + public function getFileHandler(): FileHandlerInterface { return $this->fileHandler; } diff --git a/lib/SP/Services/Import/ImportException.php b/lib/SP/Domain/Import/Services/ImportException.php similarity index 86% rename from lib/SP/Services/Import/ImportException.php rename to lib/SP/Domain/Import/Services/ImportException.php index 699309e7..88229969 100644 --- a/lib/SP/Services/Import/ImportException.php +++ b/lib/SP/Domain/Import/Services/ImportException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use SP\Core\Exceptions\SPException; /** * Class ImportException * - * @package SP\Services\Import + * @package SP\Domain\Import\Services */ final class ImportException extends SPException { diff --git a/lib/SP/Domain/Import/Services/ImportHelper.php b/lib/SP/Domain/Import/Services/ImportHelper.php new file mode 100644 index 00000000..532e1e80 --- /dev/null +++ b/lib/SP/Domain/Import/Services/ImportHelper.php @@ -0,0 +1,74 @@ +. + */ + +namespace SP\Domain\Import\Services; + + +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Category\CategoryServiceInterface; +use SP\Domain\Client\ClientServiceInterface; +use SP\Domain\Tag\TagServiceInterface; + +/** + * A helper class to provide the needed services. + */ +final class ImportHelper +{ + private AccountServiceInterface $accountService; + private CategoryServiceInterface $categoryService; + private ClientServiceInterface $clientService; + private TagServiceInterface $tagService; + + public function __construct( + AccountServiceInterface $accountService, + CategoryServiceInterface $categoryService, + ClientServiceInterface $clientService, + TagServiceInterface $tagService + ) { + $this->accountService = $accountService; + $this->categoryService = $categoryService; + $this->clientService = $clientService; + $this->tagService = $tagService; + } + + public function getAccountService(): AccountServiceInterface + { + return $this->accountService; + } + + public function getCategoryService(): CategoryServiceInterface + { + return $this->categoryService; + } + + public function getClientService(): ClientServiceInterface + { + return $this->clientService; + } + + public function getTagService(): TagServiceInterface + { + return $this->tagService; + } +} \ No newline at end of file diff --git a/lib/SP/Services/Import/ImportParams.php b/lib/SP/Domain/Import/Services/ImportParams.php similarity index 85% rename from lib/SP/Services/Import/ImportParams.php rename to lib/SP/Domain/Import/Services/ImportParams.php index cf2dc8c8..3ca03d44 100644 --- a/lib/SP/Services/Import/ImportParams.php +++ b/lib/SP/Domain/Import/Services/ImportParams.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,21 +22,21 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; /** * Class ImportParams * - * @package SP\Services\Import + * @package SP\Domain\Import\Services */ final class ImportParams { - protected ?string $importPwd = null; + protected ?string $importPwd = null; protected ?string $importMasterPwd = null; - protected int $defaultUser = 0; - protected int $defaultGroup = 0; - protected string $csvDelimiter = ';'; + protected int $defaultUser = 0; + protected int $defaultGroup = 0; + protected string $csvDelimiter = ';'; public function getImportPwd(): ?string { diff --git a/lib/SP/Services/Import/ImportService.php b/lib/SP/Domain/Import/Services/ImportService.php similarity index 58% rename from lib/SP/Services/Import/ImportService.php rename to lib/SP/Domain/Import/Services/ImportService.php index 2acf93a9..70936043 100644 --- a/lib/SP/Services/Import/ImportService.php +++ b/lib/SP/Domain/Import/Services/ImportService.php @@ -5,7 +5,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -23,21 +23,25 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\SPException; -use SP\Services\Service; -use SP\Storage\File\FileException; +use SP\Domain\Common\Services\Service; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Import\FileImportInterface; +use SP\Domain\Import\ImportInterface; +use SP\Domain\Import\ImportServiceInterface; +use SP\Infrastructure\Database\DatabaseInterface; +use SP\Infrastructure\File\FileException; defined('APP_ROOT') || die(); /** * Esta clase es la encargada de importar cuentas. */ -final class ImportService extends Service +final class ImportService extends Service implements ImportServiceInterface { public const ALLOWED_MIME = [ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', @@ -46,34 +50,47 @@ final class ImportService extends Service 'text/csv', 'text/x-csv', 'application/xml', - 'text/xml' + 'text/xml', ]; - protected ?ImportParams $importParams = null; - protected ?FileImport $fileImport = null; + private ?ImportParams $importParams = null; + private ?FileImportInterface $fileImport = null; + private Application $application; + private ImportHelper $importHelper; + private ConfigServiceInterface $configService; + private DatabaseInterface $database; + + public function __construct( + Application $application, + ImportHelper $importHelper, + ConfigServiceInterface $configService, + DatabaseInterface $database + ) { + parent::__construct($application); + + $this->application = $application; + $this->importHelper = $importHelper; + $this->configService = $configService; + $this->database = $database; + + set_time_limit(0); + } + /** * Iniciar la importación de cuentas. * * @return int Returns the total number of imported items * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface */ - public function doImport( - ImportParams $importParams, - FileImport $fileImport - ): int + public function doImport(ImportParams $importParams, FileImportInterface $fileImport): int { $this->importParams = $importParams; $this->fileImport = $fileImport; return $this->transactionAware( - function () { - return $this->selectImportType() - ->doImport() - ->getCounter(); - } + fn() => $this->selectImportType()->doImport()->getCounter(), + $this->database ); } @@ -88,14 +105,17 @@ final class ImportService extends Service switch ($fileType) { case 'text/plain': return new CsvImport( - $this->dic, + $this->application, + $this->importHelper, $this->fileImport, $this->importParams ); case 'text/xml': case 'application/xml': return new XmlImport( - $this->dic, + $this->application, + $this->importHelper, + $this->configService, new XmlFileImport($this->fileImport), $this->importParams ); @@ -107,13 +127,4 @@ final class ImportService extends Service __u('Please, check the file format') ); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - set_time_limit(0); - } } \ No newline at end of file diff --git a/lib/SP/Services/Import/ImportTrait.php b/lib/SP/Domain/Import/Services/ImportTrait.php similarity index 80% rename from lib/SP/Services/Import/ImportTrait.php rename to lib/SP/Domain/Import/Services/ImportTrait.php index ad503bbf..0529a150 100644 --- a/lib/SP/Services/Import/ImportTrait.php +++ b/lib/SP/Domain/Import/Services/ImportTrait.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use Defuse\Crypto\Exception\CryptoException; use SP\Core\Crypt\Crypt; @@ -34,17 +34,17 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ClientData; use SP\DataModel\TagData; -use SP\Repositories\DuplicatedItemException; -use SP\Services\Account\AccountRequest; -use SP\Services\Account\AccountService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Tag\TagService; +use SP\Domain\Account\AccountServiceInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Category\CategoryServiceInterface; +use SP\Domain\Client\ClientServiceInterface; +use SP\Domain\Tag\TagServiceInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; /** * Trait ImportTrait * - * @package SP\Services\Import + * @package SP\Domain\Import\Services */ trait ImportTrait { @@ -52,14 +52,14 @@ trait ImportTrait /** * @var bool Indica si el hash de la clave suministrada es igual a la actual */ - protected bool $mPassValidHash = false; - protected int $counter = 0; - protected ImportParams $importParams; - private AccountService $accountService; - private CategoryService $categoryService; - private ClientService $clientService; - private TagService $tagService; - private array $items; + protected bool $mPassValidHash = false; + protected int $counter = 0; + protected ImportParams $importParams; + private AccountServiceInterface $accountService; + private CategoryServiceInterface $categoryService; + private ClientServiceInterface $clientService; + private TagServiceInterface $tagService; + private array $items; /** * @return int @@ -72,7 +72,7 @@ trait ImportTrait /** * Añadir una cuenta desde un archivo importado. * - * @param AccountRequest $accountRequest + * @param AccountRequest $accountRequest * * @throws ImportException * @throws SPException @@ -122,7 +122,7 @@ trait ImportTrait /** * Añadir una categoría y devolver el Id * - * @param CategoryData $categoryData + * @param CategoryData $categoryData * * @return int * @throws DuplicatedItemException @@ -141,17 +141,13 @@ trait ImportTrait throw $e; } - return $this->addWorkingItem( - 'category', - $itemData->getName(), - $itemData->getId() - ); + return $this->addWorkingItem('category', $itemData->getName(), $itemData->getId()); } } /** - * @param string $type - * @param string|int $value + * @param string $type + * @param string|int $value * * @return int|null */ @@ -161,17 +157,13 @@ trait ImportTrait } /** - * @param string $type - * @param string|int $value - * @param int $id + * @param string $type + * @param string|int $value + * @param int $id * * @return int */ - protected function addWorkingItem( - string $type, - $value, - int $id - ): int + protected function addWorkingItem(string $type, $value, int $id): int { if (isset($this->items[$type][$value])) { return $this->items[$type][$value]; @@ -185,7 +177,7 @@ trait ImportTrait /** * Añadir un cliente y devolver el Id * - * @param ClientData $clientData + * @param ClientData $clientData * * @return int * @throws DuplicatedItemException @@ -215,7 +207,7 @@ trait ImportTrait /** * Añadir una etiqueta y devolver el Id * - * @param TagData $tagData + * @param TagData $tagData * * @return int * @throws SPException diff --git a/lib/SP/Services/Import/KeepassImport.php b/lib/SP/Domain/Import/Services/KeepassImport.php similarity index 82% rename from lib/SP/Services/Import/KeepassImport.php rename to lib/SP/Domain/Import/Services/KeepassImport.php index dde63bb2..8e55215f 100644 --- a/lib/SP/Services/Import/KeepassImport.php +++ b/lib/SP/Domain/Import/Services/KeepassImport.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use DOMElement; use DOMXPath; @@ -32,7 +32,8 @@ use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ClientData; -use SP\Services\Account\AccountRequest; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Import\ImportInterface; use SP\Util\Filter; defined('APP_ROOT') || die(); @@ -53,8 +54,7 @@ final class KeepassImport extends XmlImportBase implements ImportInterface { $this->eventDispatcher->notifyEvent( 'run.import.keepass', - new Event($this, EventMessage::factory() - ->addDescription(__u('KeePass XML Import'))) + new Event($this, EventMessage::factory()->addDescription(__u('KeePass XML Import'))) ); $this->process(); @@ -73,8 +73,7 @@ final class KeepassImport extends XmlImportBase implements ImportInterface $this->eventDispatcher->notifyEvent( 'run.import.keepass.process.client', - new Event($this, EventMessage::factory() - ->addDetail(__u('Client added'), 'KeePass')) + new Event($this, EventMessage::factory()->addDetail(__u('Client added'), 'KeePass')) ); $this->getGroups(); @@ -84,14 +83,11 @@ final class KeepassImport extends XmlImportBase implements ImportInterface /** @var AccountRequest[] $group */ foreach ($this->items as $group => $entry) { try { - $categoryId = $this->addCategory( - new CategoryData(null, $group, 'KeePass') - ); + $categoryId = $this->addCategory(new CategoryData(null, $group, 'KeePass')); $this->eventDispatcher->notifyEvent( 'run.import.keepass.process.category', - new Event($this, EventMessage::factory() - ->addDetail(__u('Category imported'), $group)) + new Event($this, EventMessage::factory()->addDetail(__u('Category imported'), $group)) ); if (count($entry) > 0) { @@ -103,9 +99,12 @@ final class KeepassImport extends XmlImportBase implements ImportInterface $this->eventDispatcher->notifyEvent( 'run.import.keepass.process.account', - new Event($this, EventMessage::factory() - ->addDetail(__u('Account imported'), $account->name) - ->addDetail(__u('Category'), $group)) + new Event( + $this, + EventMessage::factory() + ->addDetail(__u('Account imported'), $account->name) + ->addDetail(__u('Category'), $group) + ) ); } } @@ -131,7 +130,7 @@ final class KeepassImport extends XmlImportBase implements ImportInterface /** @var DOMElement[] $tags */ foreach ($tags as $tag) { if ($tag->nodeType === 1) { - $groupName = $DomXpath->query($tag->getNodePath() . '/Name') + $groupName = $DomXpath->query($tag->getNodePath().'/Name') ->item(0) ->nodeValue; @@ -157,15 +156,15 @@ final class KeepassImport extends XmlImportBase implements ImportInterface $entryData = []; /** @var DOMElement $key */ - foreach ($DomXpath->query($path . '/String/Key') as $key) { - $value = $DomXpath->query($key->getNodePath() . '/../Value') + foreach ($DomXpath->query($path.'/String/Key') as $key) { + $value = $DomXpath->query($key->getNodePath().'/../Value') ->item(0) ->nodeValue; $entryData[$key->nodeValue] = $value; } - $groupName = $DomXpath->query($path . '/../Name') + $groupName = $DomXpath->query($path.'/../Name') ->item(0) ->nodeValue; diff --git a/lib/SP/Services/Ldap/LdapImportParams.php b/lib/SP/Domain/Import/Services/LdapImportParams.php similarity index 68% rename from lib/SP/Services/Ldap/LdapImportParams.php rename to lib/SP/Domain/Import/Services/LdapImportParams.php index 67bf19ad..a88e0e0f 100644 --- a/lib/SP/Services/Ldap/LdapImportParams.php +++ b/lib/SP/Domain/Import/Services/LdapImportParams.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,19 +22,19 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Ldap; +namespace SP\Domain\Import\Services; /** * Class LdapImportParams * - * @package SP\Services\Ldap + * @package SP\Domain\Import\Services */ final class LdapImportParams { - public ?int $defaultUserGroup = null; - public ?int $defaultUserProfile = null; - public ?string $loginAttribute = null; - public ?string $userNameAttribute = null; + public ?int $defaultUserGroup = null; + public ?int $defaultUserProfile = null; + public ?string $loginAttribute = null; + public ?string $userNameAttribute = null; public ?string $userGroupNameAttribute = null; - public ?string $filter = null; + public ?string $filter = null; } \ No newline at end of file diff --git a/lib/SP/Services/Ldap/LdapImportService.php b/lib/SP/Domain/Import/Services/LdapImportService.php similarity index 67% rename from lib/SP/Services/Ldap/LdapImportService.php rename to lib/SP/Domain/Import/Services/LdapImportService.php index eba1ac6a..5af68e52 100644 --- a/lib/SP/Services/Ldap/LdapImportService.php +++ b/lib/SP/Domain/Import/Services/LdapImportService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,31 +22,47 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Ldap; +namespace SP\Domain\Import\Services; use Exception; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\DataModel\UserData; use SP\DataModel\UserGroupData; +use SP\Domain\Common\Services\Service; +use SP\Domain\Import\LdapImportServiceInterface; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\UserServiceInterface; use SP\Providers\Auth\Ldap\Ldap; use SP\Providers\Auth\Ldap\LdapException; use SP\Providers\Auth\Ldap\LdapInterface; use SP\Providers\Auth\Ldap\LdapParams; -use SP\Services\Service; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; /** * Class UserLdapService * - * @package SP\Services\User + * @package SP\Domain\User\Services */ -final class LdapImportService extends Service +final class LdapImportService extends Service implements LdapImportServiceInterface { - protected int $totalObjects = 0; - protected int $syncedObjects = 0; - protected int $errorObjects = 0; + protected int $totalObjects = 0; + protected int $syncedObjects = 0; + protected int $errorObjects = 0; + private UserServiceInterface $userService; + private UserGroupService $userGroupService; + + public function __construct( + Application $application, + UserServiceInterface $userService, + UserGroupService $userGroupService + ) { + parent::__construct($application); + + $this->userService = $userService; + $this->userGroupService = $userGroupService; + } + public function getTotalObjects(): int { @@ -69,33 +85,27 @@ final class LdapImportService extends Service * @throws LdapException */ public function importGroups( - LdapParams $ldapParams, + LdapParams $ldapParams, LdapImportParams $ldapImportParams - ): void - { + ): void { $ldap = $this->getLdap($ldapParams); if (empty($ldapImportParams->filter)) { - $objects = $ldap->getLdapActions() - ->getObjects($ldap->getGroupObjectFilter()); + $objects = $ldap->getLdapActions()->getObjects($ldap->getGroupObjectFilter()); } else { - $objects = $ldap->getLdapActions() - ->getObjects($ldapImportParams->filter); + $objects = $ldap->getLdapActions()->getObjects($ldapImportParams->filter); } $numObjects = (int)$objects['count']; $this->eventDispatcher->notifyEvent( 'import.ldap.groups', - new Event($this, EventMessage::factory() - ->addDetail(__u('Objects found'), $numObjects)) + new Event($this, EventMessage::factory()->addDetail(__u('Objects found'), $numObjects)) ); $this->totalObjects += $numObjects; if ($numObjects > 0) { - $userGroupService = $this->dic->get(UserGroupService::class); - foreach ($objects as $result) { if (is_array($result)) { $userGroupData = new UserGroupData(); @@ -113,22 +123,24 @@ final class LdapImportService extends Service try { $userGroupData->setDescription(__('Imported from LDAP')); - $userGroupService->create($userGroupData); + $this->userGroupService->create($userGroupData); $this->eventDispatcher->notifyEvent( 'import.ldap.progress.groups', - new Event($this, EventMessage::factory() - ->addDetail(__u('Group'), sprintf('%s', $userGroupData->getName()))) + new Event( + $this, + EventMessage::factory()->addDetail( + __u('Group'), + sprintf('%s', $userGroupData->getName()) + ) + ) ); $this->syncedObjects++; } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); $this->errorObjects++; } @@ -154,33 +166,27 @@ final class LdapImportService extends Service * @throws LdapException */ public function importUsers( - LdapParams $ldapParams, + LdapParams $ldapParams, LdapImportParams $ldapImportParams - ): void - { + ): void { $ldap = $this->getLdap($ldapParams); if (empty($ldapImportParams->filter)) { - $objects = $ldap->getLdapActions() - ->getObjects($ldap->getGroupMembershipIndirectFilter()); + $objects = $ldap->getLdapActions()->getObjects($ldap->getGroupMembershipIndirectFilter()); } else { - $objects = $ldap->getLdapActions() - ->getObjects($ldapImportParams->filter); + $objects = $ldap->getLdapActions()->getObjects($ldapImportParams->filter); } $numObjects = (int)$objects['count']; $this->eventDispatcher->notifyEvent( 'import.ldap.users', - new Event($this, EventMessage::factory() - ->addDetail(__u('Objects found'), $numObjects)) + new Event($this, EventMessage::factory()->addDetail(__u('Objects found'), $numObjects)) ); $this->totalObjects += $numObjects; if ($numObjects > 0) { - $userService = $this->dic->get(UserService::class); - foreach ($objects as $result) { if (is_array($result)) { $userData = new UserData(); @@ -211,22 +217,25 @@ final class LdapImportService extends Service $userData->setUserProfileId($ldapImportParams->defaultUserProfile); $userData->setIsLdap(true); - $userService->create($userData); + $this->userService->create($userData); $this->eventDispatcher->notifyEvent( 'import.ldap.progress.users', - new Event($this, EventMessage::factory() - ->addDetail(__u('User'), sprintf('%s (%s)', $userData->getName(), $userData->getLogin()))) + new Event( + $this, + EventMessage::factory() + ->addDetail( + __u('User'), + sprintf('%s (%s)', $userData->getName(), $userData->getLogin()) + ) + ) ); $this->syncedObjects++; } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); $this->errorObjects++; } diff --git a/lib/SP/Services/Import/SyspassImport.php b/lib/SP/Domain/Import/Services/SyspassImport.php similarity index 73% rename from lib/SP/Services/Import/SyspassImport.php rename to lib/SP/Domain/Import/Services/SyspassImport.php index f3b4fb1e..c452e019 100644 --- a/lib/SP/Services/Import/SyspassImport.php +++ b/lib/SP/Domain/Import/Services/SyspassImport.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use Defuse\Crypto\Exception\CryptoException; use DOMDocument; @@ -39,8 +39,9 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ClientData; use SP\DataModel\TagData; -use SP\Services\Account\AccountRequest; -use SP\Services\Export\XmlVerifyService; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Export\Services\XmlVerifyService; +use SP\Domain\Import\ImportInterface; use SP\Util\VersionUtil; defined('APP_ROOT') || die(); @@ -60,8 +61,7 @@ final class SyspassImport extends XmlImportBase implements ImportInterface try { $this->eventDispatcher->notifyEvent( 'run.import.syspass', - new Event($this, EventMessage::factory() - ->addDescription(__u('sysPass XML Import'))) + new Event($this, EventMessage::factory()->addDescription(__u('sysPass XML Import'))) ); if (!empty($this->importParams->getImportMasterPwd())) { @@ -75,10 +75,7 @@ final class SyspassImport extends XmlImportBase implements ImportInterface if ($this->detectEncrypted()) { if ($this->importParams->getImportPwd() === '') { - throw new ImportException( - __u('Encryption password not set'), - SPException::INFO - ); + throw new ImportException(__u('Encryption password not set'), SPException::INFO); } $this->processEncrypted(); @@ -113,8 +110,10 @@ final class SyspassImport extends XmlImportBase implements ImportInterface */ protected function getXmlVersion() { - return VersionUtil::versionToInteger((new DOMXPath($this->xmlDOM)) - ->query('/Root/Meta/Version')->item(0)->nodeValue); + return VersionUtil::versionToInteger( + (new DOMXPath($this->xmlDOM)) + ->query('/Root/Meta/Version')->item(0)->nodeValue + ); } /** @@ -122,8 +121,7 @@ final class SyspassImport extends XmlImportBase implements ImportInterface */ protected function detectEncrypted(): bool { - return $this->xmlDOM - ->getElementsByTagName('Encrypted')->length > 0; + return $this->xmlDOM->getElementsByTagName('Encrypted')->length > 0; } /** @@ -153,26 +151,25 @@ final class SyspassImport extends XmlImportBase implements ImportInterface $node->getAttribute('key'), $this->importParams->getImportPwd() ); - } else if ($this->version >= 320) { - $xmlDecrypted = Crypt::decrypt( - $node->nodeValue, - $node->getAttribute('key'), - $this->importParams->getImportPwd() - ); } else { - $xmlDecrypted = OldCrypt::getDecrypt( - base64_decode($node->nodeValue), - base64_decode($node->getAttribute('iv')), - $this->importParams->getImportPwd() - ); + if ($this->version >= 320) { + $xmlDecrypted = Crypt::decrypt( + $node->nodeValue, + $node->getAttribute('key'), + $this->importParams->getImportPwd() + ); + } else { + $xmlDecrypted = OldCrypt::getDecrypt( + base64_decode($node->nodeValue), + base64_decode($node->getAttribute('iv')), + $this->importParams->getImportPwd() + ); + } } } catch (CryptoException $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); continue; } @@ -184,8 +181,9 @@ final class SyspassImport extends XmlImportBase implements ImportInterface } $this->xmlDOM->documentElement - ->appendChild($this->xmlDOM - ->importNode($newXmlData->documentElement, true)); + ->appendChild( + $this->xmlDOM->importNode($newXmlData->documentElement, true) + ); } // Eliminar los datos encriptados tras desencriptar los mismos @@ -198,8 +196,7 @@ final class SyspassImport extends XmlImportBase implements ImportInterface $this->eventDispatcher->notifyEvent( 'run.import.syspass.process.decryption', - new Event($this, EventMessage::factory() - ->addDescription(__u('Data unencrypted'))) + new Event($this, EventMessage::factory()->addDescription(__u('Data unencrypted'))) ); } @@ -213,9 +210,16 @@ final class SyspassImport extends XmlImportBase implements ImportInterface if (!XmlVerifyService::checkXmlHash($this->xmlDOM, $key)) { $this->eventDispatcher->notifyEvent( 'run.import.syspass.process.verify', - new Event($this, EventMessage::factory() - ->addDescription(__u('Error while checking integrity hash')) - ->addDescription(__u('If you are importing an exported file from the same origin, the data could be compromised.'))) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Error while checking integrity hash')) + ->addDescription( + __u( + 'If you are importing an exported file from the same origin, the data could be compromised.' + ) + ) + ) ); } } @@ -227,7 +231,9 @@ final class SyspassImport extends XmlImportBase implements ImportInterface */ protected function processCategories(): void { - $this->getNodesData('Categories', 'Category', + $this->getNodesData( + 'Categories', + 'Category', function (DOMElement $category) { $categoryData = new CategoryData(); @@ -253,18 +259,19 @@ final class SyspassImport extends XmlImportBase implements ImportInterface $this->eventDispatcher->notifyEvent( 'run.import.syspass.process.category', - new Event($this, EventMessage::factory() - ->addDetail(__u('Category imported'), $categoryData->getName())) + new Event( + $this, + EventMessage::factory() + ->addDetail(__u('Category imported'), $categoryData->getName()) + ) ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); } - }); + } + ); } /** @@ -274,7 +281,9 @@ final class SyspassImport extends XmlImportBase implements ImportInterface */ protected function processClients(): void { - $this->getNodesData('Clients', 'Client', + $this->getNodesData( + 'Clients', + 'Client', function (DOMElement $client) { $clientData = new ClientData(); @@ -300,18 +309,19 @@ final class SyspassImport extends XmlImportBase implements ImportInterface $this->eventDispatcher->notifyEvent( 'run.import.syspass.process.client', - new Event($this, EventMessage::factory() - ->addDetail(__u('Client imported'), $clientData->getName())) + new Event( + $this, + EventMessage::factory() + ->addDetail(__u('Client imported'), $clientData->getName()) + ) ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); } - }); + } + ); } /** @@ -322,7 +332,9 @@ final class SyspassImport extends XmlImportBase implements ImportInterface */ protected function processCustomers(): void { - $this->getNodesData('Customers', 'Customer', + $this->getNodesData( + 'Customers', + 'Customer', function (DOMElement $client) { $clientData = new ClientData(); @@ -348,18 +360,18 @@ final class SyspassImport extends XmlImportBase implements ImportInterface $this->eventDispatcher->notifyEvent( 'run.import.syspass.process.customer', - new Event($this, EventMessage::factory() - ->addDetail(__u('Client imported'), $clientData->getName())) + new Event( + $this, + EventMessage::factory()->addDetail(__u('Client imported'), $clientData->getName()) + ) ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); } - }); + } + ); } /** @@ -369,13 +381,14 @@ final class SyspassImport extends XmlImportBase implements ImportInterface */ protected function processTags(): void { - $this->getNodesData('Tags', 'Tag', + $this->getNodesData( + 'Tags', + 'Tag', function (DOMElement $tag) { $tagData = new TagData(); foreach ($tag->childNodes as $node) { - if (isset($node->tagName) - && $node->tagName === 'name') { + if (isset($node->tagName) && $node->tagName === 'name') { $tagData->setName($node->nodeValue); } } @@ -389,18 +402,19 @@ final class SyspassImport extends XmlImportBase implements ImportInterface $this->eventDispatcher->notifyEvent( 'run.import.syspass.process.tag', - new Event($this, EventMessage::factory() - ->addDetail(__u('Tag imported'), $tagData->getName())) + new Event( + $this, + EventMessage::factory()->addDetail(__u('Tag imported'), $tagData->getName()) + ) ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); } - }, false); + }, + false + ); } /** @@ -410,7 +424,9 @@ final class SyspassImport extends XmlImportBase implements ImportInterface */ protected function processAccounts(): void { - $this->getNodesData('Accounts', 'Account', + $this->getNodesData( + 'Accounts', + 'Account', function (DOMElement $account) { $accountRequest = new AccountRequest(); @@ -426,18 +442,12 @@ final class SyspassImport extends XmlImportBase implements ImportInterface break; case 'categoryId'; $accountRequest->categoryId = - $this->getWorkingItem( - 'category', - (int)$node->nodeValue - ); + $this->getWorkingItem('category', (int)$node->nodeValue); break; case 'clientId'; case 'customerId'; $accountRequest->clientId = - $this->getWorkingItem( - 'client', - (int)$node->nodeValue - ); + $this->getWorkingItem('client', (int)$node->nodeValue); break; case 'url'; $accountRequest->url = $node->nodeValue; @@ -452,8 +462,7 @@ final class SyspassImport extends XmlImportBase implements ImportInterface $accountRequest->notes = $node->nodeValue; break; case 'tags': - $accountRequest->tags = - $this->processAccountTags($node->childNodes); + $accountRequest->tags = $this->processAccountTags($node->childNodes); } } } @@ -463,18 +472,18 @@ final class SyspassImport extends XmlImportBase implements ImportInterface $this->eventDispatcher->notifyEvent( 'run.import.syspass.process.account', - new Event($this, EventMessage::factory() - ->addDetail(__u('Account imported'), $accountRequest->name)) + new Event( + $this, + EventMessage::factory()->addDetail(__u('Account imported'), $accountRequest->name) + ) ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); } - }); + } + ); } /** @@ -488,10 +497,7 @@ final class SyspassImport extends XmlImportBase implements ImportInterface /** @var DOMElement $node */ foreach ($nodes as $node) { if (isset($node->tagName)) { - $tags[] = $this->getWorkingItem( - 'tag', - (int)$node->getAttribute('id') - ); + $tags[] = $this->getWorkingItem('tag', (int)$node->getAttribute('id')); } } } diff --git a/lib/SP/Services/Import/XmlFileImport.php b/lib/SP/Domain/Import/Services/XmlFileImport.php similarity index 83% rename from lib/SP/Services/Import/XmlFileImport.php rename to lib/SP/Domain/Import/Services/XmlFileImport.php index e1c80813..9ee95b86 100644 --- a/lib/SP/Services/Import/XmlFileImport.php +++ b/lib/SP/Domain/Import/Services/XmlFileImport.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,31 +22,33 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use DOMDocument; use SP\Core\Exceptions\SPException; -use SP\Storage\File\FileException; +use SP\Domain\Import\FileImportInterface; +use SP\Domain\Import\XmlFileImportInterface; +use SP\Infrastructure\File\FileException; /** * Class XmlFileImport * * @package Import */ -final class XmlFileImport +final class XmlFileImport implements XmlFileImportInterface { - protected FileImport $fileImport; + protected FileImport $fileImport; protected ?DOMDocument $xmlDOM = null; /** * XmlFileImport constructor. * - * @param FileImport $fileImport + * @param \SP\Domain\Import\FileImportInterface $fileImport * * @throws ImportException * @throws FileException */ - public function __construct(FileImport $fileImport) + public function __construct(FileImportInterface $fileImport) { $this->fileImport = $fileImport; @@ -70,14 +72,10 @@ final class XmlFileImport if ($this->xmlDOM->loadXML($this->fileImport->readFileToString(), LIBXML_PARSEHUGE) === false) { foreach (libxml_get_errors() as $error) { - logger(__METHOD__ . ' - ' . $error->message); + logger(__METHOD__.' - '.$error->message); } - throw new ImportException( - __u('Internal error'), - SPException::ERROR, - __u('Unable to process the XML file') - ); + throw new ImportException(__u('Internal error'), SPException::ERROR, __u('Unable to process the XML file')); } } @@ -123,6 +121,7 @@ final class XmlFileImport while (($buffer = fgets($handle, 4096)) !== false && $count <= $maxLines) { if (preg_match('/(?P
KEEPASSX_DATABASE|revelationdata)/i', $buffer, $matches)) { fclose($handle); + return strtolower($matches['header']); } $count++; diff --git a/lib/SP/Services/Import/XmlImport.php b/lib/SP/Domain/Import/Services/XmlImport.php similarity index 63% rename from lib/SP/Services/Import/XmlImport.php rename to lib/SP/Domain/Import/Services/XmlImport.php index 6b18de01..32ac0322 100644 --- a/lib/SP/Services/Import/XmlImport.php +++ b/lib/SP/Domain/Import/Services/XmlImport.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,10 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; -use Psr\Container\ContainerInterface; +use SP\Core\Application; use SP\Core\Exceptions\SPException; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Import\ImportInterface; +use SP\Domain\Import\XmlFileImportInterface; +use SP\Domain\Import\XmlImportInterface; defined('APP_ROOT') || die(); @@ -35,28 +39,29 @@ defined('APP_ROOT') || die(); * * @package SP */ -final class XmlImport implements ImportInterface +final class XmlImport implements XmlImportInterface { - protected XmlFileImport $xmlFileImport; - protected ImportParams $importParams; - private ContainerInterface $dic; + private XmlFileImport $xmlFileImport; + private ImportParams $importParams; + private ImportHelper $importHelper; + private ConfigServiceInterface $configService; + private Application $application; /** * XmlImport constructor. - * - * @param ContainerInterface $dic - * @param XmlFileImport $xmlFileImport - * @param ImportParams $importParams */ public function __construct( - ContainerInterface $dic, - XmlFileImport $xmlFileImport, - ImportParams $importParams - ) - { + Application $application, + ImportHelper $importHelper, + ConfigServiceInterface $configService, + XmlFileImportInterface $xmlFileImport, + ImportParams $importParams + ) { + $this->application = $application; + $this->importHelper = $importHelper; + $this->configService = $configService; $this->xmlFileImport = $xmlFileImport; $this->importParams = $importParams; - $this->dic = $dic; } /** @@ -73,23 +78,27 @@ final class XmlImport implements ImportInterface } /** - * @param string $format + * @param string $format * * @return KeepassImport|SyspassImport - * @throws \SP\Services\Import\ImportException + * @throws \SP\Domain\Import\Services\ImportException */ protected function selectImportType(string $format) { switch ($format) { case 'syspass': return new SyspassImport( - $this->dic, + $this->application, + $this->importHelper, + $this->configService, $this->xmlFileImport, $this->importParams ); case 'keepass': return new KeepassImport( - $this->dic, + $this->application, + $this->importHelper, + $this->configService, $this->xmlFileImport, $this->importParams ); diff --git a/lib/SP/Services/Import/XmlImportBase.php b/lib/SP/Domain/Import/Services/XmlImportBase.php similarity index 52% rename from lib/SP/Services/Import/XmlImportBase.php rename to lib/SP/Domain/Import/Services/XmlImportBase.php index 24c5b819..1e60d304 100644 --- a/lib/SP/Services/Import/XmlImportBase.php +++ b/lib/SP/Domain/Import/Services/XmlImportBase.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,87 +22,76 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Import; +namespace SP\Domain\Import\Services; use DOMDocument; use DOMElement; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Config\ConfigDataInterface; +use SP\Core\Application; use SP\Core\Events\EventDispatcher; use SP\Core\Exceptions\SPException; -use SP\Services\Account\AccountService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Config\ConfigService; -use SP\Services\Tag\TagService; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Import\XmlFileImportInterface; /** * Class XmlImportBase * - * @package SP\Services\Import + * @package SP\Domain\Import\Services */ abstract class XmlImportBase { use ImportTrait; - protected XmlFileImport $xmlFileImport; - protected DOMDocument $xmlDOM; - protected EventDispatcher $eventDispatcher; - protected ConfigService $configService; - protected ConfigDataInterface $configData; + protected XmlFileImportInterface $xmlFileImport; + protected DOMDocument $xmlDOM; + protected EventDispatcher $eventDispatcher; + protected ConfigServiceInterface $configService; + protected ConfigDataInterface $configData; /** * ImportBase constructor. - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface */ public function __construct( - ContainerInterface $dic, - XmlFileImport $xmlFileImport, - ImportParams $importParams - ) - { + Application $application, + ImportHelper $importHelper, + ConfigServiceInterface $configService, + XmlFileImportInterface $xmlFileImport, + ImportParams $importParams + ) { + $this->eventDispatcher = $application->getEventDispatcher(); $this->xmlFileImport = $xmlFileImport; $this->importParams = $importParams; - $this->xmlDOM = $xmlFileImport->getXmlDOM(); + $this->accountService = $importHelper->getAccountService(); + $this->categoryService = $importHelper->getCategoryService(); + $this->clientService = $importHelper->getClientService(); + $this->tagService = $importHelper->getTagService(); + $this->configService = $configService; - $this->configData = $dic->get(ConfigDataInterface::class); - $this->accountService = $dic->get(AccountService::class); - $this->categoryService = $dic->get(CategoryService::class); - $this->clientService = $dic->get(ClientService::class); - $this->tagService = $dic->get(TagService::class); - $this->eventDispatcher = $dic->get(EventDispatcher::class); - $this->configService = $dic->get(ConfigService::class); + $this->configData = $application->getConfig()->getConfigData(); + $this->xmlDOM = $xmlFileImport->getXmlDOM(); } /** * Obtener los datos de los nodos * - * @param string $nodeName Nombre del nodo principal - * @param string $childNodeName Nombre de los nodos hijos - * @param callable $callback Método a ejecutar - * @param bool $required Indica si el nodo es requerido + * @param string $nodeName Nombre del nodo principal + * @param string $childNodeName Nombre de los nodos hijos + * @param callable $callback Método a ejecutar + * @param bool $required Indica si el nodo es requerido * * @throws ImportException */ protected function getNodesData( - string $nodeName, - string $childNodeName, + string $nodeName, + string $childNodeName, callable $callback, - bool $required = true - ): void - { + bool $required = true + ): void { $nodeList = $this->xmlDOM->getElementsByTagName($nodeName); if ($nodeList->length > 0) { if (!is_callable($callback)) { - throw new ImportException( - __u('Invalid Method'), - SPException::WARNING - ); + throw new ImportException(__u('Invalid Method'), SPException::WARNING); } /** @var DOMElement $nodes */ diff --git a/lib/SP/Domain/Import/XmlFileImportInterface.php b/lib/SP/Domain/Import/XmlFileImportInterface.php new file mode 100644 index 00000000..fe2bb332 --- /dev/null +++ b/lib/SP/Domain/Import/XmlFileImportInterface.php @@ -0,0 +1,46 @@ +. + */ + +namespace SP\Domain\Import; + + +use DOMDocument; +use SP\Domain\Import\Services\ImportException; + +/** + * Class XmlFileImport + * + * @package Import + */ +interface XmlFileImportInterface +{ + /** + * Detectar la aplicación que generó el XML. + * + * @throws ImportException + */ + public function detectXMLFormat(): string; + + public function getXmlDOM(): DOMDocument; +} \ No newline at end of file diff --git a/lib/SP/Domain/Import/XmlImportInterface.php b/lib/SP/Domain/Import/XmlImportInterface.php new file mode 100644 index 00000000..f10c7528 --- /dev/null +++ b/lib/SP/Domain/Import/XmlImportInterface.php @@ -0,0 +1,36 @@ +. + */ + +namespace SP\Domain\Import; + + +/** + * Clase XmlImport para usarla como envoltorio para llamar a la clase que corresponda + * según el tipo de archivo XML detectado. + * + * @package SP + */ +interface XmlImportInterface extends ImportInterface +{ +} \ No newline at end of file diff --git a/lib/SP/Services/Install/DatabaseSetupInterface.php b/lib/SP/Domain/Install/DatabaseSetupInterface.php similarity index 93% rename from lib/SP/Services/Install/DatabaseSetupInterface.php rename to lib/SP/Domain/Install/DatabaseSetupInterface.php index b25f2cfb..0c8a8eb5 100644 --- a/lib/SP/Services/Install/DatabaseSetupInterface.php +++ b/lib/SP/Domain/Install/DatabaseSetupInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,12 +22,12 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Install; +namespace SP\Domain\Install; /** * Interface DatabaseInterface * - * @package SP\Services\Install + * @package SP\Domain\Install\Services */ interface DatabaseSetupInterface { diff --git a/lib/SP/Domain/Install/InstallerInterface.php b/lib/SP/Domain/Install/InstallerInterface.php new file mode 100644 index 00000000..eed66748 --- /dev/null +++ b/lib/SP/Domain/Install/InstallerInterface.php @@ -0,0 +1,42 @@ +. + */ + +namespace SP\Domain\Install; + + +use SP\Core\Exceptions\InvalidArgumentException; +use SP\Core\Exceptions\SPException; +use SP\Domain\Install\Services\InstallData; + +/** + * Installer class + */ +interface InstallerInterface +{ + /** + * @throws InvalidArgumentException + * @throws SPException + */ + public function run(DatabaseSetupInterface $databaseSetup, InstallData $installData): InstallerInterface; +} \ No newline at end of file diff --git a/lib/SP/Services/Install/InstallData.php b/lib/SP/Domain/Install/Services/InstallData.php similarity index 99% rename from lib/SP/Services/Install/InstallData.php rename to lib/SP/Domain/Install/Services/InstallData.php index 76a854c6..df62f204 100644 --- a/lib/SP/Services/Install/InstallData.php +++ b/lib/SP/Domain/Install/Services/InstallData.php @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Install; +namespace SP\Domain\Install\Services; /** * Class InstallData diff --git a/lib/SP/Services/Install/Installer.php b/lib/SP/Domain/Install/Services/Installer.php similarity index 86% rename from lib/SP/Services/Install/Installer.php rename to lib/SP/Domain/Install/Services/Installer.php index 8cc43542..691913c4 100644 --- a/lib/SP/Services/Install/Installer.php +++ b/lib/SP/Domain/Install/Services/Installer.php @@ -5,7 +5,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -23,12 +23,9 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Install; +namespace SP\Domain\Install\Services; use Exception; -use SP\Config\Config; -use SP\Config\ConfigData as ConfigSettings; -use SP\Config\ConfigDataInterface; use SP\Core\Crypt\Hash; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\InvalidArgumentException; @@ -39,16 +36,26 @@ use SP\DataModel\ProfileData; use SP\DataModel\UserData; use SP\DataModel\UserGroupData; use SP\DataModel\UserProfileData; +use SP\Domain\Config\Adapters\ConfigData as ConfigSettings; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\Config\Services\ConfigService; +use SP\Domain\Install\DatabaseSetupInterface; +use SP\Domain\Install\InstallerInterface; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserProfileService; +use SP\Domain\User\Services\UserService; +use SP\Domain\User\UserGroupServiceInterface; +use SP\Domain\User\UserProfileServiceInterface; use SP\Http\Request; -use SP\Services\Config\ConfigService; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserProfile\UserProfileService; -use SP\Storage\Database\DatabaseConnectionData; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\Database\MySQLFileParser; -use SP\Storage\Database\MySQLHandler; -use SP\Storage\File\FileHandler; +use SP\Http\RequestInterface; +use SP\Infrastructure\Database\DatabaseConnectionData; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\Database\MySQLFileParser; +use SP\Infrastructure\Database\MySQLHandler; +use SP\Infrastructure\File\FileHandler; use SP\Util\VersionUtil; defined('APP_ROOT') || die(); @@ -56,18 +63,18 @@ defined('APP_ROOT') || die(); /** * Installer class */ -final class Installer +final class Installer implements InstallerInterface { /** * sysPass' version and build number */ - public const VERSION = [3, 2, 2]; - public const VERSION_TEXT = '3.2'; + public const VERSION = [4, 0, 0]; + public const VERSION_TEXT = '4.0'; public const BUILD = 21031301; - private Request $request; - private Config $config; - private UserService $userService; + private Request $request; + private ConfigFileService $config; + private UserService $userService; private UserGroupService $userGroupService; private UserProfileService $userProfileService; private ConfigService $configService; @@ -75,12 +82,12 @@ final class Installer private ?InstallData $installData = null; public function __construct( - Request $request, - Config $config, + RequestInterface $request, + ConfigInterface $config, UserService $userService, - UserGroupService $userGroupService, - UserProfileService $userProfileService, - ConfigService $configService + UserGroupServiceInterface $userGroupService, + UserProfileServiceInterface $userProfileService, + ConfigServiceInterface $configService ) { $this->request = $request; $this->config = $config; @@ -91,10 +98,10 @@ final class Installer } /** - * @param \SP\Services\Install\InstallData $installData + * @param \SP\Domain\Install\Services\InstallData $installData * @param $configData * - * @return \SP\Services\Install\DatabaseSetupInterface + * @return \SP\Domain\Install\DatabaseSetupInterface * @throws \SP\Core\Exceptions\SPException */ public static function getDatabaseSetup(InstallData $installData, $configData): DatabaseSetupInterface @@ -107,13 +114,7 @@ final class Installer ->setDbPass($installData->getDbAdminPass()); if ($installData->getBackendType() === 'mysql') { - $parser = new MySQLFileParser( - new FileHandler( - SQL_PATH. - DIRECTORY_SEPARATOR. - 'dbstructure.sql' - ) - ); + $parser = new MySQLFileParser(new FileHandler(SQL_PATH.DIRECTORY_SEPARATOR.'dbstructure.sql')); $mySQLHandler = new MySQLHandler($connectionData); @@ -127,7 +128,7 @@ final class Installer * @throws InvalidArgumentException * @throws SPException */ - public function run(DatabaseSetupInterface $databaseSetup, InstallData $installData): Installer + public function run(DatabaseSetupInterface $databaseSetup, InstallData $installData): InstallerInterface { $this->databaseSetup = $databaseSetup; $this->installData = $installData; @@ -341,16 +342,10 @@ final class Installer { try { $this->configService->create( - new ConfigData( - 'masterPwd', - Hash::hashKey($this->installData->getMasterPassword()) - ) + new ConfigData('masterPwd', Hash::hashKey($this->installData->getMasterPassword())) ); $this->configService->create( - new ConfigData( - 'lastupdatempass', - time() - ) + new ConfigData('lastupdatempass', time()) ); } catch (Exception $e) { processException($e); diff --git a/lib/SP/Services/Install/MySQL.php b/lib/SP/Domain/Install/Services/MySQL.php similarity index 96% rename from lib/SP/Services/Install/MySQL.php rename to lib/SP/Domain/Install/Services/MySQL.php index f6850c7c..7d9852ac 100644 --- a/lib/SP/Services/Install/MySQL.php +++ b/lib/SP/Domain/Install/Services/MySQL.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,21 +22,22 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Install; +namespace SP\Domain\Install\Services; use PDOException; -use SP\Config\ConfigDataInterface; use SP\Core\Exceptions\SPException; -use SP\Storage\Database\DatabaseFileInterface; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\Database\DBStorageInterface; -use SP\Storage\File\FileException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Install\DatabaseSetupInterface; +use SP\Infrastructure\Database\DatabaseFileInterface; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\Database\DBStorageInterface; +use SP\Infrastructure\File\FileException; use SP\Util\PasswordUtil; /** * Class MySQL * - * @package SP\Services\Install + * @package SP\Domain\Install\Services */ final class MySQL implements DatabaseSetupInterface { diff --git a/lib/SP/Domain/ItemPreset/In/ItemPresetRepositoryInterface.php b/lib/SP/Domain/ItemPreset/In/ItemPresetRepositoryInterface.php new file mode 100644 index 00000000..741d627d --- /dev/null +++ b/lib/SP/Domain/ItemPreset/In/ItemPresetRepositoryInterface.php @@ -0,0 +1,53 @@ +. + */ + +namespace SP\Domain\ItemPreset\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class AccountDefaultPermissionRepository + * + * @package SP\Infrastructure\Account\Repositories + */ +interface ItemPresetRepositoryInterface extends RepositoryInterface +{ + /** + * Returns the item for given id + * + * @param string $type + * @param int $userId + * @param int $userGroupId + * @param int $userProfileId + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByFilter(string $type, int $userId, int $userGroupId, int $userProfileId): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Services/ItemPreset/ItemPresetInterface.php b/lib/SP/Domain/ItemPreset/ItemPresetInterface.php similarity index 72% rename from lib/SP/Services/ItemPreset/ItemPresetInterface.php rename to lib/SP/Domain/ItemPreset/ItemPresetInterface.php index fe49bbc1..21ae53c7 100644 --- a/lib/SP/Services/ItemPreset/ItemPresetInterface.php +++ b/lib/SP/Domain/ItemPreset/ItemPresetInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,17 +22,17 @@ * along with sysPass. If not, see . */ -namespace SP\Services\ItemPreset; +namespace SP\Domain\ItemPreset; /** * Interface ItemPresetInterface * - * @package SP\Services\ItemPreset + * @package SP\Domain\ItemPreset\Services */ interface ItemPresetInterface { public const ITEM_TYPE_ACCOUNT_PERMISSION = 'account.permission'; - public const ITEM_TYPE_ACCOUNT_PASSWORD = 'account.password'; - public const ITEM_TYPE_ACCOUNT_PRIVATE = 'account.private'; - public const ITEM_TYPE_SESSION_TIMEOUT = 'session.timeout'; + public const ITEM_TYPE_ACCOUNT_PASSWORD = 'account.password'; + public const ITEM_TYPE_ACCOUNT_PRIVATE = 'account.private'; + public const ITEM_TYPE_SESSION_TIMEOUT = 'session.timeout'; } \ No newline at end of file diff --git a/lib/SP/Domain/ItemPreset/ItemPresetServiceInterface.php b/lib/SP/Domain/ItemPreset/ItemPresetServiceInterface.php new file mode 100644 index 00000000..6abd921c --- /dev/null +++ b/lib/SP/Domain/ItemPreset/ItemPresetServiceInterface.php @@ -0,0 +1,111 @@ +. + */ + +namespace SP\Domain\ItemPreset; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ItemPresetData; +use SP\DataModel\ItemSearchData; +use SP\Domain\ItemPreset\Services\ItemPresetRequest; +use SP\Domain\ItemPreset\Services\ItemPresetService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class ItemPresetService + * + * @package SP\Domain\Account\Services + */ +interface ItemPresetServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function create(ItemPresetRequest $itemPresetRequest): int; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function update(ItemPresetRequest $itemPresetRequest): int; + + /** + * Deletes an item + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): ItemPresetService; + + /** + * Returns the item for given id + * + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function getById(int $id): ItemPresetData; + + /** + * Returns all the items + * + * @return ItemPresetData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): array; + + /** + * Searches for items by a given filter + * + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function getForCurrentUser(string $type): ?ItemPresetData; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function getForUser(string $type, int $userId, int $userGroupId, int $userProfileId): ?ItemPresetData; + + /** + * @param int[] $ids + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function deleteByIdBatch(array $ids): int; +} \ No newline at end of file diff --git a/lib/SP/Services/ItemPreset/ItemPresetRequest.php b/lib/SP/Domain/ItemPreset/Services/ItemPresetRequest.php similarity index 89% rename from lib/SP/Services/ItemPreset/ItemPresetRequest.php rename to lib/SP/Domain/ItemPreset/Services/ItemPresetRequest.php index 03689f63..5bcd091a 100644 --- a/lib/SP/Services/ItemPreset/ItemPresetRequest.php +++ b/lib/SP/Domain/ItemPreset/Services/ItemPresetRequest.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,19 +22,19 @@ * along with sysPass. If not, see . */ -namespace SP\Services\ItemPreset; +namespace SP\Domain\ItemPreset\Services; use SP\DataModel\ItemPresetData; /** * Class ItemPresetRequest * - * @package SP\Services\ItemPreset + * @package SP\Domain\ItemPreset\Services */ final class ItemPresetRequest { private ItemPresetData $itemPresetData; - private $data; + private $data; /** * ItemPresetRequest constructor. diff --git a/lib/SP/Services/ItemPreset/ItemPresetService.php b/lib/SP/Domain/ItemPreset/Services/ItemPresetService.php similarity index 74% rename from lib/SP/Services/ItemPreset/ItemPresetService.php rename to lib/SP/Domain/ItemPreset/Services/ItemPresetService.php index 64686cae..e54c17ac 100644 --- a/lib/SP/Services/ItemPreset/ItemPresetService.php +++ b/lib/SP/Domain/ItemPreset/Services/ItemPresetService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,27 +22,37 @@ * along with sysPass. If not, see . */ -namespace SP\Services\ItemPreset; +namespace SP\Domain\ItemPreset\Services; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemPresetData; use SP\DataModel\ItemSearchData; -use SP\Repositories\ItemPreset\ItemPresetRepository; -use SP\Repositories\NoSuchItemException; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\ItemPreset\In\ItemPresetRepositoryInterface; +use SP\Domain\ItemPreset\ItemPresetServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\ItemPreset\Repositories\ItemPresetRepository; /** * Class ItemPresetService * - * @package SP\Services\Account + * @package SP\Domain\Account\Services */ -final class ItemPresetService extends Service +final class ItemPresetService extends Service implements ItemPresetServiceInterface { - private ?ItemPresetRepository $itemPresetRepository = null; + private ItemPresetRepository $itemPresetRepository; + + public function __construct(Application $application, ItemPresetRepositoryInterface $itemPresetRepository) + { + parent::__construct($application); + + $this->itemPresetRepository = $itemPresetRepository; + } /** * @throws ConstraintException @@ -50,8 +60,7 @@ final class ItemPresetService extends Service */ public function create(ItemPresetRequest $itemPresetRequest): int { - return $this->itemPresetRepository - ->create($itemPresetRequest->prepareToPersist()); + return $this->itemPresetRepository->create($itemPresetRequest->prepareToPersist()); } /** @@ -60,8 +69,7 @@ final class ItemPresetService extends Service */ public function update(ItemPresetRequest $itemPresetRequest): int { - return $this->itemPresetRepository - ->update($itemPresetRequest->prepareToPersist()); + return $this->itemPresetRepository->update($itemPresetRequest->prepareToPersist()); } /** @@ -69,7 +77,7 @@ final class ItemPresetService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function delete(int $id): ItemPresetService { @@ -143,11 +151,10 @@ final class ItemPresetService extends Service */ public function getForUser( string $type, - int $userId, - int $userGroupId, - int $userProfileId - ): ?ItemPresetData - { + int $userId, + int $userGroupId, + int $userProfileId + ): ?ItemPresetData { $result = $this->itemPresetRepository->getByFilter( $type, $userId, @@ -163,11 +170,11 @@ final class ItemPresetService extends Service } /** - * @param int[] $ids + * @param int[] $ids * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function deleteByIdBatch(array $ids): int { @@ -182,9 +189,4 @@ final class ItemPresetService extends Service return $count; } - - protected function initialize(): void - { - $this->itemPresetRepository = $this->dic->get(ItemPresetRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Domain/Notification/In/NotificationRepositoryInterface.php b/lib/SP/Domain/Notification/In/NotificationRepositoryInterface.php new file mode 100644 index 00000000..980bf044 --- /dev/null +++ b/lib/SP/Domain/Notification/In/NotificationRepositoryInterface.php @@ -0,0 +1,137 @@ +. + */ + +namespace SP\Domain\Notification\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ItemSearchData; +use SP\DataModel\NotificationData; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class NotificationRepository + * + * @package SP\Infrastructure\Notification\Repositories + */ +interface NotificationRepositoryInterface extends RepositoryInterface +{ + /** + * Deletes an item + * + * @param int $id + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function deleteAdmin(int $id): int; + + /** + * Deletes an item + * + * @param array $ids + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteAdminBatch(array $ids): int; + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $itemSearchData + * @param int $userId + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function searchForUserId(ItemSearchData $itemSearchData, int $userId): QueryResult; + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $itemSearchData + * @param int $userId + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function searchForAdmin(ItemSearchData $itemSearchData, int $userId): QueryResult; + + /** + * Marcar una notificación como leída + * + * @param int $id + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function setCheckedById(int $id): int; + + /** + * Devolver las notificaciones de un usuario para una fecha y componente determinados + * + * @param string $component + * @param int $userId + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getForUserIdByDate(string $component, int $userId): QueryResult; + + /** + * @param int $id + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getAllForUserId(int $id): QueryResult; + + /** + * @param int $id + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getAllActiveForUserId(int $id): QueryResult; + + /** + * @param int $id + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getAllActiveForAdmin(int $id): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/Notification/MailServiceInterface.php b/lib/SP/Domain/Notification/MailServiceInterface.php new file mode 100644 index 00000000..d76178d3 --- /dev/null +++ b/lib/SP/Domain/Notification/MailServiceInterface.php @@ -0,0 +1,63 @@ +. + */ + +namespace SP\Domain\Notification; + + +use SP\Core\Messages\MailMessage; +use SP\Domain\Common\Services\ServiceException; +use SP\Providers\Mail\MailParams; + +/** + * Class MailService + * + * @package SP\Domain\Common\Services + */ +interface MailServiceInterface +{ + /** + * Checks mail params by sending a test email + * + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function check(MailParams $mailParams, string $to): void; + + /** + * @param string $subject + * @param array|string $to + * @param MailMessage $mailMessage + * + * @throws \PHPMailer\PHPMailer\Exception + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function send(string $subject, $to, MailMessage $mailMessage): void; + + /** + * @throws \PHPMailer\PHPMailer\Exception + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function sendBatch(string $subject, array $to, MailMessage $mailMessage): void; + + public function getParamsFromConfig(): MailParams; +} \ No newline at end of file diff --git a/lib/SP/Domain/Notification/NotificationServiceInterface.php b/lib/SP/Domain/Notification/NotificationServiceInterface.php new file mode 100644 index 00000000..7d72e072 --- /dev/null +++ b/lib/SP/Domain/Notification/NotificationServiceInterface.php @@ -0,0 +1,174 @@ +. + */ + +namespace SP\Domain\Notification; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ItemSearchData; +use SP\DataModel\NotificationData; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class NotificationService + * + * @package SP\Domain\Notification\Services + */ +interface NotificationServiceInterface +{ + /** + * Creates an item + * + * @throws ConstraintException + * @throws QueryException + */ + public function create(NotificationData $itemData): int; + + /** + * Updates an item + * + * @throws ConstraintException + * @throws QueryException + */ + public function update(NotificationData $itemData): int; + + /** + * Devolver los elementos con los ids especificados + * + * @param int[] $ids + * + * @return NotificationData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getByIdBatch(array $ids): array; + + /** + * Deletes an item preserving the sticky ones + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): NotificationServiceInterface; + + /** + * Deletes an item + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function deleteAdmin(int $id): NotificationServiceInterface; + + /** + * Deletes an item + * + * @param int[] $ids + * + * @throws ConstraintException + * @throws QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function deleteAdminBatch(array $ids): int; + + /** + * Deletes all the items for given ids + * + * @param int[] $ids + * + * @throws ConstraintException + * @throws QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * Returns the item for given id + * + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function getById(int $id): NotificationData; + + /** + * Returns all the items + * + * @return NotificationData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): array; + + /** + * Marcar una notificación como leída + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function setCheckedById(int $id): void; + + /** + * Devolver las notificaciones de un usuario para una fecha y componente determinados + * + * @return NotificationData[] + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getForUserIdByDate(string $component, int $id): array; + + /** + * @return NotificationData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllForUserId(int $id): array; + + /** + * @return NotificationData[] + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getAllActiveForUserId(int $id): array; + + /** + * Searches for items by a given filter + * + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * Searches for items by a given filter + * + * @throws ConstraintException + * @throws QueryException + */ + public function searchForUserId(ItemSearchData $itemSearchData, int $userId): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Services/Mail/MailService.php b/lib/SP/Domain/Notification/Services/MailService.php similarity index 62% rename from lib/SP/Services/Mail/MailService.php rename to lib/SP/Domain/Notification/Services/MailService.php index 7839e6ce..eb0ff063 100644 --- a/lib/SP/Services/Mail/MailService.php +++ b/lib/SP/Domain/Notification/Services/MailService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,31 +22,63 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Mail; +namespace SP\Domain\Notification\Services; use Exception; -use PHPMailer\PHPMailer\PHPMailer; use SP\Core\AppInfoInterface; +use SP\Core\Application; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SPException; use SP\Core\Messages\MailMessage; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Notification\MailServiceInterface; +use SP\Domain\Providers\MailerInterface; +use SP\Domain\Providers\MailProviderInterface; use SP\Html\Html; use SP\Providers\Mail\MailParams; -use SP\Providers\Mail\MailProvider; -use SP\Providers\Mail\MailProviderException; -use SP\Services\Service; -use SP\Services\ServiceException; /** * Class MailService * - * @package SP\Services + * @package SP\Domain\Common\Services */ -final class MailService extends Service +final class MailService extends Service implements MailServiceInterface { - protected ?PHPMailer $mailer = null; + private MailerInterface $mailer; + private MailProviderInterface $mailProvider; + + /** + * @throws \SP\Providers\Mail\MailProviderException + */ + public function __construct(Application $application, MailProviderInterface $mailProvider) + { + parent::__construct($application); + + $this->mailProvider = $mailProvider; + + if ($this->config->getConfigData()->isMailEnabled()) { + $this->mailer = $this->mailProvider->getMailerFrom($this->getParamsFromConfig()); + } + } + + public function getParamsFromConfig(): MailParams + { + $configData = $this->config->getConfigData(); + + $mailParams = new MailParams(); + $mailParams->server = $configData->getMailServer(); + $mailParams->port = $configData->getMailPort(); + $mailParams->user = $configData->getMailUser(); + $mailParams->pass = $configData->getMailPass(); + $mailParams->security = $configData->getMailSecurity(); + $mailParams->from = $configData->getMailFrom(); + $mailParams->mailAuthenabled = $configData->isMailAuthenabled(); + + return $mailParams; + } /** * Checks mail params by sending a test email @@ -56,8 +88,7 @@ final class MailService extends Service public function check(MailParams $mailParams, string $to): void { try { - $mailer = $this->dic->get(MailProvider::class) - ->getMailer($mailParams); + $mailer = $this->mailProvider->getMailerFrom($mailParams); $mailMessage = new MailMessage(); $mailMessage->setTitle(__u('Mail test')); @@ -68,16 +99,13 @@ final class MailService extends Service $mailer->isHTML(); $mailer->addAddress($to); - $mailer->Subject = $this->getSubjectForAction($mailMessage->getTitle()); - $mailer->Body = $mailMessage->composeHtml(); + $mailer->subject($this->getSubjectForAction($mailMessage->getTitle())); + $mailer->body($mailMessage->composeHtml()); $mailer->send(); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); throw new ServiceException( __u('Error while sending the email'), @@ -97,11 +125,7 @@ final class MailService extends Service return [ '', '--', - sprintf( - '%s - %s', - AppInfoInterface::APP_NAME, - AppInfoInterface::APP_DESC - ), + sprintf('%s - %s', AppInfoInterface::APP_NAME, AppInfoInterface::APP_DESC), Html::anchorText(BootstrapBase::$WEBURI), ]; } @@ -113,11 +137,7 @@ final class MailService extends Service */ protected function getSubjectForAction($action): string { - return sprintf( - '%s - %s', - AppInfoInterface::APP_NAME, - $action - ); + return sprintf('%s - %s', AppInfoInterface::APP_NAME, $action); } /** @@ -125,8 +145,7 @@ final class MailService extends Service * @param array|string $to * @param MailMessage $mailMessage * - * @throws \PHPMailer\PHPMailer\Exception - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function send(string $subject, $to, MailMessage $mailMessage): void { @@ -140,9 +159,8 @@ final class MailService extends Service $this->mailer->addAddress($to); } - $this->mailer->Subject = $this->getSubjectForAction($subject); - $this->mailer->Body = $mailMessage->setFooter($this->getEmailFooter()) - ->composeHtml(); + $this->mailer->subject($this->getSubjectForAction($subject)); + $this->mailer->body($mailMessage->setFooter($this->getEmailFooter())->composeHtml()); $this->sendMail(); } @@ -158,80 +176,44 @@ final class MailService extends Service $this->eventDispatcher->notifyEvent( 'send.mail', new Event( - $this, EventMessage::factory() - ->addDescription(__u('Email sent')) - ->addDetail( - __u('Recipient'), - implode( - ',', - array_map( - static function ($value) { - return $value[0]; - }, - $this->mailer->getToAddresses() + $this, + EventMessage::factory() + ->addDescription(__u('Email sent')) + ->addDetail( + __u('Recipient'), + implode( + ',', + array_map( + static fn($value) => $value[0], + $this->mailer->getToAddresses() + ) ) ) - ) ) ); } catch (Exception $e) { processException($e); - $this->eventDispatcher->notifyEvent( - 'exception', - new Event($e) - ); + $this->eventDispatcher->notifyEvent('exception', new Event($e)); throw new ServiceException(__u('Error while sending the email')); } } /** - * @throws \PHPMailer\PHPMailer\Exception - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ - public function sendBatch( - string $subject, - array $to, - MailMessage $mailMessage - ): void { + public function sendBatch(string $subject, array $to, MailMessage $mailMessage): void + { $this->mailer->isHTML(); foreach ($to as $address) { $this->mailer->addAddress($address); } - $this->mailer->Subject = $this->getSubjectForAction($subject); - $this->mailer->Body = $mailMessage->setFooter($this->getEmailFooter()) - ->composeHtml(); + $this->mailer->subject($this->getSubjectForAction($subject)); + $this->mailer->body($mailMessage->setFooter($this->getEmailFooter())->composeHtml()); $this->sendMail(); } - - /** - * @throws MailProviderException - */ - protected function initialize(): void - { - if ($this->config->getConfigData()->isMailEnabled()) { - $this->mailer = $this->dic->get(MailProvider::class) - ->getMailer($this->getParamsFromConfig()); - } - } - - public function getParamsFromConfig(): MailParams - { - $configData = $this->config->getConfigData(); - - $mailParams = new MailParams(); - $mailParams->server = $configData->getMailServer(); - $mailParams->port = $configData->getMailPort(); - $mailParams->user = $configData->getMailUser(); - $mailParams->pass = $configData->getMailPass(); - $mailParams->security = $configData->getMailSecurity(); - $mailParams->from = $configData->getMailFrom(); - $mailParams->mailAuthenabled = $configData->isMailAuthenabled(); - - return $mailParams; - } } \ No newline at end of file diff --git a/lib/SP/Services/Notification/NotificationService.php b/lib/SP/Domain/Notification/Services/NotificationService.php similarity index 66% rename from lib/SP/Services/Notification/NotificationService.php rename to lib/SP/Domain/Notification/Services/NotificationService.php index da194d74..474e24b9 100644 --- a/lib/SP/Services/Notification/NotificationService.php +++ b/lib/SP/Domain/Notification/Services/NotificationService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,29 +22,37 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Notification; +namespace SP\Domain\Notification\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\NotificationData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Notification\NotificationRepository; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Notification\In\NotificationRepositoryInterface; +use SP\Domain\Notification\NotificationServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Notification\Repositories\NotificationRepository; /** * Class NotificationService * - * @package SP\Services\Notification + * @package SP\Domain\Notification\Services */ -final class NotificationService extends Service +final class NotificationService extends Service implements NotificationServiceInterface { - protected ?NotificationRepository $notificationRepository = null; + protected NotificationRepository $notificationRepository; + + public function __construct(Application $application, NotificationRepositoryInterface $notificationRepository) + { + parent::__construct($application); + + $this->notificationRepository = $notificationRepository; + } /** * Creates an item @@ -71,7 +79,7 @@ final class NotificationService extends Service /** * Devolver los elementos con los ids especificados * - * @param int[] $ids + * @param int[] $ids * * @return NotificationData[] * @throws ConstraintException @@ -79,9 +87,7 @@ final class NotificationService extends Service */ public function getByIdBatch(array $ids): array { - return $this->notificationRepository - ->getByIdBatch($ids) - ->getDataAsArray(); + return $this->notificationRepository->getByIdBatch($ids)->getDataAsArray(); } /** @@ -89,15 +95,12 @@ final class NotificationService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function delete(int $id): NotificationService + public function delete(int $id): NotificationServiceInterface { if ($this->notificationRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Notification not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Notification not found'), SPException::INFO); } return $this; @@ -108,15 +111,12 @@ final class NotificationService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function deleteAdmin(int $id): NotificationService + public function deleteAdmin(int $id): NotificationServiceInterface { if ($this->notificationRepository->deleteAdmin($id) === 0) { - throw new NoSuchItemException( - __u('Notification not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Notification not found'), SPException::INFO); } return $this; @@ -125,11 +125,11 @@ final class NotificationService extends Service /** * Deletes an item * - * @param int[] $ids + * @param int[] $ids * * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function deleteAdminBatch(array $ids): int { @@ -148,11 +148,11 @@ final class NotificationService extends Service /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function deleteByIdBatch(array $ids): int { @@ -180,10 +180,7 @@ final class NotificationService extends Service $result = $this->notificationRepository->getById($id); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Notification not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Notification not found'), SPException::INFO); } return $result->getData(); @@ -206,15 +203,12 @@ final class NotificationService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function setCheckedById(int $id): void { if ($this->notificationRepository->setCheckedById($id) === 0) { - throw new NoSuchItemException( - __u('Notification not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Notification not found'), SPException::INFO); } } @@ -227,9 +221,7 @@ final class NotificationService extends Service */ public function getForUserIdByDate(string $component, int $id): array { - return $this->notificationRepository - ->getForUserIdByDate($component, $id) - ->getDataAsArray(); + return $this->notificationRepository->getForUserIdByDate($component, $id)->getDataAsArray(); } /** @@ -239,9 +231,7 @@ final class NotificationService extends Service */ public function getAllForUserId(int $id): array { - return $this->notificationRepository - ->getAllForUserId($id) - ->getDataAsArray(); + return $this->notificationRepository->getAllForUserId($id)->getDataAsArray(); } /** @@ -252,14 +242,10 @@ final class NotificationService extends Service public function getAllActiveForUserId(int $id): array { if ($this->context->getUserData()->getIsAdminApp()) { - return $this->notificationRepository - ->getAllActiveForAdmin($id) - ->getDataAsArray(); + return $this->notificationRepository->getAllActiveForAdmin($id)->getDataAsArray(); } - return $this->notificationRepository - ->getAllActiveForUserId($id) - ->getDataAsArray(); + return $this->notificationRepository->getAllActiveForUserId($id)->getDataAsArray(); } /** @@ -273,12 +259,10 @@ final class NotificationService extends Service $userData = $this->context->getUserData(); if ($userData->getIsAdminApp()) { - return $this->notificationRepository - ->searchForAdmin($itemSearchData, $userData->getId()); + return $this->notificationRepository->searchForAdmin($itemSearchData, $userData->getId()); } - return $this->notificationRepository - ->searchForUserId($itemSearchData, $userData->getId()); + return $this->notificationRepository->searchForUserId($itemSearchData, $userData->getId()); } /** @@ -287,21 +271,8 @@ final class NotificationService extends Service * @throws ConstraintException * @throws QueryException */ - public function searchForUserId( - ItemSearchData $itemSearchData, - int $userId - ): QueryResult + public function searchForUserId(ItemSearchData $itemSearchData, int $userId): QueryResult { - return $this->notificationRepository - ->searchForUserId($itemSearchData, $userId); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->notificationRepository = $this->dic->get(NotificationRepository::class); + return $this->notificationRepository->searchForUserId($itemSearchData, $userId); } } \ No newline at end of file diff --git a/lib/SP/Domain/Persistence/UpgradeDatabaseServiceInterface.php b/lib/SP/Domain/Persistence/UpgradeDatabaseServiceInterface.php new file mode 100644 index 00000000..12fb3167 --- /dev/null +++ b/lib/SP/Domain/Persistence/UpgradeDatabaseServiceInterface.php @@ -0,0 +1,37 @@ +. + */ + +namespace SP\Domain\Persistence; + + +use SP\Domain\Upgrade\UpgradeInterface; + +/** + * Class UpgradeDatabaseService + * + * @package SP\Domain\Upgrade\Services + */ +interface UpgradeDatabaseServiceInterface extends UpgradeInterface +{ +} \ No newline at end of file diff --git a/lib/SP/Domain/Plugin/In/PluginDataRepositoryInterface.php b/lib/SP/Domain/Plugin/In/PluginDataRepositoryInterface.php new file mode 100644 index 00000000..b9876fa0 --- /dev/null +++ b/lib/SP/Domain/Plugin/In/PluginDataRepositoryInterface.php @@ -0,0 +1,138 @@ +. + */ + +namespace SP\Domain\Plugin\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Plugin\Repositories\PluginDataModel; + +/** + * Class PluginDataRepository + * + * @package SP\Infrastructure\Plugin\Repositories + */ +interface PluginDataRepositoryInterface +{ + /** + * Creates an item + * + * @param PluginDataModel $itemData + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function create(PluginDataModel $itemData): QueryResult; + + /** + * Updates an item + * + * @param PluginDataModel $itemData + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function update(PluginDataModel $itemData): int; + + /** + * Deletes an item + * + * @param string $id + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function delete(string $id): int; + + /** + * Deletes an item + * + * @param string $name + * @param int $itemId + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByItemId(string $name, int $itemId): int; + + /** + * Returns the item for given id + * + * @param string $id + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getById(string $id): QueryResult; + + /** + * Returns all the items + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): QueryResult; + + /** + * Returns all the items for given ids + * + * @param string[] $ids + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByIdBatch(array $ids): QueryResult; + + /** + * Deletes all the items for given ids + * + * @param string[] $ids + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * Devuelve los datos de un plugin por su nombre + * + * @param string $name + * @param int $itemId + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByItemId(string $name, int $itemId): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/Plugin/In/PluginRepositoryInterface.php b/lib/SP/Domain/Plugin/In/PluginRepositoryInterface.php new file mode 100644 index 00000000..923a4844 --- /dev/null +++ b/lib/SP/Domain/Plugin/In/PluginRepositoryInterface.php @@ -0,0 +1,121 @@ +. + */ + +namespace SP\Domain\Plugin\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\ItemSearchData; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Plugin\Repositories\PluginModel; + +/** + * Class PluginRepository + * + * @package SP\Infrastructure\Plugin\Repositories + */ +interface PluginRepositoryInterface extends RepositoryInterface +{ + /** + * Devuelve los datos de un plugin por su nombre + * + * @param string $name + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByName(string $name): QueryResult; + + /** + * Cambiar el estado del plugin + * + * @param int $id + * @param bool $enabled + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function toggleEnabled(int $id, bool $enabled): int; + + /** + * Cambiar el estado del plugin + * + * @param string $name + * @param bool $enabled + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function toggleEnabledByName(string $name, bool $enabled): int; + + /** + * Cambiar el estado del plugin + * + * @param int $id + * @param bool $available + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function toggleAvailable(int $id, bool $available): int; + + /** + * Cambiar el estado del plugin + * + * @param string $name + * @param bool $available + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function toggleAvailableByName(string $name, bool $available): int; + + /** + * Restablecer los datos de un plugin + * + * @param int $id Id del plugin + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function resetById(int $id): int; + + /** + * Devolver los plugins activados + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getEnabled(): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/Plugin/PluginDataServiceInterface.php b/lib/SP/Domain/Plugin/PluginDataServiceInterface.php new file mode 100644 index 00000000..7a37341b --- /dev/null +++ b/lib/SP/Domain/Plugin/PluginDataServiceInterface.php @@ -0,0 +1,119 @@ +. + */ + +namespace SP\Domain\Plugin; + + +use Defuse\Crypto\Exception\CryptoException; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\NoSuchPropertyException; +use SP\Core\Exceptions\QueryException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Plugin\Repositories\PluginDataModel; + +/** + * Class PluginDataService + * + * @package SP\Domain\Plugin\Services + */ +interface PluginDataServiceInterface +{ + /** + * Creates an item + * + * @throws CryptoException + * @throws ConstraintException + * @throws NoSuchPropertyException + * @throws QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function create(PluginDataModel $itemData): QueryResult; + + /** + * Updates an item + * + * @throws CryptoException + * @throws ConstraintException + * @throws NoSuchPropertyException + * @throws QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function update(PluginDataModel $itemData): int; + + /** + * Returns the item for given plugin and id + * + * @throws NoSuchItemException + * @throws CryptoException + * @throws ConstraintException + * @throws NoSuchPropertyException + * @throws QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function getByItemId(string $name, int $id): PluginDataModel; + + /** + * Returns the item for given id + * + * @return PluginDataModel[] + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\NoSuchPropertyException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function getById(string $id): array; + + /** + * Returns all the items + * + * @return PluginDataModel[] + * @throws \Defuse\Crypto\Exception\CryptoException + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\NoSuchPropertyException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function getAll(): array; + + /** + * Deletes an item + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(string $id): void; + + /** + * Deletes an item + * + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByItemId(string $name, int $itemId): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Plugin/PluginServiceInterface.php b/lib/SP/Domain/Plugin/PluginServiceInterface.php new file mode 100644 index 00000000..ff5ea518 --- /dev/null +++ b/lib/SP/Domain/Plugin/PluginServiceInterface.php @@ -0,0 +1,180 @@ +. + */ + +namespace SP\Domain\Plugin; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\ItemData; +use SP\DataModel\ItemSearchData; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Plugin\Repositories\PluginModel; + +/** + * Class PluginService + * + * @package SP\Domain\Plugin\Services + */ +interface PluginServiceInterface +{ + /** + * Creates an item + * + * @throws ConstraintException + * @throws QueryException + */ + public function create(PluginModel $itemData): int; + + /** + * Updates an item + * + * @throws ConstraintException + * @throws QueryException + */ + public function update(PluginModel $itemData): int; + + /** + * Returns the item for given id + * + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function getById(int $id): PluginModel; + + /** + * Returns all the items + * + * @return PluginModel[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): array; + + /** + * Returns all the items for given ids + * + * @param int[] $ids + * + * @return PluginModel[] + * @throws ConstraintException + * @throws QueryException + */ + public function getByIdBatch(array $ids): array; + + /** + * Deletes all the items for given ids + * + * @param int[] $ids + * + * @throws SPException + * @throws ConstraintException + * @throws QueryException + * @throws SPException + */ + public function deleteByIdBatch(array $ids): void; + + /** + * Deletes an item + * + * @throws SPException + * @throws ConstraintException + * @throws QueryException + */ + public function delete(int $id): void; + + /** + * Searches for items by a given filter + * + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * Devuelve los datos de un plugin por su nombre + * + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function getByName(string $name): PluginModel; + + /** + * Cambiar el estado del plugin + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function toggleEnabled(int $id, bool $enabled): void; + + /** + * Cambiar el estado del plugin + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function toggleEnabledByName(string $name, bool $enabled): void; + + /** + * Cambiar el estado del plugin + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function toggleAvailable(int $id, bool $available): void; + + /** + * Cambiar el estado del plugin + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function toggleAvailableByName(string $name, bool $available): void; + + /** + * Restablecer los datos de un plugin + * + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function resetById(int $id): bool; + + /** + * Devolver los plugins activados + * + * @return ItemData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getEnabled(): array; +} \ No newline at end of file diff --git a/lib/SP/Services/Plugin/PluginDataService.php b/lib/SP/Domain/Plugin/Services/PluginDataService.php similarity index 59% rename from lib/SP/Services/Plugin/PluginDataService.php rename to lib/SP/Domain/Plugin/Services/PluginDataService.php index 65b875cf..c44f9069 100644 --- a/lib/SP/Services/Plugin/PluginDataService.php +++ b/lib/SP/Domain/Plugin/Services/PluginDataService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,28 +22,38 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Plugin; +namespace SP\Domain\Plugin\Services; use Defuse\Crypto\Exception\CryptoException; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Plugin\PluginDataModel; -use SP\Repositories\Plugin\PluginDataRepository; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Plugin\In\PluginDataRepositoryInterface; +use SP\Domain\Plugin\PluginDataServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Plugin\Repositories\PluginDataModel; +use SP\Infrastructure\Plugin\Repositories\PluginDataRepository; /** * Class PluginDataService * - * @package SP\Services\Plugin + * @package SP\Domain\Plugin\Services */ -final class PluginDataService extends Service +final class PluginDataService extends Service implements PluginDataServiceInterface { - protected ?PluginDataRepository $pluginRepository = null; + private PluginDataRepository $pluginDataRepository; + + public function __construct(Application $application, PluginDataRepositoryInterface $pluginDataRepository) + { + parent::__construct($application); + + $this->pluginDataRepository = $pluginDataRepository; + } + /** * Creates an item @@ -52,12 +62,11 @@ final class PluginDataService extends Service * @throws ConstraintException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function create(PluginDataModel $itemData): QueryResult { - return $this->pluginRepository - ->create($itemData->encrypt($this->getMasterKeyFromContext())); + return $this->pluginDataRepository->create($itemData->encrypt($this->getMasterKeyFromContext())); } /** @@ -67,12 +76,11 @@ final class PluginDataService extends Service * @throws ConstraintException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function update(PluginDataModel $itemData): int { - return $this->pluginRepository - ->update($itemData->encrypt($this->getMasterKeyFromContext())); + return $this->pluginDataRepository->update($itemData->encrypt($this->getMasterKeyFromContext())); } /** @@ -83,17 +91,14 @@ final class PluginDataService extends Service * @throws ConstraintException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function getByItemId(string $name, int $id): PluginDataModel { - $result = $this->pluginRepository->getByItemId($name, $id); + $result = $this->pluginDataRepository->getByItemId($name, $id); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Plugin\'s data not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin\'s data not found'), SPException::INFO); } /** @var PluginDataModel $itemData */ @@ -105,23 +110,20 @@ final class PluginDataService extends Service /** * Returns the item for given id * - * @return PluginDataModel[] + * @return \SP\Infrastructure\Plugin\Repositories\PluginDataModel[] * @throws \Defuse\Crypto\Exception\CryptoException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\NoSuchPropertyException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException - * @throws \SP\Services\ServiceException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException */ public function getById(string $id): array { - $result = $this->pluginRepository->getById($id); + $result = $this->pluginDataRepository->getById($id); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Plugin\'s data not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin\'s data not found'), SPException::INFO); } $data = $result->getDataAsArray(); @@ -140,21 +142,21 @@ final class PluginDataService extends Service /** * Returns all the items * - * @return PluginDataModel[] + * @return \SP\Infrastructure\Plugin\Repositories\PluginDataModel[] * @throws \Defuse\Crypto\Exception\CryptoException * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\NoSuchPropertyException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function getAll(): array { - $data = $this->pluginRepository->getAll()->getDataAsArray(); + $data = $this->pluginDataRepository->getAll()->getDataAsArray(); array_walk( $data, function ($itemData) { - /** @var PluginDataModel $itemData */ + /** @var \SP\Infrastructure\Plugin\Repositories\PluginDataModel $itemData */ $itemData->decrypt($this->getMasterKeyFromContext()); } ); @@ -167,15 +169,12 @@ final class PluginDataService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function delete(string $id): void { - if ($this->pluginRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Plugin\'s data not found'), - SPException::INFO - ); + if ($this->pluginDataRepository->delete($id) === 0) { + throw new NoSuchItemException(__u('Plugin\'s data not found'), SPException::INFO); } } @@ -188,16 +187,8 @@ final class PluginDataService extends Service */ public function deleteByItemId(string $name, int $itemId): void { - if ($this->pluginRepository->deleteByItemId($name, $itemId) === 0) { - throw new NoSuchItemException( - __u('Plugin\'s data not found'), - SPException::INFO - ); + if ($this->pluginDataRepository->deleteByItemId($name, $itemId) === 0) { + throw new NoSuchItemException(__u('Plugin\'s data not found'), SPException::INFO); } } - - protected function initialize(): void - { - $this->pluginRepository = $this->dic->get(PluginDataRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Plugin/PluginService.php b/lib/SP/Domain/Plugin/Services/PluginService.php similarity index 74% rename from lib/SP/Services/Plugin/PluginService.php rename to lib/SP/Domain/Plugin/Services/PluginService.php index 4b7c7aa9..1eac463e 100644 --- a/lib/SP/Services/Plugin/PluginService.php +++ b/lib/SP/Domain/Plugin/Services/PluginService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,28 +22,38 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Plugin; +namespace SP\Domain\Plugin\Services; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemData; use SP\DataModel\ItemSearchData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Plugin\PluginModel; -use SP\Repositories\Plugin\PluginRepository; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Plugin\In\PluginRepositoryInterface; +use SP\Domain\Plugin\PluginServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Plugin\Repositories\PluginModel; +use SP\Infrastructure\Plugin\Repositories\PluginRepository; /** * Class PluginService * - * @package SP\Services\Plugin + * @package SP\Domain\Plugin\Services */ -final class PluginService extends Service +final class PluginService extends Service implements PluginServiceInterface { - protected PluginRepository $pluginRepository; + private PluginRepository $pluginRepository; + + public function __construct(Application $application, PluginRepositoryInterface $pluginRepository) + { + parent::__construct($application); + + $this->pluginRepository = $pluginRepository; + } /** * Creates an item @@ -79,10 +89,7 @@ final class PluginService extends Service $result = $this->pluginRepository->getById($id); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Plugin not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin not found'), SPException::INFO); } return $result->getData(); @@ -103,7 +110,7 @@ final class PluginService extends Service /** * Returns all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @return PluginModel[] * @throws ConstraintException @@ -117,7 +124,7 @@ final class PluginService extends Service /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @throws SPException * @throws ConstraintException @@ -141,10 +148,7 @@ final class PluginService extends Service public function delete(int $id): void { if ($this->pluginRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Plugin not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin not found'), SPException::INFO); } } @@ -171,10 +175,7 @@ final class PluginService extends Service $result = $this->pluginRepository->getByName($name); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Plugin not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin not found'), SPException::INFO); } return $result->getData(); @@ -185,15 +186,12 @@ final class PluginService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function toggleEnabled(int $id, bool $enabled): void { if ($this->pluginRepository->toggleEnabled($id, $enabled) === 0) { - throw new NoSuchItemException( - __u('Plugin not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin not found'), SPException::INFO); } } @@ -202,15 +200,12 @@ final class PluginService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function toggleEnabledByName(string $name, bool $enabled): void { if ($this->pluginRepository->toggleEnabledByName($name, $enabled) === 0) { - throw new NoSuchItemException( - __u('Plugin not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin not found'), SPException::INFO); } } @@ -219,15 +214,12 @@ final class PluginService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function toggleAvailable(int $id, bool $available): void { if ($this->pluginRepository->toggleAvailable($id, $available) === 0) { - throw new NoSuchItemException( - __u('Plugin not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin not found'), SPException::INFO); } } @@ -236,15 +228,12 @@ final class PluginService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function toggleAvailableByName(string $name, bool $available): void { if ($this->pluginRepository->toggleAvailableByName($name, $available) === 0) { - throw new NoSuchItemException( - __u('Plugin not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin not found'), SPException::INFO); } } @@ -258,10 +247,7 @@ final class PluginService extends Service public function resetById(int $id): bool { if (($count = $this->pluginRepository->resetById($id)) === 0) { - throw new NoSuchItemException( - __u('Plugin not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Plugin not found'), SPException::INFO); } return $count; @@ -278,9 +264,4 @@ final class PluginService extends Service { return $this->pluginRepository->getEnabled()->getDataAsArray(); } - - protected function initialize(): void - { - $this->pluginRepository = $this->dic->get(PluginRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Domain/Plugin/UpgradePluginServiceInterface.php b/lib/SP/Domain/Plugin/UpgradePluginServiceInterface.php new file mode 100644 index 00000000..b09288ad --- /dev/null +++ b/lib/SP/Domain/Plugin/UpgradePluginServiceInterface.php @@ -0,0 +1,43 @@ +. + */ + +namespace SP\Domain\Plugin; + + +use Exception; + +/** + * Class UpgradePlugin + * + * @package SP\Domain\Upgrade\Services + */ +interface UpgradePluginServiceInterface +{ + /** + * upgrade_300_18010101 + * + * @throws Exception + */ + public function upgrade_310_19012201(): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Providers/MailProviderInterface.php b/lib/SP/Domain/Providers/MailProviderInterface.php new file mode 100644 index 00000000..dd1e4e99 --- /dev/null +++ b/lib/SP/Domain/Providers/MailProviderInterface.php @@ -0,0 +1,52 @@ +. + */ + +namespace SP\Domain\Providers; + + +use SP\Providers\Mail\MailParams; +use SP\Providers\Mail\MailProviderException; + +/** + * Class MailProvider + * + * @package SP\Providers\Mail + */ +interface MailProviderInterface +{ + /** + * Inicializar la clase PHPMailer. + * + * @param MailParams $mailParams + * + * @throws MailProviderException + */ + public function getMailerFrom(MailParams $mailParams): MailerInterface; + + public function isDebug(): bool; + + public function setDebug(bool $debug): void; + + public function initialize(): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Providers/MailerInterface.php b/lib/SP/Domain/Providers/MailerInterface.php new file mode 100644 index 00000000..1391d91e --- /dev/null +++ b/lib/SP/Domain/Providers/MailerInterface.php @@ -0,0 +1,45 @@ +. + */ + +namespace SP\Domain\Providers; + +/** + * A wrapper for a mailer + */ +interface MailerInterface +{ + public function isHtml(): MailerInterface; + + public function addAddress(string $address): MailerInterface; + + public function subject(string $subject): MailerInterface; + + public function body(string $body): MailerInterface; + + public function send(): bool; + + public function getToAddresses(): array; + + public function getMailer(); +} \ No newline at end of file diff --git a/lib/SP/Domain/Security/EventlogServiceInterface.php b/lib/SP/Domain/Security/EventlogServiceInterface.php new file mode 100644 index 00000000..ac7c3660 --- /dev/null +++ b/lib/SP/Domain/Security/EventlogServiceInterface.php @@ -0,0 +1,60 @@ +. + */ + +namespace SP\Domain\Security; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\EventlogData; +use SP\DataModel\ItemSearchData; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class EventlogService + * + * @package SP\Domain\Common\Services\EventLog + */ +interface EventlogServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws ConstraintException + * @throws QueryException + * @throws SPException + */ + public function clear(): bool; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function create(EventlogData $eventlogData): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/Security/In/EventlogRepositoryInterface.php b/lib/SP/Domain/Security/In/EventlogRepositoryInterface.php new file mode 100644 index 00000000..37d183db --- /dev/null +++ b/lib/SP/Domain/Security/In/EventlogRepositoryInterface.php @@ -0,0 +1,69 @@ +. + */ + +namespace SP\Domain\Security\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\EventlogData; +use SP\DataModel\ItemSearchData; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class EventlogRepository + * + * @package SP\Infrastructure\Security\Repositories + */ +interface EventlogRepositoryInterface +{ + /** + * Clears the event log + * + * @return bool con el resultado + * @throws QueryException + * @throws ConstraintException + */ + public function clear(): bool; + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $itemSearchData + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @param EventlogData $eventlogData + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function create(EventlogData $eventlogData): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/Security/In/TrackRepositoryInterface.php b/lib/SP/Domain/Security/In/TrackRepositoryInterface.php new file mode 100644 index 00000000..2cd0072b --- /dev/null +++ b/lib/SP/Domain/Security/In/TrackRepositoryInterface.php @@ -0,0 +1,114 @@ +. + */ + +namespace SP\Domain\Security\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ItemSearchData; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Security\Repositories\TrackRequest; + +/** + * Class TrackRepository + * + * @package SP\Infrastructure\Security\Repositories + */ +interface TrackRepositoryInterface +{ + /** + * @param TrackRequest $trackRequest + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function add(TrackRequest $trackRequest): int; + + /** + * @param $id int + * + * @return int + * @throws QueryException + * @throws ConstraintException + */ + public function delete(int $id): int; + + /** + * @param $id int + * + * @return int + * @throws QueryException + * @throws ConstraintException + */ + public function unlock(int $id): int; + + /** + * Clears tracks + * + * @return bool con el resultado + * @throws QueryException + * @throws ConstraintException + */ + public function clear(): bool; + + /** + * @param $id int + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getById(int $id): QueryResult; + + /** + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): QueryResult; + + /** + * Devuelve los tracks de un cliente desde un tiempo y origen determinados + * + * @param TrackRequest $trackRequest + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getTracksForClientFromTime(TrackRequest $trackRequest): QueryResult; + + /** + * Searches for items by a given filter + * + * @param ItemSearchData $itemSearchData + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Services/EventLog/EventlogService.php b/lib/SP/Domain/Security/Services/EventlogService.php similarity index 66% rename from lib/SP/Services/EventLog/EventlogService.php rename to lib/SP/Domain/Security/Services/EventlogService.php index fe38cff6..06b69b19 100644 --- a/lib/SP/Services/EventLog/EventlogService.php +++ b/lib/SP/Domain/Security/Services/EventlogService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,29 +22,41 @@ * along with sysPass. If not, see . */ -namespace SP\Services\EventLog; +namespace SP\Domain\Security\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\EventlogData; use SP\DataModel\ItemSearchData; -use SP\Http\Request; -use SP\Repositories\EventLog\EventlogRepository; -use SP\Services\Service; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Security\EventlogServiceInterface; +use SP\Domain\Security\In\EventlogRepositoryInterface; +use SP\Http\RequestInterface; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Security\Repositories\EventlogRepository; /** * Class EventlogService * - * @package SP\Services\EventLog + * @package SP\Domain\Common\Services\EventLog */ -final class EventlogService extends Service +final class EventlogService extends Service implements EventlogServiceInterface { - protected ?EventlogRepository $eventLogRepository = null; - protected ?Request $request = null; + protected EventlogRepository $eventLogRepository; + protected RequestInterface $request; + + public function __construct( + Application $application, + EventlogRepositoryInterface $eventLogRepository, + RequestInterface $request + ) { + parent::__construct($application); + + $this->eventLogRepository = $eventLogRepository; + $this->request = $request; + } /** * @throws ConstraintException @@ -79,14 +91,4 @@ final class EventlogService extends Service return $this->eventLogRepository->create($eventlogData); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->eventLogRepository = $this->dic->get(EventlogRepository::class); - $this->request = $this->dic->get(Request::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Track/TrackService.php b/lib/SP/Domain/Security/Services/TrackService.php similarity index 66% rename from lib/SP/Services/Track/TrackService.php rename to lib/SP/Domain/Security/Services/TrackService.php index 5b77a587..d1cc534f 100644 --- a/lib/SP/Services/Track/TrackService.php +++ b/lib/SP/Domain/Security/Services/TrackService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,11 +22,10 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Track; +namespace SP\Domain\Security\Services; use Exception; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ConstraintException; @@ -34,40 +33,48 @@ use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemSearchData; use SP\DataModel\TrackData; -use SP\Http\Request; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Track\TrackRepository; -use SP\Repositories\Track\TrackRequest; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Security\In\TrackRepositoryInterface; +use SP\Domain\Security\TrackServiceInterface; +use SP\Http\RequestInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Security\Repositories\TrackRepository; +use SP\Infrastructure\Security\Repositories\TrackRequest; /** * Class TrackService * - * @package SP\Services + * @package SP\Domain\Common\Services */ -final class TrackService extends Service +final class TrackService extends Service implements TrackServiceInterface { /** * Tiempo para contador de intentos */ - public const TIME_TRACKING = 600; + public const TIME_TRACKING = 600; public const TIME_TRACKING_MAX_ATTEMPTS = 10; - public const TIME_SLEEP = 0.5; + public const TIME_SLEEP = 0.5; + + private TrackRepository $trackRepository; + private RequestInterface $request; + + public function __construct(Application $application, TrackRepositoryInterface $trackRepository, RequestInterface $request) + { + parent::__construct($application); + + $this->trackRepository = $trackRepository; + $this->request = $request; + } - protected ?TrackRepository $trackRepository = null; - protected ?Request $request = null; /** * @throws InvalidArgumentException */ public function getTrackRequest(string $source): TrackRequest { - $trackRequest = new TrackRequest( - time() - self::TIME_TRACKING, - $source - ); + $trackRequest = new TrackRequest(time() - self::TIME_TRACKING, $source); $trackRequest->setTrackIp($this->request->getClientAddress()); return $trackRequest; @@ -146,13 +153,19 @@ final class TrackService extends Service if ($attempts >= self::TIME_TRACKING_MAX_ATTEMPTS) { $delaySeconds = self::TIME_SLEEP * $attempts; - $this->eventDispatcher->notifyEvent('track.delay', - new Event($this, EventMessage::factory() - ->addDescription(sprintf(__('Attempts exceeded (%d/%d)'), $attempts, self::TIME_TRACKING_MAX_ATTEMPTS)) - ->addDetail(__u('Seconds'), $delaySeconds)) + $this->eventDispatcher->notifyEvent( + 'track.delay', + new Event( + $this, + EventMessage::factory() + ->addDescription( + sprintf(__('Attempts exceeded (%d/%d)'), $attempts, self::TIME_TRACKING_MAX_ATTEMPTS) + ) + ->addDetail(__u('Seconds'), $delaySeconds) + ) ); - logger('Tracking delay: ' . $delaySeconds . 's'); + logger('Tracking delay: '.$delaySeconds.'s'); sleep($delaySeconds); @@ -175,21 +188,17 @@ final class TrackService extends Service */ public function getTracksForClientFromTime(TrackRequest $trackRequest): int { - return $this->trackRepository - ->getTracksForClientFromTime($trackRequest) - ->getNumRows(); + return $this->trackRepository->getTracksForClientFromTime($trackRequest)->getNumRows(); } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ConstraintException * @throws QueryException */ public function add(TrackRequest $trackRequest): int { - if ($trackRequest->getIpv4() === null - && $trackRequest->getIpv6() === null - ) { + if ($trackRequest->getIpv4() === null && $trackRequest->getIpv6() === null) { throw new ServiceException(__u('IP address not set')); } @@ -197,8 +206,10 @@ final class TrackService extends Service $this->eventDispatcher->notifyEvent( 'track.add', - new Event($this, EventMessage::factory() - ->addDescription($this->request->getClientAddress(true))) + new Event( + $this, + EventMessage::factory()->addDescription($this->request->getClientAddress(true)) + ) ); return $result; @@ -212,14 +223,4 @@ final class TrackService extends Service { return $this->trackRepository->search($itemSearchData); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->trackRepository = $this->dic->get(TrackRepository::class); - $this->request = $this->dic->get(Request::class); - } } \ No newline at end of file diff --git a/lib/SP/Domain/Security/TrackServiceInterface.php b/lib/SP/Domain/Security/TrackServiceInterface.php new file mode 100644 index 00000000..ab8467a0 --- /dev/null +++ b/lib/SP/Domain/Security/TrackServiceInterface.php @@ -0,0 +1,112 @@ +. + */ + +namespace SP\Domain\Security; + + +use Exception; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\InvalidArgumentException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ItemSearchData; +use SP\DataModel\TrackData; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Security\Repositories\TrackRequest; + +/** + * Class TrackService + * + * @package SP\Domain\Common\Services + */ +interface TrackServiceInterface +{ + /** + * @throws InvalidArgumentException + */ + public function getTrackRequest(string $source): TrackRequest; + + /** + * @throws QueryException + * @throws ConstraintException + * @throws NoSuchItemException + */ + public function delete(int $id): void; + + /** + * @throws QueryException + * @throws ConstraintException + * @throws NoSuchItemException + */ + public function unlock(int $id): void; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function clear(): bool; + + /** + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function getById(int $id): TrackData; + + /** + * @return TrackData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAll(): array; + + /** + * Comprobar los intentos de login + * + * @return bool True if delay is performed, false otherwise + * @throws Exception + */ + public function checkTracking(TrackRequest $trackRequest): bool; + + /** + * Devuelve los tracks de un cliente desde un tiempo y origen determinados + * + * @throws ConstraintException + * @throws QueryException + */ + public function getTracksForClientFromTime(TrackRequest $trackRequest): int; + + /** + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function add(TrackRequest $trackRequest): int; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/Tag/In/TagRepositoryInterface.php b/lib/SP/Domain/Tag/In/TagRepositoryInterface.php new file mode 100644 index 00000000..beee8444 --- /dev/null +++ b/lib/SP/Domain/Tag/In/TagRepositoryInterface.php @@ -0,0 +1,50 @@ +. + */ + +namespace SP\Domain\Tag\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class TagRepository + * + * @package SP\Infrastructure\Common\Repositories\Tag + */ +interface TagRepositoryInterface extends RepositoryInterface +{ + /** + * Returns the item for given id + * + * @param string $name + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByName(string $name): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Services/Tag/TagService.php b/lib/SP/Domain/Tag/Services/TagService.php similarity index 65% rename from lib/SP/Services/Tag/TagService.php rename to lib/SP/Domain/Tag/Services/TagService.php index 14d5258f..6b8c1a6b 100644 --- a/lib/SP/Services/Tag/TagService.php +++ b/lib/SP/Domain/Tag/Services/TagService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,33 +22,41 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Tag; +namespace SP\Domain\Tag\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\TagData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Tag\TagRepository; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\Tag\In\TagRepositoryInterface; +use SP\Domain\Tag\TagServiceInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\Tag\Repositories\TagRepository; /** * Class TagService * - * @package SP\Services\Tag + * @package SP\Domain\Tag\Services */ -final class TagService extends Service +final class TagService extends Service implements TagServiceInterface { use ServiceItemTrait; - protected ?TagRepository $tagRepository = null; + private TagRepository $tagRepository; + + public function __construct(Application $application, TagRepositoryInterface $tagRepository) + { + parent::__construct($application); + + $this->tagRepository = $tagRepository; + } /** * @throws ConstraintException @@ -62,17 +70,14 @@ final class TagService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function getById(int $id): TagData { $result = $this->tagRepository->getById($id); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Tag not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Tag not found'), SPException::INFO); } return $result->getData(); @@ -88,10 +93,7 @@ final class TagService extends Service $result = $this->tagRepository->getByName($name); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Tag not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Tag not found'), SPException::INFO); } return $result->getData(); @@ -100,32 +102,26 @@ final class TagService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function delete(int $id): TagService + public function delete(int $id): TagServiceInterface { if ($this->tagRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Tag not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Tag not found'), SPException::INFO); } return $this; } /** - * @param int[] $ids + * @param int[] $ids * * @throws SPException */ - public function deleteByIdBatch(array $ids): TagService + public function deleteByIdBatch(array $ids): TagServiceInterface { if ($this->tagRepository->deleteByIdBatch($ids) !== count($ids)) { - throw new ServiceException( - __u('Error while removing the tags'), - SPException::WARNING - ); + throw new ServiceException(__u('Error while removing the tags'), SPException::WARNING); } return $this; @@ -162,13 +158,4 @@ final class TagService extends Service { return $this->tagRepository->getAll(); } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->tagRepository = $this->dic->get(TagRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Domain/Tag/TagServiceInterface.php b/lib/SP/Domain/Tag/TagServiceInterface.php new file mode 100644 index 00000000..ffc2798f --- /dev/null +++ b/lib/SP/Domain/Tag/TagServiceInterface.php @@ -0,0 +1,100 @@ +. + */ + +namespace SP\Domain\Tag; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\ItemSearchData; +use SP\DataModel\TagData; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class TagService + * + * @package SP\Domain\Tag\Services + */ +interface TagServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id): TagData; + + /** + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function getByName(string $name): ?TagData; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): TagServiceInterface; + + /** + * @param int[] $ids + * + * @throws SPException + */ + public function deleteByIdBatch(array $ids): TagServiceInterface; + + /** + * @throws ConstraintException + * @throws QueryException + * @throws DuplicatedItemException + */ + public function create(TagData $itemData): int; + + /** + * @throws SPException + * @throws ConstraintException + * @throws QueryException + */ + public function update(TagData $itemData): int; + + /** + * Get all items from the service's repository + * + * @return TagData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; +} \ No newline at end of file diff --git a/lib/SP/Services/Task/Task.php b/lib/SP/Domain/Task/Services/Task.php similarity index 82% rename from lib/SP/Services/Task/Task.php rename to lib/SP/Domain/Task/Services/Task.php index e167c95f..da582f59 100644 --- a/lib/SP/Services/Task/Task.php +++ b/lib/SP/Domain/Task/Services/Task.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,13 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Task; +namespace SP\Domain\Task\Services; use JsonException; use SP\Core\Context\SessionContext; use SP\Core\Messages\TaskMessage; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; +use SP\Infrastructure\File\FileHandlerInterface; use SP\Util\Util; /** @@ -45,8 +46,8 @@ final class Task /** * @var string ID de la tarea */ - private string $taskId; - private ?FileHandler $fileOut = null; + private string $taskId; + private ?FileHandler $fileOut = null; private ?FileHandler $fileTask = null; /** * @var int Intérvalo en segundos @@ -55,14 +56,14 @@ final class Task /** * @var bool Si se ha inicializado para escribir en el archivo */ - private bool $initialized; + private bool $initialized; private string $uid; /** * Task constructor. * - * @param string $name Nombre de la tarea - * @param string $id + * @param string $name Nombre de la tarea + * @param string $id */ public function __construct(string $name, string $id) { @@ -81,15 +82,15 @@ final class Task if ($tempDir !== false) { $this->fileOut = new FileHandler( - $tempDir . - DIRECTORY_SEPARATOR . - $this->taskId . + $tempDir. + DIRECTORY_SEPARATOR. + $this->taskId. '.out' ); $this->fileTask = new FileHandler( - $tempDir . - DIRECTORY_SEPARATOR . - $this->taskId . + $tempDir. + DIRECTORY_SEPARATOR. + $this->taskId. '.task' ); @@ -107,14 +108,14 @@ final class Task private function deleteTaskFiles(): void { $filesOut = - dirname($this->fileOut->getFile()) . - DIRECTORY_SEPARATOR . - $this->taskId . + dirname($this->fileOut->getFile()). + DIRECTORY_SEPARATOR. + $this->taskId. '*.out'; $filesTask = - dirname($this->fileTask->getFile()) . - DIRECTORY_SEPARATOR . - $this->taskId . + dirname($this->fileTask->getFile()). + DIRECTORY_SEPARATOR. + $this->taskId. '*.task'; array_map( @@ -125,7 +126,7 @@ final class Task public function genUid(): string { - return md5($this->name . $this->taskId); + return md5($this->name.$this->taskId); } /** @@ -144,6 +145,7 @@ final class Task try { if ($this->initialized === true) { $this->fileOut->save($message->composeText()); + return true; } } catch (FileException $e) { @@ -162,7 +164,7 @@ final class Task if ($this->initialized === true) { $this->fileOut->save($message->composeJson()); } - } catch (FileException | JsonException $e) { + } catch (FileException|JsonException $e) { processException($e); } } @@ -212,7 +214,7 @@ final class Task return $this->taskId; } - public function getFileOut(): ?FileHandler + public function getFileOut(): ?FileHandlerInterface { return $this->fileOut; } @@ -254,7 +256,7 @@ final class Task return $this->uid; } - public function getFileTask(): ?FileHandler + public function getFileTask(): ?FileHandlerInterface { return $this->fileTask; } diff --git a/lib/SP/Services/Task/TaskFactory.php b/lib/SP/Domain/Task/Services/TaskFactory.php similarity index 92% rename from lib/SP/Services/Task/TaskFactory.php rename to lib/SP/Domain/Task/Services/TaskFactory.php index c4068f71..7e194d86 100644 --- a/lib/SP/Services/Task/TaskFactory.php +++ b/lib/SP/Domain/Task/Services/TaskFactory.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,11 +22,11 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Task; +namespace SP\Domain\Task\Services; use RuntimeException; use SP\Core\Messages\TaskMessage; -use SP\Storage\File\FileException; +use SP\Infrastructure\File\FileException; /** * Class TaskFactory @@ -48,9 +48,8 @@ final class TaskFactory public static function create( string $name, string $id, - bool $hasSession = true - ): Task - { + bool $hasSession = true + ): Task { $task = self::add((new Task($name, $id))); if ($hasSession) { @@ -101,8 +100,7 @@ final class TaskFactory public static function createMessage( string $taskId, string $task - ): TaskMessage - { + ): TaskMessage { return new TaskMessage($taskId, $task); } diff --git a/lib/SP/Services/Task/TaskService.php b/lib/SP/Domain/Task/Services/TaskService.php similarity index 76% rename from lib/SP/Services/Task/TaskService.php rename to lib/SP/Domain/Task/Services/TaskService.php index 6742cd5d..279ac939 100644 --- a/lib/SP/Services/Task/TaskService.php +++ b/lib/SP/Domain/Task/Services/TaskService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,21 +22,22 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Task; +namespace SP\Domain\Task\Services; use Closure; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Task\TaskServiceInterface; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; use SP\Util\Util; /** * Class TaskService * - * @package SP\Services + * @package SP\Domain\Common\Services */ -final class TaskService extends Service +final class TaskService extends Service implements TaskServiceInterface { /** * Time for waiting to initialization @@ -47,17 +48,17 @@ final class TaskService extends Service */ private const STARTUP_WAIT_COUNT = 30; - private ?Closure $messagePusher = null; - private ?Task $task = null; - private ?string $taskDirectory = null; - private ?string $taskId = null; - private ?FileHandler $taskFile = null; + private ?Closure $messagePusher = null; + private ?Task $task = null; + private ?string $taskDirectory = null; + private ?string $taskId = null; + private ?FileHandler $taskFile = null; /** * Track task status * * @throws \JsonException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function trackStatus(string $taskId, Closure $messagePusher): void { @@ -72,20 +73,23 @@ final class TaskService extends Service $count = 0; while (!$this->checkTaskRegistered() - || !file_exists($this->task->getFileOut()->getFile()) + || !file_exists($this->task->getFileOut()->getFile()) ) { if ($count >= self::STARTUP_WAIT_COUNT) { throw new ServiceException(__('Task not set within wait time')); - } else { - logger(sprintf( + } + + logger( + sprintf( 'Waiting for task "%s" (%ds) ...', $taskId, (self::STARTUP_WAIT_COUNT - $count) * self::STARTUP_WAIT_TIME - )); + ) + ); - $count++; - sleep(self::STARTUP_WAIT_TIME); - } + $count++; + + sleep(self::STARTUP_WAIT_TIME); } $this->readTaskStatus(); @@ -96,12 +100,7 @@ final class TaskService extends Service */ private function getLock(): bool { - $lockFile = new FileHandler( - $this->taskDirectory . - DIRECTORY_SEPARATOR . - $this->taskId . - '.lock' - ); + $lockFile = new FileHandler($this->taskDirectory.DIRECTORY_SEPARATOR.$this->taskId.'.lock'); try { if ($lockFile->getFileTime() + (self::STARTUP_WAIT_COUNT * self::STARTUP_WAIT_TIME) < time()) { @@ -128,18 +127,13 @@ final class TaskService extends Service private function checkTaskRegistered(): bool { if (is_object($this->task)) { - logger('Task detected: ' . $this->task->getTaskId()); + logger('Task detected: '.$this->task->getTaskId()); return true; } try { - $this->taskFile = new FileHandler( - $this->taskDirectory . - DIRECTORY_SEPARATOR . - $this->taskId . - '.task' - ); + $this->taskFile = new FileHandler($this->taskDirectory.DIRECTORY_SEPARATOR.$this->taskId.'.task'); $this->taskFile->checkFileExists(); $this->task = unserialize($this->taskFile->readToString()); @@ -156,14 +150,14 @@ final class TaskService extends Service */ private function readTaskStatus(): void { - logger('Tracking task status: ' . $this->task->getTaskId()); + logger('Tracking task status: '.$this->task->getTaskId()); $id = 0; $failCount = 0; $outputFile = $this->task->getFileOut(); while ($failCount <= self::STARTUP_WAIT_COUNT - && $this->checkTaskFile() + && $this->checkTaskFile() ) { try { $content = $outputFile->readToString(); @@ -179,11 +173,7 @@ final class TaskService extends Service logger($message->getTask()); - $this->messagePusher->call( - $this, - $id, - $message->composeJson() - ); + $this->messagePusher->call($this, $id, $message->composeJson()); $failCount++; } diff --git a/lib/SP/Domain/Task/TaskServiceInterface.php b/lib/SP/Domain/Task/TaskServiceInterface.php new file mode 100644 index 00000000..a5ffe14a --- /dev/null +++ b/lib/SP/Domain/Task/TaskServiceInterface.php @@ -0,0 +1,44 @@ +. + */ + +namespace SP\Domain\Task; + + +use Closure; + +/** + * Class TaskService + * + * @package SP\Domain\Common\Services + */ +interface TaskServiceInterface +{ + /** + * Track task status + * + * @throws \JsonException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function trackStatus(string $taskId, Closure $messagePusher): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/Upgrade/Services/UpgradeAppService.php b/lib/SP/Domain/Upgrade/Services/UpgradeAppService.php new file mode 100644 index 00000000..aa97c08d --- /dev/null +++ b/lib/SP/Domain/Upgrade/Services/UpgradeAppService.php @@ -0,0 +1,172 @@ +. + */ + +namespace SP\Domain\Upgrade\Services; + +use Exception; +use SP\Core\Application; +use SP\Core\Events\Event; +use SP\Core\Events\EventMessage; +use SP\Core\Exceptions\SPException; +use SP\Domain\Account\Services\UpgradePublicLinkService; +use SP\Domain\Account\UpgradePublicLinkServiceInterface; +use SP\Domain\Auth\Services\UpgradeAuthTokenService; +use SP\Domain\Auth\UpgradeAuthTokenServiceInterface; +use SP\Domain\Common\Services\Service; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\CustomField\Services\UpgradeCustomFieldDataService; +use SP\Domain\CustomField\Services\UpgradeCustomFieldDefinitionService; +use SP\Domain\CustomField\UpgradeCustomFieldDataServiceInterface; +use SP\Domain\CustomField\UpgradeCustomFieldDefinitionServiceInterface; +use SP\Domain\Plugin\UpgradePluginServiceInterface; +use SP\Domain\Upgrade\UpgradeAppServiceInterface; +use SP\Infrastructure\File\FileException; +use SP\Providers\Log\FileLogHandler; +use SP\Util\VersionUtil; + +/** + * Class UpgradeAppService + * + * @package SP\Domain\Upgrade\Services + */ +final class UpgradeAppService extends Service implements UpgradeAppServiceInterface +{ + private const UPGRADES = [ + '300.18010101', + '300.18072901', + '300.18072902', + '310.19012201', + '310.19042701', + ]; + private UpgradeCustomFieldDefinitionService $upgradeCustomFieldDefinition; + private UpgradePublicLinkService $upgradePublicLink; + private UpgradeAuthTokenService $upgradeAuthToken; + private UpgradeCustomFieldDataService $upgradeCustomFieldData; + private UpgradePluginService $upgradePlugin; + + public function __construct( + Application $application, + FileLogHandler $fileLogHandler, + UpgradeCustomFieldDefinitionServiceInterface $upgradeCustomFieldDefinition, + UpgradePublicLinkServiceInterface $upgradePublicLink, + UpgradeAuthTokenServiceInterface $upgradeAuthToken, + UpgradeCustomFieldDataServiceInterface $upgradeCustomFieldData, + UpgradePluginServiceInterface $upgradePlugin + ) { + parent::__construct($application); + + $this->eventDispatcher->attach($fileLogHandler); + + $this->upgradeCustomFieldDefinition = $upgradeCustomFieldDefinition; + $this->upgradePublicLink = $upgradePublicLink; + $this->upgradeAuthToken = $upgradeAuthToken; + $this->upgradeCustomFieldData = $upgradeCustomFieldData; + $this->upgradePlugin = $upgradePlugin; + } + + public static function needsUpgrade(string $version): bool + { + return empty($version) || VersionUtil::checkVersion($version, self::UPGRADES); + } + + /** + * @throws UpgradeException + * @throws FileException + */ + public function upgrade( + string $version, + ConfigDataInterface $configData + ): void { + $this->eventDispatcher->notifyEvent( + 'upgrade.app.start', + new Event( + $this, + EventMessage::factory()->addDescription(__u('Update Application')) + ) + ); + + foreach (self::UPGRADES as $appVersion) { + if (VersionUtil::checkVersion($version, $appVersion)) { + if ($this->applyUpgrade($appVersion) === false) { + throw new UpgradeException( + __u('Error while applying the application update'), + SPException::CRITICAL, + __u('Please, check the event log for more details') + ); + } + + logger('APP Upgrade: '.$appVersion); + + $configData->setAppVersion($appVersion); + + $this->config->saveConfig($configData, false); + } + } + + $this->eventDispatcher->notifyEvent( + 'upgrade.app.end', + new Event( + $this, + EventMessage::factory()->addDescription(__u('Update Application')) + ) + ); + } + + /** + * Actualizaciones de la aplicación + */ + private function applyUpgrade(string $version): bool + { + try { + switch ($version) { + case '300.18010101': + $this->upgradeCustomFieldDefinition->upgrade_300_18010101(); + $this->upgradePublicLink->upgrade_300_18010101(); + + return true; + case '300.18072901': + $this->upgradeCustomFieldDefinition->upgrade_300_18072901(); + $this->upgradeAuthToken->upgrade_300_18072901(); + + return true; + case '300.18072902': + $this->upgradeCustomFieldData->upgrade_300_18072902(); + + return true; + case '310.19012201': + $this->upgradePlugin->upgrade_310_19012201(); + + return true; + case '310.19042701': + $this->upgradeCustomFieldDefinition->upgrade_310_19042701(); + + return true; + } + } catch (Exception $e) { + processException($e); + } + + return false; + } +} \ No newline at end of file diff --git a/lib/SP/Services/Upgrade/UpgradeDatabaseService.php b/lib/SP/Domain/Upgrade/Services/UpgradeDatabaseService.php similarity index 65% rename from lib/SP/Services/Upgrade/UpgradeDatabaseService.php rename to lib/SP/Domain/Upgrade/Services/UpgradeDatabaseService.php index a19dd2de..a137f8cb 100644 --- a/lib/SP/Services/Upgrade/UpgradeDatabaseService.php +++ b/lib/SP/Domain/Upgrade/Services/UpgradeDatabaseService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,27 +22,29 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\Upgrade\Services; use Exception; -use SP\Config\ConfigDataInterface; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; use SP\Core\Exceptions\SPException; +use SP\Domain\Common\Services\Service; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Persistence\UpgradeDatabaseServiceInterface; +use SP\Infrastructure\Database\DatabaseInterface; +use SP\Infrastructure\Database\MySQLFileParser; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; use SP\Providers\Log\FileLogHandler; -use SP\Services\Service; -use SP\Storage\Database\Database; -use SP\Storage\Database\MySQLFileParser; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; use SP\Util\VersionUtil; /** * Class UpgradeDatabaseService * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ -final class UpgradeDatabaseService extends Service implements UpgradeInterface +final class UpgradeDatabaseService extends Service implements UpgradeDatabaseServiceInterface { /** * @var array Versiones actualizables @@ -59,18 +61,26 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface '300.18111801', '300.18111901', '310.19012201', - '310.19042701' + '310.19042701', ]; - protected ?Database $db = null; + private DatabaseInterface $database; + + public function __construct(Application $application, DatabaseInterface $database, FileLogHandler $fileLogHandler) + { + parent::__construct($application); + + $this->database = $database; + $this->eventDispatcher->attach($fileLogHandler); + } + /** * Check if it needs to be upgraded */ public static function needsUpgrade(string $version): bool { - return empty($version) - || VersionUtil::checkVersion($version, self::UPGRADES); + return empty($version) || VersionUtil::checkVersion($version, self::UPGRADES); } /** @@ -83,8 +93,7 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface { $this->eventDispatcher->notifyEvent( 'upgrade.db.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('Update DB'))) + new Event($this, EventMessage::factory()->addDescription(__u('Update DB'))) ); foreach (self::UPGRADES as $upgradeVersion) { @@ -105,7 +114,7 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface ); } - logger('DB Upgrade: ' . $upgradeVersion); + logger('DB Upgrade: '.$upgradeVersion); $configData->setDatabaseVersion($upgradeVersion); @@ -115,8 +124,7 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface $this->eventDispatcher->notifyEvent( 'upgrade.db.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('Update DB'))) + new Event($this, EventMessage::factory()->addDescription(__u('Update DB'))) ); return true; @@ -133,7 +141,7 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface /** * Actualiza la BBDD según la versión. * - * @throws \SP\Services\Upgrade\UpgradeException + * @throws \SP\Domain\Upgrade\Services\UpgradeException */ private function applyUpgrade(string $version): bool { @@ -142,35 +150,31 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface if (count($queries) === 0) { logger(__('Update file does not contain data'), 'ERROR'); - throw new UpgradeException( - __u('Update file does not contain data'), - SPException::ERROR, - $version - ); + throw new UpgradeException(__u('Update file does not contain data'), SPException::ERROR, $version); } foreach ($queries as $query) { try { $this->eventDispatcher->notifyEvent( 'upgrade.db.process', - new Event($this, EventMessage::factory() - ->addDetail(__u('Version'), $version)) + new Event($this, EventMessage::factory()->addDetail(__u('Version'), $version)) ); // Direct PDO handling - $this->db->getDbHandler() - ->getConnection() - ->exec($query); + $this->database->getDbHandler()->getConnection()->exec($query); } catch (Exception $e) { processException($e); - logger('SQL: ' . $query); + logger('SQL: '.$query); $this->eventDispatcher->notifyEvent( 'exception', - new Event($this, EventMessage::factory() - ->addDescription(__u('Error while updating the database')) - ->addDetail('ERROR', sprintf('%s (%s)', $e->getMessage(), $e->getCode()))) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Error while updating the database')) + ->addDetail('ERROR', sprintf('%s (%s)', $e->getMessage(), $e->getCode())) + ) ); throw new UpgradeException(__u('Error while updating the database')); @@ -179,8 +183,10 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface $this->eventDispatcher->notifyEvent( 'upgrade.db.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('Database updating was completed successfully.'))) + new Event( + $this, + EventMessage::factory()->addDescription(__u('Database updating was completed successfully.')) + ) ); return true; @@ -193,26 +199,17 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface */ private function getQueriesFromFile(string $filename): array { - $fileName = SQL_PATH . - DIRECTORY_SEPARATOR . - str_replace('.', '', $filename) . - '.sql'; + $fileName = SQL_PATH. + DIRECTORY_SEPARATOR. + str_replace('.', '', $filename). + '.sql'; try { - $parser = new MySQLFileParser(new FileHandler($fileName)); - - return $parser->parse('$$'); + return (new MySQLFileParser(new FileHandler($fileName)))->parse('$$'); } catch (FileException $e) { processException($e); throw new UpgradeException($e->getMessage()); } } - - protected function initialize(): void - { - $this->eventDispatcher->attach($this->dic->get(FileLogHandler::class)); - - $this->db = $this->dic->get(Database::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/Upgrade/UpgradeException.php b/lib/SP/Domain/Upgrade/Services/UpgradeException.php similarity index 86% rename from lib/SP/Services/Upgrade/UpgradeException.php rename to lib/SP/Domain/Upgrade/Services/UpgradeException.php index 90d3613f..97b1e313 100644 --- a/lib/SP/Services/Upgrade/UpgradeException.php +++ b/lib/SP/Domain/Upgrade/Services/UpgradeException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\Upgrade\Services; use SP\Core\Exceptions\SPException; /** * Class UpgradeException * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ final class UpgradeException extends SPException { diff --git a/lib/SP/Services/Upgrade/UpgradePlugin.php b/lib/SP/Domain/Upgrade/Services/UpgradePluginService.php similarity index 53% rename from lib/SP/Services/Upgrade/UpgradePlugin.php rename to lib/SP/Domain/Upgrade/Services/UpgradePluginService.php index 65d8fe68..81298c92 100644 --- a/lib/SP/Services/Upgrade/UpgradePlugin.php +++ b/lib/SP/Domain/Upgrade/Services/UpgradePluginService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,21 +22,32 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\Upgrade\Services; use Exception; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventMessage; +use SP\Domain\Common\Services\Service; +use SP\Domain\Plugin\UpgradePluginServiceInterface; use SP\Plugin\PluginManager; -use SP\Services\Service; /** * Class UpgradePlugin * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ -final class UpgradePlugin extends Service +final class UpgradePluginService extends Service implements UpgradePluginServiceInterface { + private PluginManager $pluginManager; + + public function __construct(Application $application, PluginManager $pluginManager) + { + parent::__construct($application); + + $this->pluginManager = $pluginManager; + } + /** * upgrade_300_18010101 * @@ -46,19 +57,24 @@ final class UpgradePlugin extends Service { $this->eventDispatcher->notifyEvent( 'upgrade.plugin.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('Plugins upgrade')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Plugins upgrade')) + ->addDescription(__FUNCTION__) + ) ); - $this->dic->get(PluginManager::class) - ->upgradePlugins('310.19012201'); + $this->pluginManager->upgradePlugins('310.19012201'); $this->eventDispatcher->notifyEvent( 'upgrade.plugin.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('Plugins upgrade')) - ->addDescription(__FUNCTION__)) + new Event( + $this, + EventMessage::factory() + ->addDescription(__u('Plugins upgrade')) + ->addDescription(__FUNCTION__) + ) ); } } \ No newline at end of file diff --git a/lib/SP/Services/Upgrade/UpgradeUtil.php b/lib/SP/Domain/Upgrade/Services/UpgradeUtil.php similarity index 75% rename from lib/SP/Services/Upgrade/UpgradeUtil.php rename to lib/SP/Domain/Upgrade/Services/UpgradeUtil.php index 681ee8e7..e02dbee1 100644 --- a/lib/SP/Services/Upgrade/UpgradeUtil.php +++ b/lib/SP/Domain/Upgrade/Services/UpgradeUtil.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,17 +22,17 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\Upgrade\Services; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; -use SP\Storage\File\FileException; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Infrastructure\File\FileException; use SP\Util\VersionUtil; /** * Class UpgradeUtil * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ final class UpgradeUtil { @@ -43,10 +43,10 @@ final class UpgradeUtil { if (strpos($version, '.') === false) { if (strlen($version) === 10) { - return substr($version, 0, 2) . '0.' . substr($version, 2); + return substr($version, 0, 2).'0.'.substr($version, 2); } - return substr($version, 0, 3) . '.' . substr($version, 3); + return substr($version, 0, 3).'.'.substr($version, 3); } return $version; @@ -55,10 +55,7 @@ final class UpgradeUtil /** * @throws FileException */ - public static function fixAppUpgrade( - ConfigDataInterface $configData, - Config $config - ): void + public static function fixAppUpgrade(ConfigDataInterface $configData, ConfigInterface $config): void { // Fixes bug in 3.0.X version where some updates weren't applied // when upgrading from v2 diff --git a/lib/SP/Domain/Upgrade/UpgradeAppServiceInterface.php b/lib/SP/Domain/Upgrade/UpgradeAppServiceInterface.php new file mode 100644 index 00000000..5f2b5ed3 --- /dev/null +++ b/lib/SP/Domain/Upgrade/UpgradeAppServiceInterface.php @@ -0,0 +1,35 @@ +. + */ + +namespace SP\Domain\Upgrade; + + +/** + * Class UpgradeAppService + * + * @package SP\Domain\Upgrade\Services + */ +interface UpgradeAppServiceInterface extends UpgradeInterface +{ +} \ No newline at end of file diff --git a/lib/SP/Services/Upgrade/UpgradeInterface.php b/lib/SP/Domain/Upgrade/UpgradeInterface.php similarity index 85% rename from lib/SP/Services/Upgrade/UpgradeInterface.php rename to lib/SP/Domain/Upgrade/UpgradeInterface.php index b24072e2..a2eded79 100644 --- a/lib/SP/Services/Upgrade/UpgradeInterface.php +++ b/lib/SP/Domain/Upgrade/UpgradeInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Services\Upgrade; +namespace SP\Domain\Upgrade; -use SP\Config\ConfigDataInterface; +use SP\Domain\Config\In\ConfigDataInterface; /** * Interface UpgradeInterface * - * @package SP\Services\Upgrade + * @package SP\Domain\Upgrade\Services */ interface UpgradeInterface { diff --git a/lib/SP/Domain/User/In/UserGroupRepositoryInterface.php b/lib/SP/Domain/User/In/UserGroupRepositoryInterface.php new file mode 100644 index 00000000..b03ae628 --- /dev/null +++ b/lib/SP/Domain/User/In/UserGroupRepositoryInterface.php @@ -0,0 +1,72 @@ +. + */ + +namespace SP\Domain\User\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class UserGroupRepository + * + * @package SP\Infrastructure\User\Repositories + */ +interface UserGroupRepositoryInterface extends RepositoryInterface +{ + /** + * Returns the items that are using the given group id + * + * @param $id int + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getUsage(int $id): QueryResult; + + /** + * Returns the users that are using the given group id + * + * @param $id int + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getUsageByUsers(int $id): QueryResult; + + /** + * Returns the item for given name + * + * @param string $name + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByName(string $name): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/In/UserPassRecoverRepositoryInterface.php b/lib/SP/Domain/User/In/UserPassRecoverRepositoryInterface.php new file mode 100644 index 00000000..9b91b0a9 --- /dev/null +++ b/lib/SP/Domain/User/In/UserPassRecoverRepositoryInterface.php @@ -0,0 +1,86 @@ +. + */ + +namespace SP\Domain\User\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class UserPassRecoverRepository + * + * @package SP\Infrastructure\Common\Repositories\UserPassRecover + */ +interface UserPassRecoverRepositoryInterface +{ + /** + * Checks recovery limit attempts by user's id and time + * + * @param int $userId + * @param int $time + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function getAttemptsByUserId(int $userId, int $time): int; + + /** + * Adds a hash for a user's id + * + * @param int $userId + * @param string $hash + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function add(int $userId, string $hash): int; + + /** + * Toggles a hash used + * + * @param string $hash + * @param int $time + * + * @return int + * @throws SPException + */ + public function toggleUsedByHash(string $hash, int $time): int; + + /** + * Comprobar el hash de recuperación de clave. + * + * @param string $hash + * @param int $time + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getUserIdForHash(string $hash, int $time): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/In/UserProfileRepositoryInterface.php b/lib/SP/Domain/User/In/UserProfileRepositoryInterface.php new file mode 100644 index 00000000..77763b31 --- /dev/null +++ b/lib/SP/Domain/User/In/UserProfileRepositoryInterface.php @@ -0,0 +1,50 @@ +. + */ + +namespace SP\Domain\User\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class UserProfileRepository + * + * @package SP\Infrastructure\User\Repositories + */ +interface UserProfileRepositoryInterface extends RepositoryInterface +{ + /** + * Obtener el nombre de los usuarios que usan un perfil. + * + * @param $id int El id del perfil + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getUsersForProfile(int $id): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/In/UserRepositoryInterface.php b/lib/SP/Domain/User/In/UserRepositoryInterface.php new file mode 100644 index 00000000..368294a5 --- /dev/null +++ b/lib/SP/Domain/User/In/UserRepositoryInterface.php @@ -0,0 +1,168 @@ +. + */ + +namespace SP\Domain\User\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\UserData; +use SP\DataModel\UserPreferencesData; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Domain\User\Services\UpdatePassRequest; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class UserRepository + * + * @package SP\Infrastructure\User\Repositories + */ +interface UserRepositoryInterface extends RepositoryInterface +{ + /** + * Updates an user's pass + * + * @param int $id + * @param UpdatePassRequest $passRequest + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function updatePassById(int $id, UpdatePassRequest $passRequest): int; + + /** + * @param $login string + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getByLogin(string $login): QueryResult; + + /** + * Returns items' basic information + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getBasicInfo(): QueryResult; + + /** + * Updates user's master password + * + * @param int $id + * @param string $pass + * @param string $key + * + * @return int + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function updateMasterPassById(int $id, string $pass, string $key): int; + + /** + * Actualiza el último inicio de sesión del usuario en la BBDD. + * + * @param $id int El id del usuario + * + * @return int + * @throws QueryException + * @throws ConstraintException + */ + public function updateLastLoginById(int $id): int; + + /** + * @param string $login + * + * @return bool + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function checkExistsByLogin(string $login): bool; + + /** + * @param UserData $itemData + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function updateOnLogin(UserData $itemData): int; + + /** + * Updates an user's pass + * + * @param int $id + * @param UserPreferencesData $userPreferencesData + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function updatePreferencesById(int $id, UserPreferencesData $userPreferencesData): int; + + /** + * Obtener el email de los usuarios de un grupo + * + * @param int $groupId + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getUserEmailForGroup(int $groupId): QueryResult; + + /** + * Obtener el email de los usuarios + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getUserEmail(): QueryResult; + + /** + * Return the email of the given user's id + * + * @param int[] $ids + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getUserEmailById(array $ids): QueryResult; + + /** + * Returns the usage of the given user's id + * + * @param int $id + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getUsageForUser(int $id): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/In/UserToUserGroupRepositoryInterface.php b/lib/SP/Domain/User/In/UserToUserGroupRepositoryInterface.php new file mode 100644 index 00000000..4cecc972 --- /dev/null +++ b/lib/SP/Domain/User/In/UserToUserGroupRepositoryInterface.php @@ -0,0 +1,107 @@ +. + */ + +namespace SP\Domain\User\In; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class UserToUserGroupRepository + * + * @package SP\Infrastructure\User\Repositories + */ +interface UserToUserGroupRepositoryInterface +{ + /** + * Checks whether the user is included in the group + * + * @param int $groupId + * @param int $userId + * + * @return bool + * @throws ConstraintException + * @throws QueryException + */ + public function checkUserInGroup(int $groupId, int $userId): bool; + + /** + * Returns the groups which the user belongs to + * + * @param int $userId + * + * @return QueryResult + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getGroupsForUser(int $userId): QueryResult; + + /** + * Updates users from a group + * + * @param int $id + * @param array $users + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function update(int $id, array $users): int; + + /** + * Deletes users from a group + * + * @param $id int + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function delete(int $id): int; + + /** + * Adds users to a group + * + * @param int $groupId + * @param array $users + * + * @return int + * @throws ConstraintException + * @throws QueryException + */ + public function add(int $groupId, array $users): int; + + /** + * Returns users from a group by group Id + * + * @param $id int + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getById(int $id): QueryResult; +} \ No newline at end of file diff --git a/lib/SP/Services/User/UpdatePassRequest.php b/lib/SP/Domain/User/Services/UpdatePassRequest.php similarity index 86% rename from lib/SP/Services/User/UpdatePassRequest.php rename to lib/SP/Domain/User/Services/UpdatePassRequest.php index 35e93bcf..1aca643a 100644 --- a/lib/SP/Services/User/UpdatePassRequest.php +++ b/lib/SP/Domain/User/Services/UpdatePassRequest.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,18 +22,18 @@ * along with sysPass. If not, see . */ -namespace SP\Services\User; +namespace SP\Domain\User\Services; /** * Class UpdatePassRequest * - * @package SP\Services\User + * @package SP\Domain\User\Services */ final class UpdatePassRequest { private string $pass; - private bool $isChangePass = false; - private bool $isChangedPass = false; + private bool $isChangePass = false; + private bool $isChangedPass = false; public function __construct(string $pass) { diff --git a/lib/SP/Services/User/UpdatedMasterPassException.php b/lib/SP/Domain/User/Services/UpdatedMasterPassException.php similarity index 84% rename from lib/SP/Services/User/UpdatedMasterPassException.php rename to lib/SP/Domain/User/Services/UpdatedMasterPassException.php index ec9177f3..6991a3b4 100644 --- a/lib/SP/Services/User/UpdatedMasterPassException.php +++ b/lib/SP/Domain/User/Services/UpdatedMasterPassException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\User; +namespace SP\Domain\User\Services; use Exception; use SP\Core\Exceptions\SPException; @@ -30,16 +30,16 @@ use SP\Core\Exceptions\SPException; /** * Class UpdatedMasterPassException * - * @package SP\Services\User + * @package SP\Domain\User\Services */ final class UpdatedMasterPassException extends SPException { /** * SPException constructor. * - * @param string $type - * @param int $code - * @param \Exception|null $previous + * @param string $type + * @param int $code + * @param \Exception|null $previous */ public function __construct(string $type, int $code = 0, Exception $previous = null) { diff --git a/lib/SP/Services/UserGroup/UserGroupService.php b/lib/SP/Domain/User/Services/UserGroupService.php similarity index 63% rename from lib/SP/Services/UserGroup/UserGroupService.php rename to lib/SP/Domain/User/Services/UserGroupService.php index fd5ee20a..4cef1e8e 100644 --- a/lib/SP/Services/UserGroup/UserGroupService.php +++ b/lib/SP/Domain/User/Services/UserGroupService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,34 +22,51 @@ * along with sysPass. If not, see . */ -namespace SP\Services\UserGroup; +namespace SP\Domain\User\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserGroupData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\UserGroup\UserGroupRepository; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\User\In\UserGroupRepositoryInterface; +use SP\Domain\User\UserGroupServiceInterface; +use SP\Domain\User\UserToUserGroupServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\DatabaseInterface; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\User\Repositories\UserGroupRepository; /** * Class UserGroupService * - * @package SP\Services\UserGroup + * @package SP\Domain\Common\Services\UserGroup */ -final class UserGroupService extends Service +final class UserGroupService extends Service implements UserGroupServiceInterface { use ServiceItemTrait; - protected ?UserGroupRepository $userGroupRepository = null; - protected ?UserToUserGroupService $userToUserGroupService = null; + protected UserGroupRepository $userGroupRepository; + protected UserToUserGroupServiceInterface $userToUserGroupService; + private DatabaseInterface $database; + + public function __construct( + Application $application, + UserGroupRepositoryInterface $userGroupRepository, + UserToUserGroupServiceInterface $userToUserGroupService, + DatabaseInterface $database + ) { + parent::__construct($application); + + $this->userGroupRepository = $userGroupRepository; + $this->userToUserGroupService = $userToUserGroupService; + $this->database = $database; + } /** * @throws ConstraintException @@ -70,10 +87,7 @@ final class UserGroupService extends Service $result = $this->userGroupRepository->getById($id); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Group not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Group not found'), SPException::INFO); } $data = $result->getData(); @@ -85,26 +99,23 @@ final class UserGroupService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function delete(int $id): UserGroupService + public function delete(int $id): UserGroupServiceInterface { $delete = $this->userGroupRepository->delete($id); if ($delete === 0) { - throw new NoSuchItemException( - __u('Group not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Group not found'), SPException::INFO); } return $this; } /** - * @param int[] $ids + * @param int[] $ids * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ConstraintException * @throws QueryException */ @@ -123,7 +134,7 @@ final class UserGroupService extends Service } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function create(UserGroupData $itemData): int { @@ -138,12 +149,13 @@ final class UserGroupService extends Service } return $id; - } + }, + $this->database ); } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function update(UserGroupData $itemData): void { @@ -154,12 +166,10 @@ final class UserGroupService extends Service $users = $itemData->getUsers(); if ($users !== null) { - $this->userToUserGroupService->update( - $itemData->getId(), - $users - ); + $this->userToUserGroupService->update($itemData->getId(), $users); } - } + }, + $this->database ); } @@ -172,9 +182,7 @@ final class UserGroupService extends Service */ public function getAllBasic(): array { - return $this->userGroupRepository - ->getAll() - ->getDataAsArray(); + return $this->userGroupRepository->getAll()->getDataAsArray(); } /** @@ -189,10 +197,7 @@ final class UserGroupService extends Service $result = $this->userGroupRepository->getByName($name); if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Group not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Group not found'), SPException::INFO); } return $result->getData(); @@ -206,9 +211,7 @@ final class UserGroupService extends Service */ public function getUsage(int $id): array { - return $this->userGroupRepository - ->getUsage($id) - ->getDataAsArray(); + return $this->userGroupRepository->getUsage($id)->getDataAsArray(); } /** @@ -219,18 +222,6 @@ final class UserGroupService extends Service */ public function getUsageByUsers(int $id): array { - return $this->userGroupRepository - ->getUsageByUsers($id) - ->getDataAsArray(); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->userGroupRepository = $this->dic->get(UserGroupRepository::class); - $this->userToUserGroupService = $this->dic->get(UserToUserGroupService::class); + return $this->userGroupRepository->getUsageByUsers($id)->getDataAsArray(); } } \ No newline at end of file diff --git a/lib/SP/Services/User/UserLoginRequest.php b/lib/SP/Domain/User/Services/UserLoginRequest.php similarity index 85% rename from lib/SP/Services/User/UserLoginRequest.php rename to lib/SP/Domain/User/Services/UserLoginRequest.php index 5a1d456f..19be1fb8 100644 --- a/lib/SP/Services/User/UserLoginRequest.php +++ b/lib/SP/Domain/User/Services/UserLoginRequest.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,20 +22,20 @@ * along with sysPass. If not, see . */ -namespace SP\Services\User; +namespace SP\Domain\User\Services; /** * Class UserLoginRequest * - * @package SP\Services\User + * @package SP\Domain\User\Services */ final class UserLoginRequest { - private ?string $login = null; - private ?string $name = null; + private ?string $login = null; + private ?string $name = null; private ?string $password = null; - private ?string $email = null; - private ?bool $isLdap = null; + private ?string $email = null; + private ?bool $isLdap = null; public function getLogin(): ?string { diff --git a/lib/SP/Services/User/UserLoginResponse.php b/lib/SP/Domain/User/Services/UserLoginResponse.php similarity index 80% rename from lib/SP/Services/User/UserLoginResponse.php rename to lib/SP/Domain/User/Services/UserLoginResponse.php index 6acfa831..3b51aeb8 100644 --- a/lib/SP/Services/User/UserLoginResponse.php +++ b/lib/SP/Domain/User/Services/UserLoginResponse.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,39 +22,39 @@ * along with sysPass. If not, see . */ -namespace SP\Services\User; +namespace SP\Domain\User\Services; use SP\DataModel\UserPreferencesData; /** * Class UserLoginResponse * - * @package SP\Services\User + * @package SP\Domain\User\Services */ final class UserLoginResponse { - private ?int $id = null; - private ?string $login = null; - private ?string $ssoLogin = null; - private ?string $name = null; - private ?string $email = null; - private int $userGroupId = 0; - private ?string $userGroupName = null; - private int $userProfileId = 0; - private bool $isAdminApp = false; - private bool $isAdminAcc = false; - private bool $isDisabled = false; - private bool $isChangePass = false; - private bool $isChangedPass = false; - private bool $isLdap = false; - private bool $isMigrate = false; - private ?UserPreferencesData $preferences = null; - private ?string $pass = null; - private ?string $hashSalt = null; - private ?string $mPass = null; - private ?string $mKey = null; - private int $lastUpdateMPass = 0; - private ?int $lastUpdate = null; + private ?int $id = null; + private ?string $login = null; + private ?string $ssoLogin = null; + private ?string $name = null; + private ?string $email = null; + private int $userGroupId = 0; + private ?string $userGroupName = null; + private int $userProfileId = 0; + private bool $isAdminApp = false; + private bool $isAdminAcc = false; + private bool $isDisabled = false; + private bool $isChangePass = false; + private bool $isChangedPass = false; + private bool $isLdap = false; + private bool $isMigrate = false; + private ?UserPreferencesData $preferences = null; + private ?string $pass = null; + private ?string $hashSalt = null; + private ?string $mPass = null; + private ?string $mKey = null; + private int $lastUpdateMPass = 0; + private ?int $lastUpdate = null; public function getLogin(): ?string { @@ -64,6 +64,7 @@ final class UserLoginResponse public function setLogin(string $login): UserLoginResponse { $this->login = $login; + return $this; } @@ -75,6 +76,7 @@ final class UserLoginResponse public function setSsoLogin(?string $ssoLogin): UserLoginResponse { $this->ssoLogin = $ssoLogin; + return $this; } @@ -86,6 +88,7 @@ final class UserLoginResponse public function setName(string $name): UserLoginResponse { $this->name = $name; + return $this; } @@ -97,6 +100,7 @@ final class UserLoginResponse public function setEmail(?string $email): UserLoginResponse { $this->email = $email; + return $this; } @@ -108,6 +112,7 @@ final class UserLoginResponse public function setUserGroupId(int $userGroupId): UserLoginResponse { $this->userGroupId = $userGroupId; + return $this; } @@ -119,6 +124,7 @@ final class UserLoginResponse public function setUserProfileId(int $userProfileId): UserLoginResponse { $this->userProfileId = $userProfileId; + return $this; } @@ -130,6 +136,7 @@ final class UserLoginResponse public function setIsAdminApp(bool $isAdminApp): UserLoginResponse { $this->isAdminApp = $isAdminApp; + return $this; } @@ -141,6 +148,7 @@ final class UserLoginResponse public function setIsAdminAcc(bool $isAdminAcc): UserLoginResponse { $this->isAdminAcc = $isAdminAcc; + return $this; } @@ -152,6 +160,7 @@ final class UserLoginResponse public function setIsDisabled(bool $isDisabled): UserLoginResponse { $this->isDisabled = $isDisabled; + return $this; } @@ -163,6 +172,7 @@ final class UserLoginResponse public function setIsChangePass(bool $isChangePass): UserLoginResponse { $this->isChangePass = $isChangePass; + return $this; } @@ -174,6 +184,7 @@ final class UserLoginResponse public function setIsChangedPass(bool $isChangedPass): UserLoginResponse { $this->isChangedPass = $isChangedPass; + return $this; } @@ -185,6 +196,7 @@ final class UserLoginResponse public function setIsLdap(bool $isLdap): UserLoginResponse { $this->isLdap = $isLdap; + return $this; } @@ -196,6 +208,7 @@ final class UserLoginResponse public function setIsMigrate(bool $isMigrate): UserLoginResponse { $this->isMigrate = $isMigrate; + return $this; } @@ -207,6 +220,7 @@ final class UserLoginResponse public function setPreferences(UserPreferencesData $preferences): UserLoginResponse { $this->preferences = $preferences; + return $this; } @@ -218,6 +232,7 @@ final class UserLoginResponse public function setPass(string $pass): UserLoginResponse { $this->pass = $pass; + return $this; } @@ -229,6 +244,7 @@ final class UserLoginResponse public function setMPass(string $mPass): UserLoginResponse { $this->mPass = $mPass; + return $this; } @@ -240,6 +256,7 @@ final class UserLoginResponse public function setMKey(string $mKey): UserLoginResponse { $this->mKey = $mKey; + return $this; } @@ -251,6 +268,7 @@ final class UserLoginResponse public function setLastUpdateMPass(int $lastUpdateMPass): UserLoginResponse { $this->lastUpdateMPass = $lastUpdateMPass; + return $this; } @@ -262,6 +280,7 @@ final class UserLoginResponse public function setHashSalt(string $hashSalt): UserLoginResponse { $this->hashSalt = $hashSalt; + return $this; } @@ -273,6 +292,7 @@ final class UserLoginResponse public function setId(int $id): UserLoginResponse { $this->id = $id; + return $this; } @@ -284,6 +304,7 @@ final class UserLoginResponse public function setUserGroupName(string $userGroupName): UserLoginResponse { $this->userGroupName = $userGroupName; + return $this; } diff --git a/lib/SP/Services/UserPassRecover/UserPassRecoverService.php b/lib/SP/Domain/User/Services/UserPassRecoverService.php similarity index 75% rename from lib/SP/Services/UserPassRecover/UserPassRecoverService.php rename to lib/SP/Domain/User/Services/UserPassRecoverService.php index ec7b797b..8b010ec2 100644 --- a/lib/SP/Services/UserPassRecover/UserPassRecoverService.php +++ b/lib/SP/Domain/User/Services/UserPassRecoverService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,28 +22,29 @@ * along with sysPass. If not, see . */ -namespace SP\Services\UserPassRecover; +namespace SP\Domain\User\Services; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\Core\Messages\MailMessage; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\User\In\UserPassRecoverRepositoryInterface; +use SP\Domain\User\UserPassRecoverServiceInterface; use SP\Html\Html; -use SP\Repositories\User\UserPassRecoverRepository; -use SP\Services\Service; -use SP\Services\ServiceException; +use SP\Infrastructure\User\Repositories\UserPassRecoverRepository; use SP\Util\PasswordUtil; /** * Class UserPassRecoverService * - * @package SP\Services\UserPassRecover + * @package SP\Domain\Common\Services\UserPassRecover */ -final class UserPassRecoverService extends Service +final class UserPassRecoverService extends Service implements UserPassRecoverServiceInterface { /** * Tiempo máximo para recuperar la clave @@ -54,7 +55,14 @@ final class UserPassRecoverService extends Service */ public const MAX_PASS_RECOVER_LIMIT = 3; - protected ?UserPassRecoverRepository $userPassRecoverRepository = null; + protected UserPassRecoverRepository $userPassRecoverRepository; + + public function __construct(Application $application, UserPassRecoverRepositoryInterface $userPassRecoverRepository) + { + parent::__construct($application); + + $this->userPassRecoverRepository = $userPassRecoverRepository; + } public static function getMailMessage(string $hash): MailMessage { @@ -75,7 +83,7 @@ final class UserPassRecoverService extends Service /** * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function toggleUsedByHash(string $hash): void { @@ -84,26 +92,20 @@ final class UserPassRecoverService extends Service time() - self::MAX_PASS_RECOVER_TIME ) === 0 ) { - throw new ServiceException( - __u('Wrong hash or expired'), - SPException::INFO - ); + throw new ServiceException(__u('Wrong hash or expired'), SPException::INFO); } } /** * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws EnvironmentIsBrokenException */ public function requestForUserId(int $id): string { if ($this->checkAttemptsByUserId($id)) { - throw new ServiceException( - __u('Attempts exceeded'), - SPException::WARNING - ); + throw new ServiceException(__u('Attempts exceeded'), SPException::WARNING); } $hash = PasswordUtil::generateRandomBytes(16); @@ -139,7 +141,7 @@ final class UserPassRecoverService extends Service /** * Comprobar el hash de recuperación de clave. * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ConstraintException * @throws QueryException */ @@ -151,21 +153,9 @@ final class UserPassRecoverService extends Service ); if ($result->getNumRows() === 0) { - throw new ServiceException( - __u('Wrong hash or expired'), - SPException::INFO - ); + throw new ServiceException(__u('Wrong hash or expired'), SPException::INFO); } return (int)$result->getData()->userId; } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->userPassRecoverRepository = $this->dic->get(UserPassRecoverRepository::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/User/UserPassResponse.php b/lib/SP/Domain/User/Services/UserPassResponse.php similarity index 93% rename from lib/SP/Services/User/UserPassResponse.php rename to lib/SP/Domain/User/Services/UserPassResponse.php index f988df2b..73bafa58 100644 --- a/lib/SP/Services/User/UserPassResponse.php +++ b/lib/SP/Domain/User/Services/UserPassResponse.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Services\User; +namespace SP\Domain\User\Services; /** * Class UserPassResponse @@ -31,7 +31,7 @@ namespace SP\Services\User; */ final class UserPassResponse { - private int $status; + private int $status; private ?string $cryptMasterPass = null; private ?string $cryptSecuredKey = null; private ?string $clearMasterPass; diff --git a/lib/SP/Services/User/UserPassService.php b/lib/SP/Domain/User/Services/UserPassService.php similarity index 75% rename from lib/SP/Services/User/UserPassService.php rename to lib/SP/Domain/User/Services/UserPassService.php index 2ec92c13..8d26e752 100644 --- a/lib/SP/Services/User/UserPassService.php +++ b/lib/SP/Domain/User/Services/UserPassService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,30 +22,31 @@ * along with sysPass. If not, see . */ -namespace SP\Services\User; +namespace SP\Domain\User\Services; use Defuse\Crypto\Exception\CryptoException; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; +use SP\Core\Application; use SP\Core\Crypt\Crypt; use SP\Core\Crypt\Hash; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\UserLoginData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\User\UserRepository; -use SP\Services\Config\ConfigService; -use SP\Services\Service; +use SP\Domain\Common\Services\Service; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\User\In\UserRepositoryInterface; +use SP\Domain\User\UserPassServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\User\Repositories\UserRepository; /** * Class UserPassService * - * @package SP\Services\User + * @package SP\Domain\User\Services */ -final class UserPassService extends Service +final class UserPassService extends Service implements UserPassServiceInterface { // La clave maestra incorrecta public const MPASS_WRONG = 0; @@ -58,30 +59,37 @@ final class UserPassService extends Service // Comprobar la clave maestra con la clave del usuario anterior public const MPASS_CHECKOLD = 4; - protected ?ConfigDataInterface $configData = null; - protected ?UserRepository $userRepository = null; - protected ?ConfigService $configService = null; + private ConfigDataInterface $configData; + private UserRepository $userRepository; + private ConfigServiceInterface $configService; + + public function __construct( + Application $application, + UserRepositoryInterface $userRepository, + ConfigServiceInterface $configService + ) { + parent::__construct($application); + + $this->userRepository = $userRepository; + $this->configService = $configService; + + $this->configData = $this->config->getConfigData(); + } /** * Actualizar la clave maestra con la clave anterior del usuario * * @throws SPException * @throws CryptoException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface */ public function updateMasterPassFromOldPass( - string $oldUserPass, + string $oldUserPass, UserLoginData $userLoginData - ): UserPassResponse - { + ): UserPassResponse { $response = $this->loadUserMPass($userLoginData, $oldUserPass); if ($response->getStatus() === self::MPASS_OK) { - return $this->updateMasterPassOnLogin( - $response->getClearMasterPass(), - $userLoginData - ); + return $this->updateMasterPassOnLogin($response->getClearMasterPass(), $userLoginData); } return new UserPassResponse(self::MPASS_WRONG); @@ -91,13 +99,11 @@ final class UserPassService extends Service * Comprueba la clave maestra del usuario. * * @throws SPException - * @throws ContainerExceptionInterface */ public function loadUserMPass( UserLoginData $userLoginData, - ?string $userPass = null - ): UserPassResponse - { + ?string $userPass = null + ): UserPassResponse { $userLoginResponse = $userLoginData->getUserLoginResponse(); $configHashMPass = $this->configService->getByParam('masterPwd'); @@ -134,10 +140,7 @@ final class UserPassService extends Service if (Hash::checkHashKey($clearMPass, $configHashMPass)) { $this->setMasterKeyInContext($clearMPass); - $response = new UserPassResponse( - self::MPASS_OK, - $clearMPass - ); + $response = new UserPassResponse(self::MPASS_OK, $clearMPass); $response->setCryptMasterPass($userLoginResponse->getMPass()); $response->setCryptSecuredKey($userLoginResponse->getMKey()); @@ -158,17 +161,13 @@ final class UserPassService extends Service public function makeKeyForUser(string $userLogin, string $userPass): string { // Use always the most recent config data - if (Config::getTimeUpdated() > $this->configData->getConfigDate()) { - return trim( - $userPass . - $userLogin . - $this->config->getConfigData()->getPasswordSalt() - ); + if (ConfigFileService::getTimeUpdated() > $this->configData->getConfigDate()) { + return trim($userPass.$userLogin.$this->config->getConfigData()->getPasswordSalt()); } return trim( - $userPass . - $userLogin . + $userPass. + $userLogin. $this->configData->getPasswordSalt() ); } @@ -178,14 +177,9 @@ final class UserPassService extends Service * * @throws SPException * @throws CryptoException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface * @throws SPException */ - public function updateMasterPassOnLogin( - string $userMPass, - UserLoginData $userLoginData - ): UserPassResponse + public function updateMasterPassOnLogin(string $userMPass, UserLoginData $userLoginData): UserPassResponse { $userData = $userLoginData->getUserLoginResponse(); $configHashMPass = $this->configService->getByParam('masterPwd'); @@ -230,11 +224,7 @@ final class UserPassService extends Service * @throws CryptoException * @throws SPException */ - public function createMasterPass( - string $masterPass, - string $userLogin, - string $userPass - ): UserPassResponse + public function createMasterPass(string $masterPass, string $userLogin, string $userPass): UserPassResponse { $key = $this->makeKeyForUser($userLogin, $userPass); @@ -246,7 +236,8 @@ final class UserPassService extends Service __u('Internal error'), SPException::ERROR, '', - Service::STATUS_INTERNAL_ERROR); + Service::STATUS_INTERNAL_ERROR + ); } $response = new UserPassResponse(self::MPASS_OK, $masterPass); @@ -272,15 +263,4 @@ final class UserPassService extends Service throw new NoSuchItemException(__u('User does not exist')); } } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->configData = $this->config->getConfigData(); - $this->userRepository = $this->dic->get(UserRepository::class); - $this->configService = $this->dic->get(ConfigService::class); - } } \ No newline at end of file diff --git a/lib/SP/Services/UserProfile/UserProfileService.php b/lib/SP/Domain/User/Services/UserProfileService.php similarity index 65% rename from lib/SP/Services/UserProfile/UserProfileService.php rename to lib/SP/Domain/User/Services/UserProfileService.php index 36fb4d25..d14ab27e 100644 --- a/lib/SP/Services/UserProfile/UserProfileService.php +++ b/lib/SP/Domain/User/Services/UserProfileService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,39 +22,47 @@ * along with sysPass. If not, see . */ -namespace SP\Services\UserProfile; +namespace SP\Domain\User\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\ProfileData; use SP\DataModel\UserProfileData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\UserProfile\UserProfileRepository; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\User\In\UserProfileRepositoryInterface; +use SP\Domain\User\UserProfileServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\User\Repositories\UserProfileRepository; use SP\Util\Util; /** * Class UserProfileService * - * @package SP\Services\UserProfile + * @package SP\Domain\Common\Services\UserProfile */ -final class UserProfileService extends Service +final class UserProfileService extends Service implements UserProfileServiceInterface { use ServiceItemTrait; - protected ?UserProfileRepository $userProfileRepository = null; + protected UserProfileRepository $userProfileRepository; + + public function __construct(Application $application, UserProfileRepositoryInterface $userProfileRepository) + { + parent::__construct($application); + + $this->userProfileRepository = $userProfileRepository; + } /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function getById(int $id): UserProfileData { @@ -65,12 +73,7 @@ final class UserProfileService extends Service } $userProfileData = $result->getData(); - $userProfileData->setProfile( - Util::unserialize( - ProfileData::class, - $userProfileData->getProfile() - ) - ); + $userProfileData->setProfile(Util::unserialize(ProfileData::class, $userProfileData->getProfile())); return $userProfileData; } @@ -87,24 +90,21 @@ final class UserProfileService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function delete(int $id): UserProfileService + public function delete(int $id): UserProfileServiceInterface { if ($this->userProfileRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('Profile not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('Profile not found'), SPException::INFO); } return $this; } /** - * @param int[] $ids + * @param int[] $ids * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ConstraintException * @throws QueryException */ @@ -125,7 +125,7 @@ final class UserProfileService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\DuplicatedItemException + * @throws \SP\Infrastructure\Common\Repositories\DuplicatedItemException */ public function create(UserProfileData $itemData): int { @@ -135,8 +135,8 @@ final class UserProfileService extends Service /** * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\DuplicatedItemException - * @throws \SP\Services\ServiceException + * @throws \SP\Infrastructure\Common\Repositories\DuplicatedItemException + * @throws \SP\Domain\Common\Services\ServiceException */ public function update(UserProfileData $itemData): void { @@ -153,9 +153,7 @@ final class UserProfileService extends Service */ public function getUsersForProfile(int $id): array { - return $this->userProfileRepository - ->getUsersForProfile($id) - ->getDataAsArray(); + return $this->userProfileRepository->getUsersForProfile($id)->getDataAsArray(); } /** @@ -167,17 +165,6 @@ final class UserProfileService extends Service */ public function getAllBasic(): array { - return $this->userProfileRepository - ->getAll() - ->getDataAsArray(); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->userProfileRepository = $this->dic->get(UserProfileRepository::class); + return $this->userProfileRepository->getAll()->getDataAsArray(); } } \ No newline at end of file diff --git a/lib/SP/Services/User/UserService.php b/lib/SP/Domain/User/Services/UserService.php similarity index 80% rename from lib/SP/Services/User/UserService.php rename to lib/SP/Domain/User/Services/UserService.php index c2b8bfab..25d353a0 100644 --- a/lib/SP/Services/User/UserService.php +++ b/lib/SP/Domain/User/Services/UserService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,11 +22,10 @@ * along with sysPass. If not, see . */ -namespace SP\Services\User; +namespace SP\Domain\User\Services; use Defuse\Crypto\Exception\CryptoException; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Crypt\Hash; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; @@ -34,31 +33,44 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserData; use SP\DataModel\UserPreferencesData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\User\UserRepository; -use SP\Services\Service; -use SP\Services\ServiceException; -use SP\Services\ServiceItemTrait; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\Services\Service; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Common\Services\ServiceItemTrait; +use SP\Domain\User\In\UserRepositoryInterface; +use SP\Domain\User\UserPassServiceInterface; +use SP\Domain\User\UserServiceInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; +use SP\Infrastructure\User\Repositories\UserRepository; use SP\Util\Util; /** * Class UserService * - * @package SP\Services\User + * @package SP\Domain\User\Services */ -final class UserService extends Service +final class UserService extends Service implements UserServiceInterface { use ServiceItemTrait; - protected ?UserRepository $userRepository = null; - protected ?UserPassService $userPassService = null; + private UserRepository $userRepository; + private UserPassService $userPassService; + + public function __construct( + Application $application, + UserRepositoryInterface $userRepository, + UserPassServiceInterface $userPassService + ) { + parent::__construct($application); + + $this->userRepository = $userRepository; + $this->userPassService = $userPassService; + } public static function mapUserLoginResponse( UserData $userData - ): UserLoginResponse - { + ): UserLoginResponse { return (new UserLoginResponse())->setId($userData->getId()) ->setName($userData->getName()) ->setLogin($userData->getLogin()) @@ -86,16 +98,10 @@ final class UserService extends Service /** * Returns user's preferences object */ - public static function getUserPreferences( - ?string $preferences - ): UserPreferencesData + public static function getUserPreferences(?string $preferences): UserPreferencesData { if (!empty($preferences)) { - return Util::unserialize( - UserPreferencesData::class, - $preferences, - 'SP\UserPreferences' - ); + return Util::unserialize(UserPreferencesData::class, $preferences, 'SP\UserPreferences'); } return new UserPreferencesData(); @@ -149,9 +155,9 @@ final class UserService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ - public function getByLogin(string $login): UserData + public function getByLogin(string $login): ?UserData { $result = $this->userRepository->getByLogin($login); @@ -167,24 +173,21 @@ final class UserService extends Service * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException */ public function delete(int $id): UserService { if ($this->userRepository->delete($id) === 0) { - throw new NoSuchItemException( - __u('User not found'), - SPException::INFO - ); + throw new NoSuchItemException(__u('User not found'), SPException::INFO); } return $this; } /** - * @param int[] $ids + * @param int[] $ids * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ConstraintException * @throws QueryException */ @@ -247,11 +250,7 @@ final class UserService extends Service * @throws SPException * @throws CryptoException */ - public function createWithMasterPass( - UserData $itemData, - string $userPass, - string $masterPass - ): int + public function createWithMasterPass(UserData $itemData, string $userPass, string $masterPass): int { $response = $this->userPassService->createMasterPass( $masterPass, @@ -284,7 +283,7 @@ final class UserService extends Service * @throws ConstraintException * @throws QueryException * @throws DuplicatedItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function update(UserData $userData): void { @@ -300,7 +299,7 @@ final class UserService extends Service * * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function updatePass(int $userId, string $pass): void { @@ -322,10 +321,7 @@ final class UserService extends Service * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ - public function updatePreferencesById( - int $userId, - UserPreferencesData $userPreferencesData - ): int + public function updatePreferencesById(int $userId, UserPreferencesData $userPreferencesData): int { return $this->userRepository->updatePreferencesById( $userId, @@ -358,9 +354,7 @@ final class UserService extends Service */ public function getAllBasic(): array { - return $this->userRepository - ->getBasicInfo() - ->getDataAsArray(); + return $this->userRepository->getBasicInfo()->getDataAsArray(); } /** @@ -371,9 +365,7 @@ final class UserService extends Service */ public function getUserEmailForGroup(int $groupId): array { - return $this->userRepository - ->getUserEmailForGroup($groupId) - ->getDataAsArray(); + return $this->userRepository->getUserEmailForGroup($groupId)->getDataAsArray(); } /** @@ -386,16 +378,14 @@ final class UserService extends Service */ public function getUserEmailForAll(): array { - return $this->userRepository - ->getUserEmail() - ->getDataAsArray(); + return $this->userRepository->getUserEmail()->getDataAsArray(); } /** * Return the email of the given user's id * - * @param int[] $ids + * @param int[] $ids * * @throws ConstraintException * @throws QueryException @@ -403,9 +393,7 @@ final class UserService extends Service */ public function getUserEmailById(array $ids): array { - return $this->userRepository - ->getUserEmailById($ids) - ->getDataAsArray(); + return $this->userRepository->getUserEmailById($ids)->getDataAsArray(); } /** @@ -416,18 +404,6 @@ final class UserService extends Service */ public function getUsageForUser(int $id): array { - return $this->userRepository - ->getUsageForUser($id) - ->getDataAsArray(); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->userRepository = $this->dic->get(UserRepository::class); - $this->userPassService = $this->dic->get(UserPassService::class); + return $this->userRepository->getUsageForUser($id)->getDataAsArray(); } } \ No newline at end of file diff --git a/lib/SP/Services/UserGroup/UserToUserGroupService.php b/lib/SP/Domain/User/Services/UserToUserGroupService.php similarity index 68% rename from lib/SP/Services/UserGroup/UserToUserGroupService.php rename to lib/SP/Domain/User/Services/UserToUserGroupService.php index 386d7af1..1fd07ac7 100644 --- a/lib/SP/Services/UserGroup/UserToUserGroupService.php +++ b/lib/SP/Domain/User/Services/UserToUserGroupService.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,44 +22,33 @@ * along with sysPass. If not, see . */ -namespace SP\Services\UserGroup; +namespace SP\Domain\User\Services; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; +use SP\Core\Application; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\UserToUserGroupData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\UserGroup\UserToUserGroupRepository; -use SP\Services\Service; +use SP\Domain\Common\Services\Service; +use SP\Domain\User\In\UserToUserGroupRepositoryInterface; +use SP\Domain\User\UserToUserGroupServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\User\Repositories\UserToUserGroupRepository; /** * Class UserToUserGroupService * - * @package SP\Services\UserGroup + * @package SP\Domain\Common\Services\UserGroup */ -final class UserToUserGroupService extends Service +final class UserToUserGroupService extends Service implements UserToUserGroupServiceInterface { - protected ?UserToUserGroupRepository $userToUserGroupRepository = null; + protected UserToUserGroupRepository $userToUserGroupRepository; - /** - * @throws \SP\Core\Exceptions\ConstraintException - * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\NoSuchItemException - */ - public function getById(int $id): array + public function __construct(Application $application, UserToUserGroupRepositoryInterface $userToUserGroupRepository) { - $result = $this->userToUserGroupRepository->getById($id); + parent::__construct($application); - if ($result->getNumRows() === 0) { - throw new NoSuchItemException( - __u('Group not found'), - SPException::INFO - ); - } - - return $result->getDataAsArray(); + $this->userToUserGroupRepository = $userToUserGroupRepository; } /** @@ -93,9 +82,7 @@ final class UserToUserGroupService extends Service $usersId = []; /** @var UserToUserGroupData $userToUserGroupData */ - $userByGroup = $this->userToUserGroupRepository - ->getById($id) - ->getDataAsArray(); + $userByGroup = $this->userToUserGroupRepository->getById($id)->getDataAsArray(); foreach ($userByGroup as $userToUserGroupData) { $usersId[] = $userToUserGroupData->getUserId(); @@ -104,6 +91,22 @@ final class UserToUserGroupService extends Service return $usersId; } + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id): array + { + $result = $this->userToUserGroupRepository->getById($id); + + if ($result->getNumRows() === 0) { + throw new NoSuchItemException(__u('Group not found'), SPException::INFO); + } + + return $result->getDataAsArray(); + } + /** * Checks whether the user is included in the group * @@ -112,8 +115,7 @@ final class UserToUserGroupService extends Service */ public function checkUserInGroup(int $groupId, int $userId): bool { - return $this->userToUserGroupRepository - ->checkUserInGroup($groupId, $userId); + return $this->userToUserGroupRepository->checkUserInGroup($groupId, $userId); } /** @@ -124,17 +126,6 @@ final class UserToUserGroupService extends Service */ public function getGroupsForUser(int $userId): array { - return $this->userToUserGroupRepository - ->getGroupsForUser($userId) - ->getDataAsArray(); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function initialize(): void - { - $this->userToUserGroupRepository = $this->dic->get(UserToUserGroupRepository::class); + return $this->userToUserGroupRepository->getGroupsForUser($userId)->getDataAsArray(); } } \ No newline at end of file diff --git a/lib/SP/Domain/User/UserGroupServiceInterface.php b/lib/SP/Domain/User/UserGroupServiceInterface.php new file mode 100644 index 00000000..ef1d330c --- /dev/null +++ b/lib/SP/Domain/User/UserGroupServiceInterface.php @@ -0,0 +1,114 @@ +. + */ + +namespace SP\Domain\User; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ItemSearchData; +use SP\DataModel\UserGroupData; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class UserGroupService + * + * @package SP\Domain\Common\Services\UserGroup + */ +interface UserGroupServiceInterface +{ + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function getById(int $id): UserGroupData; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): UserGroupServiceInterface; + + /** + * @param int[] $ids + * + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function create(UserGroupData $itemData): int; + + /** + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function update(UserGroupData $itemData): void; + + /** + * Get all items from the service's repository + * + * @return UserGroupData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; + + /** + * Returns the item for given name + * + * @throws NoSuchItemException + * @throws ConstraintException + * @throws QueryException + */ + public function getByName(string $name): UserGroupData; + + /** + * Returns the users that are using the given group id + * + * @throws ConstraintException + * @throws QueryException + */ + public function getUsage(int $id): array; + + /** + * Returns the items that are using the given group id + * + * @throws ConstraintException + * @throws QueryException + */ + public function getUsageByUsers(int $id): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/UserPassRecoverServiceInterface.php b/lib/SP/Domain/User/UserPassRecoverServiceInterface.php new file mode 100644 index 00000000..a5a71d5d --- /dev/null +++ b/lib/SP/Domain/User/UserPassRecoverServiceInterface.php @@ -0,0 +1,76 @@ +. + */ + +namespace SP\Domain\User; + + +use Defuse\Crypto\Exception\EnvironmentIsBrokenException; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\Services\ServiceException; + +/** + * Class UserPassRecoverService + * + * @package SP\Domain\Common\Services\UserPassRecover + */ +interface UserPassRecoverServiceInterface +{ + /** + * @throws \SP\Core\Exceptions\SPException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function toggleUsedByHash(string $hash): void; + + /** + * @throws ConstraintException + * @throws QueryException + * @throws ServiceException + * @throws EnvironmentIsBrokenException + */ + public function requestForUserId(int $id): string; + + /** + * Comprobar el límite de recuperaciones de clave. + * + * @throws ConstraintException + * @throws QueryException + */ + public function checkAttemptsByUserId(int $userId): bool; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function add(int $userId, string $hash): bool; + + /** + * Comprobar el hash de recuperación de clave. + * + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function getUserIdForHash(string $hash): int; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/UserPassServiceInterface.php b/lib/SP/Domain/User/UserPassServiceInterface.php new file mode 100644 index 00000000..25ac8d1e --- /dev/null +++ b/lib/SP/Domain/User/UserPassServiceInterface.php @@ -0,0 +1,88 @@ +. + */ + +namespace SP\Domain\User; + + +use Defuse\Crypto\Exception\CryptoException; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\UserLoginData; +use SP\Domain\User\Services\UserPassResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; + +/** + * Class UserPassService + * + * @package SP\Domain\User\Services + */ +interface UserPassServiceInterface +{ + /** + * Actualizar la clave maestra con la clave anterior del usuario + * + * @throws SPException + * @throws CryptoException + */ + public function updateMasterPassFromOldPass(string $oldUserPass, UserLoginData $userLoginData): UserPassResponse; + + /** + * Comprueba la clave maestra del usuario. + * + * @throws SPException + */ + public function loadUserMPass(UserLoginData $userLoginData, ?string $userPass = null): UserPassResponse; + + /** + * Obtener una clave de cifrado basada en la clave del usuario y un salt. + * + * @return string con la clave de cifrado + */ + public function makeKeyForUser(string $userLogin, string $userPass): string; + + /** + * Actualizar la clave maestra del usuario al realizar login + * + * @throws SPException + * @throws CryptoException + * @throws SPException + */ + public function updateMasterPassOnLogin(string $userMPass, UserLoginData $userLoginData): UserPassResponse; + + /** + * Actualizar la clave maestra del usuario en la BBDD. + * + * @throws CryptoException + * @throws SPException + */ + public function createMasterPass(string $masterPass, string $userLogin, string $userPass): UserPassResponse; + + /** + * @throws ConstraintException + * @throws QueryException + * @throws NoSuchItemException + */ + public function migrateUserPassById(int $id, string $userPass): void; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/UserProfileServiceInterface.php b/lib/SP/Domain/User/UserProfileServiceInterface.php new file mode 100644 index 00000000..63c7a464 --- /dev/null +++ b/lib/SP/Domain/User/UserProfileServiceInterface.php @@ -0,0 +1,99 @@ +. + */ + +namespace SP\Domain\User; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\DataModel\ItemSearchData; +use SP\DataModel\UserProfileData; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class UserProfileService + * + * @package SP\Domain\Common\Services\UserProfile + */ +interface UserProfileServiceInterface +{ + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id): UserProfileData; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $itemSearchData): QueryResult; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): UserProfileServiceInterface; + + /** + * @param int[] $ids + * + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\DuplicatedItemException + */ + public function create(UserProfileData $itemData): int; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\DuplicatedItemException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function update(UserProfileData $itemData): void; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getUsersForProfile(int $id): array; + + /** + * Get all items from the service's repository + * + * @return UserProfileData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/UserServiceInterface.php b/lib/SP/Domain/User/UserServiceInterface.php new file mode 100644 index 00000000..d4ff6470 --- /dev/null +++ b/lib/SP/Domain/User/UserServiceInterface.php @@ -0,0 +1,200 @@ +. + */ + +namespace SP\Domain\User; + + +use Defuse\Crypto\Exception\CryptoException; +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; +use SP\Core\Exceptions\SPException; +use SP\DataModel\ItemSearchData; +use SP\DataModel\UserData; +use SP\DataModel\UserPreferencesData; +use SP\Domain\User\Services\UserLoginRequest; +use SP\Domain\User\Services\UserService; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Database\QueryResult; + +/** + * Class UserService + * + * @package SP\Domain\User\Services + */ +interface UserServiceInterface +{ + /** + * Actualiza el último inicio de sesión del usuario en la BBDD. + * + * @throws ConstraintException + * @throws NoSuchItemException + * @throws QueryException + */ + public function updateLastLoginById(int $id): int; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function checkExistsByLogin(string $login): bool; + + /** + * Returns the item for given id + * + * @throws SPException + */ + public function getById(int $id): UserData; + + /** + * Returns the item for given id + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getByLogin(string $login): ?UserData; + + /** + * Deletes an item + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function delete(int $id): UserService; + + /** + * @param int[] $ids + * + * @throws \SP\Domain\Common\Services\ServiceException + * @throws ConstraintException + * @throws QueryException + */ + public function deleteByIdBatch(array $ids): int; + + /** + * Creates an item + * + * @throws SPException + */ + public function createOnLogin(UserLoginRequest $userLoginRequest): int; + + /** + * Creates an item + * + * @throws SPException + */ + public function create(UserData $itemData): int; + + /** + * Creates an item + * + * @throws SPException + * @throws CryptoException + */ + public function createWithMasterPass(UserData $itemData, string $userPass, string $masterPass): int; + + /** + * Searches for items by a given filter + * + * @throws ConstraintException + * @throws QueryException + */ + public function search(ItemSearchData $searchData): QueryResult; + + /** + * Updates an item + * + * @throws ConstraintException + * @throws QueryException + * @throws DuplicatedItemException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function update(UserData $userData): void; + + /** + * Updates a user's pass + * + * @throws ConstraintException + * @throws QueryException + * @throws \SP\Domain\Common\Services\ServiceException + */ + public function updatePass(int $userId, string $pass): void; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function updatePreferencesById(int $userId, UserPreferencesData $userPreferencesData): int; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function updateOnLogin(UserLoginRequest $userLoginRequest): int; + + /** + * Get all items from the service's repository + * + * @return UserData[] + * @throws ConstraintException + * @throws QueryException + */ + public function getAllBasic(): array; + + /** + * Obtener el email de los usuarios de un grupo + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getUserEmailForGroup(int $groupId): array; + + /** + * Obtener el email de los usuarios de un grupo + * + * @throws ConstraintException + * @throws QueryException + **/ + public function getUserEmailForAll(): array; + + /** + * Return the email of the given user's id + * + * @param int[] $ids + * + * @throws ConstraintException + * @throws QueryException + */ + public function getUserEmailById(array $ids): array; + + /** + * Returns the usage of the given user's id + * + * @throws ConstraintException + * @throws QueryException + */ + public function getUsageForUser(int $id): array; +} \ No newline at end of file diff --git a/lib/SP/Domain/User/UserToUserGroupServiceInterface.php b/lib/SP/Domain/User/UserToUserGroupServiceInterface.php new file mode 100644 index 00000000..d36bb852 --- /dev/null +++ b/lib/SP/Domain/User/UserToUserGroupServiceInterface.php @@ -0,0 +1,78 @@ +. + */ + +namespace SP\Domain\User; + + +use SP\Core\Exceptions\ConstraintException; +use SP\Core\Exceptions\QueryException; + +/** + * Class UserToUserGroupService + * + * @package SP\Domain\Common\Services\UserGroup + */ +interface UserToUserGroupServiceInterface +{ + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function add(int $id, array $users): int; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function update(int $id, array $users): int; + + /** + * @throws ConstraintException + * @throws QueryException + */ + public function getUsersByGroupId(int $id): array; + + /** + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + */ + public function getById(int $id): array; + + /** + * Checks whether the user is included in the group + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function checkUserInGroup(int $groupId, int $userId): bool; + + /** + * Returns the groups which the user belongs to + * + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + */ + public function getGroupsForUser(int $userId): array; +} \ No newline at end of file diff --git a/lib/SP/Html/DataGrid/DataGridDataBase.php b/lib/SP/Html/DataGrid/DataGridDataBase.php index 38a26cda..5985994a 100644 --- a/lib/SP/Html/DataGrid/DataGridDataBase.php +++ b/lib/SP/Html/DataGrid/DataGridDataBase.php @@ -25,7 +25,7 @@ namespace SP\Html\DataGrid; use SP\Html\Assets\IconInterface; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; defined('APP_ROOT') || die(); diff --git a/lib/SP/Html/DataGrid/DataGridDataInterface.php b/lib/SP/Html/DataGrid/DataGridDataInterface.php index cc88b960..374fb142 100644 --- a/lib/SP/Html/DataGrid/DataGridDataInterface.php +++ b/lib/SP/Html/DataGrid/DataGridDataInterface.php @@ -25,7 +25,7 @@ namespace SP\Html\DataGrid; use SP\Html\Assets\IconInterface; -use SP\Storage\Database\QueryResult; +use SP\Infrastructure\Database\QueryResult; defined('APP_ROOT') || die(); diff --git a/lib/SP/Html/Minify.php b/lib/SP/Html/Minify.php index 435368d0..cd2a1ce7 100644 --- a/lib/SP/Html/Minify.php +++ b/lib/SP/Html/Minify.php @@ -36,7 +36,7 @@ defined('APP_ROOT') || die(); * * @package SP */ -final class Minify +class Minify { /** * Constantes para tipos de archivos @@ -80,9 +80,6 @@ final class Minify * devuelve el código HTTP/304 * * @param bool $disableMinify Deshabilitar minimizar - * - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface */ public function getMinified(bool $disableMinify = false): void { diff --git a/lib/SP/Http/Client.php b/lib/SP/Http/Client.php index 58537a8e..86063a0f 100644 --- a/lib/SP/Http/Client.php +++ b/lib/SP/Http/Client.php @@ -24,7 +24,7 @@ namespace SP\Http; -use SP\Config\ConfigDataInterface; +use SP\Domain\Config\In\ConfigDataInterface; /** * Class Client @@ -35,24 +35,13 @@ final class Client { public static function getOptions(ConfigDataInterface $configData): array { - $options = [ - 'timeout' => 10, - 'version' => 1.1 - ]; + $options = ['timeout' => 10, 'version' => 1.1,]; if ($configData->isProxyEnabled()) { - $options['proxy'] = sprintf( - 'tcp://%s:%d', - $configData->getProxyServer(), - $configData->getProxyPort() - ); + $options['proxy'] = sprintf('tcp://%s:%d', $configData->getProxyServer(), $configData->getProxyPort()); - if (!empty($configData->getProxyUser()) - && !empty($configData->getProxyPass())) { - $options['auth'] = [ - $configData->getProxyUser(), - $configData->getProxyPass() - ]; + if (!empty($configData->getProxyUser()) && !empty($configData->getProxyPass())) { + $options['auth'] = [$configData->getProxyUser(), $configData->getProxyPass()]; } } diff --git a/lib/SP/Http/Message.php b/lib/SP/Http/Message.php index 5f861519..3e5906b6 100644 --- a/lib/SP/Http/Message.php +++ b/lib/SP/Http/Message.php @@ -31,10 +31,6 @@ namespace SP\Http; */ final class Message { - public const TYPE_OK = 0; - public const TYPE_ERROR = 1; - public const TYPE_WARNING = 2; - protected int $type = 0; protected ?string $description = null; protected ?string $hint = null; diff --git a/lib/SP/Http/Request.php b/lib/SP/Http/Request.php index 8b6e5cf0..23eaff60 100644 --- a/lib/SP/Http/Request.php +++ b/lib/SP/Http/Request.php @@ -39,7 +39,7 @@ use SP\Util\Util; * * @package SP */ -final class Request +class Request implements RequestInterface { /** * @var array Directorios seguros para include diff --git a/lib/SP/Http/RequestInterface.php b/lib/SP/Http/RequestInterface.php new file mode 100644 index 00000000..a68bfb91 --- /dev/null +++ b/lib/SP/Http/RequestInterface.php @@ -0,0 +1,123 @@ +. + */ + +namespace SP\Http; + + +use SP\Core\Exceptions\SPException; + +/** + * Clase Request para la gestión de peticiones HTTP + * + * @package SP + */ +interface RequestInterface +{ + public function getClientAddress(bool $fullForwarded = false): string; + + /** + * @return string[]|null + */ + public function getForwardedFor(): ?array; + + /** + * Comprobar si se realiza una recarga de la página + */ + public function checkReload(): bool; + + public function analyzeEmail(string $param, ?string $default = null): ?string; + + /** + * Analizar un valor encriptado y devolverlo desencriptado + */ + public function analyzeEncrypted(string $param): string; + + public function analyzeString(string $param, ?string $default = null): ?string; + + public function analyzeUnsafeString(string $param, ?string $default = null): ?string; + + /** + * @param string $param + * @param callable|null $mapper + * @param null $default + * + * @return array|null + */ + public function analyzeArray(string $param, callable $mapper = null, $default = null): ?array; + + /** + * Comprobar si la petición es en formato JSON + */ + public function isJson(): bool; + + /** + * Comprobar si la petición es Ajax + */ + public function isAjax(): bool; + + public function analyzeInt(string $param, ?int $default = null): ?int; + + public function getFile(string $file): ?array; + + public function analyzeBool(string $param, ?bool $default = null): bool; + + /** + * @param string $key + * @param string|null $param Checks the signature only for the given param + * + * @throws SPException + */ + public function verifySignature(string $key, ?string $param = null): void; + + /** + * Returns the URI used by the browser and checks for the protocol used + * + * @see https://tools.ietf.org/html/rfc7239#section-7.5 + */ + public function getHttpHost(): string; + + /** + * Devolver datos de forward RFC 7239 + * + * @see https://tools.ietf.org/html/rfc7239#section-7.5 + */ + public function getForwardedData(): ?array; + + public function getHeader(string $header): string; + + /** + * Devolver datos de x-forward + */ + public function getXForwardedData(): ?array; + + public function getMethod(): ?string; + + public function isHttps(): ?bool; + + public function getServerPort(): int; + + public function getRequest(): \Klein\Request; + + public function getServer(string $key): string; +} \ No newline at end of file diff --git a/lib/SP/Http/XMLRPCResponseParse.php b/lib/SP/Http/XMLRPCResponseParse.php deleted file mode 100644 index a69f260d..00000000 --- a/lib/SP/Http/XMLRPCResponseParse.php +++ /dev/null @@ -1,276 +0,0 @@ -. - */ - -namespace SP\Http; - -use DOMDocument; -use DOMElement; -use DOMException; -use DOMNode; -use DOMNodeList; -use InvalidArgumentException; - -/** - * Class XMLRPCResponseParse para el parseo de respuestas HTTP en formato XML-RPC - * - * @package SP\Http - */ -abstract class XMLRPCResponseParse -{ - /** - * @var DOMElement - */ - private DOMElement $root; - /** - * @var string - */ - private string $xml; - /** - * @var array - */ - private array $data = []; - - /** - * Constructor - * - * @param string $xml El documento XML - * - * @throws InvalidArgumentException - */ - public function __construct(string $xml) - { - try { - $this->xml = $xml; - - $dom = new DOMDocument(); - $dom->loadXML($xml); - - if ($dom->getElementsByTagName('methodResponse')->length === 0) { - throw new DOMException(__u('Invalid XML-RPC response')); - } - - $this->root = $dom->documentElement; - } catch (DOMException $e) { - throw new InvalidArgumentException($e->getMessage(), $e->getCode()); - } - } - - /** - * Obtener los datos del error - * - * @return array - */ - public function getError(): array - { - return $this->parseNodes($this->root->getElementsByTagName('fault')); - } - - /** - * Obtener los nodos recursivamente y almacenar los datos en el atributo - * de la clase _data - * - * @param DOMNodeList $nodes - * - * @return array - */ - private function parseNodes(DOMNodeList $nodes): array - { - if ($nodes->length > 0) { - foreach ($nodes as $node) { - if ($node instanceof DOMElement) { - /** - * @var $node DOMElement - */ - switch ($node->nodeName) { - case 'struct': - return $this->parseStruct($node); - case 'array': - return $this->parseArray($node); - case 'fault': - return $this->parseFault($node); - case 'value': - $this->data = $this->parseValues($node); - break; - default: - $this->parseNodes($node->childNodes); - } - } - } - } - - return []; - } - - /** - * Procesar nodos del tipo struct - * - * @param DOMElement $xmlStruct - * - * @return array - */ - private function parseStruct(DOMElement $xmlStruct): array - { - $dataStruct = []; - $nStruct = 0; - - foreach ($xmlStruct->childNodes as $struct) { - if ($struct instanceof DOMElement) { - foreach ($struct->childNodes as $member) { - /** - * @var $member DOMNode - */ - switch ($member->nodeName) { - case 'name': - $name = $member->nodeValue; - break; - case 'value': - $dataStruct[$name] = $this->parseNodeType($member->firstChild); - break; - } - } - $nStruct++; - } - } - - return $dataStruct; - } - - /** - * @param DOMNode $node - * - * @return bool|int|string|null - */ - private function parseNodeType(DOMNode $node) - { - switch ($node->nodeName) { - case 'int' : - case 'i4' : - return (int)$node->nodeValue; - case 'string' : - return $node->nodeValue; - case 'dateTime.iso8601' : - return date('d M y H:i:s', strtotime($node->nodeValue)); - case 'boolean' : - return (bool)$node->nodeValue; - default : - return null; - } - } - - /** - * Procesar nodos del tipo array - * - * @param DOMElement $xmlArray - * - * @return array - */ - private function parseArray(DOMElement $xmlArray): array - { - $arrayData = []; - - foreach ($xmlArray->childNodes as $array) { - foreach ($array->childNodes as $data) { - /** - * @var $data DOMElement - */ - if ($data instanceof DOMElement && $data->nodeName === 'value') { - $values = $this->parseValues($data); - - $arrayData[] = $values; - } - } - } - - return $arrayData; - } - - /** - * Procesar nodos del tipo value - * - * @param DOMElement $xmlValues - * - * @return array - */ - private function parseValues(DOMElement $xmlValues): array - { - $valuesData = []; - - foreach ($xmlValues->childNodes as $xmlValue) { - if ($xmlValue instanceof DOMElement) { - $val = $this->parseNodeType($xmlValue); - - if (null === $val) { - return $this->parseNodes($xmlValues->childNodes); - } - - $valuesData[] = $val; - } - } - - return $valuesData; - } - - /** - * Procesar nodos del tipo fault - * - * @param DOMElement $xmlFault - * - * @return array - */ - private function parseFault(DOMElement $xmlFault): array - { - $faultData = []; - - foreach ($xmlFault->childNodes as $fault) { - /** - * @var $fault DOMElement - */ - if ($fault instanceof DOMElement && $fault->nodeName === 'value') { - return $this->parseValues($fault); - } - } - - return $faultData; - } - - /** - * Obtener los datos de la respuesta - */ - public function parseParams(): array - { - $this->parseNodes($this->root->getElementsByTagName('params')); - - return $this->data; - } - - /** - * Devolver el documento XML - * - * @return string - */ - public function getXml(): string - { - return $this->xml; - } -} \ No newline at end of file diff --git a/lib/SP/Repositories/Account/AccountFileRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountFileRepository.php similarity index 89% rename from lib/SP/Repositories/Account/AccountFileRepository.php rename to lib/SP/Infrastructure/Account/Repositories/AccountFileRepository.php index e7f22e42..1fc39671 100644 --- a/lib/SP/Repositories/Account/AccountFileRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/AccountFileRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Account; +namespace SP\Infrastructure\Account\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -30,25 +30,25 @@ use SP\Core\Exceptions\QueryException; use SP\DataModel\FileData; use SP\DataModel\FileExtData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\In\AccountFileRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountFileRepository * - * @package SP\Repositories\Account + * @package SP\Infrastructure\Account\Repositories */ -final class AccountFileRepository extends Repository implements RepositoryInterface +final class AccountFileRepository extends Repository implements AccountFileRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param FileData $itemData + * @param FileData $itemData * * @return int * @throws ConstraintException @@ -75,7 +75,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf $itemData->getSize(), $itemData->getContent(), $itemData->getExtension(), - $itemData->getThumb() + $itemData->getThumb(), ]); $queryData->setOnErrorMessage(__u('Error while saving file')); @@ -85,7 +85,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Updates an item * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -95,7 +95,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf } /** - * @param int $id + * @param int $id * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -127,7 +127,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -162,7 +162,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -226,7 +226,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult * @throws ConstraintException @@ -252,7 +252,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf FROM AccountFile AF INNER JOIN Account A ON A.id = AF.accountId INNER JOIN Client C ON A.clientId = C.id - WHERE AF.id IN (' . $this->getParamsFromArray($ids) . ')'; + WHERE AF.id IN ('.$this->getParamsFromArray($ids).')'; $queryData = new QueryData(); $queryData->setMapClassName(FileExtData::class); @@ -265,7 +265,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -287,7 +287,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -300,7 +300,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM AccountFile WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM AccountFile WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the files')); @@ -320,7 +320,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnUpdate($itemData): bool { @@ -330,7 +330,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnAdd($itemData): bool { @@ -340,9 +340,9 @@ final class AccountFileRepository extends Repository implements RepositoryInterf /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * - * @return \SP\Storage\Database\QueryResult + * @return \SP\Infrastructure\Database\QueryResult * @throws ConstraintException * @throws QueryException */ @@ -361,9 +361,11 @@ final class AccountFileRepository extends Repository implements RepositoryInterf Account.name as accountName, Client.name as clientName' ); - $queryData->setFrom('AccountFile + $queryData->setFrom( + 'AccountFile INNER JOIN Account ON Account.id = AccountFile.accountId - INNER JOIN Client ON Account.clientId = Client.id'); + INNER JOIN Client ON Account.clientId = Client.id' + ); $queryData->setOrder('Account.name'); if (!empty($itemSearchData->getSeachString())) { @@ -374,7 +376,7 @@ final class AccountFileRepository extends Repository implements RepositoryInterf OR Client.name LIKE ?' ); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); $queryData->addParam($search); diff --git a/lib/SP/Repositories/Account/AccountHistoryRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountHistoryRepository.php similarity index 89% rename from lib/SP/Repositories/Account/AccountHistoryRepository.php rename to lib/SP/Infrastructure/Account/Repositories/AccountHistoryRepository.php index 74a4405d..2bb464c3 100644 --- a/lib/SP/Repositories/Account/AccountHistoryRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/AccountHistoryRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Account; +namespace SP\Infrastructure\Account\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -31,19 +31,19 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\AccountHistoryData; use SP\DataModel\Dto\AccountHistoryCreateDto; use SP\DataModel\ItemSearchData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Services\Account\AccountPasswordRequest; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\In\AccountHistoryRepositoryInterface; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountHistoryRepository * * @package Services */ -final class AccountHistoryRepository extends Repository implements RepositoryInterface +final class AccountHistoryRepository extends Repository implements AccountHistoryRepositoryInterface { use RepositoryItemTrait; @@ -80,7 +80,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Crea una nueva cuenta en la BBDD * - * @param AccountHistoryCreateDto $dto + * @param AccountHistoryCreateDto $dto * * @return int * @throws QueryException @@ -149,7 +149,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Elimina los datos de una cuenta en la BBDD. * - * @param int $id + * @param int $id * * @return int Los ids de las cuentas eliminadas * @throws ConstraintException @@ -168,7 +168,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Updates an item * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -180,7 +180,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws SPException @@ -263,7 +263,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult */ @@ -275,7 +275,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -288,7 +288,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM AccountHistory WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM AccountHistory WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the accounts')); @@ -298,7 +298,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Deletes all the items for given accounts id * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -311,7 +311,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM AccountHistory WHERE accountId IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM AccountHistory WHERE accountId IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the accounts')); @@ -333,7 +333,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -345,7 +345,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -357,7 +357,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -366,17 +366,21 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt public function search(ItemSearchData $itemSearchData): QueryResult { $queryData = new QueryData(); - $queryData->setSelect('AH.id, AH.name, C.name as clientName, C2.name as categoryName, IFNULL(AH.dateEdit,AH.dateAdd) as date, AH.isModify, AH.isDeleted'); - $queryData->setFrom('AccountHistory AH + $queryData->setSelect( + 'AH.id, AH.name, C.name as clientName, C2.name as categoryName, IFNULL(AH.dateEdit,AH.dateAdd) as date, AH.isModify, AH.isDeleted' + ); + $queryData->setFrom( + 'AccountHistory AH INNER JOIN Client C ON AH.clientId = C.id INNER JOIN Category C2 ON AH.categoryId = C2.id - '); + ' + ); $queryData->setOrder('date DESC, AH.name, C.name, AH.id DESC'); if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('AH.name LIKE ? OR C.name LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); } @@ -411,7 +415,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt /** * Actualiza la clave de una cuenta en la BBDD. * - * @param AccountPasswordRequest $request + * @param AccountPasswordRequest $request * * @return int * @throws ConstraintException @@ -432,7 +436,7 @@ final class AccountHistoryRepository extends Repository implements RepositoryInt $request->pass, $request->key, $request->hash, - $request->id + $request->id, ]); $queryData->setOnErrorMessage(__u('Error while updating the password')); diff --git a/lib/SP/Repositories/Account/AccountRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php similarity index 87% rename from lib/SP/Repositories/Account/AccountRepository.php rename to lib/SP/Infrastructure/Account/Repositories/AccountRepository.php index ec13f9e9..04e3be3e 100644 --- a/lib/SP/Repositories/Account/AccountRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Account; +namespace SP\Infrastructure\Account\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -35,17 +35,17 @@ use SP\DataModel\AccountSearchVData; use SP\DataModel\AccountVData; use SP\DataModel\ItemData; use SP\DataModel\ItemSearchData; +use SP\Domain\Account\In\AccountRepositoryInterface; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; use SP\Mvc\Model\QueryAssignment; use SP\Mvc\Model\QueryCondition; use SP\Mvc\Model\QueryJoin; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Services\Account\AccountPasswordRequest; -use SP\Services\Account\AccountRequest; -use SP\Services\Account\AccountSearchFilter; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; use stdClass; /** @@ -53,7 +53,7 @@ use stdClass; * * @package Services */ -final class AccountRepository extends Repository implements RepositoryInterface +final class AccountRepository extends Repository implements AccountRepositoryInterface { use RepositoryItemTrait; @@ -77,8 +77,8 @@ final class AccountRepository extends Repository implements RepositoryInterface } /** - * @param int $id - * @param QueryCondition $queryCondition + * @param int $id + * @param QueryCondition $queryCondition * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -100,7 +100,7 @@ final class AccountRepository extends Repository implements RepositoryInterface } /** - * @param QueryCondition $queryCondition + * @param QueryCondition $queryCondition * * @return QueryResult * @throws ConstraintException @@ -118,7 +118,7 @@ final class AccountRepository extends Repository implements RepositoryInterface AccountHistory.parentId, AccountHistory.mPassHash FROM AccountHistory - WHERE ' . $queryCondition->getFilters(); + WHERE '.$queryCondition->getFilters(); $queryData = new QueryData(); $queryData->setMapClassName(AccountPassData::class); @@ -131,7 +131,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Incrementa el contador de vista de clave de una cuenta en la BBDD * - * @param int $id + * @param int $id * * @return bool * @throws ConstraintException @@ -152,7 +152,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Crea una nueva cuenta en la BBDD * - * @param AccountRequest $itemData + * @param AccountRequest $itemData * * @return int * @throws ConstraintException @@ -197,7 +197,7 @@ final class AccountRepository extends Repository implements RepositoryInterface $itemData->isPrivate, $itemData->isPrivateGroup, $itemData->passDateChange, - $itemData->parentId + $itemData->parentId, ]); $queryData->setOnErrorMessage(__u('Error while creating the account')); @@ -207,7 +207,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Actualiza la clave de una cuenta en la BBDD. * - * @param AccountRequest $accountRequest + * @param AccountRequest $accountRequest * * @return int * @throws ConstraintException @@ -232,7 +232,7 @@ final class AccountRepository extends Repository implements RepositoryInterface $accountRequest->key, $accountRequest->userEditId, $accountRequest->passDateChange, - $accountRequest->id + $accountRequest->id, ]); $queryData->setOnErrorMessage(__u('Error while updating the password')); @@ -242,7 +242,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Actualiza la clave de una cuenta en la BBDD. * - * @param AccountPasswordRequest $request + * @param AccountPasswordRequest $request * * @return bool * @throws ConstraintException @@ -267,8 +267,8 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Restaurar una cuenta desde el histórico. * - * @param int $historyId El Id del registro en el histórico - * @param int $userId User's Id + * @param int $historyId El Id del registro en el histórico + * @param int $userId User's Id * * @return bool * @throws ConstraintException @@ -308,7 +308,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Elimina los datos de una cuenta en la BBDD. * - * @param int $id + * @param int $id * * @return int EL número de cuentas eliminadas * @throws ConstraintException @@ -328,7 +328,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Updates an item * - * @param AccountRequest $itemData + * @param AccountRequest $itemData * * @return int * @throws SPException @@ -349,7 +349,7 @@ final class AccountRepository extends Repository implements RepositoryInterface 'passDateChange', 'isPrivate', 'isPrivateGroup', - 'parentId' + 'parentId', ], [ $itemData->clientId, $itemData->categoryId, @@ -361,7 +361,7 @@ final class AccountRepository extends Repository implements RepositoryInterface $itemData->passDateChange, $itemData->isPrivate, $itemData->isPrivateGroup, - $itemData->parentId + $itemData->parentId, ]); @@ -376,7 +376,7 @@ final class AccountRepository extends Repository implements RepositoryInterface } $query = /** @lang SQL */ - 'UPDATE Account SET ' . $queryAssignment->getAssignments() . ' WHERE id = ?'; + 'UPDATE Account SET '.$queryAssignment->getAssignments().' WHERE id = ?'; $queryData->setQuery($query); $queryData->setParams($queryAssignment->getValues()); @@ -389,7 +389,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Updates an item for bulk action * - * @param AccountRequest $itemData + * @param AccountRequest $itemData * * @return int * @throws SPException @@ -400,7 +400,7 @@ final class AccountRepository extends Repository implements RepositoryInterface $queryAssignment->setFields([ 'userEditId', - 'dateEdit = NOW()' + 'dateEdit = NOW()', ], [ $itemData->userEditId, ]); @@ -425,7 +425,7 @@ final class AccountRepository extends Repository implements RepositoryInterface } $query = /** @lang SQL */ - 'UPDATE Account SET ' . $queryAssignment->getAssignments() . ' WHERE id = ?'; + 'UPDATE Account SET '.$queryAssignment->getAssignments().' WHERE id = ?'; $queryData->setQuery($query); $queryData->setParams($queryAssignment->getValues()); @@ -438,7 +438,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws QueryException @@ -474,7 +474,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids */ public function getByIdBatch(array $ids): QueryResult { @@ -484,7 +484,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -498,7 +498,7 @@ final class AccountRepository extends Repository implements RepositoryInterface $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM Account WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM Account WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the accounts')); @@ -518,7 +518,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnUpdate($itemData): bool { @@ -528,7 +528,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnAdd($itemData): bool { @@ -538,7 +538,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -552,13 +552,15 @@ final class AccountRepository extends Repository implements RepositoryInterface $queryData->setOrder('name, clientName'); if (!empty($itemSearchData->getSeachString())) { - $queryData->setWhere('name LIKE ? + $queryData->setWhere( + 'name LIKE ? OR clientName LIKE ? OR categoryName LIKE ? OR userName LIKE ? - OR userGroupName LIKE ?'); + OR userGroupName LIKE ?' + ); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); $queryData->addParam($search); @@ -577,7 +579,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Incrementa el contador de visitas de una cuenta en la BBDD * - * @param int $id + * @param int $id * * @return bool * @throws ConstraintException @@ -595,7 +597,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Obtener los datos de una cuenta. * - * @param int $id + * @param int $id * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -630,8 +632,8 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Obtener las cuentas de una búsqueda. * - * @param AccountSearchFilter $accountSearchFilter - * @param QueryCondition $queryFilterUser + * @param AccountSearchFilter $accountSearchFilter + * @param QueryCondition $queryFilterUser * * @return QueryResult * @throws ConstraintException @@ -640,9 +642,8 @@ final class AccountRepository extends Repository implements RepositoryInterface */ public function getByFilter( AccountSearchFilter $accountSearchFilter, - QueryCondition $queryFilterUser - ): QueryResult - { + QueryCondition $queryFilterUser + ): QueryResult { $queryFilters = new QueryCondition(); // Sets the search text depending on if special search filters are being used @@ -651,7 +652,7 @@ final class AccountRepository extends Repository implements RepositoryInterface if (!empty($searchText)) { $queryFilters->addFilter( 'Account.name LIKE ? OR Account.login LIKE ? OR Account.url LIKE ? OR Account.notes LIKE ?', - array_fill(0, 4, '%' . $searchText . '%') + array_fill(0, 4, '%'.$searchText.'%') ); } @@ -698,12 +699,15 @@ final class AccountRepository extends Repository implements RepositoryInterface if ($accountSearchFilter->hasTags()) { $queryJoins->addJoin('INNER JOIN AccountToTag ON AccountToTag.accountId = Account.id'); $queryFilters->addFilter( - 'AccountToTag.tagId IN (' . $this->getParamsFromArray($accountSearchFilter->getTagsId()) . ')', + 'AccountToTag.tagId IN ('.$this->getParamsFromArray($accountSearchFilter->getTagsId()).')', $accountSearchFilter->getTagsId() ); if (QueryCondition::CONDITION_AND === $accountSearchFilter->getFilterOperator()) { - $groupBy = sprintf('Account.id HAVING COUNT(DISTINCT AccountToTag.tagId) = %d', count($accountSearchFilter->getTagsId())); + $groupBy = sprintf( + 'Account.id HAVING COUNT(DISTINCT AccountToTag.tagId) = %d', + count($accountSearchFilter->getTagsId()) + ); $queryData->setGroupBy($groupBy); } @@ -714,13 +718,15 @@ final class AccountRepository extends Repository implements RepositoryInterface } $queryData->setWhere($where); - $queryData->setParams(array_merge( - $queryJoins->getParams(), - $queryFilterUser->getParams(), - $queryFilters->getParams() - )); + $queryData->setParams( + array_merge( + $queryJoins->getParams(), + $queryFilterUser->getParams(), + $queryFilters->getParams() + ) + ); $queryData->setSelect('DISTINCT Account.*'); - $queryData->setFrom('account_search_v Account ' . $queryJoins->getJoins()); + $queryData->setFrom('account_search_v Account '.$queryJoins->getJoins()); $queryData->setOrder($accountSearchFilter->getOrderString()); if ($accountSearchFilter->getLimitCount() > 0) { @@ -737,7 +743,7 @@ final class AccountRepository extends Repository implements RepositoryInterface } /** - * @param QueryCondition $queryFilter + * @param QueryCondition $queryFilter * * @return QueryResult * @throws ConstraintException @@ -749,7 +755,7 @@ final class AccountRepository extends Repository implements RepositoryInterface 'SELECT Account.id, Account.name, C.name AS clientName FROM Account LEFT JOIN Client C ON Account.clientId = C.id - WHERE ' . $queryFilter->getFilters() . ' ORDER BY name'; + WHERE '.$queryFilter->getFilters().' ORDER BY name'; $queryData = new QueryData(); $queryData->setMapClassName(ItemData::class); @@ -760,7 +766,7 @@ final class AccountRepository extends Repository implements RepositoryInterface } /** - * @param QueryCondition $queryFilter + * @param QueryCondition $queryFilter * * @return QueryResult * @throws ConstraintException @@ -772,7 +778,7 @@ final class AccountRepository extends Repository implements RepositoryInterface 'SELECT Account.id, Account.name, Client.name AS clientName FROM Account INNER JOIN Client ON Account.clientId = Client.id - WHERE ' . $queryFilter->getFilters() . ' ORDER BY Account.name'; + WHERE '.$queryFilter->getFilters().' ORDER BY Account.name'; $queryData = new QueryData(); $queryData->setQuery($query); @@ -784,7 +790,7 @@ final class AccountRepository extends Repository implements RepositoryInterface /** * Obtener los datos relativos a la clave de todas las cuentas. * - * @return \SP\Storage\Database\QueryResult + * @return \SP\Infrastructure\Database\QueryResult * @throws ConstraintException * @throws QueryException */ diff --git a/lib/SP/Repositories/Account/AccountToFavoriteRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountToFavoriteRepository.php similarity index 85% rename from lib/SP/Repositories/Account/AccountToFavoriteRepository.php rename to lib/SP/Infrastructure/Account/Repositories/AccountToFavoriteRepository.php index a21ce8d8..d12c98d1 100644 --- a/lib/SP/Repositories/Account/AccountToFavoriteRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/AccountToFavoriteRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,20 +22,21 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Account; +namespace SP\Infrastructure\Account\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\Repository; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\In\AccountToFavoriteRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountFavoriteRepository * - * @package SP\Repositories\Account + * @package SP\Infrastructure\Account\Repositories */ -final class AccountToFavoriteRepository extends Repository +final class AccountToFavoriteRepository extends Repository implements AccountToFavoriteRepositoryInterface { /** * Obtener un array con los Ids de cuentas favoritas diff --git a/lib/SP/Repositories/Account/AccountToTagRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountToTagRepository.php similarity index 79% rename from lib/SP/Repositories/Account/AccountToTagRepository.php rename to lib/SP/Infrastructure/Account/Repositories/AccountToTagRepository.php index 61a8fb41..6206c6c2 100644 --- a/lib/SP/Repositories/Account/AccountToTagRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/AccountToTagRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,30 +22,31 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Account; +namespace SP\Infrastructure\Account\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryItemTrait; -use SP\Services\Account\AccountRequest; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\In\AccountToTagRepositoryInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountToTagRepository * - * @package SP\Repositories\Account + * @package SP\Infrastructure\Account\Repositories */ -final class AccountToTagRepository extends Repository +final class AccountToTagRepository extends Repository implements AccountToTagRepositoryInterface { use RepositoryItemTrait; /** * Devolver las etiquetas de una cuenta * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -69,7 +70,7 @@ final class AccountToTagRepository extends Repository } /** - * @param AccountRequest $accountRequest + * @param AccountRequest $accountRequest * * @throws ConstraintException * @throws QueryException @@ -83,7 +84,7 @@ final class AccountToTagRepository extends Repository /** * Eliminar las etiquetas de una cuenta * - * @param int $id + * @param int $id * * @return int * @throws ConstraintException @@ -102,7 +103,7 @@ final class AccountToTagRepository extends Repository /** * Actualizar las etiquetas de una cuenta * - * @param AccountRequest $accountRequest + * @param AccountRequest $accountRequest * * @return int * @throws ConstraintException @@ -111,7 +112,10 @@ final class AccountToTagRepository extends Repository public function add(AccountRequest $accountRequest): int { $query = /** @lang SQL */ - 'INSERT INTO AccountToTag (accountId, tagId) VALUES ' . $this->getParamsFromArray($accountRequest->tags, '(?,?)'); + 'INSERT INTO AccountToTag (accountId, tagId) VALUES '.$this->getParamsFromArray( + $accountRequest->tags, + '(?,?)' + ); $queryData = new QueryData(); $queryData->setQuery($query); diff --git a/lib/SP/Repositories/Account/AccountToUserGroupRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountToUserGroupRepository.php similarity index 85% rename from lib/SP/Repositories/Account/AccountToUserGroupRepository.php rename to lib/SP/Infrastructure/Account/Repositories/AccountToUserGroupRepository.php index c4ab8988..0d7eca79 100644 --- a/lib/SP/Repositories/Account/AccountToUserGroupRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/AccountToUserGroupRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,30 +22,31 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Account; +namespace SP\Infrastructure\Account\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryItemTrait; -use SP\Services\Account\AccountRequest; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\In\AccountToUserGroupRepositoryInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountToUserGroupRepository * - * @package SP\Repositories\Account + * @package SP\Infrastructure\Account\Repositories */ -final class AccountToUserGroupRepository extends Repository +final class AccountToUserGroupRepository extends Repository implements AccountToUserGroupRepositoryInterface { use RepositoryItemTrait; /** * Obtiene el listado con el nombre de los grupos de una cuenta. * - * @param int $id con el Id de la cuenta + * @param int $id con el Id de la cuenta * * @return QueryResult * @throws ConstraintException @@ -71,7 +72,7 @@ final class AccountToUserGroupRepository extends Repository /** * Obtiene el listado con el nombre de los grupos de una cuenta. * - * @param int $id + * @param int $id * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -112,8 +113,8 @@ final class AccountToUserGroupRepository extends Repository } /** - * @param AccountRequest $accountRequest - * @param bool $isEdit + * @param AccountRequest $accountRequest + * @param bool $isEdit * * @return int * @throws ConstraintException @@ -127,8 +128,8 @@ final class AccountToUserGroupRepository extends Repository } /** - * @param int $id - * @param bool $isEdit + * @param int $id + * @param bool $isEdit * * @return int * @throws ConstraintException @@ -145,8 +146,8 @@ final class AccountToUserGroupRepository extends Repository } /** - * @param AccountRequest $accountRequest - * @param bool $isEdit + * @param AccountRequest $accountRequest + * @param bool $isEdit * * @return int Last ID inserted * @throws ConstraintException @@ -159,8 +160,8 @@ final class AccountToUserGroupRepository extends Repository $query = /** @lang SQL */ 'INSERT INTO AccountToUserGroup (accountId, userGroupId, isEdit) - VALUES ' . $values . ' - ON DUPLICATE KEY UPDATE isEdit = ' . (int)$isEdit; + VALUES '.$values.' + ON DUPLICATE KEY UPDATE isEdit = '.(int)$isEdit; $queryData = new QueryData(); $queryData->setQuery($query); diff --git a/lib/SP/Repositories/Account/AccountToUserRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountToUserRepository.php similarity index 81% rename from lib/SP/Repositories/Account/AccountToUserRepository.php rename to lib/SP/Infrastructure/Account/Repositories/AccountToUserRepository.php index 01464f96..7186753b 100644 --- a/lib/SP/Repositories/Account/AccountToUserRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/AccountToUserRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,32 +22,32 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Account; +namespace SP\Infrastructure\Account\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryItemTrait; -use SP\Services\Account\AccountRequest; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Account\In\AccountToUserRepositoryInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountToUserRepository * - * @package SP\Repositories\Account + * @package SP\Infrastructure\Account\Repositories */ -final class AccountToUserRepository extends Repository +final class AccountToUserRepository extends Repository implements AccountToUserRepositoryInterface { use RepositoryItemTrait; /** * Actualizar la asociación de grupos con cuentas. * - * @param AccountRequest $accountRequest - * - * @param bool $isEdit + * @param AccountRequest $accountRequest + * @param bool $isEdit * * @return void * @throws \SP\Core\Exceptions\ConstraintException @@ -62,8 +62,8 @@ final class AccountToUserRepository extends Repository /** * Eliminar la asociación de grupos con cuentas. * - * @param int $id con el Id de la cuenta - * @param bool $isEdit + * @param int $id con el Id de la cuenta + * @param bool $isEdit * * @return int * @throws ConstraintException @@ -82,8 +82,8 @@ final class AccountToUserRepository extends Repository /** * Crear asociación de usuarios con cuentas. * - * @param AccountRequest $accountRequest - * @param bool $isEdit + * @param AccountRequest $accountRequest + * @param bool $isEdit * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -96,8 +96,8 @@ final class AccountToUserRepository extends Repository $query = /** @lang SQL */ 'INSERT INTO AccountToUser (accountId, userId, isEdit) - VALUES ' . $values . ' - ON DUPLICATE KEY UPDATE isEdit = ' . (int)$isEdit; + VALUES '.$values.' + ON DUPLICATE KEY UPDATE isEdit = '.(int)$isEdit; $queryData = new QueryData(); $queryData->setQuery($query); @@ -119,7 +119,7 @@ final class AccountToUserRepository extends Repository /** * Eliminar la asociación de grupos con cuentas. * - * @param int $id con el Id de la cuenta + * @param int $id con el Id de la cuenta * * @return int * @throws ConstraintException @@ -138,7 +138,7 @@ final class AccountToUserRepository extends Repository /** * Obtiene el listado de usuarios de una cuenta. * - * @param int $id con el id de la cuenta + * @param int $id con el id de la cuenta * * @return QueryResult * @throws ConstraintException diff --git a/lib/SP/Repositories/PublicLink/PublicLinkRepository.php b/lib/SP/Infrastructure/Account/Repositories/PublicLinkRepository.php similarity index 91% rename from lib/SP/Repositories/PublicLink/PublicLinkRepository.php rename to lib/SP/Infrastructure/Account/Repositories/PublicLinkRepository.php index 95e5bb35..9047373b 100644 --- a/lib/SP/Repositories/PublicLink/PublicLinkRepository.php +++ b/lib/SP/Infrastructure/Account/Repositories/PublicLinkRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\PublicLink; +namespace SP\Infrastructure\Account\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -31,17 +31,17 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\PublicLinkData; use SP\DataModel\PublicLinkListData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class PublicLinkRepository * - * @package SP\Repositories\PublicLink + * @package SP\Infrastructure\Common\Repositories\PublicLink */ final class PublicLinkRepository extends Repository implements RepositoryInterface { @@ -50,7 +50,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -108,7 +108,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult * @throws QueryException @@ -141,7 +141,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa FROM PublicLink PL INNER JOIN User U ON PL.userId = U.id INNER JOIN Account A ON itemId = A.id - WHERE PL.id IN (' . $this->getParamsFromArray($ids) . ') + WHERE PL.id IN ('.$this->getParamsFromArray($ids).') ORDER BY PL.id'; $queryData = new QueryData(); @@ -155,7 +155,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -168,7 +168,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM PublicLink WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM PublicLink WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); return $this->db->doQuery($queryData)->getAffectedNumRows(); @@ -189,7 +189,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws QueryException @@ -199,7 +199,8 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa { $queryData = new QueryData(); $queryData->setMapClassName(PublicLinkListData::class); - $queryData->setSelect('PublicLink.id, + $queryData->setSelect( + 'PublicLink.id, PublicLink.itemId, PublicLink.hash, PublicLink.data, @@ -216,17 +217,20 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa User.name AS userName, User.login AS userLogin, Account.name AS accountName, - Client.name AS clientName'); - $queryData->setFrom('PublicLink + Client.name AS clientName' + ); + $queryData->setFrom( + 'PublicLink INNER JOIN User ON PublicLink.userId = User.id INNER JOIN Account ON PublicLink.itemId = Account.id - INNER JOIN Client ON Account.clientId = Client.id'); + INNER JOIN Client ON Account.clientId = Client.id' + ); $queryData->setOrder('PublicLink.dateExpire DESC'); if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('User.login LIKE ? OR Account.name LIKE ? OR Client.name LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); $queryData->addParam($search); @@ -243,7 +247,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Creates an item * - * @param PublicLinkData $itemData + * @param PublicLinkData $itemData * * @return QueryResult * @throws DuplicatedItemException @@ -278,7 +282,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa $itemData->getTypeId(), (int)$itemData->isNotify(), $itemData->getDateExpire(), - $itemData->getMaxCountViews() + $itemData->getMaxCountViews(), ]); $queryData->setOnErrorMessage(__u('Error while creating the link')); @@ -288,7 +292,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Checks whether the item is duplicated on adding * - * @param PublicLinkData $itemData + * @param PublicLinkData $itemData * * @return bool * @throws ConstraintException @@ -306,7 +310,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -318,7 +322,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Incrementar el contador de visitas de un enlace * - * @param PublicLinkData $publicLinkData + * @param PublicLinkData $publicLinkData * * @return int * @throws ConstraintException @@ -337,7 +341,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa $queryData->setQuery($query); $queryData->setParams([ $publicLinkData->getUseInfo(), - $publicLinkData->getHash() + $publicLinkData->getHash(), ]); $queryData->setOnErrorMessage(__u('Error while updating the link')); @@ -347,7 +351,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Updates an item * - * @param PublicLinkData $itemData + * @param PublicLinkData $itemData * * @return int * @throws SPException @@ -385,7 +389,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa $itemData->getMaxCountViews(), $itemData->getUseInfo(), $itemData->getTypeId(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the link')); @@ -395,7 +399,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Refreshes a public link * - * @param PublicLinkData $publicLinkData + * @param PublicLinkData $publicLinkData * * @return int * @throws SPException @@ -420,7 +424,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa $publicLinkData->getData(), $publicLinkData->getDateExpire(), $publicLinkData->getMaxCountViews(), - $publicLinkData->getId() + $publicLinkData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while renewing link')); @@ -430,7 +434,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws QueryException @@ -513,7 +517,7 @@ final class PublicLinkRepository extends Repository implements RepositoryInterfa /** * Devolver el hash asociado a un elemento * - * @param int $itemId + * @param int $itemId * * @return QueryResult * @throws ConstraintException diff --git a/lib/SP/Repositories/AuthToken/AuthTokenRepository.php b/lib/SP/Infrastructure/Auth/Repositories/AuthTokenRepository.php similarity index 89% rename from lib/SP/Repositories/AuthToken/AuthTokenRepository.php rename to lib/SP/Infrastructure/Auth/Repositories/AuthTokenRepository.php index c33f25e0..d6f4876f 100644 --- a/lib/SP/Repositories/AuthToken/AuthTokenRepository.php +++ b/lib/SP/Infrastructure/Auth/Repositories/AuthTokenRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,24 +22,24 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\AuthToken; +namespace SP\Infrastructure\Auth\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\AuthTokenData; use SP\DataModel\ItemSearchData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class AuthTokenRepository * - * @package SP\Repositories\ApiToken + * @package SP\Infrastructure\Common\Repositories\ApiToken */ final class AuthTokenRepository extends Repository implements RepositoryInterface { @@ -48,7 +48,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -67,7 +67,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -127,7 +127,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return void */ @@ -139,7 +139,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -152,7 +152,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM AuthToken WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM AuthToken WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Internal error')); @@ -174,7 +174,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -183,18 +183,22 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac public function search(ItemSearchData $itemSearchData): QueryResult { $queryData = new QueryData(); - $queryData->setSelect('AuthToken.id, + $queryData->setSelect( + 'AuthToken.id, AuthToken.userId, AuthToken.actionId, AuthToken.token, - CONCAT(User.name, \' (\', User.login, \')\') AS userLogin'); - $queryData->setFrom('AuthToken - INNER JOIN User ON AuthToken.userid = User.id'); + CONCAT(User.name, \' (\', User.login, \')\') AS userLogin' + ); + $queryData->setFrom( + 'AuthToken + INNER JOIN User ON AuthToken.userid = User.id' + ); if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('User.login LIKE ? OR User.name LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); } @@ -211,7 +215,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Creates an item * - * @param AuthTokenData $itemData + * @param AuthTokenData $itemData * * @return int * @throws DuplicatedItemException @@ -242,7 +246,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac $itemData->getCreatedBy(), $itemData->getToken(), $itemData->getVault(), - $itemData->getHash() + $itemData->getHash(), ]); $queryData->setOnErrorMessage(__u('Internal error')); @@ -252,7 +256,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Checks whether the item is duplicated on adding * - * @param AuthTokenData $itemData + * @param AuthTokenData $itemData * * @return bool * @throws ConstraintException @@ -270,7 +274,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac $queryData->setParams([ $itemData->getUserId(), $itemData->getToken(), - $itemData->getActionId() + $itemData->getActionId(), ]); return $this->db->doSelect($queryData)->getNumRows() === 1; @@ -279,7 +283,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Obtener el token de la API de un usuario * - * @param int $id + * @param int $id * * @return string * @throws \SP\Core\Exceptions\ConstraintException @@ -299,7 +303,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Updates an item * - * @param AuthTokenData $itemData + * @param AuthTokenData $itemData * * @return int * @throws DuplicatedItemException @@ -332,7 +336,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac $itemData->getToken(), $itemData->getVault(), $itemData->getHash(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Internal error')); @@ -342,7 +346,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Checks whether the item is duplicated on updating * - * @param AuthTokenData $itemData + * @param AuthTokenData $itemData * * @return bool * @throws ConstraintException @@ -362,7 +366,7 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac $itemData->getUserId(), $itemData->getToken(), $itemData->getActionId(), - $itemData->getId() + $itemData->getId(), ]); return $this->db->doSelect($queryData)->getNumRows() === 1; @@ -371,8 +375,8 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Regenerar el hash de los tokens de un usuario * - * @param int $id - * @param string $token + * @param int $id + * @param string $token * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -397,9 +401,9 @@ final class AuthTokenRepository extends Repository implements RepositoryInterfac /** * Regenerar el hash de los tokens de un usuario * - * @param int $id - * @param string $vault - * @param string $hash + * @param int $id + * @param string $vault + * @param string $hash * * @return int * @throws \SP\Core\Exceptions\ConstraintException diff --git a/lib/SP/Repositories/Category/CategoryRepository.php b/lib/SP/Infrastructure/Category/Repositories/CategoryRepository.php similarity index 87% rename from lib/SP/Repositories/Category/CategoryRepository.php rename to lib/SP/Infrastructure/Category/Repositories/CategoryRepository.php index 7db4b50d..c28eb566 100644 --- a/lib/SP/Repositories/Category/CategoryRepository.php +++ b/lib/SP/Infrastructure/Category/Repositories/CategoryRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Category; +namespace SP\Infrastructure\Category\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -30,26 +30,26 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ItemSearchData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Category\In\CategoryRepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class CategoryRepository * - * @package SP\Repositories\Category + * @package SP\Infrastructure\Common\Repositories\Category */ -final class CategoryRepository extends Repository implements RepositoryInterface +final class CategoryRepository extends Repository implements CategoryRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param CategoryData $itemData + * @param CategoryData $itemData * * @return int * @throws SPException @@ -66,7 +66,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface $queryData->setParams([ $itemData->getName(), $itemData->getDescription(), - $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()) + $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), ]); $queryData->setOnErrorMessage(__u('Error while creating the category')); @@ -76,7 +76,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on adding * - * @param CategoryData $itemData + * @param CategoryData $itemData * * @return bool * @throws ConstraintException @@ -88,7 +88,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface $queryData->setQuery('SELECT id FROM Category WHERE `hash` = ? OR `name` = ?'); $queryData->setParams([ $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), - $itemData->getName() + $itemData->getName(), ]); return $this->db->doQuery($queryData)->getNumRows() > 0; @@ -97,7 +97,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Updates an item * - * @param CategoryData $itemData + * @param CategoryData $itemData * * @return int * @throws DuplicatedItemException @@ -123,7 +123,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface $itemData->getName(), $itemData->getDescription(), $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the category')); @@ -133,7 +133,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on updating * - * @param CategoryData $itemData + * @param CategoryData $itemData * * @return bool * @throws ConstraintException @@ -146,7 +146,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface $queryData->setParams([ $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), $itemData->getName(), - $itemData->getId() + $itemData->getId(), ]); return $this->db->doQuery($queryData)->getNumRows() > 0; @@ -155,7 +155,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -174,7 +174,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param string $name + * @param string $name * * @return QueryResult * @throws ConstraintException @@ -187,7 +187,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface $queryData->setQuery('SELECT id, `name`, description FROM Category WHERE `name` = ? OR `hash` = ? LIMIT 1'); $queryData->setParams([ $name, - $this->makeItemHash($name, $this->db->getDbHandler()) + $this->makeItemHash($name, $this->db->getDbHandler()), ]); return $this->db->doSelect($queryData); @@ -212,7 +212,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult * @throws ConstraintException @@ -225,7 +225,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface } $query = /** @lang SQL */ - 'SELECT id, `name`, description FROM Category WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + 'SELECT id, `name`, description FROM Category WHERE id IN ('.$this->getParamsFromArray($ids).')'; $queryData = new QueryData(); $queryData->setMapClassName(CategoryData::class); @@ -238,7 +238,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -251,7 +251,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM Category WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM Category WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the categories')); @@ -261,7 +261,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws ConstraintException @@ -295,7 +295,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -311,7 +311,7 @@ final class CategoryRepository extends Repository implements RepositoryInterface if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('name LIKE ? OR description LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); } diff --git a/lib/SP/Repositories/Client/ClientRepository.php b/lib/SP/Infrastructure/Client/Repositories/ClientRepository.php similarity index 86% rename from lib/SP/Repositories/Client/ClientRepository.php rename to lib/SP/Infrastructure/Client/Repositories/ClientRepository.php index b47506fb..75fe2bb5 100644 --- a/lib/SP/Repositories/Client/ClientRepository.php +++ b/lib/SP/Infrastructure/Client/Repositories/ClientRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Client; +namespace SP\Infrastructure\Client\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -31,27 +31,27 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ClientData; use SP\DataModel\ItemData; use SP\DataModel\ItemSearchData; +use SP\Domain\Client\In\ClientRepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; use SP\Mvc\Model\QueryCondition; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; /** * Class ClientRepository * - * @package SP\Repositories\Client + * @package SP\Infrastructure\Common\Repositories\Client */ -final class ClientRepository extends Repository implements RepositoryInterface +final class ClientRepository extends Repository implements ClientRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param ClientData $itemData + * @param ClientData $itemData * * @return int * @throws DuplicatedItemException @@ -76,7 +76,7 @@ final class ClientRepository extends Repository implements RepositoryInterface $itemData->getName(), $itemData->getDescription(), $itemData->getIsGlobal(), - $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()) + $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), ]); $queryData->setOnErrorMessage(__u('Error while creating the client')); @@ -86,7 +86,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on adding * - * @param ClientData $itemData + * @param ClientData $itemData * * @return bool * @throws ConstraintException @@ -104,7 +104,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Updates an item * - * @param ClientData $itemData + * @param ClientData $itemData * * @return int * @throws ConstraintException @@ -132,7 +132,7 @@ final class ClientRepository extends Repository implements RepositoryInterface $itemData->getDescription(), $itemData->getIsGlobal(), $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the client')); @@ -142,7 +142,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on updating * - * @param ClientData $itemData + * @param ClientData $itemData * * @return bool * @throws ConstraintException @@ -155,7 +155,7 @@ final class ClientRepository extends Repository implements RepositoryInterface $queryData->setParams([ $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), $itemData->getName(), - $itemData->getId() + $itemData->getId(), ]); return $this->db->doQuery($queryData)->getNumRows() > 0; @@ -164,7 +164,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws QueryException @@ -183,7 +183,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Returns the item for given name * - * @param string $name + * @param string $name * * @return QueryResult * @throws QueryException @@ -193,10 +193,12 @@ final class ClientRepository extends Repository implements RepositoryInterface { $queryData = new QueryData(); $queryData->setMapClassName(ClientData::class); - $queryData->setQuery('SELECT id, `name`, description, isGlobal FROM Client WHERE `name` = ? OR `hash` = ? LIMIT 1'); + $queryData->setQuery( + 'SELECT id, `name`, description, isGlobal FROM Client WHERE `name` = ? OR `hash` = ? LIMIT 1' + ); $queryData->setParams([ $name, - $this->makeItemHash($name, $this->db->getDbHandler()) + $this->makeItemHash($name, $this->db->getDbHandler()), ]); return $this->db->doSelect($queryData); @@ -221,7 +223,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult * @throws QueryException @@ -234,7 +236,7 @@ final class ClientRepository extends Repository implements RepositoryInterface } $query = /** @lang SQL */ - 'SELECT id, `name`, description, isGlobal FROM Client WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + 'SELECT id, `name`, description, isGlobal FROM Client WHERE id IN ('.$this->getParamsFromArray($ids).')'; $queryData = new QueryData(); $queryData->setMapClassName(ClientData::class); @@ -247,7 +249,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -260,7 +262,7 @@ final class ClientRepository extends Repository implements RepositoryInterface } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM Client WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM Client WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the clients')); @@ -270,7 +272,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -301,7 +303,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws QueryException @@ -318,7 +320,7 @@ final class ClientRepository extends Repository implements RepositoryInterface if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('name LIKE ? OR description LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); } @@ -334,7 +336,7 @@ final class ClientRepository extends Repository implements RepositoryInterface /** * Devolver los clientes visibles por el usuario * - * @param QueryCondition $queryFilter + * @param QueryCondition $queryFilter * * @return QueryResult * @throws QueryException @@ -352,7 +354,7 @@ final class ClientRepository extends Repository implements RepositoryInterface RIGHT JOIN Client ON Account.clientId = Client.id WHERE Account.clientId IS NULL OR Client.isGlobal = 1 - OR ' . $queryFilter->getFilters() . ' + OR '.$queryFilter->getFilters().' GROUP BY id ORDER BY Client.name'; diff --git a/lib/SP/Repositories/DuplicatedItemException.php b/lib/SP/Infrastructure/Common/Repositories/DuplicatedItemException.php similarity index 84% rename from lib/SP/Repositories/DuplicatedItemException.php rename to lib/SP/Infrastructure/Common/Repositories/DuplicatedItemException.php index 94e195d5..9fc47f9e 100644 --- a/lib/SP/Repositories/DuplicatedItemException.php +++ b/lib/SP/Infrastructure/Common/Repositories/DuplicatedItemException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories; +namespace SP\Infrastructure\Common\Repositories; use SP\Core\Exceptions\SPException; /** * Class DuplicatedItemException * - * @package SP\Repositories + * @package SP\Infrastructure\Common\Repositories */ final class DuplicatedItemException extends SPException { diff --git a/lib/SP/Repositories/NoSuchItemException.php b/lib/SP/Infrastructure/Common/Repositories/NoSuchItemException.php similarity index 84% rename from lib/SP/Repositories/NoSuchItemException.php rename to lib/SP/Infrastructure/Common/Repositories/NoSuchItemException.php index b35993e9..010a3de6 100644 --- a/lib/SP/Repositories/NoSuchItemException.php +++ b/lib/SP/Infrastructure/Common/Repositories/NoSuchItemException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories; +namespace SP\Infrastructure\Common\Repositories; use SP\Core\Exceptions\SPException; @@ -30,7 +30,7 @@ use SP\Core\Exceptions\SPException; /** * Class NoSuchItemException * - * @package SP\Repositories + * @package SP\Infrastructure\Common\Repositories */ final class NoSuchItemException extends SPException { diff --git a/lib/SP/Repositories/Repository.php b/lib/SP/Infrastructure/Common/Repositories/Repository.php similarity index 72% rename from lib/SP/Repositories/Repository.php rename to lib/SP/Infrastructure/Common/Repositories/Repository.php index 7aa2bac5..21a769cc 100644 --- a/lib/SP/Repositories/Repository.php +++ b/lib/SP/Infrastructure/Common/Repositories/Repository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,22 +22,22 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories; +namespace SP\Infrastructure\Common\Repositories; use SP\Core\Context\ContextInterface; -use SP\Storage\Database\Database; +use SP\Infrastructure\Database\DatabaseInterface; /** * Class Repository * - * @package SP\Repositories + * @package SP\Infrastructure\Common\Repositories */ abstract class Repository { - protected ContextInterface $context; - protected Database $db; + protected ContextInterface $context; + protected DatabaseInterface $db; - final public function __construct(Database $database, ContextInterface $session) + final public function __construct(DatabaseInterface $database, ContextInterface $session) { $this->db = $database; $this->context = $session; diff --git a/lib/SP/Repositories/RepositoryItemTrait.php b/lib/SP/Infrastructure/Common/Repositories/RepositoryItemTrait.php similarity index 83% rename from lib/SP/Repositories/RepositoryItemTrait.php rename to lib/SP/Infrastructure/Common/Repositories/RepositoryItemTrait.php index 8b8ecab9..ad26a25a 100644 --- a/lib/SP/Repositories/RepositoryItemTrait.php +++ b/lib/SP/Infrastructure/Common/Repositories/RepositoryItemTrait.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,25 +22,26 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories; +namespace SP\Infrastructure\Common\Repositories; use Exception; use RuntimeException; use SP\DataModel\DataModelInterface; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\Database\DBStorageInterface; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\Database\DBStorageInterface; /** * Trait RepositoryItemTrait * - * @package SP\Repositories + * @package SP\Infrastructure\Common\Repositories */ trait RepositoryItemTrait { /** * Eliminar elementos en lotes * - * @param int[] $ids + * @param int[] $ids * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException @@ -77,10 +78,9 @@ trait RepositoryItemTrait * la eliminación de carácteres especiales y capitalización */ protected function makeItemHash( - string $name, + string $name, DBStorageInterface $DBStorage - ): string - { + ): string { $charsSrc = ['.', ' ', '_', ', ', '-', ';', '\'', '"', ':', '(', ')', '|', '/']; $databaseUtil = new DatabaseUtil($DBStorage); @@ -95,16 +95,15 @@ trait RepositoryItemTrait /** * Devuelve una cadena con los parámetros para una consulta SQL desde un array * - * @param array $items - * @param string $placeholder Cadena a utilizar para los parámetros + * @param array $items + * @param string $placeholder Cadena a utilizar para los parámetros * * @return string */ protected function getParamsFromArray( - array $items, + array $items, string $placeholder = '?' - ): string - { + ): string { return implode( ',', array_fill(0, count($items), $placeholder) diff --git a/lib/SP/Repositories/Config/ConfigRepository.php b/lib/SP/Infrastructure/Config/Repositories/ConfigRepository.php similarity index 84% rename from lib/SP/Repositories/Config/ConfigRepository.php rename to lib/SP/Infrastructure/Config/Repositories/ConfigRepository.php index 9d109167..caab293e 100644 --- a/lib/SP/Repositories/Config/ConfigRepository.php +++ b/lib/SP/Infrastructure/Config/Repositories/ConfigRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,24 +22,25 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Config; +namespace SP\Infrastructure\Config\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ConfigData; -use SP\Repositories\Repository; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Config\In\ConfigRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class ConfigRepository * - * @package SP\Repositories\Config + * @package SP\Infrastructure\Common\Repositories\Config */ -final class ConfigRepository extends Repository +final class ConfigRepository extends Repository implements ConfigRepositoryInterface { /** - * @param ConfigData $configData + * @param ConfigData $configData * * @return bool * @throws ConstraintException @@ -55,7 +56,7 @@ final class ConfigRepository extends Repository } /** - * @param ConfigData $configData + * @param ConfigData $configData * * @return int * @throws ConstraintException @@ -86,7 +87,7 @@ final class ConfigRepository extends Repository } /** - * @param string $param + * @param string $param * * @return QueryResult * @throws ConstraintException @@ -102,7 +103,7 @@ final class ConfigRepository extends Repository } /** - * @param string $param + * @param string $param * * @return bool * @throws ConstraintException @@ -118,7 +119,7 @@ final class ConfigRepository extends Repository } /** - * @param string $param + * @param string $param * * @return int * @throws \SP\Core\Exceptions\ConstraintException diff --git a/lib/SP/Repositories/CustomField/CustomFieldDefCollection.php b/lib/SP/Infrastructure/CustomField/Repositories/CustomFieldDefCollection.php similarity index 83% rename from lib/SP/Repositories/CustomField/CustomFieldDefCollection.php rename to lib/SP/Infrastructure/CustomField/Repositories/CustomFieldDefCollection.php index d65b8849..11793718 100644 --- a/lib/SP/Repositories/CustomField/CustomFieldDefCollection.php +++ b/lib/SP/Infrastructure/CustomField/Repositories/CustomFieldDefCollection.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\CustomField; +namespace SP\Infrastructure\CustomField\Repositories; use SP\Core\DataCollection; /** * Class CustomFieldDefCollection * - * @package SP\Repositories\CustomField + * @package SP\Infrastructure\CustomField\Repositories */ final class CustomFieldDefCollection extends DataCollection { diff --git a/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php b/lib/SP/Infrastructure/CustomField/Repositories/CustomFieldDefRepository.php similarity index 86% rename from lib/SP/Repositories/CustomField/CustomFieldDefRepository.php rename to lib/SP/Infrastructure/CustomField/Repositories/CustomFieldDefRepository.php index 2507397a..e869e998 100644 --- a/lib/SP/Repositories/CustomField/CustomFieldDefRepository.php +++ b/lib/SP/Infrastructure/CustomField/Repositories/CustomFieldDefRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\CustomField; +namespace SP\Infrastructure\CustomField\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -30,31 +30,28 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldDefinitionData; use SP\DataModel\ItemSearchData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\CustomField\In\CustomFieldDefRepositoryInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class CustomFieldDefRepository * - * @package SP\Repositories\CustomField + * @package SP\Infrastructure\CustomField\Repositories */ -final class CustomFieldDefRepository extends Repository implements RepositoryInterface +final class CustomFieldDefRepository extends Repository implements CustomFieldDefRepositoryInterface { use RepositoryItemTrait; - /** - * @var CustomFieldDefCollection - */ private CustomFieldDefCollection $customFieldDefCollection; /** * Creates an item * - * @param CustomFieldDefinitionData $itemData + * @param CustomFieldDefinitionData $itemData * * @return int * @throws ConstraintException @@ -74,7 +71,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt $itemData->getHelp(), $itemData->getShowInList(), $itemData->getTypeId(), - $itemData->getisEncrypted() + $itemData->getisEncrypted(), ]); $queryData->setOnErrorMessage(__u('Error while creating the custom field')); @@ -84,7 +81,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt /** * Updates an item * - * @param CustomFieldDefinitionData $itemData + * @param CustomFieldDefinitionData $itemData * * @return int * @throws ConstraintException @@ -117,7 +114,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt $itemData->getShowInList(), $itemData->getTypeId(), $itemData->getisEncrypted(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the custom field')); @@ -127,7 +124,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return CustomFieldDefinitionData * @throws ConstraintException @@ -192,7 +189,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult * @throws ConstraintException @@ -207,7 +204,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt $query = /** @lang SQL */ 'SELECT id, `name`, moduleId, required, `help`, showInList, typeId, isEncrypted FROM CustomFieldDefinition - WHERE id IN (' . $this->getParamsFromArray($ids) . ') + WHERE id IN ('.$this->getParamsFromArray($ids).') ORDER BY id'; $queryData = new QueryData(); @@ -221,7 +218,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws SPException @@ -235,7 +232,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt } $query = /** @lang SQL */ - 'DELETE FROM CustomFieldDefinition WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + 'DELETE FROM CustomFieldDefinition WHERE id IN ('.$this->getParamsFromArray($ids).')'; $queryData = new QueryData(); $queryData->setQuery($query); @@ -248,7 +245,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -277,7 +274,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnUpdate($itemData): bool { @@ -287,7 +284,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnAdd($itemData): bool { @@ -297,7 +294,7 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -307,14 +304,16 @@ final class CustomFieldDefRepository extends Repository implements RepositoryInt { $queryData = new QueryData(); $queryData->setMapClassName(CustomFieldDefinitionData::class); - $queryData->setSelect('CFD.id, CFD.name, CFD.moduleId, CFD.required, CFD.help, CFD.showInList, CFD.typeId, CFD.isEncrypted, CFT.name AS typeName'); + $queryData->setSelect( + 'CFD.id, CFD.name, CFD.moduleId, CFD.required, CFD.help, CFD.showInList, CFD.typeId, CFD.isEncrypted, CFT.name AS typeName' + ); $queryData->setFrom('CustomFieldDefinition CFD INNER JOIN CustomFieldType CFT ON CFD.typeId = CFT.id'); $queryData->setOrder('CFD.moduleId'); if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('CFD.name LIKE ? OR CFT.name LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParams([$search, $search]); } diff --git a/lib/SP/Repositories/CustomField/CustomFieldRepository.php b/lib/SP/Infrastructure/CustomField/Repositories/CustomFieldRepository.php similarity index 86% rename from lib/SP/Repositories/CustomField/CustomFieldRepository.php rename to lib/SP/Infrastructure/CustomField/Repositories/CustomFieldRepository.php index a43f3e75..9865c2e3 100644 --- a/lib/SP/Repositories/CustomField/CustomFieldRepository.php +++ b/lib/SP/Infrastructure/CustomField/Repositories/CustomFieldRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,32 +22,32 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\CustomField; +namespace SP\Infrastructure\CustomField\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\CustomFieldData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\CustomField\In\CustomFieldRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class CustomFieldRepository * - * @package SP\Services + * @package SP\Domain\Common\Services */ -final class CustomFieldRepository extends Repository implements RepositoryInterface +final class CustomFieldRepository extends Repository implements CustomFieldRepositoryInterface { use RepositoryItemTrait; /** * Updates an item * - * @param CustomFieldData $itemData + * @param CustomFieldData $itemData * * @return int * @throws QueryException @@ -70,7 +70,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf $itemData->getKey(), $itemData->getModuleId(), $itemData->getItemId(), - $itemData->getDefinitionId() + $itemData->getDefinitionId(), ]); return $this->db->doQuery($queryData)->getAffectedNumRows(); @@ -79,7 +79,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Comprueba si el elemento tiene campos personalizados con datos * - * @param CustomFieldData $itemData + * @param CustomFieldData $itemData * * @return bool * @throws QueryException @@ -99,7 +99,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf $queryData->setParams([ $itemData->getModuleId(), $itemData->getItemId(), - $itemData->getDefinitionId() + $itemData->getDefinitionId(), ]); return $this->db->doSelect($queryData)->getNumRows() >= 1; @@ -120,7 +120,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Creates an item * - * @param CustomFieldData $itemData + * @param CustomFieldData $itemData * * @return int * @throws QueryException @@ -138,7 +138,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf $itemData->getModuleId(), $itemData->getDefinitionId(), $itemData->getData(), - $itemData->getKey() + $itemData->getKey(), ]); return $this->db->doQuery($queryData)->getLastId(); @@ -147,8 +147,8 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Eliminar los datos de los campos personalizados del módulo * - * @param int $itemId - * @param int $moduleId + * @param int $itemId + * @param int $moduleId * * @return int * @throws QueryException @@ -171,20 +171,19 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Eliminar los datos de los campos personalizados del módulo * - * @param int $id - * @param int $moduleId - * @param int|null $definitionId + * @param int $id + * @param int $moduleId + * @param int|null $definitionId * * @return int * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ public function deleteCustomFieldDataForDefinition( - int $id, - int $moduleId, + int $id, + int $moduleId, ?int $definitionId - ): int - { + ): int { $query = /** @lang SQL */ 'DELETE FROM CustomFieldData WHERE itemId = ? @@ -201,7 +200,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Eliminar los datos de los campos personalizados del módulo * - * @param int $definitionId + * @param int $definitionId * * @return int * @throws QueryException @@ -219,7 +218,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Eliminar los datos de los elementos de una definición * - * @param array $definitionIds + * @param array $definitionIds * * @return int * @throws ConstraintException @@ -232,7 +231,9 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM CustomFieldData WHERE definitionId IN (' . $this->getParamsFromArray($definitionIds) . ')'); + $queryData->setQuery( + 'DELETE FROM CustomFieldData WHERE definitionId IN ('.$this->getParamsFromArray($definitionIds).')' + ); $queryData->setParams($definitionIds); return $this->db->doQuery($queryData)->getAffectedNumRows(); @@ -241,8 +242,8 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Eliminar los datos de los campos personalizados del módulo * - * @param int[] $ids - * @param int $moduleId + * @param int[] $ids + * @param int $moduleId * * @return int * @throws QueryException @@ -256,7 +257,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf $query = /** @lang SQL */ 'DELETE FROM CustomFieldData - WHERE itemId IN (' . $this->getParamsFromArray($ids) . ') + WHERE itemId IN ('.$this->getParamsFromArray($ids).') AND moduleId = ?'; $queryData = new QueryData(); @@ -270,7 +271,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return void */ @@ -314,7 +315,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return void */ @@ -326,7 +327,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return void */ @@ -350,7 +351,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return void */ @@ -362,8 +363,8 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Returns the module's item for given id * - * @param int $moduleId - * @param int|null $itemId + * @param int $moduleId + * @param int|null $itemId * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -400,7 +401,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -412,7 +413,7 @@ final class CustomFieldRepository extends Repository implements RepositoryInterf /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ diff --git a/lib/SP/Repositories/CustomField/CustomFieldTypeRepository.php b/lib/SP/Infrastructure/CustomField/Repositories/CustomFieldTypeRepository.php similarity index 86% rename from lib/SP/Repositories/CustomField/CustomFieldTypeRepository.php rename to lib/SP/Infrastructure/CustomField/Repositories/CustomFieldTypeRepository.php index cb33006b..40f4e642 100644 --- a/lib/SP/Repositories/CustomField/CustomFieldTypeRepository.php +++ b/lib/SP/Infrastructure/CustomField/Repositories/CustomFieldTypeRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\CustomField; +namespace SP\Infrastructure\CustomField\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -30,25 +30,25 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldTypeData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\CustomField\In\CustomFieldTypeRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class CustomFieldTypeRepository * - * @package SP\Repositories\CustomField + * @package SP\Infrastructure\CustomField\Repositories */ -final class CustomFieldTypeRepository extends Repository implements RepositoryInterface +final class CustomFieldTypeRepository extends Repository implements CustomFieldTypeRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param CustomFieldTypeData $itemData + * @param CustomFieldTypeData $itemData * * @return int * @throws SPException @@ -68,7 +68,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -80,7 +80,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn /** * Updates an item * - * @param CustomFieldTypeData $itemData + * @param CustomFieldTypeData $itemData * * @return int * @throws SPException @@ -94,7 +94,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn $queryData->setParams([ $itemData->getName(), $itemData->getText(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the field type')); @@ -104,7 +104,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -116,7 +116,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -151,7 +151,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return void */ @@ -163,7 +163,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -176,7 +176,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM CustomFieldType WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM CustomFieldType WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the field type')); @@ -217,7 +217,7 @@ final class CustomFieldTypeRepository extends Repository implements RepositoryIn /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return void */ diff --git a/lib/SP/Storage/Database/DBStorageInterface.php b/lib/SP/Infrastructure/Database/DBStorageInterface.php similarity index 93% rename from lib/SP/Storage/Database/DBStorageInterface.php rename to lib/SP/Infrastructure/Database/DBStorageInterface.php index b05c64af..bcc87f84 100644 --- a/lib/SP/Storage/Database/DBStorageInterface.php +++ b/lib/SP/Infrastructure/Database/DBStorageInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; use PDO; diff --git a/lib/SP/Storage/Database/Database.php b/lib/SP/Infrastructure/Database/Database.php similarity index 80% rename from lib/SP/Storage/Database/Database.php rename to lib/SP/Infrastructure/Database/Database.php index 0a3e38cc..0062825a 100644 --- a/lib/SP/Storage/Database/Database.php +++ b/lib/SP/Infrastructure/Database/Database.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; use Exception; use PDO; @@ -41,24 +41,23 @@ use SP\Core\Exceptions\SPException; */ final class Database implements DatabaseInterface { - protected int $numRows = 0; - protected int $numFields = 0; - protected ?array $lastResult = null; + protected int $numRows = 0; + protected int $numFields = 0; + protected ?array $lastResult = null; protected DBStorageInterface $dbHandler; - private ?int $lastId = null; - private EventDispatcher $eventDispatcher; + private ?int $lastId = null; + private EventDispatcher $eventDispatcher; /** * DB constructor. * - * @param DBStorageInterface $dbHandler - * @param EventDispatcher $eventDispatcher + * @param DBStorageInterface $dbHandler + * @param EventDispatcher $eventDispatcher */ public function __construct( DBStorageInterface $dbHandler, - EventDispatcher $eventDispatcher - ) - { + EventDispatcher $eventDispatcher + ) { $this->dbHandler = $dbHandler; $this->eventDispatcher = $eventDispatcher; } @@ -94,9 +93,8 @@ final class Database implements DatabaseInterface */ public function doSelect( QueryData $queryData, - bool $fullCount = false - ): QueryResult - { + bool $fullCount = false + ): QueryResult { if ($queryData->getQuery() === '') { throw new QueryException( $queryData->getOnErrorMessage(), @@ -113,7 +111,7 @@ final class Database implements DatabaseInterface } return $queryResult; - } catch (ConstraintException | QueryException $e) { + } catch (ConstraintException|QueryException $e) { processException($e); throw $e; @@ -142,8 +140,10 @@ final class Database implements DatabaseInterface $this->eventDispatcher->notifyEvent( 'database.query', - new Event($this, EventMessage::factory() - ->addDescription($queryData->getQuery()) + new Event( + $this, + EventMessage::factory() + ->addDescription($queryData->getQuery()) ) ); @@ -153,17 +153,15 @@ final class Database implements DatabaseInterface return new QueryResult($this->fetch($queryData, $stmt)); } - return (new QueryResult()) - ->setAffectedNumRows($stmt->rowCount()) - ->setLastId($this->lastId); + return (new QueryResult())->setAffectedNumRows($stmt->rowCount())->setLastId($this->lastId); } /** * Asociar los parámetros de la consulta utilizando el tipo adecuado * - * @param QueryData $queryData Los datos de la consulta - * @param bool $isCount Indica si es una consulta de contador de registros - * @param array $options + * @param QueryData $queryData Los datos de la consulta + * @param bool $isCount Indica si es una consulta de contador de registros + * @param array $options * * @return \PDOStatement * @throws \SP\Core\Exceptions\ConstraintException @@ -171,10 +169,9 @@ final class Database implements DatabaseInterface */ private function prepareQueryData( QueryData $queryData, - bool $isCount = false, - array $options = [] - ): PDOStatement - { + bool $isCount = false, + array $options = [] + ): PDOStatement { $query = $queryData->getQuery(); $params = $queryData->getParams(); @@ -192,7 +189,7 @@ final class Database implements DatabaseInterface foreach ($params as $param => $value) { // Si la clave es un número utilizamos marcadores de posición "?" en // la consulta. En caso contrario marcadores de nombre - $param = is_int($param) ? $param + 1 : ':' . $param; + $param = is_int($param) ? $param + 1 : ':'.$param; if ($param === 'blobcontent') { $stmt->bindValue($param, $value, PDO::PARAM_LOB); @@ -243,11 +240,7 @@ final class Database implements DatabaseInterface $countFrom = substr_count($queryData->getFrom(), '?'); $countWhere = substr_count($queryData->getWhere(), '?'); - return array_slice( - $queryData->getParams(), - $countSelect, - $countFrom + $countWhere - ); + return array_slice($queryData->getParams(), $countSelect, $countFrom + $countWhere); } private function fetch(QueryData $queryData, PDOStatement $stmt): array @@ -257,10 +250,7 @@ final class Database implements DatabaseInterface } if ($queryData->getMapClassName()) { - return $stmt->fetchAll( - PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, - $queryData->getMapClassName() - ); + return $stmt->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, $queryData->getMapClassName()); } return $stmt->fetchAll(); @@ -288,9 +278,9 @@ final class Database implements DatabaseInterface /** * Don't fetch records and return prepared statement * - * @param QueryData $queryData - * @param array $options - * @param bool|null $buffered Set buffered behavior (useful for big datasets) + * @param QueryData $queryData + * @param array $options + * @param bool|null $buffered Set buffered behavior (useful for big datasets) * * @return PDOStatement * @throws ConstraintException @@ -298,13 +288,10 @@ final class Database implements DatabaseInterface */ public function doQueryRaw( QueryData $queryData, - array $options = [], - ?bool $buffered = null - ): PDOStatement - { - if ($buffered === false - && $this->dbHandler instanceof MySQLHandler - ) { + array $options = [], + ?bool $buffered = null + ): PDOStatement { + if ($buffered === false && $this->dbHandler instanceof MySQLHandler) { $this->dbHandler ->getConnection() ->setAttribute( @@ -330,8 +317,7 @@ final class Database implements DatabaseInterface 'database.transaction.begin', new Event( $this, - EventMessage::factory() - ->addExtra('result', $result) + EventMessage::factory()->addExtra('result', $result) ) ); @@ -356,8 +342,7 @@ final class Database implements DatabaseInterface 'database.transaction.end', new Event( $this, - EventMessage::factory() - ->addExtra('result', $result) + EventMessage::factory()->addExtra('result', $result) ) ); @@ -377,8 +362,7 @@ final class Database implements DatabaseInterface 'database.transaction.rollback', new Event( $this, - EventMessage::factory() - ->addExtra('result', $result) + EventMessage::factory()->addExtra('result', $result) ) ); @@ -387,8 +371,7 @@ final class Database implements DatabaseInterface public function getColumnsForTable(string $table): array { - $conn = $this->dbHandler->getConnection() - ->query("SELECT * FROM `$table` LIMIT 0"); + $conn = $this->dbHandler->getConnection()->query("SELECT * FROM `$table` LIMIT 0"); $columns = []; for ($i = 0; $i < $conn->columnCount(); $i++) { diff --git a/lib/SP/Storage/Database/DatabaseConnectionData.php b/lib/SP/Infrastructure/Database/DatabaseConnectionData.php similarity index 75% rename from lib/SP/Storage/Database/DatabaseConnectionData.php rename to lib/SP/Infrastructure/Database/DatabaseConnectionData.php index 3ecb4995..7e4aae72 100644 --- a/lib/SP/Storage/Database/DatabaseConnectionData.php +++ b/lib/SP/Infrastructure/Database/DatabaseConnectionData.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,27 +22,25 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; -use SP\Config\ConfigDataInterface; +use SP\Domain\Config\In\ConfigDataInterface; /** * Class DatabaseConnectionData * - * @package SP\Storage\Database + * @package SP\Infrastructure\Database */ final class DatabaseConnectionData { - private ?string $dbHost = null; + private ?string $dbHost = null; private ?string $dbSocket = null; - private ?int $dbPort = null; - private ?string $dbName = null; - private ?string $dbUser = null; - private ?string $dbPass = null; + private ?int $dbPort = null; + private ?string $dbName = null; + private ?string $dbUser = null; + private ?string $dbPass = null; - public static function getFromConfig( - ConfigDataInterface $configData - ): DatabaseConnectionData + public static function getFromConfig(ConfigDataInterface $configData): DatabaseConnectionData { return (new self()) ->setDbHost($configData->getDbHost()) @@ -53,31 +51,6 @@ final class DatabaseConnectionData ->setDbSocket($configData->getDbSocket()); } - public static function getFromEnvironment(): DatabaseConnectionData - { - return (new self()) - ->setDbHost(getenv('DB_SERVER')) - ->setDbName(getenv('DB_NAME')) - ->setDbUser(getenv('DB_USER')) - ->setDbPass(getenv('DB_PASS')) - ->setDbPort((int)getenv('DB_PORT')) - ->setDbSocket(getenv('DB_SOCKET')); - } - - public function refreshFromConfig( - ConfigDataInterface $configData - ): DatabaseConnectionData - { - logger('Refresh DB connection data'); - - return $this->setDbHost($configData->getDbHost()) - ->setDbName($configData->getDbName()) - ->setDbUser($configData->getDbUser()) - ->setDbPass($configData->getDbPass()) - ->setDbPort($configData->getDbPort()) - ->setDbSocket($configData->getDbSocket()); - } - public function getDbHost(): ?string { return $this->dbHost; @@ -86,28 +59,7 @@ final class DatabaseConnectionData public function setDbHost(string $dbHost): DatabaseConnectionData { $this->dbHost = $dbHost; - return $this; - } - public function getDbSocket(): ?string - { - return $this->dbSocket; - } - - public function setDbSocket(?string $dbSocket): DatabaseConnectionData - { - $this->dbSocket = $dbSocket; - return $this; - } - - public function getDbPort(): ?int - { - return $this->dbPort; - } - - public function setDbPort(int $dbPort): DatabaseConnectionData - { - $this->dbPort = $dbPort; return $this; } @@ -119,6 +71,7 @@ final class DatabaseConnectionData public function setDbName(string $dbName): DatabaseConnectionData { $this->dbName = $dbName; + return $this; } @@ -130,6 +83,7 @@ final class DatabaseConnectionData public function setDbUser(string $dbUser): DatabaseConnectionData { $this->dbUser = $dbUser; + return $this; } @@ -141,6 +95,42 @@ final class DatabaseConnectionData public function setDbPass(string $dbPass): DatabaseConnectionData { $this->dbPass = $dbPass; + return $this; } + + public function getDbPort(): ?int + { + return $this->dbPort; + } + + public function setDbPort(int $dbPort): DatabaseConnectionData + { + $this->dbPort = $dbPort; + + return $this; + } + + public function getDbSocket(): ?string + { + return $this->dbSocket; + } + + public function setDbSocket(?string $dbSocket): DatabaseConnectionData + { + $this->dbSocket = $dbSocket; + + return $this; + } + + public static function getFromEnvironment(): DatabaseConnectionData + { + return (new self()) + ->setDbHost(getenv('DB_SERVER')) + ->setDbName(getenv('DB_NAME')) + ->setDbUser(getenv('DB_USER')) + ->setDbPass(getenv('DB_PASS')) + ->setDbPort((int)getenv('DB_PORT')) + ->setDbSocket(getenv('DB_SOCKET')); + } } \ No newline at end of file diff --git a/lib/SP/Storage/Database/DatabaseException.php b/lib/SP/Infrastructure/Database/DatabaseException.php similarity index 86% rename from lib/SP/Storage/Database/DatabaseException.php rename to lib/SP/Infrastructure/Database/DatabaseException.php index 4d382b1b..1d2e059b 100644 --- a/lib/SP/Storage/Database/DatabaseException.php +++ b/lib/SP/Infrastructure/Database/DatabaseException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; use SP\Core\Exceptions\SPException; /** * Class DatabaseException * - * @package SP\Storage\Database + * @package SP\Infrastructure\Database */ final class DatabaseException extends SPException { diff --git a/lib/SP/Storage/Database/DatabaseFileInterface.php b/lib/SP/Infrastructure/Database/DatabaseFileInterface.php similarity index 96% rename from lib/SP/Storage/Database/DatabaseFileInterface.php rename to lib/SP/Infrastructure/Database/DatabaseFileInterface.php index 5653e6c0..fd6b2fc0 100644 --- a/lib/SP/Storage/Database/DatabaseFileInterface.php +++ b/lib/SP/Infrastructure/Database/DatabaseFileInterface.php @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; /** * Interface DatabaseFileInterface diff --git a/lib/SP/Storage/Database/DatabaseInterface.php b/lib/SP/Infrastructure/Database/DatabaseInterface.php similarity index 94% rename from lib/SP/Storage/Database/DatabaseInterface.php rename to lib/SP/Infrastructure/Database/DatabaseInterface.php index d7247eef..fa5d2f6b 100644 --- a/lib/SP/Storage/Database/DatabaseInterface.php +++ b/lib/SP/Infrastructure/Database/DatabaseInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; use PDOStatement; use SP\Core\Exceptions\ConstraintException; diff --git a/lib/SP/Storage/Database/DatabaseUtil.php b/lib/SP/Infrastructure/Database/DatabaseUtil.php similarity index 85% rename from lib/SP/Storage/Database/DatabaseUtil.php rename to lib/SP/Infrastructure/Database/DatabaseUtil.php index f02a659a..62062b89 100644 --- a/lib/SP/Storage/Database/DatabaseUtil.php +++ b/lib/SP/Infrastructure/Database/DatabaseUtil.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; use Exception; @@ -63,7 +63,7 @@ final class DatabaseUtil 'Track', 'Notification', 'account_data_v', - 'account_search_v' + 'account_search_v', ]; private DBStorageInterface $DBStorage; @@ -81,18 +81,25 @@ final class DatabaseUtil public function checkDatabaseTables(string $dbName): bool { try { - $tables = implode(',', array_map( - static function ($value) { - return '\'' . $value . '\''; - }, - self::TABLES - )); + $tables = implode( + ',', + array_map( + static function ($value) { + return '\''.$value.'\''; + }, + self::TABLES + ) + ); $query = /** @lang SQL */ - sprintf('SELECT COUNT(*) + sprintf( + 'SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = \'%s\' - AND `table_name` IN (%s)', $dbName, $tables); + AND `table_name` IN (%s)', + $dbName, + $tables + ); $numTables = $this->DBStorage ->getConnection() @@ -138,7 +145,7 @@ final class DatabaseUtil ]; foreach ($attributes as $val) { - $dbinfo[$val] = $db->getAttribute(constant('PDO::ATTR_' . $val)); + $dbinfo[$val] = $db->getAttribute(constant('PDO::ATTR_'.$val)); } } catch (Exception $e) { processException($e); diff --git a/lib/SP/Storage/Database/MySQLFileParser.php b/lib/SP/Infrastructure/Database/MySQLFileParser.php similarity index 84% rename from lib/SP/Storage/Database/MySQLFileParser.php rename to lib/SP/Infrastructure/Database/MySQLFileParser.php index bf967fce..66735b0c 100644 --- a/lib/SP/Storage/Database/MySQLFileParser.php +++ b/lib/SP/Infrastructure/Database/MySQLFileParser.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,10 +22,11 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; +use SP\Infrastructure\File\FileHandlerInterface; /** * Class MysqlFileParser @@ -36,7 +37,7 @@ final class MySQLFileParser implements DatabaseFileInterface { private FileHandler $fileHandler; - public function __construct(FileHandler $fileHandler) + public function __construct(FileHandlerInterface $fileHandler) { $this->fileHandler = $fileHandler; } @@ -80,11 +81,7 @@ final class MySQLFileParser implements DatabaseFileInterface } elseif (strpos($buffer, 'DELIMITER') === false) { $queries[] = $query. trim( - substr_replace( - $buffer, - '', - $length - $delimiterLength - ), + substr_replace($buffer, '', $length - $delimiterLength), $delimiterLength ); diff --git a/lib/SP/Storage/Database/MySQLHandler.php b/lib/SP/Infrastructure/Database/MySQLHandler.php similarity index 84% rename from lib/SP/Storage/Database/MySQLHandler.php rename to lib/SP/Infrastructure/Database/MySQLHandler.php index d9e66c85..bf6df337 100644 --- a/lib/SP/Storage/Database/MySQLHandler.php +++ b/lib/SP/Infrastructure/Database/MySQLHandler.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; use Exception; use PDO; @@ -39,15 +39,15 @@ final class MySQLHandler implements DBStorageInterface { public const STATUS_OK = 0; public const STATUS_KO = 1; - public const PDO_OPTS = [ - PDO::ATTR_EMULATE_PREPARES => false, - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - PDO::MYSQL_ATTR_FOUND_ROWS => true, - PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ + public const PDO_OPTS = [ + PDO::ATTR_EMULATE_PREPARES => false, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::MYSQL_ATTR_FOUND_ROWS => true, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, ]; - private ?PDO $db = null; - private int $dbStatus = self::STATUS_KO; + private ?PDO $db = null; + private int $dbStatus = self::STATUS_KO; private DatabaseConnectionData $connectionData; public function __construct(DatabaseConnectionData $connectionData) @@ -84,7 +84,8 @@ final class MySQLHandler implements DBStorageInterface throw new DatabaseException( __u('Unable to connect to DB'), SPException::CRITICAL, - __u('Please, check the connection parameters')); + __u('Please, check the connection parameters') + ); } try { @@ -122,20 +123,20 @@ final class MySQLHandler implements DBStorageInterface $dsn = ['charset=utf8']; if (empty($this->connectionData->getDbSocket())) { - $dsn[] = 'host=' . $this->connectionData->getDbHost(); + $dsn[] = 'host='.$this->connectionData->getDbHost(); if (null !== $this->connectionData->getDbPort()) { - $dsn[] = 'port=' . $this->connectionData->getDbPort(); + $dsn[] = 'port='.$this->connectionData->getDbPort(); } } else { - $dsn[] = 'unix_socket=' . $this->connectionData->getDbSocket(); + $dsn[] = 'unix_socket='.$this->connectionData->getDbSocket(); } if (!empty($this->connectionData->getDbName())) { - $dsn[] = 'dbname=' . $this->connectionData->getDbName(); + $dsn[] = 'dbname='.$this->connectionData->getDbName(); } - return 'mysql:' . implode(';', $dsn); + return 'mysql:'.implode(';', $dsn); } /** @@ -152,13 +153,14 @@ final class MySQLHandler implements DBStorageInterface throw new DatabaseException( __u('Unable to connect to DB'), SPException::CRITICAL, - __u('Please, check the connection parameters')); + __u('Please, check the connection parameters') + ); } try { $opts = [ PDO::ATTR_EMULATE_PREPARES => true, - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]; $this->db = new PDO( diff --git a/lib/SP/Storage/Database/QueryData.php b/lib/SP/Infrastructure/Database/QueryData.php similarity index 69% rename from lib/SP/Storage/Database/QueryData.php rename to lib/SP/Infrastructure/Database/QueryData.php index edf0f4d8..6e67306e 100644 --- a/lib/SP/Storage/Database/QueryData.php +++ b/lib/SP/Infrastructure/Database/QueryData.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; /** * Class QueryData @@ -31,18 +31,17 @@ namespace SP\Storage\Database; */ final class QueryData { - protected array $params = []; - protected ?string $query = null; - protected ?string $mapClassName = null; - protected bool $useKeyPair = false; - protected ?string $select = null; - protected ?string $from = null; - protected ?string $where = null; - protected ?string $groupBy = null; - protected ?string $order = null; - protected ?string $limit = null; - protected ?string $queryCount = null; - protected int $queryStatus = 0; + protected array $params = []; + protected ?string $query = null; + protected ?string $mapClassName = null; + protected bool $useKeyPair = false; + protected ?string $select = null; + protected ?string $from = null; + protected ?string $where = null; + protected ?string $groupBy = null; + protected ?string $order = null; + protected ?string $limit = null; + protected ?string $queryCount = null; protected ?string $onErrorMessage = null; /** @@ -73,17 +72,17 @@ final class QueryData public function getQuery(): string { if (empty($this->query)) { - return $this->select . - ' ' . - $this->from . - ' ' . - $this->where . - ' ' . - $this->groupBy . - ' ' . - $this->order . - ' ' . - $this->limit; + return $this->select. + ' '. + $this->from. + ' '. + $this->where. + ' '. + $this->groupBy. + ' '. + $this->order. + ' '. + $this->limit; } return $this->query; @@ -121,30 +120,20 @@ final class QueryData public function setSelect(string $select): void { - $this->select = 'SELECT ' . $select; - } - - public function getOrder(): ?string - { - return $this->order; + $this->select = 'SELECT '.$select; } public function setOrder(string $order): void { if (!empty($order)) { - $this->order = 'ORDER BY ' . $order; + $this->order = 'ORDER BY '.$order; } } - public function getLimit(): ?string - { - return $this->limit; - } - public function setLimit(string $limit, ?array $params = null): void { if (!empty($limit)) { - $this->limit = 'LIMIT ' . $limit; + $this->limit = 'LIMIT '.$limit; if ($params !== null) { $this->addParams($params); @@ -160,7 +149,7 @@ final class QueryData public function getQueryCount(): string { if (empty($this->queryCount)) { - return 'SELECT COUNT(*) ' . $this->from . ' ' . $this->where; + return 'SELECT COUNT(*) '.$this->from.' '.$this->where; } return $this->queryCount; @@ -174,7 +163,7 @@ final class QueryData public function setFrom(string $from): void { if (!empty($from)) { - $this->from = 'FROM ' . $from; + $this->from = 'FROM '.$from; } } @@ -184,15 +173,15 @@ final class QueryData } /** - * @param string[]|string $where + * @param string[]|string $where */ public function setWhere($where): void { if (!empty($where)) { if (is_array($where)) { - $this->where = 'WHERE ' . implode(' AND ', $where); + $this->where = 'WHERE '.implode(' AND ', $where); } else { - $this->where = 'WHERE ' . $where; + $this->where = 'WHERE '.$where; } } } @@ -207,15 +196,10 @@ final class QueryData $this->onErrorMessage = $onErrorMessage; } - public function getGroupBy(): ?string - { - return $this->groupBy; - } - public function setGroupBy(string $groupBy): void { if (!empty($groupBy)) { - $this->groupBy = 'GROUP BY ' . $groupBy; + $this->groupBy = 'GROUP BY '.$groupBy; } } } \ No newline at end of file diff --git a/lib/SP/Storage/Database/QueryResult.php b/lib/SP/Infrastructure/Database/QueryResult.php similarity index 81% rename from lib/SP/Storage/Database/QueryResult.php rename to lib/SP/Infrastructure/Database/QueryResult.php index 66010b67..7fa603a5 100644 --- a/lib/SP/Storage/Database/QueryResult.php +++ b/lib/SP/Infrastructure/Database/QueryResult.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,26 +22,26 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\Database; +namespace SP\Infrastructure\Database; /** * Class QueryResult * - * @package SP\Storage\Database + * @package SP\Infrastructure\Database */ final class QueryResult { - private ?array $data = null; - private int $numRows = 0; - private int $totalNumRows = 0; - private int $affectedNumRows = 0; - private int $statusCode = 0; - private int $lastId = 0; + private ?array $data = null; + private int $numRows = 0; + private int $totalNumRows = 0; + private int $affectedNumRows = 0; + private int $statusCode = 0; + private int $lastId = 0; /** * QueryResult constructor. * - * @param array|null $data + * @param array|null $data */ public function __construct(?array $data = null) { @@ -53,9 +53,8 @@ final class QueryResult public static function fromResults( array $data, - ?int $totalNumRows = null - ): QueryResult - { + ?int $totalNumRows = null + ): QueryResult { $result = new self($data); if (null !== $totalNumRows) { @@ -101,13 +100,6 @@ final class QueryResult return $this->statusCode; } - public function setStatusCode(int $statusCode): QueryResult - { - $this->statusCode = $statusCode; - - return $this; - } - public function getAffectedNumRows(): int { return $this->affectedNumRows; diff --git a/lib/SP/Storage/File/ArchiveHandler.php b/lib/SP/Infrastructure/File/ArchiveHandler.php similarity index 89% rename from lib/SP/Storage/File/ArchiveHandler.php rename to lib/SP/Infrastructure/File/ArchiveHandler.php index 60007232..b4d57476 100644 --- a/lib/SP/Storage/File/ArchiveHandler.php +++ b/lib/SP/Infrastructure/File/ArchiveHandler.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; use Phar; @@ -32,9 +32,9 @@ use SP\Core\PhpExtensionChecker; /** * Class ArchiveHandler * - * @package SP\Storage\File + * @package SP\Infrastructure\File */ -final class ArchiveHandler +final class ArchiveHandler implements ArchiveHandlerInterface { public const COMPRESS_EXTENSION = '.tar.gz'; @@ -43,10 +43,8 @@ final class ArchiveHandler /** * @throws \SP\Core\Exceptions\CheckException */ - public function __construct( - string $archive, - PhpExtensionChecker $extensionChecker - ) { + public function __construct(string $archive, PhpExtensionChecker $extensionChecker) + { $extensionChecker->checkPharAvailable(true); $this->archive = new PharData(self::makeArchiveName($archive)); diff --git a/lib/SP/Infrastructure/File/ArchiveHandlerInterface.php b/lib/SP/Infrastructure/File/ArchiveHandlerInterface.php new file mode 100644 index 00000000..c1a865b7 --- /dev/null +++ b/lib/SP/Infrastructure/File/ArchiveHandlerInterface.php @@ -0,0 +1,48 @@ +. + */ + +namespace SP\Infrastructure\File; + + +/** + * Class ArchiveHandler + * + * @package SP\Infrastructure\File + */ +interface ArchiveHandlerInterface +{ + /** + * Realizar un backup de la aplicación y comprimirlo. + * + * @throws FileException + */ + public function compressDirectory(string $directory, ?string $regex = null): void; + + /** + * Realizar un backup de la aplicación y comprimirlo. + * + * @throws FileException + */ + public function compressFile(string $file): void; +} \ No newline at end of file diff --git a/lib/SP/Storage/File/FileCache.php b/lib/SP/Infrastructure/File/FileCache.php similarity index 90% rename from lib/SP/Storage/File/FileCache.php rename to lib/SP/Infrastructure/File/FileCache.php index 4d57ea6f..0de62c45 100644 --- a/lib/SP/Storage/File/FileCache.php +++ b/lib/SP/Infrastructure/File/FileCache.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,12 +22,12 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; /** * Class FileCache * - * @package SP\Storage\File; + * @package SP\Infrastructure\File; */ final class FileCache extends FileCacheBase { diff --git a/lib/SP/Storage/File/FileCacheBase.php b/lib/SP/Infrastructure/File/FileCacheBase.php similarity index 89% rename from lib/SP/Storage/File/FileCacheBase.php rename to lib/SP/Infrastructure/File/FileCacheBase.php index e6afb266..10fa51ec 100644 --- a/lib/SP/Storage/File/FileCacheBase.php +++ b/lib/SP/Infrastructure/File/FileCacheBase.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,13 +22,13 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; /** * Class FileCacheBase * - * @package SP\Storage\File + * @package SP\Infrastructure\File */ abstract class FileCacheBase implements FileCacheInterface { @@ -78,9 +78,7 @@ abstract class FileCacheBase implements FileCacheInterface if (!is_dir($path) && !mkdir($path, 0700, true) && !is_dir($path)) { - throw new FileException( - sprintf(__('Unable to create the directory (%s)'), $path) - ); + throw new FileException(sprintf(__('Unable to create the directory (%s)'), $path)); } } diff --git a/lib/SP/Storage/File/FileCacheInterface.php b/lib/SP/Infrastructure/File/FileCacheInterface.php similarity index 91% rename from lib/SP/Storage/File/FileCacheInterface.php rename to lib/SP/Infrastructure/File/FileCacheInterface.php index 6ccc0791..763e7549 100644 --- a/lib/SP/Storage/File/FileCacheInterface.php +++ b/lib/SP/Infrastructure/File/FileCacheInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,12 +22,12 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; /** * Interface FileStorageInterface * - * @package SP\Storage\File; + * @package SP\Infrastructure\File; */ interface FileCacheInterface { diff --git a/lib/SP/Storage/File/FileCachePacked.php b/lib/SP/Infrastructure/File/FileCachePacked.php similarity index 71% rename from lib/SP/Storage/File/FileCachePacked.php rename to lib/SP/Infrastructure/File/FileCachePacked.php index f9edda4a..258858f9 100644 --- a/lib/SP/Storage/File/FileCachePacked.php +++ b/lib/SP/Infrastructure/File/FileCachePacked.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; use RuntimeException; /** * Class FileCachePacked * - * @package SP\Storage\File; + * @package SP\Infrastructure\File; */ final class FileCachePacked extends FileCacheBase { @@ -43,10 +43,12 @@ final class FileCachePacked extends FileCacheBase $dataUnpacked = gzuncompress($this->path->readToString()); if ($dataUnpacked === false) { - throw new FileException(sprintf( - __('Error while decompressing the file data (%s)'), - $this->path->getFile() - )); + throw new FileException( + sprintf( + __('Error while decompressing the file data (%s)'), + $this->path->getFile() + ) + ); } $data = unserialize($dataUnpacked); @@ -68,15 +70,15 @@ final class FileCachePacked extends FileCacheBase $data = gzcompress(serialize($data)); if ($data === false) { - throw new FileException(sprintf( - __('Error while compressing the file data (%s)'), - $this->path->getFile() - )); + throw new FileException( + sprintf( + __('Error while compressing the file data (%s)'), + $this->path->getFile() + ) + ); } - $this->path->checkIsWritable() - ->write($data) - ->close(); + $this->path->checkIsWritable()->write($data)->close(); return $this; } diff --git a/lib/SP/Storage/File/FileException.php b/lib/SP/Infrastructure/File/FileException.php similarity index 86% rename from lib/SP/Storage/File/FileException.php rename to lib/SP/Infrastructure/File/FileException.php index a2a566cb..6e4479a7 100644 --- a/lib/SP/Storage/File/FileException.php +++ b/lib/SP/Infrastructure/File/FileException.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,14 +22,14 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; use SP\Core\Exceptions\SPException; /** * Class FileException * - * @package SP\Storage\File; + * @package SP\Infrastructure\File; */ final class FileException extends SPException { diff --git a/lib/SP/Storage/File/FileHandler.php b/lib/SP/Infrastructure/File/FileHandler.php similarity index 71% rename from lib/SP/Storage/File/FileHandler.php rename to lib/SP/Infrastructure/File/FileHandler.php index 5c137634..44e20125 100644 --- a/lib/SP/Storage/File/FileHandler.php +++ b/lib/SP/Infrastructure/File/FileHandler.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,24 +22,24 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; use SP\Util\Util; /** * Class FileHandler * - * @package SP\Storage\File; + * @package SP\Infrastructure\File; */ -final class FileHandler +final class FileHandler implements FileHandlerInterface { private const CHUNK_LENGTH = 8192; - public const CHUNK_FACTOR = 3; + public const CHUNK_FACTOR = 3; protected string $file; /** * @var resource */ - protected $handle; + protected $handle; private bool $locked = false; /** @@ -55,17 +55,14 @@ final class FileHandler * * @throws FileException */ - public function write($data): FileHandler + public function write($data): FileHandlerInterface { if (!is_resource($this->handle)) { $this->open('wb'); } if (@fwrite($this->handle, $data) === false) { - throw new FileException(sprintf( - __('Unable to read/write the file (%s)'), - $this->file) - ); + throw new FileException(sprintf(__('Unable to read/write the file (%s)'), $this->file)); } return $this; @@ -86,10 +83,7 @@ final class FileHandler } if ($this->handle === false) { - throw new FileException(sprintf( - __('Unable to open the file (%s)'), - $this->file) - ); + throw new FileException(sprintf(__('Unable to open the file (%s)'), $this->file)); } return $this->handle; @@ -105,10 +99,7 @@ final class FileHandler $this->locked = flock($this->handle, $mode); if (!$this->locked) { - throw new FileException(sprintf( - __('Unable to obtain a lock (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to obtain a lock (%s)'), $this->file)); } logger(sprintf('File locked: %s', $this->file)); @@ -124,10 +115,7 @@ final class FileHandler $data = file_get_contents($this->file); if ($data === false) { - throw new FileException(sprintf( - __('Unable to read from file (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to read from file (%s)'), $this->file)); } return $data; @@ -143,10 +131,7 @@ final class FileHandler $data = @file($this->file, FILE_SKIP_EMPTY_LINES); if ($data === false) { - throw new FileException(sprintf( - __('Unable to read from file (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to read from file (%s)'), $this->file)); } return $data; @@ -157,13 +142,10 @@ final class FileHandler * * @throws FileException */ - public function save(string $data): FileHandler + public function save(string $data): FileHandlerInterface { if (file_put_contents($this->file, $data, LOCK_EX) === false) { - throw new FileException(sprintf( - __('Unable to read/write the file (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to read/write the file (%s)'), $this->file)); } return $this; @@ -196,17 +178,14 @@ final class FileHandler * * @throws FileException */ - public function close(): FileHandler + public function close(): FileHandlerInterface { if ($this->locked) { $this->unlock(); } if (!is_resource($this->handle) || @fclose($this->handle) === false) { - throw new FileException(sprintf( - __('Unable to close the file (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to close the file (%s)'), $this->file)); } return $this; @@ -221,16 +200,15 @@ final class FileHandler } /** - * @param callable|null $chunker - * @param float|null $rate + * @param callable|null $chunker + * @param float|null $rate * * @throws FileException */ public function readChunked( callable $chunker = null, - ?float $rate = null - ): void - { + ?float $rate = null + ): void { $maxRate = Util::getMaxDownloadChunk() / self::CHUNK_FACTOR; if ($rate === null || $rate > $maxRate) { @@ -259,13 +237,10 @@ final class FileHandler * * @throws FileException */ - public function checkIsWritable(): FileHandler + public function checkIsWritable(): FileHandlerInterface { if (!is_writable($this->file) && @touch($this->file) === false) { - throw new FileException(sprintf( - __('Unable to write in file (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to write in file (%s)'), $this->file)); } return $this; @@ -276,13 +251,10 @@ final class FileHandler * * @throws FileException */ - public function checkFileExists(): FileHandler + public function checkFileExists(): FileHandlerInterface { if (!file_exists($this->file)) { - throw new FileException(sprintf( - __('File not found (%s)'), - $this->file - )); + throw new FileException(sprintf(__('File not found (%s)'), $this->file)); } return $this; @@ -302,10 +274,7 @@ final class FileHandler if ($size === false || ($isExceptionOnZero === true && $size === 0)) { - throw new FileException(sprintf( - __('Unable to read/write file (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to read/write file (%s)'), $this->file)); } return $size; @@ -314,7 +283,7 @@ final class FileHandler /** * Clears the stat cache for the given file */ - public function clearCache(): FileHandler + public function clearCache(): FileHandlerInterface { clearstatcache(true, $this->file); @@ -326,13 +295,10 @@ final class FileHandler * * @throws FileException */ - public function delete(): FileHandler + public function delete(): FileHandlerInterface { if (file_exists($this->file) && @unlink($this->file) === false) { - throw new FileException(sprintf( - __('Unable to delete file (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to delete file (%s)'), $this->file)); } return $this; @@ -355,13 +321,10 @@ final class FileHandler * * @throws FileException */ - public function checkIsReadable(): FileHandler + public function checkIsReadable(): FileHandlerInterface { if (!is_readable($this->file)) { - throw new FileException(sprintf( - __('Unable to read/write file (%s)'), - $this->file - )); + throw new FileException(sprintf(__('Unable to read/write file (%s)'), $this->file)); } return $this; diff --git a/lib/SP/Infrastructure/File/FileHandlerInterface.php b/lib/SP/Infrastructure/File/FileHandlerInterface.php new file mode 100644 index 00000000..023c3331 --- /dev/null +++ b/lib/SP/Infrastructure/File/FileHandlerInterface.php @@ -0,0 +1,144 @@ +. + */ + +namespace SP\Infrastructure\File; + + +/** + * Class FileHandler + * + * @package SP\Infrastructure\File; + */ +interface FileHandlerInterface +{ + /** + * Writes data into file + * + * @throws FileException + */ + public function write($data): FileHandlerInterface; + + /** + * Opens the file + * + * @return resource + * @throws FileException + */ + public function open(string $mode = 'rb', ?bool $lock = false); + + /** + * Reads data from file into a string + * + * @throws FileException + */ + public function readToString(): string; + + /** + * Reads data from file into an array + * + * @throws FileException + */ + public function readToArray(): array; + + /** + * Saves a string into a file + * + * @throws FileException + */ + public function save(string $data): FileHandlerInterface; + + /** + * Reads data from file + * + * @throws FileException + */ + public function read(): string; + + /** + * Closes the file + * + * @throws FileException + */ + public function close(): FileHandlerInterface; + + /** + * @param callable|null $chunker + * @param float|null $rate + * + * @throws FileException + */ + public function readChunked(callable $chunker = null, ?float $rate = null): void; + + /** + * Checks if the file is writable + * + * @throws FileException + */ + public function checkIsWritable(): FileHandlerInterface; + + /** + * Checks if the file exists + * + * @throws FileException + */ + public function checkFileExists(): FileHandlerInterface; + + public function getFile(): string; + + /** + * @throws FileException + */ + public function getFileSize(bool $isExceptionOnZero = false): int; + + /** + * Clears the stat cache for the given file + */ + public function clearCache(): FileHandlerInterface; + + /** + * Deletes a file + * + * @throws FileException + */ + public function delete(): FileHandlerInterface; + + /** + * Returns the content type in MIME format + * + * @throws FileException + */ + public function getFileType(): string; + + /** + * Checks if the file is readable + * + * @throws FileException + */ + public function checkIsReadable(): FileHandlerInterface; + + /** + * @throws FileException + */ + public function getFileTime(): int; +} \ No newline at end of file diff --git a/lib/SP/Storage/File/XmlFileStorageInterface.php b/lib/SP/Infrastructure/File/XmlFileStorageInterface.php similarity index 81% rename from lib/SP/Storage/File/XmlFileStorageInterface.php rename to lib/SP/Infrastructure/File/XmlFileStorageInterface.php index 69137637..852ce197 100644 --- a/lib/SP/Storage/File/XmlFileStorageInterface.php +++ b/lib/SP/Infrastructure/File/XmlFileStorageInterface.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; /** * Interface StorageInterface @@ -37,8 +37,8 @@ interface XmlFileStorageInterface public function load(string $node = ''): XmlFileStorageInterface; /** - * @param mixed $data Data to be saved - * @param string $node + * @param mixed $data Data to be saved + * @param string $node * * @throws FileException */ @@ -49,9 +49,9 @@ interface XmlFileStorageInterface /** * Returns the given path node value * - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\File\FileException */ public function getPathValue(string $path): string; - public function getFileHandler(): FileHandler; + public function getFileHandler(): FileHandlerInterface; } \ No newline at end of file diff --git a/lib/SP/Storage/File/XmlHandler.php b/lib/SP/Infrastructure/File/XmlHandler.php similarity index 92% rename from lib/SP/Storage/File/XmlHandler.php rename to lib/SP/Infrastructure/File/XmlHandler.php index 287f0868..8fd89fab 100644 --- a/lib/SP/Storage/File/XmlHandler.php +++ b/lib/SP/Infrastructure/File/XmlHandler.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Storage\File; +namespace SP\Infrastructure\File; use DOMDocument; use DOMElement; @@ -35,105 +35,25 @@ use RuntimeException; /** * Class XmlHandler para manejo básico de documentos XML * - * @package SP\Storage\File; + * @package SP\Infrastructure\File; */ final class XmlHandler implements XmlFileStorageInterface { /** * @var mixed */ - protected $items; + protected $items; private ?DOMDocument $document = null; - private FileHandler $fileHandler; + private FileHandler $fileHandler; /** * XmlHandler constructor. */ - public function __construct(FileHandler $fileHandler) + public function __construct(FileHandlerInterface $fileHandler) { $this->fileHandler = $fileHandler; } - /** - * Cargar un archivo XML - * - * @throws FileException - * @throws RuntimeException - */ - public function load(string $node = 'root'): XmlFileStorageInterface - { - $this->fileHandler->checkIsReadable(); - $this->fileHandler->getFileSize(true); - - $this->items = []; - $this->setDOM(); - $this->document->load($this->fileHandler->getFile()); - - $nodes = $this->document->getElementsByTagName($node); - - if ($nodes->length === 0) { - throw new RuntimeException(__u('XML node does not exist')); - } - - $this->items = $this->readChildNodes($nodes->item(0)->childNodes); - - return $this; - } - - /** - * Crear un nuevo documento XML - */ - private function setDOM(): void - { - $this->document = new DOMDocument('1.0', 'utf-8'); - } - - /** - * Leer de forma recursiva los nodos hijos y devolver un array multidimensional - */ - protected function readChildNodes(DOMNodeList $nodeList): array - { - $nodes = []; - - /** @var DOMElement $node */ - foreach ($nodeList as $node) { - if ($node->nodeType === XML_ELEMENT_NODE) { - if (is_object($node->childNodes) - && $node->childNodes->length > 1 - ) { - if ($node->hasAttribute('multiple') - && (int)$node->getAttribute('multiple') === 1 - ) { - $nodes[] = $this->readChildNodes($node->childNodes); - - } elseif ($node->hasAttribute('class')) { - $nodes[$node->nodeName] = $this->readChildNodes($node->childNodes); - $nodes[$node->nodeName]['__class__'] = (string)$node->getAttribute('class'); - } else { - $nodes[$node->nodeName] = $this->readChildNodes($node->childNodes); - } - } else { - $val = null; - - if (is_numeric($node->nodeValue) - && strpos($node->nodeValue, '.') === false) { - $val = (int)$node->nodeValue; - } else if (!empty($node->nodeValue)) { - $val = $node->nodeValue; - } - - if ($node->nodeName === 'item') { - $nodes[] = $val; - } else { - $nodes[$node->nodeName] = $val; - } - } - } - } - - return $nodes; - } - /** * Obtener un elemento del array */ @@ -168,6 +88,14 @@ final class XmlHandler implements XmlFileStorageInterface return $this; } + /** + * Crear un nuevo documento XML + */ + private function setDOM(): void + { + $this->document = new DOMDocument('1.0', 'utf-8'); + } + /** * Crear los nodos hijos recursivamente a partir de un array multidimensional */ @@ -175,8 +103,7 @@ final class XmlHandler implements XmlFileStorageInterface $items, DOMNode $node, $type = null - ): void - { + ): void { foreach ($this->analyzeItems($items) as $key => $value) { if (is_int($key)) { $newNode = $this->document->createElement('item'); @@ -187,7 +114,7 @@ final class XmlHandler implements XmlFileStorageInterface if (is_array($value)) { $this->writeChildNodes($value, $newNode, $key); - } else if (is_object($value)) { + } elseif (is_object($value)) { $newNode->setAttribute('class', get_class($value)); $this->writeChildNodes($value, $newNode, $key); // $newNode->appendChild($this->document->createTextNode(base64_encode(serialize($value)))); @@ -234,9 +161,7 @@ final class XmlHandler implements XmlFileStorageInterface if (is_bool($value)) { $items[$property->getName()] = (int)$value; - } elseif (is_numeric($value) - && strpos($value, '.') === false - ) { + } elseif (is_numeric($value) && strpos($value, '.') === false) { $items[$property->getName()] = (int)$value; } else { $items[$property->getName()] = $value; @@ -269,7 +194,7 @@ final class XmlHandler implements XmlFileStorageInterface } /** - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\File\FileException */ public function getPathValue(string $path): string { @@ -288,7 +213,79 @@ final class XmlHandler implements XmlFileStorageInterface return $query->item(0)->nodeValue; } - public function getFileHandler(): FileHandler + /** + * Cargar un archivo XML + * + * @throws FileException + * @throws RuntimeException + */ + public function load(string $node = 'root'): XmlFileStorageInterface + { + $this->fileHandler->checkIsReadable(); + $this->fileHandler->getFileSize(true); + + $this->items = []; + $this->setDOM(); + $this->document->load($this->fileHandler->getFile()); + + $nodes = $this->document->getElementsByTagName($node); + + if ($nodes->length === 0) { + throw new RuntimeException(__u('XML node does not exist')); + } + + $this->items = $this->readChildNodes($nodes->item(0)->childNodes); + + return $this; + } + + /** + * Leer de forma recursiva los nodos hijos y devolver un array multidimensional + */ + protected function readChildNodes(DOMNodeList $nodeList): array + { + $nodes = []; + + /** @var DOMElement $node */ + foreach ($nodeList as $node) { + if ($node->nodeType === XML_ELEMENT_NODE) { + if (is_object($node->childNodes) + && $node->childNodes->length > 1 + ) { + if ($node->hasAttribute('multiple') + && (int)$node->getAttribute('multiple') === 1 + ) { + $nodes[] = $this->readChildNodes($node->childNodes); + + } elseif ($node->hasAttribute('class')) { + $nodes[$node->nodeName] = $this->readChildNodes($node->childNodes); + $nodes[$node->nodeName]['__class__'] = (string)$node->getAttribute('class'); + } else { + $nodes[$node->nodeName] = $this->readChildNodes($node->childNodes); + } + } else { + $val = null; + + if (is_numeric($node->nodeValue) + && strpos($node->nodeValue, '.') === false) { + $val = (int)$node->nodeValue; + } elseif (!empty($node->nodeValue)) { + $val = $node->nodeValue; + } + + if ($node->nodeName === 'item') { + $nodes[] = $val; + } else { + $nodes[$node->nodeName] = $val; + } + } + } + } + + return $nodes; + } + + public function getFileHandler(): FileHandlerInterface { return $this->fileHandler; } diff --git a/lib/SP/Repositories/ItemPreset/ItemPresetRepository.php b/lib/SP/Infrastructure/ItemPreset/Repositories/ItemPresetRepository.php similarity index 84% rename from lib/SP/Repositories/ItemPreset/ItemPresetRepository.php rename to lib/SP/Infrastructure/ItemPreset/Repositories/ItemPresetRepository.php index 1d8e9de6..794f46b6 100644 --- a/lib/SP/Repositories/ItemPreset/ItemPresetRepository.php +++ b/lib/SP/Infrastructure/ItemPreset/Repositories/ItemPresetRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,32 +22,33 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\ItemPreset; +namespace SP\Infrastructure\ItemPreset\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemPresetData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Common\In\RepositoryInterface; +use SP\Domain\ItemPreset\In\ItemPresetRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class AccountDefaultPermissionRepository * - * @package SP\Repositories\Account + * @package SP\Infrastructure\Account\Repositories */ -class ItemPresetRepository extends Repository implements RepositoryInterface +class ItemPresetRepository extends Repository implements RepositoryInterface, ItemPresetRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param ItemPresetData $itemData + * @param ItemPresetData $itemData * * @return int * @throws ConstraintException @@ -65,7 +66,8 @@ class ItemPresetRepository extends Repository implements RepositoryInterface `fixed` = ?, priority = ?, `data` = ?, - `hash` = ?'); + `hash` = ?' + ); $queryData->setParams([ $itemData->getType(), $itemData->getUserId(), @@ -74,7 +76,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface $itemData->getFixed(), $itemData->getPriority(), $itemData->getData(), - $itemData->getHash() + $itemData->getHash(), ]); $queryData->setOnErrorMessage(__u('Error while creating the permission')); @@ -84,7 +86,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Updates an item * - * @param ItemPresetData $itemData + * @param ItemPresetData $itemData * * @return int * @throws ConstraintException @@ -103,7 +105,8 @@ class ItemPresetRepository extends Repository implements RepositoryInterface priority = ?, `data` = ?, `hash` = ? - WHERE id = ? LIMIT 1'); + WHERE id = ? LIMIT 1' + ); $queryData->setParams([ $itemData->getType(), $itemData->getUserId(), @@ -113,7 +116,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface $itemData->getPriority(), $itemData->getData(), $itemData->getHash(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the permission')); @@ -123,7 +126,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws ConstraintException @@ -142,7 +145,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -154,7 +157,8 @@ class ItemPresetRepository extends Repository implements RepositoryInterface $queryData->setMapClassName(ItemPresetData::class); $queryData->setQuery( 'SELECT id, type, userId, userGroupId, userProfileId, `fixed`, priority, `data` - FROM ItemPreset WHERE id = ? LIMIT 1'); + FROM ItemPreset WHERE id = ? LIMIT 1' + ); $queryData->setParams([$id]); return $this->db->doSelect($queryData); @@ -163,10 +167,10 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param string $type - * @param int $userId - * @param int $userGroupId - * @param int $userProfileId + * @param string $type + * @param int $userId + * @param int $userGroupId + * @param int $userProfileId * * @return QueryResult * @throws ConstraintException @@ -174,11 +178,10 @@ class ItemPresetRepository extends Repository implements RepositoryInterface */ public function getByFilter( string $type, - int $userId, - int $userGroupId, - int $userProfileId - ): QueryResult - { + int $userId, + int $userGroupId, + int $userProfileId + ): QueryResult { $queryData = new QueryData(); $queryData->setMapClassName(ItemPresetData::class); $queryData->setQuery( @@ -196,7 +199,8 @@ class ItemPresetRepository extends Repository implements RepositoryInterface WHERE UserToUserGroup.userId = ?) ) ORDER BY score DESC - LIMIT 1'); + LIMIT 1' + ); $queryData->setParams([$type, $userId, $userGroupId, $userProfileId, $userId]); @@ -216,7 +220,8 @@ class ItemPresetRepository extends Repository implements RepositoryInterface $queryData->setMapClassName(ItemPresetData::class); $queryData->setQuery( 'SELECT id, type, userId, userGroupId, userProfileId, `fixed`, priority, `data` - FROM ItemPreset'); + FROM ItemPreset' + ); return $this->db->doSelect($queryData); } @@ -224,7 +229,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult * @throws ConstraintException @@ -240,7 +245,8 @@ class ItemPresetRepository extends Repository implements RepositoryInterface $queryData->setMapClassName(ItemPresetData::class); $queryData->setQuery( 'SELECT type, userId, userGroupId, userProfileId, `fixed`, priority, `data` - FROM ItemPreset WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + FROM ItemPreset WHERE id IN ('.$this->getParamsFromArray($ids).')' + ); $queryData->setParams($ids); return $this->db->doSelect($queryData); @@ -249,7 +255,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @return int * @throws ConstraintException @@ -262,7 +268,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM ItemPreset WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM ItemPreset WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while removing the permissions')); @@ -282,7 +288,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnUpdate($itemData): bool { @@ -292,7 +298,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnAdd($itemData): bool { @@ -302,7 +308,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -325,14 +331,18 @@ class ItemPresetRepository extends Repository implements RepositoryInterface UserGroup.name AS userGroupName, IF(ItemPreset.userId IS NOT NULL, ItemPreset.priority + 3, IF(ItemPreset.userGroupId IS NOT NULL, ItemPreset.priority + 2, - IF(ItemPreset.userProfileId IS NOT NULL, ItemPreset.priority + 1, 0))) AS score'); - $queryData->setFrom(' + IF(ItemPreset.userProfileId IS NOT NULL, ItemPreset.priority + 1, 0))) AS score' + ); + $queryData->setFrom( + ' ItemPreset LEFT JOIN User ON ItemPreset.userId = User.id LEFT JOIN UserProfile ON ItemPreset.userProfileId = UserProfile.id - LEFT JOIN UserGroup ON ItemPreset.userGroupId = UserGroup.id'); + LEFT JOIN UserGroup ON ItemPreset.userGroupId = UserGroup.id' + ); $queryData->setOrder( - 'ItemPreset.type, score DESC'); + 'ItemPreset.type, score DESC' + ); if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere( @@ -342,7 +352,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface OR UserGroup.name LIKE ?' ); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); $queryData->addParam($search); diff --git a/lib/SP/Repositories/Notification/NotificationRepository.php b/lib/SP/Infrastructure/Notification/Repositories/NotificationRepository.php similarity index 89% rename from lib/SP/Repositories/Notification/NotificationRepository.php rename to lib/SP/Infrastructure/Notification/Repositories/NotificationRepository.php index fffe2946..94f6fc81 100644 --- a/lib/SP/Repositories/Notification/NotificationRepository.php +++ b/lib/SP/Infrastructure/Notification/Repositories/NotificationRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,33 +22,33 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Notification; +namespace SP\Infrastructure\Notification\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemSearchData; use SP\DataModel\NotificationData; +use SP\Domain\Notification\In\NotificationRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; use SP\Mvc\Model\QueryCondition; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; /** * Class NotificationRepository * - * @package SP\Repositories\Notification + * @package SP\Infrastructure\Notification\Repositories */ -final class NotificationRepository extends Repository implements RepositoryInterface +final class NotificationRepository extends Repository implements NotificationRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param NotificationData $itemData + * @param NotificationData $itemData * * @return QueryResult * @throws ConstraintException @@ -75,7 +75,7 @@ final class NotificationRepository extends Repository implements RepositoryInter $itemData->getDescription(), $itemData->getUserId() ?: null, $itemData->isSticky(), - $itemData->isOnlyAdmin() + $itemData->isOnlyAdmin(), ]); $queryData->setOnErrorMessage(__u('Error while adding the notification')); @@ -85,7 +85,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Updates an item * - * @param NotificationData $itemData + * @param NotificationData $itemData * * @return int * @throws ConstraintException @@ -115,7 +115,7 @@ final class NotificationRepository extends Repository implements RepositoryInter $itemData->getUserId() ?: null, $itemData->isSticky(), $itemData->isOnlyAdmin(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the notification')); @@ -125,7 +125,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -144,7 +144,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -163,7 +163,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Deletes an item * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -176,7 +176,7 @@ final class NotificationRepository extends Repository implements RepositoryInter } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM Notification WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM Notification WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the notifications')); @@ -186,7 +186,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -249,7 +249,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult * @throws ConstraintException @@ -272,7 +272,7 @@ final class NotificationRepository extends Repository implements RepositoryInter sticky, onlyAdmin FROM Notification - WHERE id IN (' . $this->getParamsFromArray($ids) . ') + WHERE id IN ('.$this->getParamsFromArray($ids).') ORDER BY id'; $queryData = new QueryData(); @@ -286,7 +286,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -299,7 +299,9 @@ final class NotificationRepository extends Repository implements RepositoryInter } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM Notification WHERE id IN (' . $this->getParamsFromArray($ids) . ') AND sticky = 0'); + $queryData->setQuery( + 'DELETE FROM Notification WHERE id IN ('.$this->getParamsFromArray($ids).') AND sticky = 0' + ); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the notifications')); @@ -319,7 +321,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnUpdate($itemData): bool { @@ -329,7 +331,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData */ public function checkDuplicatedOnAdd($itemData): bool { @@ -339,7 +341,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -356,7 +358,7 @@ final class NotificationRepository extends Repository implements RepositoryInter if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('type LIKE ? OR component LIKE ? OR description LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); $queryData->addParam($search); @@ -373,8 +375,8 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData - * @param int $userId + * @param ItemSearchData $itemSearchData + * @param int $userId * * @return QueryResult * @throws ConstraintException @@ -382,9 +384,8 @@ final class NotificationRepository extends Repository implements RepositoryInter */ public function searchForUserId( ItemSearchData $itemSearchData, - int $userId - ): QueryResult - { + int $userId + ): QueryResult { $queryData = new QueryData(); $queryData->setMapClassName(NotificationData::class); $queryData->setSelect('id, type, component, description, `date`, checked, userId, sticky, onlyAdmin'); @@ -400,10 +401,10 @@ final class NotificationRepository extends Repository implements RepositoryInter if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere( '(type LIKE ? OR component LIKE ? OR description LIKE ?) AND ' - . $queryCondition->getFilters(QueryCondition::CONDITION_OR) + .$queryCondition->getFilters(QueryCondition::CONDITION_OR) ); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->setParams(array_merge([$search, $search, $search], $queryCondition->getParams())); } else { $queryData->setWhere($queryCondition->getFilters(QueryCondition::CONDITION_OR)); @@ -421,8 +422,8 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData - * @param int $userId + * @param ItemSearchData $itemSearchData + * @param int $userId * * @return QueryResult * @throws ConstraintException @@ -430,9 +431,8 @@ final class NotificationRepository extends Repository implements RepositoryInter */ public function searchForAdmin( ItemSearchData $itemSearchData, - int $userId - ): QueryResult - { + int $userId + ): QueryResult { $queryData = new QueryData(); $queryData->setMapClassName(NotificationData::class); $queryData->setSelect('id, type, component, description, `date`, checked, userId, sticky, onlyAdmin'); @@ -448,10 +448,10 @@ final class NotificationRepository extends Repository implements RepositoryInter if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere( '(type LIKE ? OR component LIKE ? OR description LIKE ?) AND ' - . $queryCondition->getFilters(QueryCondition::CONDITION_OR) + .$queryCondition->getFilters(QueryCondition::CONDITION_OR) ); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->setParams(array_merge([$search, $search, $search], $queryCondition->getParams())); } else { @@ -470,7 +470,7 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Marcar una notificación como leída * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -492,8 +492,8 @@ final class NotificationRepository extends Repository implements RepositoryInter /** * Devolver las notificaciones de un usuario para una fecha y componente determinados * - * @param string $component - * @param int $userId + * @param string $component + * @param int $userId * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -527,7 +527,7 @@ final class NotificationRepository extends Repository implements RepositoryInter } /** - * @param int $id + * @param int $id * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -560,7 +560,7 @@ final class NotificationRepository extends Repository implements RepositoryInter } /** - * @param int $id + * @param int $id * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -594,7 +594,7 @@ final class NotificationRepository extends Repository implements RepositoryInter } /** - * @param int $id + * @param int $id * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException diff --git a/lib/SP/Repositories/Plugin/PluginDataModel.php b/lib/SP/Infrastructure/Plugin/Repositories/PluginDataModel.php similarity index 87% rename from lib/SP/Repositories/Plugin/PluginDataModel.php rename to lib/SP/Infrastructure/Plugin/Repositories/PluginDataModel.php index 47be6077..99663afc 100644 --- a/lib/SP/Repositories/Plugin/PluginDataModel.php +++ b/lib/SP/Infrastructure/Plugin/Repositories/PluginDataModel.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Plugin; +namespace SP\Infrastructure\Plugin\Repositories; use SP\DataModel\EncryptedModel; use SP\DataModel\HydratableInterface; @@ -31,7 +31,7 @@ use SP\DataModel\SerializedModel; /** * Class PluginData * - * @package SP\Repositories\Plugin + * @package SP\Infrastructure\Plugin\Repositories */ final class PluginDataModel implements HydratableInterface { @@ -60,7 +60,7 @@ final class PluginDataModel implements HydratableInterface } /** - * @param string $name + * @param string $name */ public function setName(string $name) { @@ -76,7 +76,7 @@ final class PluginDataModel implements HydratableInterface } /** - * @param int $itemId + * @param int $itemId */ public function setItemId(int $itemId) { @@ -92,7 +92,7 @@ final class PluginDataModel implements HydratableInterface } /** - * @param string $data + * @param string $data */ public function setData(string $data) { diff --git a/lib/SP/Repositories/Plugin/PluginDataRepository.php b/lib/SP/Infrastructure/Plugin/Repositories/PluginDataRepository.php similarity index 86% rename from lib/SP/Repositories/Plugin/PluginDataRepository.php rename to lib/SP/Infrastructure/Plugin/Repositories/PluginDataRepository.php index dcd364ad..2a1cbcaa 100644 --- a/lib/SP/Repositories/Plugin/PluginDataRepository.php +++ b/lib/SP/Infrastructure/Plugin/Repositories/PluginDataRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,28 +22,29 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Plugin; +namespace SP\Infrastructure\Plugin\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Plugin\In\PluginDataRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class PluginDataRepository * - * @package SP\Repositories\Plugin + * @package SP\Infrastructure\Plugin\Repositories */ -final class PluginDataRepository extends Repository +final class PluginDataRepository extends Repository implements PluginDataRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param PluginDataModel $itemData + * @param PluginDataModel $itemData * * @return QueryResult * @throws ConstraintException @@ -60,7 +61,7 @@ final class PluginDataRepository extends Repository $itemData->getName(), $itemData->getItemId(), $itemData->getData(), - $itemData->getKey() + $itemData->getKey(), ]); $queryData->setOnErrorMessage(__u('Error while adding plugin\'s data')); @@ -70,7 +71,7 @@ final class PluginDataRepository extends Repository /** * Updates an item * - * @param PluginDataModel $itemData + * @param PluginDataModel $itemData * * @return int * @throws ConstraintException @@ -89,7 +90,7 @@ final class PluginDataRepository extends Repository $itemData->getData(), $itemData->getKey(), $itemData->getName(), - $itemData->getItemId() + $itemData->getItemId(), ]); $queryData->setOnErrorMessage(__u('Error while updating plugin\'s data')); @@ -99,7 +100,7 @@ final class PluginDataRepository extends Repository /** * Deletes an item * - * @param string $id + * @param string $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -118,8 +119,8 @@ final class PluginDataRepository extends Repository /** * Deletes an item * - * @param string $name - * @param int $itemId + * @param string $name + * @param int $itemId * * @return int * @throws ConstraintException @@ -138,7 +139,7 @@ final class PluginDataRepository extends Repository /** * Returns the item for given id * - * @param string $id + * @param string $id * * @return QueryResult * @throws ConstraintException @@ -189,7 +190,7 @@ final class PluginDataRepository extends Repository /** * Returns all the items for given ids * - * @param string[] $ids + * @param string[] $ids * * @return QueryResult * @throws ConstraintException @@ -207,7 +208,7 @@ final class PluginDataRepository extends Repository `data`, `key` FROM PluginData - WHERE `name` IN (' . $this->getParamsFromArray($ids) . ') + WHERE `name` IN ('.$this->getParamsFromArray($ids).') ORDER BY `name`'; $queryData = new QueryData(); @@ -221,7 +222,7 @@ final class PluginDataRepository extends Repository /** * Deletes all the items for given ids * - * @param string[] $ids + * @param string[] $ids * * @return int * @throws ConstraintException @@ -234,7 +235,7 @@ final class PluginDataRepository extends Repository } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM PluginData WHERE `name` IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM PluginData WHERE `name` IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting plugin\'s data')); @@ -244,8 +245,8 @@ final class PluginDataRepository extends Repository /** * Devuelve los datos de un plugin por su nombre * - * @param string $name - * @param int $itemId + * @param string $name + * @param int $itemId * * @return QueryResult * @throws ConstraintException diff --git a/lib/SP/Repositories/Plugin/PluginModel.php b/lib/SP/Infrastructure/Plugin/Repositories/PluginModel.php similarity index 89% rename from lib/SP/Repositories/Plugin/PluginModel.php rename to lib/SP/Infrastructure/Plugin/Repositories/PluginModel.php index ce28cfd0..f834d1e0 100644 --- a/lib/SP/Repositories/Plugin/PluginModel.php +++ b/lib/SP/Infrastructure/Plugin/Repositories/PluginModel.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Plugin; +namespace SP\Infrastructure\Plugin\Repositories; use SP\DataModel\DataModelBase; use SP\DataModel\DataModelInterface; @@ -68,7 +68,7 @@ class PluginModel extends DataModelBase implements DataModelInterface } /** - * @param int $id + * @param int $id */ public function setId($id) { @@ -84,7 +84,7 @@ class PluginModel extends DataModelBase implements DataModelInterface } /** - * @param string $name + * @param string $name */ public function setName($name) { @@ -100,7 +100,7 @@ class PluginModel extends DataModelBase implements DataModelInterface } /** - * @param string $data + * @param string $data */ public function setData($data) { @@ -116,7 +116,7 @@ class PluginModel extends DataModelBase implements DataModelInterface } /** - * @param int $enabled + * @param int $enabled */ public function setEnabled($enabled) { @@ -132,7 +132,7 @@ class PluginModel extends DataModelBase implements DataModelInterface } /** - * @param int $available + * @param int $available */ public function setAvailable($available) { @@ -148,7 +148,7 @@ class PluginModel extends DataModelBase implements DataModelInterface } /** - * @param string $versionLevel + * @param string $versionLevel */ public function setVersionLevel(string $versionLevel) { diff --git a/lib/SP/Repositories/Plugin/PluginRepository.php b/lib/SP/Infrastructure/Plugin/Repositories/PluginRepository.php similarity index 89% rename from lib/SP/Repositories/Plugin/PluginRepository.php rename to lib/SP/Infrastructure/Plugin/Repositories/PluginRepository.php index b2d654f8..46fc3bac 100644 --- a/lib/SP/Repositories/Plugin/PluginRepository.php +++ b/lib/SP/Infrastructure/Plugin/Repositories/PluginRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Plugin; +namespace SP\Infrastructure\Plugin\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -30,25 +30,25 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Plugin\In\PluginRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class PluginRepository * - * @package SP\Repositories\Plugin + * @package SP\Infrastructure\Plugin\Repositories */ -final class PluginRepository extends Repository implements RepositoryInterface +final class PluginRepository extends Repository implements PluginRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param PluginModel $itemData + * @param PluginModel $itemData * * @return QueryResult * @throws ConstraintException @@ -65,17 +65,33 @@ final class PluginRepository extends Repository implements RepositoryInterface $itemData->getName(), $itemData->getData(), $itemData->getEnabled(), - $itemData->getAvailable() + $itemData->getAvailable(), ]); $queryData->setOnErrorMessage(__u('Error while adding the plugin')); return $this->db->doQuery($queryData); } + /** + * Devolver los plugins activados + * + * @return QueryResult + * @throws ConstraintException + * @throws QueryException + */ + public function getEnabled(): QueryResult + { + $queryData = new QueryData(); + $queryData->setMapClassName(ItemData::class); + $queryData->setQuery('SELECT id, `name` FROM Plugin WHERE enabled = 1 ORDER BY id'); + + return $this->db->doSelect($queryData); + } + /** * Updates an item * - * @param PluginModel $itemData + * @param PluginModel $itemData * * @return int * @throws ConstraintException @@ -101,7 +117,7 @@ final class PluginRepository extends Repository implements RepositoryInterface $itemData->getAvailable(), $itemData->getVersionLevel(), $itemData->getName(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the plugin')); @@ -111,7 +127,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -165,7 +181,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * * @return QueryResult * @throws ConstraintException @@ -184,7 +200,7 @@ final class PluginRepository extends Repository implements RepositoryInterface available, versionLevel FROM Plugin - WHERE id IN (' . $this->getParamsFromArray($ids) . ') + WHERE id IN ('.$this->getParamsFromArray($ids).') ORDER BY id'; $queryData = new QueryData(); @@ -198,7 +214,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws SPException @@ -212,7 +228,7 @@ final class PluginRepository extends Repository implements RepositoryInterface } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM Plugin WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM Plugin WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the plugins')); @@ -222,7 +238,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -253,7 +269,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on updating * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -265,7 +281,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on adding * - * @param mixed $itemData + * @param mixed $itemData * * @return void */ @@ -277,7 +293,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -294,7 +310,7 @@ final class PluginRepository extends Repository implements RepositoryInterface if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('name LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); } @@ -309,7 +325,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Devuelve los datos de un plugin por su nombre * - * @param string $name + * @param string $name * * @return QueryResult * @throws ConstraintException @@ -338,8 +354,8 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Cambiar el estado del plugin * - * @param int $id - * @param bool $enabled + * @param int $id + * @param bool $enabled * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -358,8 +374,8 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Cambiar el estado del plugin * - * @param string $name - * @param bool $enabled + * @param string $name + * @param bool $enabled * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -378,8 +394,8 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Cambiar el estado del plugin * - * @param int $id - * @param bool $available + * @param int $id + * @param bool $available * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -398,8 +414,8 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Cambiar el estado del plugin * - * @param string $name - * @param bool $available + * @param string $name + * @param bool $available * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -418,7 +434,7 @@ final class PluginRepository extends Repository implements RepositoryInterface /** * Restablecer los datos de un plugin * - * @param int $id Id del plugin + * @param int $id Id del plugin * * @return int * @throws ConstraintException @@ -433,20 +449,4 @@ final class PluginRepository extends Repository implements RepositoryInterface return $this->db->doQuery($queryData)->getAffectedNumRows(); } - - /** - * Devolver los plugins activados - * - * @return QueryResult - * @throws ConstraintException - * @throws QueryException - */ - public function getEnabled(): QueryResult - { - $queryData = new QueryData(); - $queryData->setMapClassName(ItemData::class); - $queryData->setQuery('SELECT id, `name` FROM Plugin WHERE enabled = 1 ORDER BY id'); - - return $this->db->doSelect($queryData); - } } \ No newline at end of file diff --git a/lib/SP/Repositories/EventLog/EventlogRepository.php b/lib/SP/Infrastructure/Security/Repositories/EventlogRepository.php similarity index 82% rename from lib/SP/Repositories/EventLog/EventlogRepository.php rename to lib/SP/Infrastructure/Security/Repositories/EventlogRepository.php index ec661ec3..9d225ed7 100644 --- a/lib/SP/Repositories/EventLog/EventlogRepository.php +++ b/lib/SP/Infrastructure/Security/Repositories/EventlogRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,22 +22,23 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\EventLog; +namespace SP\Infrastructure\Security\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\EventlogData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Repository; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Security\In\EventlogRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class EventlogRepository * - * @package SP\Repositories\EventLog + * @package SP\Infrastructure\Security\Repositories */ -final class EventlogRepository extends Repository +final class EventlogRepository extends Repository implements EventlogRepositoryInterface { /** * Clears the event log @@ -58,7 +59,7 @@ final class EventlogRepository extends Repository /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -74,7 +75,7 @@ final class EventlogRepository extends Repository if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('action LIKE ? OR login LIKE ? OR ipAddress LIKE ? OR description LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->setParams(array_fill(0, 4, $search)); } @@ -88,7 +89,7 @@ final class EventlogRepository extends Repository /** - * @param EventlogData $eventlogData + * @param EventlogData $eventlogData * * @return int * @throws ConstraintException @@ -113,7 +114,8 @@ final class EventlogRepository extends Repository $eventlogData->getIpAddress(), $eventlogData->getAction(), $eventlogData->getDescription(), - $eventlogData->getLevel()] + $eventlogData->getLevel(), + ] ); return $this->db->doQuery($queryData)->getLastId(); diff --git a/lib/SP/Repositories/Track/TrackRepository.php b/lib/SP/Infrastructure/Security/Repositories/TrackRepository.php similarity index 88% rename from lib/SP/Repositories/Track/TrackRepository.php rename to lib/SP/Infrastructure/Security/Repositories/TrackRepository.php index 1ffe5d98..2fcb77ee 100644 --- a/lib/SP/Repositories/Track/TrackRepository.php +++ b/lib/SP/Infrastructure/Security/Repositories/TrackRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,26 +22,27 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Track; +namespace SP\Infrastructure\Security\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemSearchData; use SP\DataModel\TrackData; -use SP\Repositories\Repository; -use SP\Services\Track\TrackService; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Security\In\TrackRepositoryInterface; +use SP\Domain\Security\Services\TrackService; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class TrackRepository * - * @package SP\Repositories\Track + * @package SP\Infrastructure\Security\Repositories */ -final class TrackRepository extends Repository +final class TrackRepository extends Repository implements TrackRepositoryInterface { /** - * @param TrackRequest $trackRequest + * @param TrackRequest $trackRequest * * @return int * @throws ConstraintException @@ -63,7 +64,7 @@ final class TrackRepository extends Repository $trackRequest->userId, $trackRequest->source, $trackRequest->getIpv4(), - $trackRequest->getIpv6() + $trackRequest->getIpv6(), ]); $queryData->setOnErrorMessage(__u('Error while creating track')); @@ -174,7 +175,7 @@ final class TrackRepository extends Repository /** * Devuelve los tracks de un cliente desde un tiempo y origen determinados * - * @param TrackRequest $trackRequest + * @param TrackRequest $trackRequest * * @return QueryResult * @throws ConstraintException @@ -197,7 +198,7 @@ final class TrackRepository extends Repository (int)$trackRequest->time, $trackRequest->getIpv4(), $trackRequest->getIpv6(), - $trackRequest->source + $trackRequest->source, ]); $queryData->setOnErrorMessage(__u('Error while retrieving the tracks')); @@ -207,7 +208,7 @@ final class TrackRepository extends Repository /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -216,7 +217,8 @@ final class TrackRepository extends Repository public function search(ItemSearchData $itemSearchData): QueryResult { $queryData = new QueryData(); - $queryData->setSelect(' + $queryData->setSelect( + ' id, userId, source, @@ -227,7 +229,8 @@ final class TrackRepository extends Repository ipv4, ipv6, IF(`time` >= ? AND `timeUnlock` IS NULL, 1, 0) AS tracked - '); + ' + ); $queryData->addParam(time() - TrackService::TIME_TRACKING); $queryData->setFrom('Track'); @@ -236,7 +239,7 @@ final class TrackRepository extends Repository if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('source LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); } diff --git a/lib/SP/Repositories/Track/TrackRequest.php b/lib/SP/Infrastructure/Security/Repositories/TrackRequest.php similarity index 78% rename from lib/SP/Repositories/Track/TrackRequest.php rename to lib/SP/Infrastructure/Security/Repositories/TrackRequest.php index b1454734..2c286563 100644 --- a/lib/SP/Repositories/Track/TrackRequest.php +++ b/lib/SP/Infrastructure/Security/Repositories/TrackRequest.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Track; +namespace SP\Infrastructure\Security\Repositories; use SP\Core\Exceptions\InvalidArgumentException; use SP\Http\Address; @@ -30,20 +30,20 @@ use SP\Http\Address; /** * Class TrackRequest * - * @package SP\Repositories\Track + * @package SP\Infrastructure\Security\Repositories */ final class TrackRequest { - public int $time; - public string $source; - public ?int $userId = null; - private ?string $ipv6 = null; - private ?string $ipv4 = null; + public int $time; + public string $source; + public ?int $userId = null; + private ?string $ipv6 = null; + private ?string $ipv4 = null; /** - * @param int $time - * @param string $source - * @param int|null $userId + * @param int $time + * @param string $source + * @param int|null $userId */ public function __construct(int $time, string $source, ?int $userId = null) { @@ -53,7 +53,7 @@ final class TrackRequest } /** - * @param string $address + * @param string $address * * @throws InvalidArgumentException */ diff --git a/lib/SP/Repositories/Tag/TagRepository.php b/lib/SP/Infrastructure/Tag/Repositories/TagRepository.php similarity index 86% rename from lib/SP/Repositories/Tag/TagRepository.php rename to lib/SP/Infrastructure/Tag/Repositories/TagRepository.php index 78831fe4..951c2f5b 100644 --- a/lib/SP/Repositories/Tag/TagRepository.php +++ b/lib/SP/Infrastructure/Tag/Repositories/TagRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,32 +22,32 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\Tag; +namespace SP\Infrastructure\Tag\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemSearchData; use SP\DataModel\TagData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\Tag\In\TagRepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class TagRepository * - * @package SP\Repositories\Tag + * @package SP\Infrastructure\Common\Repositories\Tag */ -final class TagRepository extends Repository implements RepositoryInterface +final class TagRepository extends Repository implements TagRepositoryInterface { use RepositoryItemTrait; /** * Creates an item * - * @param TagData $itemData + * @param TagData $itemData * * @return int * @throws ConstraintException @@ -64,7 +64,7 @@ final class TagRepository extends Repository implements RepositoryInterface $queryData->setQuery('INSERT INTO Tag SET `name` = ?, `hash` = ?'); $queryData->setParams([ $itemData->getName(), - $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()) + $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), ]); $queryData->setOnErrorMessage(__u('Error while creating the tag')); @@ -74,7 +74,7 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on adding * - * @param TagData $itemData + * @param TagData $itemData * * @return bool * @throws ConstraintException @@ -86,7 +86,7 @@ final class TagRepository extends Repository implements RepositoryInterface $queryData->setQuery('SELECT id FROM Tag WHERE `name` = ? OR `hash` = ?'); $queryData->setParams([ $itemData->getName(), - $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()) + $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), ]); return $this->db->doSelect($queryData)->getNumRows() > 0; @@ -95,7 +95,7 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Updates an item * - * @param TagData $itemData + * @param TagData $itemData * * @return int * @throws ConstraintException @@ -113,7 +113,7 @@ final class TagRepository extends Repository implements RepositoryInterface $queryData->setParams([ $itemData->getName(), $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the tag')); @@ -123,7 +123,7 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on updating * - * @param TagData $itemData + * @param TagData $itemData * * @return bool * @throws ConstraintException @@ -136,7 +136,7 @@ final class TagRepository extends Repository implements RepositoryInterface $queryData->setParams([ $itemData->getName(), $this->makeItemHash($itemData->getName(), $this->db->getDbHandler()), - $itemData->getId() + $itemData->getId(), ]); return $this->db->doSelect($queryData)->getNumRows() > 0; @@ -145,7 +145,7 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -164,7 +164,7 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param string $name + * @param string $name * * @return QueryResult * @throws ConstraintException @@ -199,9 +199,9 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * - * @return \SP\Storage\Database\QueryResult + * @return \SP\Infrastructure\Database\QueryResult * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ @@ -212,7 +212,7 @@ final class TagRepository extends Repository implements RepositoryInterface } $query = /** @lang SQL */ - 'SELECT id, `name` FROM Tag WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + 'SELECT id, `name` FROM Tag WHERE id IN ('.$this->getParamsFromArray($ids).')'; $queryData = new QueryData(); $queryData->setMapClassName(TagData::class); @@ -225,7 +225,7 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -238,7 +238,7 @@ final class TagRepository extends Repository implements RepositoryInterface } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM Tag WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM Tag WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while removing the tags')); @@ -248,7 +248,7 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -285,7 +285,7 @@ final class TagRepository extends Repository implements RepositoryInterface /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -301,7 +301,7 @@ final class TagRepository extends Repository implements RepositoryInterface if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('name LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); } diff --git a/lib/SP/Repositories/UserGroup/UserGroupRepository.php b/lib/SP/Infrastructure/User/Repositories/UserGroupRepository.php similarity index 89% rename from lib/SP/Repositories/UserGroup/UserGroupRepository.php rename to lib/SP/Infrastructure/User/Repositories/UserGroupRepository.php index d8c384d8..2fd8a288 100644 --- a/lib/SP/Repositories/UserGroup/UserGroupRepository.php +++ b/lib/SP/Infrastructure/User/Repositories/UserGroupRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,33 +22,33 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\UserGroup; +namespace SP\Infrastructure\User\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserGroupData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\User\In\UserGroupRepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class UserGroupRepository * - * @package SP\Repositories\UserGroup + * @package SP\Infrastructure\User\Repositories */ -final class UserGroupRepository extends Repository implements RepositoryInterface +final class UserGroupRepository extends Repository implements UserGroupRepositoryInterface { use RepositoryItemTrait; /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -158,7 +158,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -177,7 +177,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Returns the item for given name * - * @param string $name + * @param string $name * * @return QueryResult * @throws ConstraintException @@ -212,9 +212,9 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * - * @return \SP\Storage\Database\QueryResult + * @return \SP\Infrastructure\Database\QueryResult * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ @@ -225,7 +225,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac } $query = /** @lang SQL */ - 'SELECT id, name, description FROM UserGroup WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + 'SELECT id, name, description FROM UserGroup WHERE id IN ('.$this->getParamsFromArray($ids).')'; $queryData = new QueryData(); $queryData->setMapClassName(UserGroupData::class); @@ -238,7 +238,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @return int * @throws ConstraintException @@ -251,7 +251,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM UserGroup WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM UserGroup WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); return $this->db->doQuery($queryData)->getAffectedNumRows(); @@ -260,7 +260,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -277,7 +277,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('name LIKE ? OR description LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); } @@ -293,7 +293,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Creates an item * - * @param UserGroupData $itemData + * @param UserGroupData $itemData * * @return int * @throws SPException @@ -320,7 +320,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Checks whether the item is duplicated on adding * - * @param UserGroupData $itemData + * @param UserGroupData $itemData * * @return bool * @throws ConstraintException @@ -338,7 +338,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Updates an item * - * @param UserGroupData $itemData + * @param UserGroupData $itemData * * @return int * @throws ConstraintException @@ -356,7 +356,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac $queryData->setParams([ $itemData->getName(), $itemData->getDescription(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the group')); @@ -366,7 +366,7 @@ final class UserGroupRepository extends Repository implements RepositoryInterfac /** * Checks whether the item is duplicated on updating * - * @param UserGroupData $itemData + * @param UserGroupData $itemData * * @return bool * @throws ConstraintException diff --git a/lib/SP/Repositories/User/UserPassRecoverRepository.php b/lib/SP/Infrastructure/User/Repositories/UserPassRecoverRepository.php similarity index 83% rename from lib/SP/Repositories/User/UserPassRecoverRepository.php rename to lib/SP/Infrastructure/User/Repositories/UserPassRecoverRepository.php index 38844476..38e1d122 100644 --- a/lib/SP/Repositories/User/UserPassRecoverRepository.php +++ b/lib/SP/Infrastructure/User/Repositories/UserPassRecoverRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,27 +22,28 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\User; +namespace SP\Infrastructure\User\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; -use SP\Repositories\Repository; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\User\In\UserPassRecoverRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class UserPassRecoverRepository * - * @package SP\Repositories\UserPassRecover + * @package SP\Infrastructure\Common\Repositories\UserPassRecover */ -final class UserPassRecoverRepository extends Repository +final class UserPassRecoverRepository extends Repository implements UserPassRecoverRepositoryInterface { /** * Checks recovery limit attempts by user's id and time * - * @param int $userId - * @param int $time + * @param int $userId + * @param int $time * * @return int * @throws ConstraintException @@ -67,8 +68,8 @@ final class UserPassRecoverRepository extends Repository /** * Adds a hash for a user's id * - * @param int $userId - * @param string $hash + * @param int $userId + * @param string $hash * * @return int * @throws ConstraintException @@ -94,8 +95,8 @@ final class UserPassRecoverRepository extends Repository /** * Toggles a hash used * - * @param string $hash - * @param int $time + * @param string $hash + * @param int $time * * @return int * @throws SPException @@ -120,8 +121,8 @@ final class UserPassRecoverRepository extends Repository /** * Comprobar el hash de recuperación de clave. * - * @param string $hash - * @param int $time + * @param string $hash + * @param int $time * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException diff --git a/lib/SP/Repositories/UserProfile/UserProfileRepository.php b/lib/SP/Infrastructure/User/Repositories/UserProfileRepository.php similarity index 86% rename from lib/SP/Repositories/UserProfile/UserProfileRepository.php rename to lib/SP/Infrastructure/User/Repositories/UserProfileRepository.php index 180c32fc..1fce5c50 100644 --- a/lib/SP/Repositories/UserProfile/UserProfileRepository.php +++ b/lib/SP/Infrastructure/User/Repositories/UserProfileRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,25 +22,25 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\UserProfile; +namespace SP\Infrastructure\User\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserProfileData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\User\In\UserProfileRepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class UserProfileRepository * - * @package SP\Repositories\UserProfile + * @package SP\Infrastructure\User\Repositories */ -final class UserProfileRepository extends Repository implements RepositoryInterface +final class UserProfileRepository extends Repository implements UserProfileRepositoryInterface { use RepositoryItemTrait; @@ -65,7 +65,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -102,7 +102,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException @@ -137,9 +137,9 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * - * @return \SP\Storage\Database\QueryResult + * @return \SP\Infrastructure\Database\QueryResult * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ @@ -150,7 +150,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf } $query = /** @lang SQL */ - 'SELECT id, `name` FROM UserProfile WHERE id IN (' . $this->getParamsFromArray($ids) . ')'; + 'SELECT id, `name` FROM UserProfile WHERE id IN ('.$this->getParamsFromArray($ids).')'; $queryData = new QueryData(); $queryData->setMapClassName(UserProfileData::class); @@ -163,7 +163,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Deletes all the items for given ids * - * @param int[] $ids + * @param int[] $ids * * @return int * @throws ConstraintException @@ -176,7 +176,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM UserProfile WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM UserProfile WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while removing the profiles')); @@ -186,7 +186,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws ConstraintException @@ -202,7 +202,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf if (!empty($itemSearchData->getSeachString())) { $queryData->setWhere('name LIKE ?'); - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); } @@ -217,7 +217,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Creates an item * - * @param UserProfileData $itemData + * @param UserProfileData $itemData * * @return int * @throws ConstraintException @@ -234,7 +234,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf $queryData->setQuery('INSERT INTO UserProfile SET `name` = ?, `profile` = ?'); $queryData->setParams([ $itemData->getName(), - serialize($itemData->getProfile()) + serialize($itemData->getProfile()), ]); $queryData->setOnErrorMessage(__u('Error while creating the profile')); @@ -244,7 +244,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Checks whether the item is duplicated on adding * - * @param UserProfileData $itemData + * @param UserProfileData $itemData * * @return bool * @throws ConstraintException @@ -262,12 +262,12 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Updates an item * - * @param UserProfileData $itemData + * @param UserProfileData $itemData * * @return int * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException - * @throws \SP\Repositories\DuplicatedItemException + * @throws \SP\Infrastructure\Common\Repositories\DuplicatedItemException */ public function update($itemData): int { @@ -283,7 +283,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf $queryData->setParams([ $itemData->getName(), serialize($itemData->getProfile()), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the profile')); @@ -293,7 +293,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf /** * Checks whether the item is duplicated on updating * - * @param UserProfileData $itemData + * @param UserProfileData $itemData * * @return bool * @throws ConstraintException @@ -310,7 +310,7 @@ final class UserProfileRepository extends Repository implements RepositoryInterf $queryData = new QueryData(); $queryData->setParams([ $itemData->getName(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setQuery($query); diff --git a/lib/SP/Repositories/User/UserRepository.php b/lib/SP/Infrastructure/User/Repositories/UserRepository.php similarity index 91% rename from lib/SP/Repositories/User/UserRepository.php rename to lib/SP/Infrastructure/User/Repositories/UserRepository.php index 768a72e9..348c9d07 100644 --- a/lib/SP/Repositories/User/UserRepository.php +++ b/lib/SP/Infrastructure/User/Repositories/UserRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,7 +22,7 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\User; +namespace SP\Infrastructure\User\Repositories; use RuntimeException; use SP\Core\Exceptions\ConstraintException; @@ -31,27 +31,27 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserData; use SP\DataModel\UserPreferencesData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryInterface; -use SP\Repositories\RepositoryItemTrait; -use SP\Services\User\UpdatePassRequest; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\User\In\UserRepositoryInterface; +use SP\Domain\User\Services\UpdatePassRequest; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class UserRepository * - * @package SP\Repositories\User + * @package SP\Infrastructure\User\Repositories */ -final class UserRepository extends Repository implements RepositoryInterface +final class UserRepository extends Repository implements UserRepositoryInterface { use RepositoryItemTrait; /** * Updates an item * - * @param UserData $itemData + * @param UserData $itemData * * @return int * @throws ConstraintException @@ -96,7 +96,7 @@ final class UserRepository extends Repository implements RepositoryInterface $itemData->isDisabled(), $itemData->isChangePass(), $itemData->isLdap(), - $itemData->getId() + $itemData->getId(), ]); $queryData->setOnErrorMessage(__u('Error while updating the user')); @@ -106,7 +106,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on updating * - * @param UserData $itemData + * @param UserData $itemData * * @return bool * @throws ConstraintException @@ -127,7 +127,7 @@ final class UserRepository extends Repository implements RepositoryInterface $itemData->getId(), $itemData->getLogin(), $itemData->getSsoLogin(), - $itemData->getEmail() + $itemData->getEmail(), ]); return $this->db->doSelect($queryData)->getNumRows() > 0; @@ -136,18 +136,17 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Updates an user's pass * - * @param int $id - * @param UpdatePassRequest $passRequest + * @param int $id + * @param UpdatePassRequest $passRequest * * @return int * @throws ConstraintException * @throws QueryException */ public function updatePassById( - int $id, + int $id, UpdatePassRequest $passRequest - ): int - { + ): int { $query = /** @lang SQL */ 'UPDATE User SET pass = ?, @@ -164,7 +163,7 @@ final class UserRepository extends Repository implements RepositoryInterface $passRequest->getPass(), (int)$passRequest->getisChangePass(), (int)$passRequest->getisChangedPass(), - $id + $id, ]); $queryData->setOnErrorMessage(__u('Error while updating the password')); @@ -174,7 +173,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Deletes an item * - * @param int $id + * @param int $id * * @return int * @throws \SP\Core\Exceptions\ConstraintException @@ -193,7 +192,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Returns the item for given id * - * @param int $id + * @param int $id * * @return QueryResult * @throws QueryException @@ -286,9 +285,9 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Returns all the items for given ids * - * @param array $ids + * @param array $ids * - * @return \SP\Storage\Database\QueryResult + * @return \SP\Infrastructure\Database\QueryResult * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ @@ -326,7 +325,7 @@ final class UserRepository extends Repository implements RepositoryInterface U.isMigrate FROM User U INNER JOIN UserGroup UG ON U.userGroupId = UG.id - WHERE U.id IN (' . $this->getParamsFromArray($ids) . ')'; + WHERE U.id IN ('.$this->getParamsFromArray($ids).')'; $queryData = new QueryData(); $queryData->setMapClassName(UserData::class); @@ -339,7 +338,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Deletes all the items for given ids * - * @param array $ids + * @param array $ids * * @return int * @throws ConstraintException @@ -352,7 +351,7 @@ final class UserRepository extends Repository implements RepositoryInterface } $queryData = new QueryData(); - $queryData->setQuery('DELETE FROM User WHERE id IN (' . $this->getParamsFromArray($ids) . ')'); + $queryData->setQuery('DELETE FROM User WHERE id IN ('.$this->getParamsFromArray($ids).')'); $queryData->setParams($ids); $queryData->setOnErrorMessage(__u('Error while deleting the users')); @@ -374,7 +373,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Searches for items by a given filter * - * @param ItemSearchData $itemSearchData + * @param ItemSearchData $itemSearchData * * @return QueryResult * @throws QueryException @@ -383,7 +382,8 @@ final class UserRepository extends Repository implements RepositoryInterface public function search(ItemSearchData $itemSearchData): QueryResult { $queryData = new QueryData(); - $queryData->setSelect('User.id, + $queryData->setSelect( + 'User.id, User.name, User.login, UserProfile.name AS userProfileName, @@ -392,10 +392,13 @@ final class UserRepository extends Repository implements RepositoryInterface User.isAdminAcc, User.isLdap, User.isDisabled, - User.isChangePass'); - $queryData->setFrom('User + User.isChangePass' + ); + $queryData->setFrom( + 'User INNER JOIN UserProfile ON User.userProfileId = UserProfile.id - INNER JOIN UserGroup ON User.userGroupId = UserGroup.id'); + INNER JOIN UserGroup ON User.userGroupId = UserGroup.id' + ); $queryData->setOrder('User.name'); $isAdminApp = $this->context->getUserData()->getIsAdminApp(); @@ -407,7 +410,7 @@ final class UserRepository extends Repository implements RepositoryInterface $queryData->setWhere('User.name LIKE ? OR User.login LIKE ? AND User.isAdminApp = 0'); } - $search = '%' . $itemSearchData->getSeachString() . '%'; + $search = '%'.$itemSearchData->getSeachString().'%'; $queryData->addParam($search); $queryData->addParam($search); } elseif (!$isAdminApp) { @@ -425,7 +428,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Creates an item * - * @param UserData $itemData + * @param UserData $itemData * * @return int * @throws SPException @@ -474,7 +477,7 @@ final class UserRepository extends Repository implements RepositoryInterface $itemData->isDisabled(), $itemData->isChangePass(), $itemData->isLdap(), - $itemData->getPass() + $itemData->getPass(), ]); $queryData->setOnErrorMessage(__u('Error while creating the user')); @@ -485,7 +488,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Checks whether the item is duplicated on adding * - * @param UserData $itemData + * @param UserData $itemData * * @return bool * @throws ConstraintException @@ -505,7 +508,7 @@ final class UserRepository extends Repository implements RepositoryInterface $queryData->setParams([ $itemData->getLogin(), $itemData->getSsoLogin(), - $itemData->getEmail() + $itemData->getEmail(), ]); return $this->db->doSelect($queryData)->getNumRows() > 0; @@ -591,20 +594,19 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Updates user's master password * - * @param int $id - * @param string $pass - * @param string $key + * @param int $id + * @param string $pass + * @param string $key * * @return int * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException */ public function updateMasterPassById( - int $id, + int $id, string $pass, string $key - ): int - { + ): int { $query = /** @lang SQL */ 'UPDATE User SET mPass = ?, @@ -640,7 +642,7 @@ final class UserRepository extends Repository implements RepositoryInterface } /** - * @param string $login + * @param string $login * * @return bool * @throws \SP\Core\Exceptions\ConstraintException @@ -656,7 +658,7 @@ final class UserRepository extends Repository implements RepositoryInterface } /** - * @param UserData $itemData + * @param UserData $itemData * * @return int * @throws ConstraintException @@ -682,7 +684,7 @@ final class UserRepository extends Repository implements RepositoryInterface $itemData->getEmail(), $itemData->isLdap(), $itemData->getLogin(), - $itemData->getLogin() + $itemData->getLogin(), ]); $queryData->setOnErrorMessage(__u('Error while updating the user')); @@ -692,18 +694,17 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Updates an user's pass * - * @param int $id - * @param UserPreferencesData $userPreferencesData + * @param int $id + * @param UserPreferencesData $userPreferencesData * * @return int * @throws ConstraintException * @throws QueryException */ public function updatePreferencesById( - int $id, + int $id, UserPreferencesData $userPreferencesData - ): int - { + ): int { $queryData = new QueryData(); $queryData->setQuery('UPDATE User SET preferences = ? WHERE id = ? LIMIT 1'); $queryData->setParams([serialize($userPreferencesData), $id]); @@ -715,7 +716,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Obtener el email de los usuarios de un grupo * - * @param int $groupId + * @param int $groupId * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -767,7 +768,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Return the email of the given user's id * - * @param int[] $ids + * @param int[] $ids * * @return QueryResult * @throws ConstraintException @@ -781,7 +782,7 @@ final class UserRepository extends Repository implements RepositoryInterface FROM User WHERE email IS NOT NULL AND isDisabled = 0 - AND id IN (' . $this->getParamsFromArray($ids) . ') + AND id IN ('.$this->getParamsFromArray($ids).') ORDER BY login'; $queryData = new QueryData(); @@ -794,7 +795,7 @@ final class UserRepository extends Repository implements RepositoryInterface /** * Returns the usage of the given user's id * - * @param int $id + * @param int $id * * @return QueryResult * @throws ConstraintException diff --git a/lib/SP/Repositories/UserGroup/UserToUserGroupRepository.php b/lib/SP/Infrastructure/User/Repositories/UserToUserGroupRepository.php similarity index 84% rename from lib/SP/Repositories/UserGroup/UserToUserGroupRepository.php rename to lib/SP/Infrastructure/User/Repositories/UserToUserGroupRepository.php index d2180881..efbb5f57 100644 --- a/lib/SP/Repositories/UserGroup/UserToUserGroupRepository.php +++ b/lib/SP/Infrastructure/User/Repositories/UserToUserGroupRepository.php @@ -4,7 +4,7 @@ * * @author nuxsmin * @link https://syspass.org - * @copyright 2012-2021, Rubén Domínguez nuxsmin@$syspass.org + * @copyright 2012-2022, Rubén Domínguez nuxsmin@$syspass.org * * This file is part of sysPass. * @@ -22,30 +22,31 @@ * along with sysPass. If not, see . */ -namespace SP\Repositories\UserGroup; +namespace SP\Infrastructure\User\Repositories; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\UserToUserGroupData; -use SP\Repositories\Repository; -use SP\Repositories\RepositoryItemTrait; -use SP\Storage\Database\QueryData; -use SP\Storage\Database\QueryResult; +use SP\Domain\User\In\UserToUserGroupRepositoryInterface; +use SP\Infrastructure\Common\Repositories\Repository; +use SP\Infrastructure\Common\Repositories\RepositoryItemTrait; +use SP\Infrastructure\Database\QueryData; +use SP\Infrastructure\Database\QueryResult; /** * Class UserToUserGroupRepository * - * @package SP\Repositories\UserGroup + * @package SP\Infrastructure\User\Repositories */ -final class UserToUserGroupRepository extends Repository +final class UserToUserGroupRepository extends Repository implements UserToUserGroupRepositoryInterface { use RepositoryItemTrait; /** * Checks whether the user is included in the group * - * @param int $groupId - * @param int $userId + * @param int $groupId + * @param int $userId * * @return bool * @throws ConstraintException @@ -63,7 +64,7 @@ final class UserToUserGroupRepository extends Repository /** * Returns the groups which the user belongs to * - * @param int $userId + * @param int $userId * * @return QueryResult * @throws \SP\Core\Exceptions\ConstraintException @@ -81,8 +82,8 @@ final class UserToUserGroupRepository extends Repository /** * Updates users from a group * - * @param int $id - * @param array $users + * @param int $id + * @param array $users * * @return int * @throws ConstraintException @@ -91,6 +92,7 @@ final class UserToUserGroupRepository extends Repository public function update(int $id, array $users): int { $this->delete($id); + return $this->add($id, $users); } @@ -116,8 +118,8 @@ final class UserToUserGroupRepository extends Repository /** * Adds users to a group * - * @param int $groupId - * @param array $users + * @param int $groupId + * @param array $users * * @return int * @throws ConstraintException @@ -130,7 +132,7 @@ final class UserToUserGroupRepository extends Repository } $query = /** @lang SQL */ - 'INSERT INTO UserToUserGroup (userId, userGroupId) VALUES ' . $this->getParamsFromArray($users, '(?,?)'); + 'INSERT INTO UserToUserGroup (userId, userGroupId) VALUES '.$this->getParamsFromArray($users, '(?,?)'); $queryData = new QueryData(); $queryData->setQuery($query); diff --git a/lib/SP/Mvc/Controller/ControllerTrait.php b/lib/SP/Mvc/Controller/ControllerTrait.php index 84843ead..9cf1ef6e 100644 --- a/lib/SP/Mvc/Controller/ControllerTrait.php +++ b/lib/SP/Mvc/Controller/ControllerTrait.php @@ -25,12 +25,12 @@ namespace SP\Mvc\Controller; use Closure; -use SP\Config\ConfigDataInterface; use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Exceptions\SPException; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Http\Json; use SP\Http\JsonResponse; -use SP\Http\Request; +use SP\Http\RequestInterface; use SP\Http\Uri; use SP\Util\Util; @@ -53,13 +53,20 @@ trait ControllerTrait return substr($class, strrpos($class, '\\') + 1, -strlen('Controller')) ?: ''; } + protected function getViewBaseName(): string + { + $parts = explode('\\', static::class); + + return strtolower($parts[count($parts) - 2]); + } + /** * Logout from current session * * @throws \JsonException */ protected function sessionLogout( - Request $request, + RequestInterface $request, Closure $onRedirect ): void { if ($request->isJson()) { @@ -110,7 +117,7 @@ trait ControllerTrait * @throws SPException * @deprecated */ - protected function checkSecurityToken(string $previousToken, Request $request): void + protected function checkSecurityToken(string $previousToken, RequestInterface $request): void { if (isset($this->configData) && $request->analyzeString('h') !== null diff --git a/lib/SP/Mvc/Controller/ExtensibleControllerInterface.php b/lib/SP/Mvc/Controller/ExtensibleControllerInterface.php index 1c3bbc9f..40918cc4 100644 --- a/lib/SP/Mvc/Controller/ExtensibleControllerInterface.php +++ b/lib/SP/Mvc/Controller/ExtensibleControllerInterface.php @@ -26,7 +26,7 @@ namespace SP\Mvc\Controller; use SP\Core\Events\EventDispatcherInterface; -use SP\Mvc\View\Template; +use SP\Mvc\View\TemplateInterface; /** * Interface ExtensibleController @@ -36,9 +36,9 @@ use SP\Mvc\View\Template; interface ExtensibleControllerInterface { /** - * @return Template + * @return TemplateInterface */ - public function getView(): Template; + public function getView(): TemplateInterface; /** * @return void diff --git a/lib/SP/Mvc/Controller/ItemTrait.php b/lib/SP/Mvc/Controller/ItemTrait.php index 741ac723..a6975e83 100644 --- a/lib/SP/Mvc/Controller/ItemTrait.php +++ b/lib/SP/Mvc/Controller/ItemTrait.php @@ -25,15 +25,13 @@ namespace SP\Mvc\Controller; use Defuse\Crypto\Exception\CryptoException; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; -use SP\Core\Bootstrap\BootstrapBase; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldData; use SP\DataModel\ItemSearchData; -use SP\Http\Request; -use SP\Services\CustomField\CustomFieldItem; -use SP\Services\CustomField\CustomFieldService; +use SP\Domain\CustomField\CustomFieldServiceInterface; +use SP\Domain\CustomField\Services\CustomFieldItem; +use SP\Domain\CustomField\Services\CustomFieldService; +use SP\Http\RequestInterface; use SP\Util\Filter; /** @@ -49,11 +47,13 @@ trait ItemTrait * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ - protected function getCustomFieldsForItem(int $moduleId, ?int $itemId): array - { - $customFieldService = BootstrapBase::getContainer()->get(CustomFieldService::class); + protected function getCustomFieldsForItem( + int $moduleId, + ?int $itemId, + CustomFieldServiceInterface $customFieldService + ): array { $customFields = []; foreach ($customFieldService->getForModuleAndItemId($moduleId, $itemId) as $item) { @@ -95,18 +95,19 @@ trait ItemTrait * * @param int $moduleId * @param int|int[] $itemId - * @param Request $request + * @param RequestInterface $request * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException * @throws \SP\Core\Exceptions\SPException - * @throws \SP\Repositories\NoSuchItemException - * @throws \SP\Services\ServiceException + * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException + * @throws \SP\Domain\Common\Services\ServiceException */ protected function addCustomFieldsForItem( int $moduleId, $itemId, - Request $request + RequestInterface $request, + CustomFieldServiceInterface $customFieldService ): void { $customFields = $request->analyzeArray( 'customfield', @@ -121,8 +122,6 @@ trait ItemTrait ); if (!empty($customFields)) { - $customFieldService = BootstrapBase::getContainer()->get(CustomFieldService::class); - try { foreach ($customFields as $id => $value) { $customFieldData = new CustomFieldData(); @@ -144,15 +143,17 @@ trait ItemTrait * * @param int $moduleId * @param int|int[] $itemId + * @param \SP\Domain\CustomField\CustomFieldServiceInterface $customFieldService * - * @throws SPException - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface + * @throws \SP\Core\Exceptions\ConstraintException + * @throws \SP\Core\Exceptions\QueryException + * @throws \SP\Core\Exceptions\SPException */ - protected function deleteCustomFieldsForItem(int $moduleId, $itemId): void - { - $customFieldService = BootstrapBase::getContainer()->get(CustomFieldService::class); - + protected function deleteCustomFieldsForItem( + int $moduleId, + $itemId, + CustomFieldServiceInterface $customFieldService + ): void { if (is_array($itemId)) { $customFieldService->deleteCustomFieldDataBatch($itemId, $moduleId); } else { @@ -165,7 +166,8 @@ trait ItemTrait * * @param int $moduleId * @param int|int[] $itemId - * @param Request $request + * @param RequestInterface $request + * @param \SP\Domain\CustomField\CustomFieldServiceInterface $customFieldService * * @throws \SP\Core\Exceptions\ConstraintException * @throws \SP\Core\Exceptions\QueryException @@ -174,7 +176,8 @@ trait ItemTrait protected function updateCustomFieldsForItem( int $moduleId, $itemId, - Request $request + RequestInterface $request, + CustomFieldServiceInterface $customFieldService ): void { $customFields = $request->analyzeArray( 'customfield', @@ -189,9 +192,6 @@ trait ItemTrait ); if (!empty($customFields)) { - $customFieldService = BootstrapBase::getContainer() - ->get(CustomFieldService::class); - try { foreach ($customFields as $id => $value) { $customFieldData = new CustomFieldData(); @@ -215,7 +215,7 @@ trait ItemTrait */ protected function getSearchData( int $limitCount, - Request $request + RequestInterface $request ): ItemSearchData { $itemSearchData = new ItemSearchData(); $itemSearchData->setSeachString($request->analyzeString('search')); @@ -225,7 +225,7 @@ trait ItemTrait return $itemSearchData; } - protected function getItemsIdFromRequest(Request $request): ?array + protected function getItemsIdFromRequest(RequestInterface $request): ?array { return $request->analyzeArray('items'); } diff --git a/lib/SP/Mvc/Controller/WebControllerHelper.php b/lib/SP/Mvc/Controller/WebControllerHelper.php new file mode 100644 index 00000000..0707b6a4 --- /dev/null +++ b/lib/SP/Mvc/Controller/WebControllerHelper.php @@ -0,0 +1,107 @@ +. + */ + +namespace SP\Mvc\Controller; + + +use Klein\Klein; +use SP\Core\Acl\Acl; +use SP\Core\PhpExtensionChecker; +use SP\Core\UI\ThemeInterface; +use SP\Http\RequestInterface; +use SP\Modules\Web\Controllers\Helpers\LayoutHelper; +use SP\Mvc\View\TemplateInterface; +use SP\Providers\Auth\Browser\BrowserAuthInterface; + +final class WebControllerHelper +{ + private ThemeInterface $theme; + private Klein $router; + private Acl $acl; + private RequestInterface $request; + private PhpExtensionChecker $extensionChecker; + private TemplateInterface $template; + private BrowserAuthInterface $browser; + private LayoutHelper $layoutHelper; + + public function __construct( + ThemeInterface $theme, + Klein $router, + Acl $acl, + RequestInterface $request, + PhpExtensionChecker $extensionChecker, + TemplateInterface $template, + BrowserAuthInterface $browser, + LayoutHelper $layoutHelper + ) { + $this->theme = $theme; + $this->router = $router; + $this->acl = $acl; + $this->request = $request; + $this->extensionChecker = $extensionChecker; + $this->template = $template; + $this->browser = $browser; + $this->layoutHelper = $layoutHelper; + } + + public function getTheme(): ThemeInterface + { + return $this->theme; + } + + public function getRouter(): Klein + { + return $this->router; + } + + public function getAcl(): Acl + { + return $this->acl; + } + + public function getRequest(): RequestInterface + { + return $this->request; + } + + public function getExtensionChecker(): PhpExtensionChecker + { + return $this->extensionChecker; + } + + public function getTemplate(): TemplateInterface + { + return $this->template; + } + + public function getBrowser(): BrowserAuthInterface + { + return $this->browser; + } + + public function getLayoutHelper(): LayoutHelper + { + return $this->layoutHelper; + } +} \ No newline at end of file diff --git a/lib/SP/Mvc/View/Components/DataTab.php b/lib/SP/Mvc/View/Components/DataTab.php index 839c19d3..533edf8c 100644 --- a/lib/SP/Mvc/View/Components/DataTab.php +++ b/lib/SP/Mvc/View/Components/DataTab.php @@ -25,7 +25,7 @@ namespace SP\Mvc\View\Components; use SP\Core\Exceptions\FileNotFoundException; -use SP\Mvc\View\Template; +use SP\Mvc\View\TemplateInterface; /** * Class DataTab @@ -34,10 +34,10 @@ use SP\Mvc\View\Template; */ final class DataTab { - protected string $title; - protected Template $template; + protected string $title; + protected TemplateInterface $template; - public function __construct(string $title, Template $template) + public function __construct(string $title, TemplateInterface $template) { $this->title = $title; $this->template = $template; diff --git a/lib/SP/Mvc/View/Template.php b/lib/SP/Mvc/View/Template.php index 5b0215c9..63e3f0db 100644 --- a/lib/SP/Mvc/View/Template.php +++ b/lib/SP/Mvc/View/Template.php @@ -40,11 +40,10 @@ use SP\Http\Uri; * publicada en http://www.sitepoint.com/flexible-view-manipulation-1/ * */ -final class Template +final class Template implements TemplateInterface { public const TEMPLATE_EXTENSION = '.inc'; public const PARTIALS_DIR = '_partials'; - public const LAYOUTS_DIR = '_layouts'; protected ThemeInterface $theme; /** @@ -74,14 +73,14 @@ final class Template * @param string $name Con el nombre del archivo de plantilla * @param string|null $base Directorio base para la plantilla */ - public function addContentTemplate( - string $name, - ?string $base = null - ): string { + public function addContentTemplate(string $name, ?string $base = null): string + { try { $template = $this->checkTemplate($name, $base); $this->setContentTemplate($template, $name); } catch (FileNotFoundException $e) { + logger($e->getMessage(), 'WARN'); + return ''; } @@ -106,9 +105,7 @@ final class Template if ($base === null) { $templateFile = $this->theme->getViewsPath().DIRECTORY_SEPARATOR.$template.self::TEMPLATE_EXTENSION; - } elseif (strpos($base, APP_ROOT) === 0 - && is_dir($base) - ) { + } elseif (strpos($base, APP_ROOT) === 0 && is_dir($base)) { $templateFile = $base.DIRECTORY_SEPARATOR.$template.self::TEMPLATE_EXTENSION; } else { $templateFile = $this->theme->getViewsPath().DIRECTORY_SEPARATOR.$base.DIRECTORY_SEPARATOR.$template @@ -140,7 +137,7 @@ final class Template /** * Removes a template from the stack */ - public function removeTemplate(string $name): Template + public function removeTemplate(string $name): TemplateInterface { unset($this->templates[$name]); @@ -150,7 +147,7 @@ final class Template /** * Removes a template from the stack */ - public function removeContentTemplate(string $name): Template + public function removeContentTemplate(string $name): TemplateInterface { unset($this->contentTemplates[$name]); @@ -386,7 +383,7 @@ final class Template /** * Reset de las plantillas añadidas */ - public function resetTemplates(): Template + public function resetTemplates(): TemplateInterface { $this->templates = []; @@ -396,7 +393,7 @@ final class Template /** * Reset de las plantillas añadidas */ - public function resetContentTemplates(): Template + public function resetContentTemplates(): TemplateInterface { $this->contentTemplates = []; @@ -444,7 +441,7 @@ final class Template /** * Assigns the current templates to contentTemplates */ - public function upgrade(): Template + public function upgrade(): TemplateInterface { if (count($this->templates) > 0) { $this->contentTemplates = $this->templates; @@ -464,11 +461,8 @@ final class Template * @param mixed $value valor de la variable * @param string|null $scope string ámbito de la variable */ - public function assign( - string $name, - $value = '', - ?string $scope = null - ): void { + public function assign(string $name, $value = '', ?string $scope = null): void + { if (null !== $scope) { $name = $scope.'_'.$name; } diff --git a/lib/SP/Mvc/View/TemplateInterface.php b/lib/SP/Mvc/View/TemplateInterface.php new file mode 100644 index 00000000..790f767d --- /dev/null +++ b/lib/SP/Mvc/View/TemplateInterface.php @@ -0,0 +1,171 @@ +. + */ + +namespace SP\Mvc\View; + + +use SP\Core\Exceptions\FileNotFoundException; +use SP\Core\UI\ThemeInterface; + +/** + * Class Template + * + * A very basic template engine... + * + * Idea original de http://www.sitepoint.com/author/agervasio/ + * publicada en http://www.sitepoint.com/flexible-view-manipulation-1/ + * + */ +interface TemplateInterface +{ + /** + * Añadir una nueva plantilla al array de plantillas de la clase + * + * @param string $name Con el nombre del archivo de plantilla + * @param string|null $base Directorio base para la plantilla + */ + public function addContentTemplate(string $name, ?string $base = null): string; + + /** + * Removes a template from the stack + */ + public function removeTemplate(string $name): TemplateInterface; + + /** + * Removes a template from the stack + */ + public function removeContentTemplate(string $name): TemplateInterface; + + /** + * Removes a template from the stack + * + * @param string $src Source template + * @param string $dst Destination template + * @param string $base + * + * @return mixed|string + */ + public function replaceTemplate(string $src, string $dst, string $base); + + /** + * Add partial template + */ + public function addPartial(string $partial): void; + + /** + * Añadir una nueva plantilla al array de plantillas de la clase + * + * @param string $name Con el nombre del archivo de plantilla + * @param string|null $base Directorio base para la plantilla + * + * @return string + */ + public function addTemplate(string $name, ?string $base = null): string; + + /** + * Añadir una nueva plantilla dentro de una plantilla + * + * @param string $file Con el nombre del archivo de plantilla + * + * @return bool + */ + public function includePartial(string $file); + + /** + * Añadir una nueva plantilla dentro de una plantilla + * + * @param string $file Con el nombre del archivo de plantilla + * @param string|null $base Directorio base para la plantilla + * + * @return bool + */ + public function includeTemplate(string $file, ?string $base = null); + + /** + * Returns a variable value + */ + public function get(string $name); + + /** + * Mostrar la plantilla solicitada. + * La salida se almacena en buffer y se devuelve el contenido + * + * @return string Con el contenido del buffer de salida + * @throws FileNotFoundException + */ + public function render(): string; + + /** + * Anexar el valor de la variable al array de la misma en el array de variables + * + * @param string $name nombre de la variable + * @param mixed $value valor de la variable + * @param string|null $scope string ámbito de la variable + * @param int|null $index string índice del array + */ + public function append(string $name, $value, ?string $scope = null, int $index = null): void; + + /** + * Reset de las plantillas añadidas + */ + public function resetTemplates(): TemplateInterface; + + /** + * Reset de las plantillas añadidas + */ + public function resetContentTemplates(): TemplateInterface; + + public function getBase(): string; + + public function setBase(string $base): void; + + public function getTheme(): ThemeInterface; + + /** + * Dumps current stored vars + */ + public function dumpVars(); + + public function getContentTemplates(): array; + + public function hasContentTemplates(): bool; + + public function getTemplates(): array; + + /** + * Assigns the current templates to contentTemplates + */ + public function upgrade(): TemplateInterface; + + /** + * Crear la variable y asignarle un valor en el array de variables + * + * @param string $name nombre de la variable + * @param mixed $value valor de la variable + * @param string|null $scope string ámbito de la variable + */ + public function assign(string $name, $value = '', ?string $scope = null): void; + + public function isUpgraded(): bool; +} \ No newline at end of file diff --git a/lib/SP/Plugin/PluginBase.php b/lib/SP/Plugin/PluginBase.php index 7b99c891..36d447eb 100644 --- a/lib/SP/Plugin/PluginBase.php +++ b/lib/SP/Plugin/PluginBase.php @@ -29,8 +29,8 @@ use Psr\Container\ContainerInterface; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; -use SP\Services\Plugin\PluginService; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Plugin\Services\PluginService; /** * Class PluginBase diff --git a/lib/SP/Plugin/PluginManager.php b/lib/SP/Plugin/PluginManager.php index 6f19478d..7b64179b 100644 --- a/lib/SP/Plugin/PluginManager.php +++ b/lib/SP/Plugin/PluginManager.php @@ -33,11 +33,13 @@ use SP\Core\Events\EventMessage; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Plugin\PluginModel; -use SP\Services\Install\Installer; -use SP\Services\Plugin\PluginDataService; -use SP\Services\Plugin\PluginService; +use SP\Domain\Install\Services\Installer; +use SP\Domain\Plugin\PluginDataServiceInterface; +use SP\Domain\Plugin\PluginServiceInterface; +use SP\Domain\Plugin\Services\PluginDataService; +use SP\Domain\Plugin\Services\PluginService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Plugin\Repositories\PluginModel; use SP\Util\VersionUtil; /** @@ -45,7 +47,7 @@ use SP\Util\VersionUtil; * * @package SP\Plugin */ -final class PluginManager +class PluginManager { private static ?array $pluginsAvailable; private ?array $enabledPlugins = null; @@ -61,13 +63,13 @@ final class PluginManager /** * PluginManager constructor. * - * @param PluginService $pluginService - * @param PluginDataService $pluginDataService + * @param \SP\Domain\Plugin\PluginServiceInterface $pluginService + * @param PluginDataServiceInterface $pluginDataService * @param EventDispatcher $eventDispatcher */ public function __construct( - PluginService $pluginService, - PluginDataService $pluginDataService, + PluginServiceInterface $pluginService, + PluginDataServiceInterface $pluginDataService, EventDispatcher $eventDispatcher ) { $this->pluginService = $pluginService; diff --git a/lib/SP/Plugin/PluginOperation.php b/lib/SP/Plugin/PluginOperation.php index 209286e9..c08c7d4c 100644 --- a/lib/SP/Plugin/PluginOperation.php +++ b/lib/SP/Plugin/PluginOperation.php @@ -28,10 +28,11 @@ use Defuse\Crypto\Exception\CryptoException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Plugin\PluginDataModel; -use SP\Services\Plugin\PluginDataService; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Plugin\PluginDataServiceInterface; +use SP\Domain\Plugin\Services\PluginDataService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Plugin\Repositories\PluginDataModel; /** * Class PluginOperation @@ -46,11 +47,11 @@ final class PluginOperation /** * PluginOperation constructor. * - * @param PluginDataService $pluginDataService - * @param string $pluginName + * @param PluginDataServiceInterface $pluginDataService + * @param string $pluginName */ public function __construct( - PluginDataService $pluginDataService, + PluginDataServiceInterface $pluginDataService, string $pluginName ) { @@ -92,7 +93,7 @@ final class PluginOperation */ public function update(int $itemId, $data): int { - $itemData = new PluginDataModel(); + $itemData = new \SP\Infrastructure\Plugin\Repositories\PluginDataModel(); $itemData->setName($this->pluginName); $itemData->setItemId($itemId); $itemData->setData(serialize($data)); diff --git a/lib/SP/Providers/Acl/AclHandler.php b/lib/SP/Providers/Acl/AclHandler.php index 17c68e4e..465ed178 100644 --- a/lib/SP/Providers/Acl/AclHandler.php +++ b/lib/SP/Providers/Acl/AclHandler.php @@ -25,18 +25,17 @@ namespace SP\Providers\Acl; use Exception; -use SP\Config\Config; use SP\Core\Application; -use SP\Core\Context\ContextInterface; use SP\Core\Events\Event; -use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventReceiver; use SP\Core\Exceptions\SPException; +use SP\Domain\Account\Services\AccountAclService; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserProfileService; +use SP\Domain\User\UserGroupServiceInterface; +use SP\Domain\User\UserProfileServiceInterface; use SP\Providers\EventsTrait; use SP\Providers\Provider; -use SP\Services\Account\AccountAclService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserProfile\UserProfileService; use SplSubject; /** @@ -62,8 +61,8 @@ final class AclHandler extends Provider implements EventReceiver public function __construct( Application $application, - UserProfileService $userProfileService, - UserGroupService $userGroupService + UserProfileServiceInterface $userProfileService, + UserGroupServiceInterface $userGroupService ) { $this->userProfileService = $userProfileService; $this->userGroupService = $userGroupService; diff --git a/lib/SP/Providers/Auth/AuthDataBase.php b/lib/SP/Providers/Auth/AuthDataBase.php index d08edd39..c68eecad 100644 --- a/lib/SP/Providers/Auth/AuthDataBase.php +++ b/lib/SP/Providers/Auth/AuthDataBase.php @@ -42,7 +42,7 @@ abstract class AuthDataBase /** * @var bool */ - protected bool $authenticated; + protected ?bool $authenticated; /** * @var int */ @@ -69,7 +69,7 @@ abstract class AuthDataBase } /** - * @param string $name + * @param string $name */ public function setName(string $name) { @@ -85,7 +85,7 @@ abstract class AuthDataBase } /** - * @param string $email + * @param string $email */ public function setEmail(string $email): void { @@ -101,13 +101,13 @@ abstract class AuthDataBase } /** - * @param bool $authenticated + * @param bool $authenticated * * @return $this */ public function setAuthenticated(?bool $authenticated = null): AuthDataBase { - $this->authenticated = $authenticated !== null ? (bool)$authenticated : null; + $this->authenticated = $authenticated; return $this; } @@ -121,7 +121,7 @@ abstract class AuthDataBase } /** - * @param string $server + * @param string $server */ public function setServer(string $server) { @@ -137,7 +137,7 @@ abstract class AuthDataBase } /** - * @param int $statusCode + * @param int $statusCode */ public function setStatusCode(int $statusCode): void { @@ -157,7 +157,7 @@ abstract class AuthDataBase /** * Indica si es requerida para acceder a la aplicación * - * @param bool $authoritative + * @param bool $authoritative */ public function setAuthoritative(bool $authoritative): void { @@ -173,7 +173,7 @@ abstract class AuthDataBase } /** - * @param bool $failed + * @param bool $failed */ public function setFailed(bool $failed) { diff --git a/lib/SP/Providers/Auth/AuthProvider.php b/lib/SP/Providers/Auth/AuthProvider.php index 8ae2d79f..26c4fb5e 100644 --- a/lib/SP/Providers/Auth/AuthProvider.php +++ b/lib/SP/Providers/Auth/AuthProvider.php @@ -24,20 +24,14 @@ namespace SP\Providers\Auth; -use SP\Config\Config; use SP\Core\Application; -use SP\Core\Context\ContextInterface; -use SP\Core\Events\EventDispatcher; use SP\Core\Exceptions\SPException; -use SP\Core\Exceptions\ValidationException; use SP\DataModel\UserLoginData; -use SP\Providers\Auth\Browser\Browser; -use SP\Providers\Auth\Database\Database; -use SP\Providers\Auth\Ldap\Ldap; -use SP\Providers\Auth\Ldap\LdapAuth; -use SP\Providers\Auth\Ldap\LdapParams; +use SP\Domain\Auth\Services\AuthException; +use SP\Providers\Auth\Browser\BrowserAuthInterface; +use SP\Providers\Auth\Database\DatabaseAuthInterface; +use SP\Providers\Auth\Ldap\LdapAuthInterface; use SP\Providers\Provider; -use SP\Services\Auth\AuthException; defined('APP_ROOT') || die(); @@ -48,24 +42,23 @@ defined('APP_ROOT') || die(); * * @package SP\Providers\Auth */ -class AuthProvider extends Provider +class AuthProvider extends Provider implements AuthProviderInterface { /** * @var callable[] */ - protected array $auths = []; - protected Browser $browser; - protected Database $database; + protected array $auths = []; + protected DatabaseAuthInterface $databaseAuth; + protected ?BrowserAuthInterface $browserAuth = null; + protected ?LdapAuthInterface $ldapAuth = null; public function __construct( Application $application, - Browser $browser, - Database $database + DatabaseAuthInterface $databaseAuth ) { - $this->browser = $browser; - $this->database = $database; - parent::__construct($application); + + $this->databaseAuth = $databaseAuth; } /** @@ -99,58 +92,28 @@ class AuthProvider extends Provider { $configData = $this->config->getConfigData(); - if ($configData->isAuthBasicEnabled()) { + if ($this->browserAuth && $configData->isAuthBasicEnabled()) { $this->registerAuth( function (UserLoginData $userLoginData) { - $this->browser->authenticate($userLoginData); + $this->browserAuth->authenticate($userLoginData); }, 'authBrowser' ); } - if ($configData->isLdapEnabled()) { + if ($this->ldapAuth && $configData->isLdapEnabled()) { $this->registerAuth( - function (UserLoginData $userLoginData) use ($configData) { - $data = LdapParams::getServerAndPort($configData->getLdapServer()); + function (UserLoginData $userLoginData) { + $ldapAuthData = $this->ldapAuth->getLdapAuthData(); - if (count($data) === 0) { - throw new ValidationException(__u('Wrong LDAP parameters')); - } - - $ldapParams = new LdapParams(); - $ldapParams->setServer($data['server']); - $ldapParams->setPort($data['port'] ?? 389); - $ldapParams->setSearchBase($configData->getLdapBase()); - $ldapParams->setGroup($configData->getLdapGroup()); - $ldapParams->setBindDn($configData->getLdapBindUser()); - $ldapParams->setBindPass($configData->getLdapBindPass()); - $ldapParams->setType($configData->getLdapType()); - $ldapParams->setFilterUserObject($configData->getLdapFilterUserObject()); - $ldapParams->setFilterGroupObject($configData->getLdapFilterGroupObject()); - $ldapParams->setFilterUserAttributes($configData->getLdapFilterUserAttributes()); - $ldapParams->setFilterGroupAttributes($configData->getLdapFilterGroupAttributes()); - - // TODO: Use IoC?? - $ldapAuth = new LdapAuth( - Ldap::factory( - $ldapParams, - $this->eventDispatcher, - $configData->isDebug() - ), - $this->eventDispatcher, - $configData - ); - - $ldapAuthData = $ldapAuth->getLdapAuthData(); - - $ldapAuthData->setAuthenticated($ldapAuth->authenticate($userLoginData)); + $ldapAuthData->setAuthenticated($this->ldapAuth->authenticate($userLoginData)); if ($ldapAuthData->getAuthenticated()) { // Comprobamos si la cuenta está bloqueada o expirada if ($ldapAuthData->getExpire() > 0) { - $ldapAuthData->setStatusCode(LdapAuth::ACCOUNT_EXPIRED); + $ldapAuthData->setStatusCode(LdapAuthInterface::ACCOUNT_EXPIRED); } elseif (!$ldapAuthData->isInGroup()) { - $ldapAuthData->setStatusCode(LdapAuth::ACCOUNT_NO_GROUPS); + $ldapAuthData->setStatusCode(LdapAuthInterface::ACCOUNT_NO_GROUPS); } } @@ -162,7 +125,7 @@ class AuthProvider extends Provider $this->registerAuth( function (UserLoginData $userLoginData) { - return $this->database->authenticate($userLoginData); + return $this->databaseAuth->authenticate($userLoginData); }, 'authDatabase' ); @@ -188,4 +151,14 @@ class AuthProvider extends Provider $this->auths[$name] = $auth; } + + public function withLdapAuth(LdapAuthInterface $ldapAuth): void + { + $this->ldapAuth = $ldapAuth; + } + + public function withBrowserAuth(BrowserAuthInterface $browserAuth): void + { + $this->browserAuth = $browserAuth; + } } diff --git a/lib/SP/Providers/Auth/AuthProviderInterface.php b/lib/SP/Providers/Auth/AuthProviderInterface.php new file mode 100644 index 00000000..fb4390c7 --- /dev/null +++ b/lib/SP/Providers/Auth/AuthProviderInterface.php @@ -0,0 +1,61 @@ +. + */ + +namespace SP\Providers\Auth; + + +use SP\DataModel\UserLoginData; +use SP\Domain\Auth\Services\AuthException; +use SP\Providers\Auth\Browser\BrowserAuthInterface; +use SP\Providers\Auth\Ldap\LdapAuthInterface; + +/** + * Class Auth + * + * Esta clase es la encargada de realizar la autentificación de usuarios de sysPass. + * + * @package SP\Providers\Auth + */ +interface AuthProviderInterface +{ + /** + * Probar los métodos de autentificación + * + * @param UserLoginData $userLoginData + * + * @return false|AuthResult[] + */ + public function doAuth(UserLoginData $userLoginData); + + /** + * Auth initializer + * + * @throws AuthException + */ + public function initialize(): void; + + public function withLdapAuth(LdapAuthInterface $ldapAuth): void; + + public function withBrowserAuth(BrowserAuthInterface $browserAuth): void; +} \ No newline at end of file diff --git a/lib/SP/Providers/Auth/Browser/Browser.php b/lib/SP/Providers/Auth/Browser/BrowserAuth.php similarity index 85% rename from lib/SP/Providers/Auth/Browser/Browser.php rename to lib/SP/Providers/Auth/Browser/BrowserAuth.php index 89f7e69a..c2b89a54 100644 --- a/lib/SP/Providers/Auth/Browser/Browser.php +++ b/lib/SP/Providers/Auth/Browser/BrowserAuth.php @@ -24,10 +24,9 @@ namespace SP\Providers\Auth\Browser; -use SP\Config\ConfigDataInterface; use SP\DataModel\UserLoginData; -use SP\Http\Request; -use SP\Providers\Auth\AuthInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Http\RequestInterface; /** * Class Browser @@ -36,24 +35,12 @@ use SP\Providers\Auth\AuthInterface; * * @package SP\Providers\Auth\Browser */ -final class Browser implements AuthInterface +final class BrowserAuth implements BrowserAuthInterface { - /** - * @var ConfigDataInterface - */ private ConfigDataInterface $configData; - /** - * @var Request - */ - private Request $request; + private RequestInterface $request; - /** - * Browser constructor. - * - * @param ConfigDataInterface $configData - * @param Request $request - */ - public function __construct(ConfigDataInterface $configData, Request $request) + public function __construct(ConfigDataInterface $configData, RequestInterface $request) { $this->configData = $configData; $this->request = $request; @@ -62,7 +49,7 @@ final class Browser implements AuthInterface /** * Autentificar al usuario * - * @param UserLoginData $userLoginData Datos del usuario + * @param UserLoginData $userLoginData Datos del usuario * * @return BrowserAuthData */ @@ -71,8 +58,7 @@ final class Browser implements AuthInterface $browserAuthData = new BrowserAuthData(); $browserAuthData->setAuthoritative($this->isAuthGranted()); - if (!empty($userLoginData->getLoginUser()) - && !empty($userLoginData->getLoginPass())) { + if (!empty($userLoginData->getLoginUser()) && !empty($userLoginData->getLoginPass())) { return $browserAuthData->setAuthenticated($this->checkServerAuthUser($userLoginData->getLoginUser())); } @@ -85,6 +71,7 @@ final class Browser implements AuthInterface $userLoginData->setLoginPass($authPass); $browserAuthData->setName($authUser); + return $browserAuthData->setAuthenticated(true); } @@ -117,7 +104,7 @@ final class Browser implements AuthInterface $authUser = $this->getServerAuthUser(); if (!empty($domain) && !empty($authUser)) { - $login = $authUser . '@' . $domain; + $login = $authUser.'@'.$domain; } return $authUser === $login ?: null; diff --git a/lib/SP/Providers/Auth/Browser/BrowserAuthInterface.php b/lib/SP/Providers/Auth/Browser/BrowserAuthInterface.php new file mode 100644 index 00000000..55cb3f73 --- /dev/null +++ b/lib/SP/Providers/Auth/Browser/BrowserAuthInterface.php @@ -0,0 +1,54 @@ +. + */ + +namespace SP\Providers\Auth\Browser; + + +use SP\Providers\Auth\AuthInterface; + +/** + * Class Browser + * + * Autentificación basada en credenciales del navegador + * + * @package SP\Providers\Auth\Browser + */ +interface BrowserAuthInterface extends AuthInterface +{ + /** + * Comprobar si el usuario es autentificado por el servidor web + * + * @param $login string El login del usuario a comprobar + * + * @return bool|null + */ + public function checkServerAuthUser(string $login): ?bool; + + /** + * Devolver el nombre del usuario autentificado por el servidor web + * + * @return string + */ + public function getServerAuthUser(): ?string; +} \ No newline at end of file diff --git a/lib/SP/Providers/Auth/Database/Database.php b/lib/SP/Providers/Auth/Database/DatabaseAuth.php similarity index 61% rename from lib/SP/Providers/Auth/Database/Database.php rename to lib/SP/Providers/Auth/Database/DatabaseAuth.php index d878c3ae..0918e3d4 100644 --- a/lib/SP/Providers/Auth/Database/Database.php +++ b/lib/SP/Providers/Auth/Database/DatabaseAuth.php @@ -27,10 +27,11 @@ namespace SP\Providers\Auth\Database; use Exception; use SP\Core\Crypt\Hash; use SP\DataModel\UserLoginData; -use SP\Providers\Auth\AuthInterface; -use SP\Services\User\UserLoginResponse; -use SP\Services\User\UserPassService; -use SP\Services\User\UserService; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Domain\User\Services\UserPassService; +use SP\Domain\User\Services\UserService; +use SP\Domain\User\UserPassServiceInterface; +use SP\Domain\User\UserServiceInterface; /** * Class Database @@ -39,28 +40,19 @@ use SP\Services\User\UserService; * * @package SP\Providers\Auth\Database */ -final class Database implements AuthInterface +final class DatabaseAuth implements DatabaseAuthInterface { - /** - * @var UserLoginData $userLoginData - */ - protected UserLoginData $userLoginData; - /** - * @var UserService - */ - private UserService $userService; - /** - * @var UserPassService - */ - private UserPassService $userPassService; + private UserLoginData $userLoginData; + private UserServiceInterface $userService; + private UserPassService $userPassService; /** * Database constructor. * - * @param UserService $userService - * @param UserPassService $userPassService + * @param \SP\Domain\User\UserServiceInterface $userService + * @param \SP\Domain\User\UserPassServiceInterface $userPassService */ - public function __construct(UserService $userService, UserPassService $userPassService) + public function __construct(UserServiceInterface $userService, UserPassServiceInterface $userPassService) { $this->userService = $userService; $this->userPassService = $userPassService; @@ -70,7 +62,7 @@ final class Database implements AuthInterface /** * Autentificar al usuario * - * @param UserLoginData $userLoginData Datos del usuario + * @param UserLoginData $userLoginData Datos del usuario * * @return DatabaseAuthData */ @@ -106,14 +98,18 @@ final class Database implements AuthInterface protected function authUser(): bool { try { - $userLoginResponse = UserService::mapUserLoginResponse($this->userService->getByLogin($this->userLoginData->getLoginUser())); + $userLoginResponse = + UserService::mapUserLoginResponse($this->userService->getByLogin($this->userLoginData->getLoginUser())); $this->userLoginData->setUserLoginResponse($userLoginResponse); if ($userLoginResponse->getIsMigrate() && $this->checkMigrateUser($userLoginResponse) ) { - $this->userPassService->migrateUserPassById($userLoginResponse->getId(), $this->userLoginData->getLoginPass()); + $this->userPassService->migrateUserPassById( + $userLoginResponse->getId(), + $this->userLoginData->getLoginPass() + ); return true; } @@ -127,15 +123,20 @@ final class Database implements AuthInterface } /** - * @param UserLoginResponse $userLoginResponse + * @param UserLoginResponse $userLoginResponse * * @return bool */ protected function checkMigrateUser(UserLoginResponse $userLoginResponse): bool { - return ($userLoginResponse->getPass() === sha1($userLoginResponse->getHashSalt() . $this->userLoginData->getLoginPass()) - || $userLoginResponse->getPass() === md5($this->userLoginData->getLoginPass()) - || hash_equals($userLoginResponse->getPass(), crypt($this->userLoginData->getLoginPass(), $userLoginResponse->getHashSalt())) - || Hash::checkHashKey($this->userLoginData->getLoginPass(), $userLoginResponse->getPass())); + return ($userLoginResponse->getPass() === sha1( + $userLoginResponse->getHashSalt().$this->userLoginData->getLoginPass() + ) + || $userLoginResponse->getPass() === md5($this->userLoginData->getLoginPass()) + || hash_equals( + $userLoginResponse->getPass(), + crypt($this->userLoginData->getLoginPass(), $userLoginResponse->getHashSalt()) + ) + || Hash::checkHashKey($this->userLoginData->getLoginPass(), $userLoginResponse->getPass())); } } \ No newline at end of file diff --git a/lib/SP/Providers/Auth/Database/DatabaseAuthInterface.php b/lib/SP/Providers/Auth/Database/DatabaseAuthInterface.php new file mode 100644 index 00000000..e73166e0 --- /dev/null +++ b/lib/SP/Providers/Auth/Database/DatabaseAuthInterface.php @@ -0,0 +1,55 @@ +. + */ + +namespace SP\Providers\Auth\Database; + + +use SP\DataModel\UserLoginData; +use SP\Providers\Auth\AuthInterface; + +/** + * Class Database + * + * Autentificación basada en base de datos + * + * @package SP\Providers\Auth\Database + */ +interface DatabaseAuthInterface extends AuthInterface +{ + /** + * Autentificar al usuario + * + * @param UserLoginData $userLoginData Datos del usuario + * + * @return DatabaseAuthData + */ + public function authenticate(UserLoginData $userLoginData): DatabaseAuthData; + + /** + * Indica si es requerida para acceder a la aplicación + * + * @return boolean + */ + public function isAuthGranted(): bool; +} \ No newline at end of file diff --git a/lib/SP/Providers/Auth/Ldap/Ldap.php b/lib/SP/Providers/Auth/Ldap/Ldap.php index c0ea992a..a768d526 100644 --- a/lib/SP/Providers/Auth/Ldap/Ldap.php +++ b/lib/SP/Providers/Auth/Ldap/Ldap.php @@ -57,22 +57,21 @@ abstract class Ldap implements LdapInterface /** * LdapBase constructor. * - * @param LdapConnectionInterface $ldapConnection - * @param EventDispatcher $eventDispatcher - * - * @throws LdapException + * @param LdapConnectionInterface $ldapConnection + * @param \SP\Providers\Auth\Ldap\LdapActions $ldapActions + * @param EventDispatcher $eventDispatcher */ - public function __construct(LdapConnectionInterface $ldapConnection, EventDispatcher $eventDispatcher) - { + public function __construct( + LdapConnectionInterface $ldapConnection, + LdapActions $ldapActions, + EventDispatcher $eventDispatcher + ) { + $this->eventDispatcher = $eventDispatcher; + $this->ldapActions = $ldapActions; $this->ldapConnection = $ldapConnection; - $this->ldapParams = $ldapConnection->getLdapParams(); $this->server = $this->pickServer(); - $this->ldapConnection->setServer($this->server); - - $this->eventDispatcher = $eventDispatcher; - $this->ldapActions = new LdapActions($ldapConnection, $eventDispatcher); } /** @@ -83,27 +82,28 @@ abstract class Ldap implements LdapInterface abstract protected function pickServer(): string; /** - * @param LdapParams $ldapParams - * @param EventDispatcher $eventDispatcher - * @param bool $debug + * @param LdapParams $ldapParams + * @param EventDispatcher $eventDispatcher + * @param bool $debug * * @return LdapInterface * @throws LdapException */ public static function factory( - LdapParams $ldapParams, + LdapParams $ldapParams, EventDispatcher $eventDispatcher, - bool $debug - ): LdapInterface - { + bool $debug + ): LdapInterface { $ldapConnection = new LdapConnection($ldapParams, $eventDispatcher, $debug); $ldapConnection->checkConnection(); + $ldapActions = new LdapActions($ldapConnection, $eventDispatcher); + switch ($ldapParams->getType()) { case LdapTypeInterface::LDAP_STD: - return new LdapStd($ldapConnection, $eventDispatcher); + return new LdapStd($ldapConnection, $ldapActions, $eventDispatcher); case LdapTypeInterface::LDAP_ADS: - return new LdapMsAds($ldapConnection, $eventDispatcher); + return new LdapMsAds($ldapConnection, $ldapActions, $eventDispatcher); } throw new LdapException(__u('LDAP type not set')); @@ -129,8 +129,8 @@ abstract class Ldap implements LdapInterface } /** - * @param string|null $bindDn - * @param string|null $bindPass + * @param string|null $bindDn + * @param string|null $bindPass * * @return bool */ diff --git a/lib/SP/Providers/Auth/Ldap/LdapAuth.php b/lib/SP/Providers/Auth/Ldap/LdapAuth.php index 95f45b71..177b4934 100644 --- a/lib/SP/Providers/Auth/Ldap/LdapAuth.php +++ b/lib/SP/Providers/Auth/Ldap/LdapAuth.php @@ -24,57 +24,36 @@ namespace SP\Providers\Auth\Ldap; -use SP\Config\ConfigDataInterface; use SP\Core\Events\EventDispatcher; use SP\DataModel\UserLoginData; -use SP\Providers\Auth\AuthInterface; +use SP\Domain\Config\In\ConfigDataInterface; /** * Class LdapBase * * @package Auth\Ldap */ -final class LdapAuth implements AuthInterface +final class LdapAuth implements LdapAuthInterface { - public const ACCOUNT_EXPIRED = 701; - public const ACCOUNT_NO_GROUPS = 702; - - /** - * @var string - */ - protected string $userLogin; - /** - * @var LdapAuthData - */ - protected LdapAuthData $ldapAuthData; - /** - * @var EventDispatcher - */ - protected EventDispatcher $eventDispatcher; - /** - * @var string - */ - protected string $server; - /** - * @var LdapInterface - */ - private LdapInterface $ldap; - /** - * @var ConfigDataInterface - */ + protected string $userLogin; + protected LdapAuthData $ldapAuthData; + protected EventDispatcher $eventDispatcher; + protected string $server; + private LdapInterface $ldap; private ConfigDataInterface $configData; /** * LdapBase constructor. * - * @param LdapInterface $ldap - * @param EventDispatcher $eventDispatcher - * @param ConfigDataInterface $configData + * @param LdapInterface $ldap + * @param EventDispatcher $eventDispatcher + * @param \SP\Domain\Config\In\ConfigDataInterface $configData */ - public function __construct(LdapInterface $ldap, - EventDispatcher $eventDispatcher, - ConfigDataInterface $configData) - { + public function __construct( + LdapInterface $ldap, + EventDispatcher $eventDispatcher, + ConfigDataInterface $configData + ) { $this->ldap = $ldap; $this->eventDispatcher = $eventDispatcher; $this->configData = $configData; @@ -99,7 +78,7 @@ final class LdapAuth implements AuthInterface } /** - * @param string $userLogin + * @param string $userLogin */ public function setUserLogin(string $userLogin): void { @@ -109,7 +88,7 @@ final class LdapAuth implements AuthInterface /** * Autentificar al usuario * - * @param UserLoginData $userLoginData Datos del usuario + * @param UserLoginData $userLoginData Datos del usuario * * @return bool */ @@ -150,7 +129,7 @@ final class LdapAuth implements AuthInterface /** * Obtener los atributos del usuario. * - * @param string $userLogin + * @param string $userLogin * * @return LdapAuthData con los atributos disponibles y sus valores * @throws LdapException @@ -163,9 +142,11 @@ final class LdapAuth implements AuthInterface if (!empty($attributes->get('fullname'))) { $this->ldapAuthData->setName($attributes->get('fullname')); } else { - $name = trim($attributes->get('name', '') - . ' ' - . $attributes->get('sn', '')); + $name = trim( + $attributes->get('name', '') + .' ' + .$attributes->get('sn', '') + ); $this->ldapAuthData->setName($name); } diff --git a/lib/SP/Providers/Auth/Ldap/LdapAuthInterface.php b/lib/SP/Providers/Auth/Ldap/LdapAuthInterface.php new file mode 100644 index 00000000..8de21ac6 --- /dev/null +++ b/lib/SP/Providers/Auth/Ldap/LdapAuthInterface.php @@ -0,0 +1,64 @@ +. + */ + +namespace SP\Providers\Auth\Ldap; + + +use SP\Providers\Auth\AuthInterface; + +/** + * Class LdapBase + * + * @package Auth\Ldap + */ +interface LdapAuthInterface extends AuthInterface +{ + public const ACCOUNT_NO_GROUPS = 702; + public const ACCOUNT_EXPIRED = 701; + + /** + * @return LdapAuthData + */ + public function getLdapAuthData(): LdapAuthData; + + /** + * @return string + */ + public function getUserLogin(): ?string; + + /** + * @param string $userLogin + */ + public function setUserLogin(string $userLogin): void; + + /** + * Obtener los atributos del usuario. + * + * @param string $userLogin + * + * @return LdapAuthData con los atributos disponibles y sus valores + * @throws LdapException + */ + public function getAttributes(string $userLogin): LdapAuthData; +} \ No newline at end of file diff --git a/lib/SP/Providers/Auth/Ldap/LdapParams.php b/lib/SP/Providers/Auth/Ldap/LdapParams.php index 43efc5e1..7ec8f811 100644 --- a/lib/SP/Providers/Auth/Ldap/LdapParams.php +++ b/lib/SP/Providers/Auth/Ldap/LdapParams.php @@ -24,6 +24,9 @@ namespace SP\Providers\Auth\Ldap; +use SP\Core\Exceptions\ValidationException; +use SP\Domain\Config\In\ConfigDataInterface; + /** * Class LdapParams * @@ -82,6 +85,33 @@ final class LdapParams */ protected array $filterGroupAttributes; + /** + * @throws \SP\Core\Exceptions\ValidationException + */ + public static function getFrom(ConfigDataInterface $configData): LdapParams + { + $data = self::getServerAndPort($configData->getLdapServer()); + + if (count($data) === 0) { + throw new ValidationException(__u('Wrong LDAP parameters')); + } + + $ldapParams = new self(); + $ldapParams->setServer($data['server']); + $ldapParams->setPort($data['port'] ?? 389); + $ldapParams->setSearchBase($configData->getLdapBase()); + $ldapParams->setGroup($configData->getLdapGroup()); + $ldapParams->setBindDn($configData->getLdapBindUser()); + $ldapParams->setBindPass($configData->getLdapBindPass()); + $ldapParams->setType($configData->getLdapType()); + $ldapParams->setFilterUserObject($configData->getLdapFilterUserObject()); + $ldapParams->setFilterGroupObject($configData->getLdapFilterGroupObject()); + $ldapParams->setFilterUserAttributes($configData->getLdapFilterUserAttributes()); + $ldapParams->setFilterGroupAttributes($configData->getLdapFilterGroupAttributes()); + + return $ldapParams; + } + /** * Devolver el puerto del servidor si está establecido * @@ -92,7 +122,8 @@ final class LdapParams public static function getServerAndPort($server): array { return preg_match( - '#' . self::REGEX_SERVER . '#i', $server, + '#'.self::REGEX_SERVER.'#i', + $server, $matches ) ? $matches : []; } @@ -106,7 +137,7 @@ final class LdapParams } /** - * @param string|null $filterUserObject + * @param string|null $filterUserObject */ public function setFilterUserObject(?string $filterUserObject = null): void { @@ -124,7 +155,7 @@ final class LdapParams } /** - * @param string|null $filterGroupObject + * @param string|null $filterGroupObject */ public function setFilterGroupObject(?string $filterGroupObject = null): void { @@ -142,7 +173,7 @@ final class LdapParams } /** - * @param array|null $filterUserAttributes + * @param array|null $filterUserAttributes */ public function setFilterUserAttributes(?array $filterUserAttributes = null): void { @@ -158,7 +189,7 @@ final class LdapParams } /** - * @param array|null $filterGroupAttributes + * @param array|null $filterGroupAttributes */ public function setFilterGroupAttributes(?array $filterGroupAttributes = null): void { @@ -174,7 +205,7 @@ final class LdapParams } /** - * @param int $port + * @param int $port * * @return LdapParams */ @@ -194,13 +225,14 @@ final class LdapParams } /** - * @param string $searchBase + * @param string $searchBase * * @return LdapParams */ public function setSearchBase(string $searchBase): LdapParams { $this->searchBase = $searchBase; + return $this; } @@ -213,13 +245,14 @@ final class LdapParams } /** - * @param string $bindDn + * @param string $bindDn * * @return LdapParams */ public function setBindDn(string $bindDn): LdapParams { $this->bindDn = $bindDn; + return $this; } @@ -232,13 +265,14 @@ final class LdapParams } /** - * @param string $bindPass + * @param string $bindPass * * @return LdapParams */ public function setBindPass(string $bindPass): LdapParams { $this->bindPass = $bindPass; + return $this; } @@ -251,7 +285,7 @@ final class LdapParams } /** - * @param string $group + * @param string $group * * @return LdapParams */ @@ -271,7 +305,7 @@ final class LdapParams } /** - * @param string $server + * @param string $server * * @return LdapParams */ @@ -291,7 +325,7 @@ final class LdapParams } /** - * @param int $type + * @param int $type * * @return LdapParams */ @@ -311,7 +345,7 @@ final class LdapParams } /** - * @param bool $tlsEnabled + * @param bool $tlsEnabled * * @return LdapParams */ diff --git a/lib/SP/Providers/Log/DatabaseLogHandler.php b/lib/SP/Providers/Log/DatabaseLogHandler.php index 58c31908..393bbe3b 100644 --- a/lib/SP/Providers/Log/DatabaseLogHandler.php +++ b/lib/SP/Providers/Log/DatabaseLogHandler.php @@ -26,17 +26,17 @@ namespace SP\Providers\Log; use Exception; use SP\Core\Application; -use SP\Core\Context\ContextInterface; use SP\Core\Events\Event; -use SP\Core\Events\EventDispatcher; use SP\Core\Events\EventReceiver; use SP\Core\Exceptions\InvalidClassException; use SP\Core\Exceptions\SPException; use SP\Core\Language; +use SP\Core\LanguageInterface; use SP\DataModel\EventlogData; +use SP\Domain\Security\EventlogServiceInterface; +use SP\Domain\Security\Services\EventlogService; use SP\Providers\EventsTrait; use SP\Providers\Provider; -use SP\Services\EventLog\EventlogService; use SplSubject; /** @@ -54,10 +54,8 @@ final class DatabaseLogHandler extends Provider implements EventReceiver public function __construct( Application $application, - ContextInterface $context, - EventDispatcher $eventDispatcher, - EventlogService $eventlogService, - Language $language + EventlogServiceInterface $eventlogService, + LanguageInterface $language ) { $this->eventlogService = $eventlogService; $this->language = $language; diff --git a/lib/SP/Providers/Log/LoggerBase.php b/lib/SP/Providers/Log/LoggerBase.php index 9fb850d5..9fb058c9 100644 --- a/lib/SP/Providers/Log/LoggerBase.php +++ b/lib/SP/Providers/Log/LoggerBase.php @@ -31,7 +31,9 @@ use SP\Core\Events\Event; use SP\Core\Events\EventReceiver; use SP\Core\Exceptions\InvalidClassException; use SP\Core\Language; +use SP\Core\LanguageInterface; use SP\Http\Request; +use SP\Http\RequestInterface; use SP\Providers\EventsTrait; use SP\Providers\Provider; @@ -52,8 +54,8 @@ abstract class LoggerBase extends Provider implements EventReceiver public function __construct( Application $application, Logger $logger, - Language $language, - Request $request + LanguageInterface $language, + RequestInterface $request ) { $this->logger = $logger; $this->language = $language; diff --git a/lib/SP/Providers/Mail/MailHandler.php b/lib/SP/Providers/Mail/MailHandler.php index fe8f2596..3e02f800 100644 --- a/lib/SP/Providers/Mail/MailHandler.php +++ b/lib/SP/Providers/Mail/MailHandler.php @@ -30,10 +30,12 @@ use SP\Core\Events\Event; use SP\Core\Events\EventReceiver; use SP\Core\Messages\MailMessage; use SP\Core\Messages\TextFormatter; +use SP\Domain\Notification\MailServiceInterface; +use SP\Domain\Notification\Services\MailService; use SP\Http\Request; +use SP\Http\RequestInterface; use SP\Providers\EventsTrait; use SP\Providers\Provider; -use SP\Services\Mail\MailService; use SplSubject; /** @@ -72,8 +74,8 @@ final class MailHandler extends Provider implements EventReceiver public function __construct( Application $application, - MailService $mailService, - Request $request + MailServiceInterface $mailService, + RequestInterface $request ) { $this->mailService = $mailService; $this->request = $request; diff --git a/lib/SP/Providers/Mail/MailProvider.php b/lib/SP/Providers/Mail/MailProvider.php index 8e19cccb..43a182df 100644 --- a/lib/SP/Providers/Mail/MailProvider.php +++ b/lib/SP/Providers/Mail/MailProvider.php @@ -25,10 +25,11 @@ namespace SP\Providers\Mail; use Exception; -use PharIo\Manifest\Application; -use PHPMailer\PHPMailer\PHPMailer; use SP\Core\AppInfoInterface; +use SP\Core\Application; use SP\Core\Exceptions\SPException; +use SP\Domain\Providers\MailerInterface; +use SP\Domain\Providers\MailProviderInterface; use SP\Providers\Provider; /** @@ -36,57 +37,55 @@ use SP\Providers\Provider; * * @package SP\Providers\Mail */ -final class MailProvider extends Provider +final class MailProvider extends Provider implements MailProviderInterface { - private PHPMailer $mailer; - private bool $debug = false; + /** + * @var \SP\Domain\Providers\MailerInterface | \SP\Providers\Mail\PhpMailerWrapper + */ + private MailerInterface $mailer; + private bool $debug = false; public function __construct( Application $application, - PHPMailer $mailer + MailerInterface $mailer ) { - $this->mailer = $mailer; - parent::__construct($application); + + $this->mailer = $mailer; } /** * Inicializar la clase PHPMailer. * - * @param MailParams $mailParams - * - * @return PHPMailer * @throws MailProviderException */ - public function getMailer(MailParams $mailParams): PHPMailer + public function getMailerFrom(MailParams $mailParams): MailerInterface { $appName = AppInfoInterface::APP_NAME; + $mailer = $this->mailer->getMailer(); try { - $this->mailer->SMTPAutoTLS = false; - $this->mailer->isSMTP(); - $this->mailer->CharSet = 'utf-8'; - $this->mailer->Host = $mailParams->server; - $this->mailer->Port = $mailParams->port; + $mailer->set('SMTPAutoTLS', false); + $mailer->isSMTP(); + $mailer->set('CharSet', 'utf-8'); + $mailer->set('Host', $mailParams->server); + $mailer->set('Port', $mailParams->port); + $mailer->set('SMTPSecure', strtolower($mailParams->security)); if ($mailParams->mailAuthenabled) { - $this->mailer->SMTPAuth = true; - $this->mailer->Username = $mailParams->user; - $this->mailer->Password = $mailParams->pass; + $mailer->set('SMTPAuth', true); + $mailer->set('Username', $mailParams->user); + $mailer->set('Password', $mailParams->pass); } - $this->mailer->SMTPSecure = strtolower($mailParams->security); - if ($this->debug) { - $this->mailer->SMTPDebug = 2; - $this->mailer->Debugoutput = function ($str, $level) { - logger($str, strtoupper($level)); - }; + $mailer->set('SMTPDebug', 2); + $mailer->set('Debugoutput', static fn($str, $level) => logger($str, strtoupper($level))); } - $this->mailer->setFrom($mailParams->from, $appName); - $this->mailer->addReplyTo($mailParams->from, $appName); - $this->mailer->WordWrap = 100; + $mailer->setFrom($mailParams->from, $appName); + $mailer->addReplyTo($mailParams->from, $appName); + $mailer->set('WordWrap', 100); return $this->mailer; } catch (Exception $e) { @@ -113,7 +112,7 @@ final class MailProvider extends Provider /** * @param bool $debug */ - public function setDebug(bool $debug) + public function setDebug(bool $debug): void { $this->debug = $debug; } diff --git a/lib/SP/Providers/Mail/PhpMailerWrapper.php b/lib/SP/Providers/Mail/PhpMailerWrapper.php new file mode 100644 index 00000000..a30b1026 --- /dev/null +++ b/lib/SP/Providers/Mail/PhpMailerWrapper.php @@ -0,0 +1,99 @@ +. + */ + +namespace SP\Providers\Mail; + +use PHPMailer\PHPMailer\Exception; +use PHPMailer\PHPMailer\PHPMailer; +use SP\Domain\Providers\MailerInterface; + +/** + * A wrapper for PHPMailer + */ +final class PhpMailerWrapper implements MailerInterface +{ + private PHPMailer $mailer; + + public function __construct(PHPMailer $mailer) + { + $this->mailer = $mailer; + } + + public function isHtml(): MailerInterface + { + $this->mailer->isHTML(); + + return $this; + } + + /** + * @throws \SP\Providers\Mail\MailProviderException + */ + public function addAddress(string $address): MailerInterface + { + try { + $this->mailer->addAddress($address); + } catch (Exception $e) { + throw new MailProviderException($e); + } + + return $this; + } + + public function subject(string $subject): MailerInterface + { + $this->mailer->set('Subject', $subject); + + return $this; + } + + public function body(string $body): MailerInterface + { + $this->mailer->set('Body', $body); + + return $this; + } + + /** + * @throws \SP\Providers\Mail\MailProviderException + */ + public function send(): bool + { + try { + return $this->mailer->send(); + } catch (Exception $e) { + throw new MailProviderException($e); + } + } + + public function getMailer(): PHPMailer + { + return $this->mailer; + } + + public function getToAddresses(): array + { + return $this->mailer->getToAddresses(); + } +} \ No newline at end of file diff --git a/lib/SP/Providers/Notification/NotificationHandler.php b/lib/SP/Providers/Notification/NotificationHandler.php index 7c5307b5..d224273a 100644 --- a/lib/SP/Providers/Notification/NotificationHandler.php +++ b/lib/SP/Providers/Notification/NotificationHandler.php @@ -25,13 +25,14 @@ namespace SP\Providers\Notification; use Exception; -use PharIo\Manifest\Application; +use SP\Core\Application; use SP\Core\Events\Event; use SP\Core\Events\EventReceiver; use SP\DataModel\NotificationData; +use SP\Domain\Notification\NotificationServiceInterface; +use SP\Domain\Notification\Services\NotificationService; use SP\Providers\EventsTrait; use SP\Providers\Provider; -use SP\Services\Notification\NotificationService; use SplSubject; /** @@ -53,7 +54,7 @@ final class NotificationHandler extends Provider implements EventReceiver public function __construct( Application $application, - NotificationService $notificationService + NotificationServiceInterface $notificationService ) { $this->notificationService = $notificationService; diff --git a/lib/SP/Providers/Provider.php b/lib/SP/Providers/Provider.php index 0efdc0f7..e391bbb0 100644 --- a/lib/SP/Providers/Provider.php +++ b/lib/SP/Providers/Provider.php @@ -24,10 +24,10 @@ namespace SP\Providers; -use SP\Config\Config; use SP\Core\Application; use SP\Core\Context\ContextInterface; use SP\Core\Events\EventDispatcher; +use SP\Domain\Config\Services\ConfigFileService; /** * Class Service @@ -36,8 +36,8 @@ use SP\Core\Events\EventDispatcher; */ abstract class Provider implements ProviderInterface { - protected Config $config; - protected ContextInterface $context; + protected ConfigFileService $config; + protected ContextInterface $context; protected EventDispatcher $eventDispatcher; protected bool $initialized = false; diff --git a/lib/SP/Services/Account/AccountRequest.php b/lib/SP/Services/Account/AccountRequest.php deleted file mode 100644 index 791af65a..00000000 --- a/lib/SP/Services/Account/AccountRequest.php +++ /dev/null @@ -1,61 +0,0 @@ -. - */ - -namespace SP\Services\Account; - -/** - * Class AccountRequest - * - * @package SP\Account - */ -final class AccountRequest -{ - public ?int $id = null; - public ?string $name = null; - public ?int $clientId = null; - public ?int $categoryId = null; - public ?string $login = null; - public ?string $url = null; - public ?string $notes = null; - public ?int $userId = null; - public ?int $userGroupId = null; - public ?int $userEditId = null; - public ?int $otherUserEdit = null; - public ?int $otherUserGroupEdit = null; - public ?string $pass = null; - public ?string $key = null; - public ?int $isPrivate = null; - public ?int $isPrivateGroup = null; - public ?int $passDateChange = null; - public ?int $parentId = null; - public ?array $usersView = null; - public ?array $usersEdit = null; - public ?array $userGroupsView = null; - public ?array $userGroupsEdit = null; - public ?array $tags = null; - public ?bool $changeOwner = false; - public ?bool $changeUserGroup = false; - public ?bool $changePermissions = false; - public ?bool $updateTags = false; -} \ No newline at end of file diff --git a/lib/SP/Services/Upgrade/UpgradeAppService.php b/lib/SP/Services/Upgrade/UpgradeAppService.php deleted file mode 100644 index 87c33ac1..00000000 --- a/lib/SP/Services/Upgrade/UpgradeAppService.php +++ /dev/null @@ -1,141 +0,0 @@ -. - */ - -namespace SP\Services\Upgrade; - -use Exception; -use SP\Config\ConfigDataInterface; -use SP\Core\Events\Event; -use SP\Core\Events\EventMessage; -use SP\Core\Exceptions\SPException; -use SP\Providers\Log\FileLogHandler; -use SP\Services\Service; -use SP\Storage\File\FileException; -use SP\Util\VersionUtil; - -/** - * Class UpgradeAppService - * - * @package SP\Services\Upgrade - */ -final class UpgradeAppService extends Service implements UpgradeInterface -{ - private const UPGRADES = [ - '300.18010101', - '300.18072901', - '300.18072902', - '310.19012201', - '310.19042701' - ]; - - public static function needsUpgrade(string $version): bool - { - return empty($version) - || VersionUtil::checkVersion($version, self::UPGRADES); - } - - /** - * @throws UpgradeException - * @throws FileException - */ - public function upgrade( - string $version, - ConfigDataInterface $configData - ): void - { - $this->eventDispatcher->notifyEvent( - 'upgrade.app.start', - new Event($this, EventMessage::factory() - ->addDescription(__u('Update Application'))) - ); - - foreach (self::UPGRADES as $appVersion) { - if (VersionUtil::checkVersion($version, $appVersion)) { - if ($this->applyUpgrade($appVersion) === false) { - throw new UpgradeException( - __u('Error while applying the application update'), - SPException::CRITICAL, - __u('Please, check the event log for more details') - ); - } - - logger('APP Upgrade: ' . $appVersion); - - $configData->setAppVersion($appVersion); - - $this->config->saveConfig($configData, false); - } - } - - $this->eventDispatcher->notifyEvent( - 'upgrade.app.end', - new Event($this, EventMessage::factory() - ->addDescription(__u('Update Application'))) - ); - } - - /** - * Actualizaciones de la aplicación - */ - private function applyUpgrade(string $version): bool - { - try { - switch ($version) { - case '300.18010101': - $this->dic->get(UpgradeCustomFieldDefinition::class) - ->upgrade_300_18010101(); - $this->dic->get(UpgradePublicLink::class) - ->upgrade_300_18010101(); - return true; - case '300.18072901': - $this->dic->get(UpgradeCustomFieldDefinition::class) - ->upgrade_300_18072901(); - $this->dic->get(UpgradeAuthToken::class) - ->upgrade_300_18072901(); - return true; - case '300.18072902': - $this->dic->get(UpgradeCustomFieldData::class) - ->upgrade_300_18072902(); - return true; - case '310.19012201': - $this->dic->get(UpgradePlugin::class) - ->upgrade_310_19012201(); - return true; - case '310.19042701': - $this->dic->get(UpgradeCustomFieldDefinition::class) - ->upgrade_310_19042701(); - return true; - } - } catch (Exception $e) { - processException($e); - } - - return false; - } - - protected function initialize(): void - { - $this->eventDispatcher->attach($this->dic->get(FileLogHandler::class)); - } -} \ No newline at end of file diff --git a/lib/SP/Util/ArrayUtil.php b/lib/SP/Util/ArrayUtil.php index 0df7de89..da05a85e 100644 --- a/lib/SP/Util/ArrayUtil.php +++ b/lib/SP/Util/ArrayUtil.php @@ -34,25 +34,17 @@ final class ArrayUtil /** * Buscar un objeto en un array según el valor de una propiedad * - * @param array $array - * @param string $property Nombre de la propiedad - * @param string $value Valor de la propiedad - * @param null $default Valor por defecto + * @param array $array + * @param string $property Nombre de la propiedad + * @param string $value Valor de la propiedad + * @param null $default Valor por defecto * * @return false|object */ - public static function searchInObject( - array $array, - string $property, - string $value, - $default = null - ) + public static function searchInObject(array $array, string $property, string $value, $default = null) { foreach ($array as $object) { - if (is_object($object) - && isset($object->$property) - && $value == $object->$property - ) { + if (is_object($object) && isset($object->$property) && $value == $object->$property) { return $object; } } @@ -63,17 +55,13 @@ final class ArrayUtil /** * Comprobar si un valor existe en un array de objetos * - * @param array $objectArray - * @param string $method - * @param mixed $value + * @param array $objectArray + * @param string $method + * @param mixed $value * * @return bool */ - public static function checkInObjectArrayMethod( - array $objectArray, - string $method, - $value - ): bool + public static function checkInObjectArrayMethod(array $objectArray, string $method, $value): bool { foreach ($objectArray as $object) { if (is_callable([$object, $method]) && $object->$method() === $value) { @@ -87,21 +75,14 @@ final class ArrayUtil /** * Comprobar si un valor existe en un array de objetos */ - public static function checkInObjectArray( - array $objectArray, - string $property, - $value - ): bool + public static function checkInObjectArray(array $objectArray, string $property, $value): bool { if (count($objectArray) === 0) { return false; } foreach ($objectArray as $object) { - if (is_object($object) - && isset($object->$property) - && $object->$property == $value - ) { + if (is_object($object) && isset($object->$property) && $object->$property == $value) { return true; } } diff --git a/lib/SP/Util/Checks.php b/lib/SP/Util/Checks.php index 1e605bab..2670f01a 100644 --- a/lib/SP/Util/Checks.php +++ b/lib/SP/Util/Checks.php @@ -31,6 +31,9 @@ namespace SP\Util; */ final class Checks { + private const MIN_PHP_VERSION = 70400; + private const MAX_PHP_VERSION = 81000; + /** * Comprobar si sysPass se ejecuta en W$indows. */ @@ -44,7 +47,6 @@ final class Checks */ public static function checkPhpVersion(): bool { - return PHP_VERSION_ID >= 70400 - && PHP_VERSION_ID < 81000; + return PHP_VERSION_ID >= self::MIN_PHP_VERSION && PHP_VERSION_ID < self::MAX_PHP_VERSION; } } diff --git a/lib/SP/Util/Connection.php b/lib/SP/Util/Connection.php index 00cb389e..0f079446 100644 --- a/lib/SP/Util/Connection.php +++ b/lib/SP/Util/Connection.php @@ -39,8 +39,8 @@ final class Connection implements ConnectionInterface protected $socket; protected string $host; - protected int $port; - protected int $errorno = 0; + protected int $port; + protected int $errorno = 0; protected string $errorstr = ''; /** @@ -70,10 +70,7 @@ final class Connection implements ConnectionInterface } if ($this->socket === false) { - throw new SPException( - $this->getSocketError(), - SPException::WARNING - ); + throw new SPException($this->getSocketError(), SPException::WARNING); } stream_set_timeout($this->socket, self::SOCKET_TIMEOUT); @@ -89,7 +86,7 @@ final class Connection implements ConnectionInterface private function getUDPSocket() { return stream_socket_client( - 'udp://' . $this->host . ':' . $this->port, + 'udp://'.$this->host.':'.$this->port, $this->errorno, $this->errorstr, self::SOCKET_TIMEOUT @@ -104,7 +101,7 @@ final class Connection implements ConnectionInterface private function getTCPSocket() { return stream_socket_client( - 'tcp://' . $this->host . ':' . $this->port, + 'tcp://'.$this->host.':'.$this->port, $this->errorno, $this->errorstr, self::SOCKET_TIMEOUT @@ -135,20 +132,13 @@ final class Connection implements ConnectionInterface public function send(string $message): int { if (!is_resource($this->socket)) { - throw new SPException( - __u('Socket not initialized'), - SPException::WARNING - ); + throw new SPException(__u('Socket not initialized'), SPException::WARNING); } $nBytes = @fwrite($this->socket, $message); if ($nBytes === false) { - throw new SPException( - __u('Error while sending the data'), - SPException::WARNING, - $this->getSocketError() - ); + throw new SPException(__u('Error while sending the data'), SPException::WARNING, $this->getSocketError()); } return $nBytes; diff --git a/lib/SP/Util/ConnectionInterface.php b/lib/SP/Util/ConnectionInterface.php index 21b442c5..93f36753 100644 --- a/lib/SP/Util/ConnectionInterface.php +++ b/lib/SP/Util/ConnectionInterface.php @@ -31,8 +31,8 @@ namespace SP\Util; */ interface ConnectionInterface { - public const TYPE_TCP = 1; - public const TYPE_UDP = 2; + public const TYPE_TCP = 1; + public const TYPE_UDP = 2; public const SOCKET_TIMEOUT = 10; /** diff --git a/lib/SP/Util/DateUtil.php b/lib/SP/Util/DateUtil.php index eae77309..9fa07677 100644 --- a/lib/SP/Util/DateUtil.php +++ b/lib/SP/Util/DateUtil.php @@ -34,8 +34,8 @@ final class DateUtil /** * Returns date string from UNIX timestamp * - * @param int|string $date - * @param string $format + * @param int|string $date + * @param string $format * * @return false|string */ diff --git a/lib/SP/Util/ErrorUtil.php b/lib/SP/Util/ErrorUtil.php index 8dc3ed41..143fd1cd 100644 --- a/lib/SP/Util/ErrorUtil.php +++ b/lib/SP/Util/ErrorUtil.php @@ -29,8 +29,9 @@ use SP\Core\Acl\AccountPermissionException; use SP\Core\Acl\UnauthorizedPageException; use SP\Core\Exceptions\FileNotFoundException; use SP\Core\Exceptions\SPException; +use SP\Domain\User\Services\UpdatedMasterPassException; use SP\Mvc\View\Template; -use SP\Services\User\UpdatedMasterPassException; +use SP\Mvc\View\TemplateInterface; /** * Class ErrorUtil @@ -42,28 +43,27 @@ final class ErrorUtil /** * Constantes de errores */ - public const ERR_UNAVAILABLE = 0; - public const ERR_ACCOUNT_NO_PERMISSION = 1; - public const ERR_PAGE_NO_PERMISSION = 2; - public const ERR_UPDATE_MPASS = 3; + public const ERR_UNAVAILABLE = 0; + public const ERR_ACCOUNT_NO_PERMISSION = 1; + public const ERR_PAGE_NO_PERMISSION = 2; + public const ERR_UPDATE_MPASS = 3; public const ERR_OPERATION_NO_PERMISSION = 4; - public const ERR_EXCEPTION = 5; + public const ERR_EXCEPTION = 5; /** * Establecer la plantilla de error con el código indicado. * - * @param Template $view - * @param Exception $e - * @param string|null $replace Template replacement - * @param bool $render + * @param TemplateInterface $view + * @param Exception $e + * @param string|null $replace Template replacement + * @param bool $render */ public static function showExceptionInView( - Template $view, + TemplateInterface $view, Exception $e, - ?string $replace = null, - bool $render = true - ): void - { + ?string $replace = null, + bool $render = true + ): void { switch (get_class($e)) { case UpdatedMasterPassException::class: self::showErrorInView($view, self::ERR_UPDATE_MPASS, $render, $replace); @@ -82,28 +82,29 @@ final class ErrorUtil /** * Establecer la plantilla de error con el código indicado. * - * @param Template $view - * @param int $type int con el tipo de error - * @param bool $render - * @param string|null $replace + * @param TemplateInterface $view + * @param int $type int con el tipo de error + * @param bool $render + * @param string|null $replace */ public static function showErrorInView( - Template $view, - int $type, - bool $render = true, - ?string $replace = null - ): void - { + TemplateInterface $view, + int $type, + bool $render = true, + ?string $replace = null + ): void { self::addErrorTemplate($view, $replace); $error = self::getErrorTypes($type); - $view->append('errors', + $view->append( + 'errors', [ - 'type' => SPException::WARNING, + 'type' => SPException::WARNING, 'description' => $error['txt'], - 'hint' => $error['hint'] - ]); + 'hint' => $error['hint'], + ] + ); if ($render) { try { @@ -116,10 +117,7 @@ final class ErrorUtil } } - private static function addErrorTemplate( - Template $view, - string $replace = null - ): void + private static function addErrorTemplate(TemplateInterface $view, string $replace = null): void { if ($replace === null) { $view->resetTemplates(); @@ -147,35 +145,35 @@ final class ErrorUtil protected static function getErrorTypes(int $type): array { $errorTypes = [ - self::ERR_UNAVAILABLE => [ - 'txt' => __('Option unavailable'), - 'hint' => __('Please contact to the administrator') + self::ERR_UNAVAILABLE => [ + 'txt' => __('Option unavailable'), + 'hint' => __('Please contact to the administrator'), ], - self::ERR_ACCOUNT_NO_PERMISSION => [ - 'txt' => __('You don\'t have permission to access this account'), - 'hint' => __('Please contact to the administrator') + self::ERR_ACCOUNT_NO_PERMISSION => [ + 'txt' => __('You don\'t have permission to access this account'), + 'hint' => __('Please contact to the administrator'), ], - self::ERR_PAGE_NO_PERMISSION => [ - 'txt' => __('You don\'t have permission to access this page'), - 'hint' => __('Please contact to the administrator') + self::ERR_PAGE_NO_PERMISSION => [ + 'txt' => __('You don\'t have permission to access this page'), + 'hint' => __('Please contact to the administrator'), ], self::ERR_OPERATION_NO_PERMISSION => [ - 'txt' => __('You don\'t have permission to do this operation'), - 'hint' => __('Please contact to the administrator') + 'txt' => __('You don\'t have permission to do this operation'), + 'hint' => __('Please contact to the administrator'), ], - self::ERR_UPDATE_MPASS => [ - 'txt' => __('Master password updated'), - 'hint' => __('Please, restart the session for update it') + self::ERR_UPDATE_MPASS => [ + 'txt' => __('Master password updated'), + 'hint' => __('Please, restart the session for update it'), + ], + self::ERR_EXCEPTION => [ + 'txt' => __('An exception occured'), + 'hint' => __('Please contact to the administrator'), ], - self::ERR_EXCEPTION => [ - 'txt' => __('An exception occured'), - 'hint' => __('Please contact to the administrator') - ] ]; return $errorTypes[$type] ?? [ - 'txt' => __('An exception occured'), - 'hint' => __('Please contact to the administrator') + 'txt' => __('An exception occured'), + 'hint' => __('Please contact to the administrator'), ]; } } \ No newline at end of file diff --git a/lib/SP/Util/FileUtil.php b/lib/SP/Util/FileUtil.php index 720b41e1..6df0aeb5 100644 --- a/lib/SP/Util/FileUtil.php +++ b/lib/SP/Util/FileUtil.php @@ -41,7 +41,7 @@ final class FileUtil 'image/jpeg', 'image/png', 'image/bmp', - 'image/gif' + 'image/gif', ]; /** @@ -59,7 +59,8 @@ final class FileUtil $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir, - FilesystemIterator::SKIP_DOTS), + FilesystemIterator::SKIP_DOTS + ), RecursiveIteratorIterator::CHILD_FIRST ); @@ -76,10 +77,6 @@ final class FileUtil public static function isImage(FileData $fileData): bool { - return in_array( - strtolower($fileData->getType()), - self::IMAGE_MIME, - true - ); + return in_array(strtolower($fileData->getType()), self::IMAGE_MIME, true); } } \ No newline at end of file diff --git a/lib/SP/Util/Filter.php b/lib/SP/Util/Filter.php index 21139a73..5448938a 100644 --- a/lib/SP/Util/Filter.php +++ b/lib/SP/Util/Filter.php @@ -65,7 +65,7 @@ final class Filter } /** - * @param string|int $value + * @param string|int $value */ public static function getInt($value): ?int { @@ -76,11 +76,7 @@ final class Filter public static function getString(?string $value): string { - return filter_var( - trim($value), - FILTER_SANITIZE_STRING, - FILTER_FLAG_NO_ENCODE_QUOTES - ); + return filter_var(trim($value), FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); } public static function getRaw(string $value): string diff --git a/lib/SP/Util/HttpUtil.php b/lib/SP/Util/HttpUtil.php index 5f6b4e91..20d89053 100644 --- a/lib/SP/Util/HttpUtil.php +++ b/lib/SP/Util/HttpUtil.php @@ -24,9 +24,8 @@ namespace SP\Util; -use SP\Config\ConfigDataInterface; -use SP\Html\Html; -use SP\Http\Request; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Http\RequestInterface; /** * Class HttpUtil @@ -38,45 +37,22 @@ final class HttpUtil /** * Comprobar y forzar (si es necesario) la conexión HTTPS */ - public static function checkHttps( - ConfigDataInterface $configData, - Request $request - ): void + public static function checkHttps(ConfigDataInterface $configData, RequestInterface $request): void { if ($configData->isHttpsEnabled() && !$request->isHttps()) { $serverPort = $request->getServerPort(); - $port = $serverPort !== 443 ? ':' . $serverPort : ''; - $host = str_replace( - 'http', - 'https', - $request->getHttpHost() + $port = $serverPort !== 443 ? ':'.$serverPort : ''; + $host = str_replace('http', 'https', $request->getHttpHost()); + + header( + sprintf( + 'Location: %s%s%s', + $host, + $port, + $_SERVER['REQUEST_URI'] + ) ); - - header(sprintf( - 'Location: %s%s%s', - $host, - $port, - $_SERVER['REQUEST_URI'] - )); } } - - /** - * Comprobar si existen parámetros pasados por POST para enviarlos por GET - */ - public static function importUrlParamsToGet(): string - { - $params = []; - - foreach ($_REQUEST as $param => $value) { - $param = Filter::getString($param); - - if (strpos($param, 'g_') !== false) { - $params[] = substr($param, 2) . '=' . Html::sanitize($value); - } - } - - return count($params) > 0 ? '?' . implode('&', $params) : ''; - } } \ No newline at end of file diff --git a/lib/SP/Util/ImageUtil.php b/lib/SP/Util/ImageUtil.php index 7573e9df..25131023 100644 --- a/lib/SP/Util/ImageUtil.php +++ b/lib/SP/Util/ImageUtil.php @@ -117,7 +117,7 @@ final class ImageUtil imagefilledrectangle($im, 0, 0, $width, 30, $bgColor); // Ruta de la fuente - $font = PUBLIC_PATH . '/vendor/fonts/NotoSans-Regular-webfont.ttf'; + $font = PUBLIC_PATH.'/vendor/fonts/NotoSans-Regular-webfont.ttf'; // Sombra // imagettftext($im, 14, 0, 13, 23, $shadowColor, $font, $text); diff --git a/lib/SP/Util/Link.php b/lib/SP/Util/Link.php index a9603b14..948b76dd 100644 --- a/lib/SP/Util/Link.php +++ b/lib/SP/Util/Link.php @@ -24,9 +24,9 @@ namespace SP\Util; -use SP\Config\ConfigDataInterface; use SP\Core\Acl\Acl; use SP\Core\Bootstrap\BootstrapBase; +use SP\Domain\Config\In\ConfigDataInterface; use SP\Http\Uri; /** diff --git a/lib/SP/Util/PasswordUtil.php b/lib/SP/Util/PasswordUtil.php index 0fa6357c..c26028d5 100644 --- a/lib/SP/Util/PasswordUtil.php +++ b/lib/SP/Util/PasswordUtil.php @@ -36,37 +36,32 @@ use Defuse\Crypto\Exception\EnvironmentIsBrokenException; */ final class PasswordUtil { - private const CHARS = 'abcdefghijklmnopqrstuwxyz'; - private const CHARS_SPECIAL = '@$%&/()!_:.;{}^-'; - private const CHARS_NUMBER = '0123456789'; - public const FLAG_PASSWORD_NUMBER = 2; - public const FLAG_PASSWORD_SPECIAL = 4; - public const FLAG_PASSWORD_STRENGTH = 8; + private const CHARS = 'abcdefghijklmnopqrstuwxyz'; + private const CHARS_SPECIAL = '@$%&/()!_:.;{}^-'; + private const CHARS_NUMBER = '0123456789'; + public const FLAG_PASSWORD_NUMBER = 2; + public const FLAG_PASSWORD_SPECIAL = 4; + public const FLAG_PASSWORD_STRENGTH = 8; /** * Generate a ramdom password * - * @param int $length Password length - * @param int|null $flags Password chars included and checking strength flags + * @param int $length Password length + * @param int|null $flags Password chars included and checking strength flags * * @return string * @throws \Exception */ - public static function randomPassword( - int $length = 16, - int $flags = null - ): string + public static function randomPassword(int $length = 16, int $flags = null): string { if ($flags === null) { - $flags = self::FLAG_PASSWORD_SPECIAL - | self::FLAG_PASSWORD_NUMBER - | self::FLAG_PASSWORD_STRENGTH; + $flags = self::FLAG_PASSWORD_SPECIAL | self::FLAG_PASSWORD_NUMBER | self::FLAG_PASSWORD_STRENGTH; } $useSpecial = ($flags & self::FLAG_PASSWORD_SPECIAL) > 0; $useNumbers = ($flags & self::FLAG_PASSWORD_NUMBER) > 0; - $alphabet = self::CHARS . strtoupper(self::CHARS); + $alphabet = self::CHARS.strtoupper(self::CHARS); if ($useSpecial) { $alphabet .= self::CHARS_SPECIAL; @@ -132,7 +127,7 @@ final class PasswordUtil /** * Generar una cadena aleatoria usuando criptografía. * - * @param int $length opcional, con la longitud de la cadena + * @param int $length opcional, con la longitud de la cadena * * @throws EnvironmentIsBrokenException */ diff --git a/lib/SP/Util/Util.php b/lib/SP/Util/Util.php index 233f2504..3c81b775 100644 --- a/lib/SP/Util/Util.php +++ b/lib/SP/Util/Util.php @@ -24,8 +24,8 @@ namespace SP\Util; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; defined('APP_ROOT') || die(); @@ -45,12 +45,12 @@ final class Util $file = 'syspass.test'; $checkDir = static function ($dir) use ($file) { - if (file_exists($dir . DIRECTORY_SEPARATOR . $file)) { + if (file_exists($dir.DIRECTORY_SEPARATOR.$file)) { return $dir; } if (is_dir($dir) || mkdir($dir) || is_dir($dir)) { - if (touch($dir . DIRECTORY_SEPARATOR . $file)) { + if (touch($dir.DIRECTORY_SEPARATOR.$file)) { return $dir; } } @@ -80,9 +80,11 @@ final class Util */ public static function getMaxUpload(): int { - return min(self::convertShortUnit(ini_get('upload_max_filesize')), + return min( + self::convertShortUnit(ini_get('upload_max_filesize')), self::convertShortUnit(ini_get('post_max_size')), - self::convertShortUnit(ini_get('memory_limit'))); + self::convertShortUnit(ini_get('memory_limit')) + ); } public static function convertShortUnit(string $value): int @@ -106,8 +108,8 @@ final class Util * Also takes into account some text-based representations of true of false, * such as 'false','N','yes','on','off', etc. * - * @param mixed $in The variable to check - * @param bool $strict If set to false, consider everything that is not false to + * @param mixed $in The variable to check + * @param bool $strict If set to false, consider everything that is not false to * be true. * * @return bool The boolean equivalent or null (if strict, and no exact equivalent) @@ -139,9 +141,9 @@ final class Util /** * Cast an object to another class, keeping the properties, but changing the methods * - * @param string $dstClass Destination class name - * @param string|object $serialized - * @param string|null $srcClass Old class name for removing from private methods + * @param string $dstClass Destination class name + * @param string|object $serialized + * @param string|null $srcClass Old class name for removing from private methods * * @return mixed */ @@ -169,11 +171,12 @@ final class Util // If source class is set, it will try to clean up the class name from private methods if ($srcClass !== null) { $serialized = preg_replace_callback( - '/:\d+:"\x00' . preg_quote($srcClass, '/') . '\x00(\w+)"/', + '/:\d+:"\x00'.preg_quote($srcClass, '/').'\x00(\w+)"/', static function ($matches) { - return ':' . strlen($matches[1]) . ':"' . $matches[1] . '"'; + return ':'.strlen($matches[1]).':"'.$matches[1].'"'; }, - $serialized); + $serialized + ); } return self::castToClass($serialized, $dstClass); @@ -199,7 +202,7 @@ final class Util return unserialize( preg_replace( '/O:\d+:"[^"]++"/', - 'O:' . strlen($class) . ':"' . $class . '"', + 'O:'.strlen($class).':"'.$class.'"', $cast ) ); @@ -209,7 +212,7 @@ final class Util * Bloquear la aplicación * * @throws \JsonException - * @throws \SP\Storage\File\FileException + * @throws \SP\Infrastructure\File\FileException */ public static function lockApp(int $userId, string $subject): void { @@ -258,11 +261,7 @@ final class Util * * @return array Con el tiempo estimado y los elementos por segundo */ - public static function getETA( - int $startTime, - int $numItems, - int $totalItems - ): array + public static function getETA(int $startTime, int $numItems, int $totalItems): array { if ($numItems > 0 && $totalItems > 0) { $runtime = time() - $startTime; @@ -277,10 +276,7 @@ final class Util /** * Adaptador para convertir una cadena de IDs a un array */ - public static function itemsIdAdapter( - string $itemsId, - string $delimiter = ',' - ): array + public static function itemsIdAdapter(string $itemsId, string $delimiter = ','): array { return array_map( static function ($value) { diff --git a/lib/SP/Util/VersionUtil.php b/lib/SP/Util/VersionUtil.php index d10d18f7..94120480 100644 --- a/lib/SP/Util/VersionUtil.php +++ b/lib/SP/Util/VersionUtil.php @@ -24,7 +24,7 @@ namespace SP\Util; -use SP\Services\Install\Installer; +use SP\Domain\Install\Services\Installer; /** * Class VersionUtil @@ -38,14 +38,14 @@ final class VersionUtil */ public static function getVersionStringNormalized(): string { - return implode('', Installer::VERSION) . '.' . Installer::BUILD; + return implode('', Installer::VERSION).'.'.Installer::BUILD; } /** * Compare versions * - * @param string $currentVersion - * @param array|string $upgradeableVersion + * @param string $currentVersion + * @param array|string $upgradeableVersion * * @return bool True if $currentVersion is lower than $upgradeableVersion */ @@ -72,13 +72,13 @@ final class VersionUtil $versionRes = (int)$currentVersion < (int)$upgradeVersion; return (($versionRes && (int)$upgradeBuild === 0) - || ($versionRes && (int)$build < (int)$upgradeBuild)); + || ($versionRes && (int)$build < (int)$upgradeBuild)); } /** * Return a normalized version string to be compared * - * @param string|array $versionIn + * @param string|array $versionIn */ public static function normalizeVersionForCompare($versionIn): string { @@ -98,7 +98,7 @@ final class VersionUtil $nomalizedVersion += (int)$value * (10 ** (3 - $key)); } - return $nomalizedVersion . '.' . $build; + return $nomalizedVersion.'.'.$build; } return ''; @@ -123,7 +123,7 @@ final class VersionUtil /** * Devuelve la versión de sysPass. * - * @param bool $retBuild devolver el número de compilación + * @param bool $retBuild devolver el número de compilación * * @return array con el número de versión */ diff --git a/tests/SP/Config/ConfigTest.php b/tests/SP/Config/ConfigTest.php index a53397f6..b821fbdc 100644 --- a/tests/SP/Config/ConfigTest.php +++ b/tests/SP/Config/ConfigTest.php @@ -29,10 +29,10 @@ use DI\Container; use DI\DependencyException; use DI\NotFoundException; use PHPUnit\Framework\TestCase; -use SP\Config\Config; -use SP\Config\ConfigData; use SP\Core\Context\ContextException; -use SP\Storage\File\FileException; +use SP\Domain\Config\Adapters\ConfigData; +use SP\Domain\Config\ConfigInterface; +use SP\Infrastructure\File\FileException; use function SP\Tests\getResource; use function SP\Tests\recreateDir; use function SP\Tests\saveResource; @@ -83,11 +83,11 @@ class ConfigTest extends TestCase * @throws DependencyException * @throws NotFoundException */ - public function testLoadClass(): Config + public function testLoadClass(): ConfigInterface { - $config = self::$dic->get(Config::class); + $config = self::$dic->get(\SP\Domain\Config\Services\ConfigFileService::class); - $this->assertInstanceOf(Config::class, $config); + $this->assertInstanceOf(\SP\Domain\Config\Services\ConfigFileService::class, $config); $this->assertFileExists(CONFIG_FILE); return $config; @@ -98,11 +98,11 @@ class ConfigTest extends TestCase * * @depends testLoadClass * - * @param Config $config + * @param ConfigInterface $config * * @throws FileException */ - public function testSaveConfig(Config $config) + public function testSaveConfig(ConfigInterface $config) { $config->saveConfig($config->getConfigData(), false); @@ -115,9 +115,9 @@ class ConfigTest extends TestCase * * @depends testLoadClass * - * @param Config $config + * @param ConfigInterface $config */ - public function testLoadConfig(Config $config) + public function testLoadConfig(ConfigInterface $config) { $this->assertInstanceOf(ConfigData::class, $config->loadConfig()); } @@ -127,13 +127,13 @@ class ConfigTest extends TestCase * * @depends testLoadClass * - * @param Config $config + * @param ConfigInterface $config */ - public function testUpdateConfig(Config $config) + public function testUpdateConfig(ConfigInterface $config) { $config->updateConfig($config->getConfigData()); - $this->assertEquals(Config::getTimeUpdated(), $config->getConfigData()->getConfigDate()); + $this->assertEquals(\SP\Domain\Config\Services\ConfigFileService::getTimeUpdated(), $config->getConfigData()->getConfigDate()); } /** @@ -141,12 +141,12 @@ class ConfigTest extends TestCase * * @depends testLoadClass * - * @param Config $config + * @param ConfigInterface $config * * @throws EnvironmentIsBrokenException * @throws FileException */ - public function testGenerateUpgradeKey(Config $config) + public function testGenerateUpgradeKey(ConfigInterface $config) { $config->generateUpgradeKey(); diff --git a/tests/SP/Core/Acl/AclTest.php b/tests/SP/Core/Acl/AclTest.php index 88a545fa..f7f81311 100644 --- a/tests/SP/Core/Acl/AclTest.php +++ b/tests/SP/Core/Acl/AclTest.php @@ -32,7 +32,7 @@ use SP\Core\Acl\ActionsInterface; use SP\Core\Context\ContextException; use SP\Core\Context\ContextInterface; use SP\DataModel\ProfileData; -use SP\Services\User\UserLoginResponse; +use SP\Domain\User\Services\UserLoginResponse; use function SP\Tests\setupContext; /** diff --git a/tests/SP/Core/Crypt/CryptPKITest.php b/tests/SP/Core/Crypt/CryptPKITest.php index 7745faa0..d4eb9fa2 100644 --- a/tests/SP/Core/Crypt/CryptPKITest.php +++ b/tests/SP/Core/Crypt/CryptPKITest.php @@ -29,7 +29,7 @@ use phpseclib\Crypt\RSA; use PHPUnit\Framework\TestCase; use SP\Core\Crypt\CryptPKI; use SP\Core\Exceptions\SPException; -use SP\Storage\File\FileException; +use SP\Infrastructure\File\FileException; use SP\Util\PasswordUtil; /** diff --git a/tests/SP/DatabaseTrait.php b/tests/SP/DatabaseTrait.php index 174d7ee5..d2806f34 100644 --- a/tests/SP/DatabaseTrait.php +++ b/tests/SP/DatabaseTrait.php @@ -25,7 +25,7 @@ namespace SP\Tests; use PDO; -use SP\Storage\Database\DatabaseException; +use SP\Infrastructure\Database\DatabaseException; /** * diff --git a/tests/SP/DatabaseUtil.php b/tests/SP/DatabaseUtil.php index b92003fc..b23ecc43 100644 --- a/tests/SP/DatabaseUtil.php +++ b/tests/SP/DatabaseUtil.php @@ -26,8 +26,8 @@ namespace SP\Tests; use Exception; use PDO; -use SP\Storage\Database\DatabaseConnectionData; -use SP\Storage\Database\DatabaseException; +use SP\Infrastructure\Database\DatabaseConnectionData; +use SP\Infrastructure\Database\DatabaseException; /** * Trait DatabaseUtil diff --git a/tests/SP/Modules/Api/ApiTestCase.php b/tests/SP/Modules/Api/ApiTestCase.php index c6116dae..47a857ac 100644 --- a/tests/SP/Modules/Api/ApiTestCase.php +++ b/tests/SP/Modules/Api/ApiTestCase.php @@ -31,17 +31,17 @@ use Klein\Response; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use RuntimeException; -use SP\Config\Config; -use SP\Config\ConfigDataInterface; use SP\Core\Acl\ActionsInterface; use SP\Core\Bootstrap\BootstrapApi; use SP\Core\Context\ContextInterface; use SP\DataModel\AuthTokenData; -use SP\Services\Api\ApiRequest; -use SP\Services\AuthToken\AuthTokenService; -use SP\Storage\Database\DatabaseConnectionData; -use SP\Storage\Database\DBStorageInterface; -use SP\Storage\Database\MySQLHandler; +use SP\Domain\Api\Services\ApiRequest; +use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Config\ConfigInterface; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Infrastructure\Database\DatabaseConnectionData; +use SP\Infrastructure\Database\DBStorageInterface; +use SP\Infrastructure\Database\MySQLHandler; use SP\Tests\DatabaseTrait; use stdClass; use function DI\create; @@ -155,7 +155,7 @@ abstract class ApiTestCase extends TestCase }, DBStorageInterface::class => create(MySQLHandler::class) ->constructor($databaseConnectionData), - ConfigDataInterface::class => static function (Config $config) use ($databaseConnectionData) { + ConfigDataInterface::class => static function (ConfigInterface $config) use ($databaseConnectionData) { $configData = $config->getConfigData() ->setDbHost($databaseConnectionData->getDbHost()) ->setDbName($databaseConnectionData->getDbName()) diff --git a/tests/SP/Modules/Cli/CliTestCase.php b/tests/SP/Modules/Cli/CliTestCase.php index 0ba9a6dd..2b4b4e6c 100644 --- a/tests/SP/Modules/Cli/CliTestCase.php +++ b/tests/SP/Modules/Cli/CliTestCase.php @@ -31,7 +31,7 @@ use Exception; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use SP\Core\Context\ContextInterface; -use SP\Storage\Database\DBStorageInterface; +use SP\Infrastructure\Database\DBStorageInterface; use Symfony\Component\Console\Tester\CommandTester; use function SP\Tests\getDbHandler; use const SP\Tests\APP_DEFINITIONS_FILE; diff --git a/tests/SP/Modules/Cli/Commands/BackupCommandTest.php b/tests/SP/Modules/Cli/Commands/BackupCommandTest.php index 5e43422e..4de0bcc3 100644 --- a/tests/SP/Modules/Cli/Commands/BackupCommandTest.php +++ b/tests/SP/Modules/Cli/Commands/BackupCommandTest.php @@ -26,10 +26,10 @@ namespace SP\Tests\Modules\Cli\Commands; use DI\DependencyException; use DI\NotFoundException; -use SP\Config\Config; use SP\Core\Exceptions\FileNotFoundException; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\Export\Services\BackupFiles; use SP\Modules\Cli\Commands\BackupCommand; -use SP\Services\Backup\BackupFiles; use SP\Tests\Modules\Cli\CliTestCase; use function SP\Tests\recreateDir; @@ -93,7 +93,7 @@ class BackupCommandTest extends CliTestCase private function checkBackupFilesAreCreated(): void { - $configData = self::$dic->get(Config::class)->getConfigData(); + $configData = self::$dic->get(ConfigFileService::class)->getConfigData(); $this->assertFileExists( BackupFiles::getAppBackupFilename( diff --git a/tests/SP/Modules/Cli/Commands/InstallCommandTest.php b/tests/SP/Modules/Cli/Commands/InstallCommandTest.php index 411dcdc9..c6c767cc 100644 --- a/tests/SP/Modules/Cli/Commands/InstallCommandTest.php +++ b/tests/SP/Modules/Cli/Commands/InstallCommandTest.php @@ -27,9 +27,9 @@ namespace SP\Tests\Modules\Cli\Commands; use DI\DependencyException; use DI\NotFoundException; use Exception; -use SP\Config\Config; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Infrastructure\Database\DatabaseException; use SP\Modules\Cli\Commands\InstallCommand; -use SP\Storage\Database\DatabaseException; use SP\Tests\DatabaseUtil; use SP\Tests\Modules\Cli\CliTestCase; use function SP\Tests\getResource; @@ -187,7 +187,7 @@ class InstallCommandTest extends CliTestCase $output = $commandTester->getDisplay(); $this->assertStringContainsString('Installation finished', $output); - $configData = self::$dic->get(Config::class)->getConfigData(); + $configData = self::$dic->get(ConfigFileService::class)->getConfigData(); // Cleanup database DatabaseUtil::dropDatabase(self::$commandInputData['databaseName']); @@ -221,7 +221,7 @@ class InstallCommandTest extends CliTestCase $output = $commandTester->getDisplay(); $this->assertStringContainsString('Installation finished', $output); - $configData = self::$dic->get(Config::class)->getConfigData(); + $configData = self::$dic->get(ConfigFileService::class)->getConfigData(); $this->assertEquals($configData->getSiteLang(), $inputData['--language']); @@ -268,7 +268,7 @@ class InstallCommandTest extends CliTestCase $output = $commandTester->getDisplay(); $this->assertStringContainsString('Installation finished', $output); - $configData = self::$dic->get(Config::class)->getConfigData(); + $configData = self::$dic->get(ConfigFileService::class)->getConfigData(); $this->assertEquals($configData->getDbUser(), $databaseUser); $this->assertEquals($configData->getDbPass(), $databasePassword); diff --git a/tests/SP/Repositories/AccountFileRepositoryTest.php b/tests/SP/Repositories/AccountFileRepositoryTest.php index 7f337936..e661df96 100644 --- a/tests/SP/Repositories/AccountFileRepositoryTest.php +++ b/tests/SP/Repositories/AccountFileRepositoryTest.php @@ -32,7 +32,8 @@ use SP\Core\Exceptions\QueryException; use SP\DataModel\FileData; use SP\DataModel\FileExtData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Account\AccountFileRepository; +use SP\Domain\Account\In\AccountFileRepositoryInterface; +use SP\Infrastructure\Account\Repositories\AccountFileRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -44,7 +45,7 @@ use function SP\Tests\setupContext; class AccountFileRepositoryTest extends DatabaseTestCase { /** - * @var AccountFileRepository + * @var \SP\Domain\Account\In\AccountFileRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/AccountHistoryRepositoryTest.php b/tests/SP/Repositories/AccountHistoryRepositoryTest.php index 1fae60fb..267172d8 100644 --- a/tests/SP/Repositories/AccountHistoryRepositoryTest.php +++ b/tests/SP/Repositories/AccountHistoryRepositoryTest.php @@ -34,8 +34,9 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\AccountHistoryData; use SP\DataModel\Dto\AccountHistoryCreateDto; use SP\DataModel\ItemSearchData; -use SP\Repositories\Account\AccountHistoryRepository; -use SP\Services\Account\AccountPasswordRequest; +use SP\Domain\Account\In\AccountHistoryRepositoryInterface; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Infrastructure\Account\Repositories\AccountHistoryRepository; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use function SP\Tests\setupContext; @@ -48,7 +49,7 @@ use function SP\Tests\setupContext; class AccountHistoryRepositoryTest extends DatabaseTestCase { /** - * @var AccountHistoryRepository + * @var AccountHistoryRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/AccountRepositoryTest.php b/tests/SP/Repositories/AccountRepositoryTest.php index cc4f7556..09e5cd99 100644 --- a/tests/SP/Repositories/AccountRepositoryTest.php +++ b/tests/SP/Repositories/AccountRepositoryTest.php @@ -36,11 +36,12 @@ use SP\DataModel\AccountData; use SP\DataModel\AccountSearchVData; use SP\DataModel\AccountVData; use SP\DataModel\ItemSearchData; +use SP\Domain\Account\In\AccountRepositoryInterface; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Infrastructure\Account\Repositories\AccountRepository; use SP\Mvc\Model\QueryCondition; -use SP\Repositories\Account\AccountRepository; -use SP\Services\Account\AccountPasswordRequest; -use SP\Services\Account\AccountRequest; -use SP\Services\Account\AccountSearchFilter; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -56,7 +57,7 @@ class AccountRepositoryTest extends DatabaseTestCase { const SECURE_KEY_PASSWORD = 'syspass123'; /** - * @var AccountRepository + * @var AccountRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/AccountToFavoriteRepositoryTest.php b/tests/SP/Repositories/AccountToFavoriteRepositoryTest.php index b4fbfaee..bb8082ce 100644 --- a/tests/SP/Repositories/AccountToFavoriteRepositoryTest.php +++ b/tests/SP/Repositories/AccountToFavoriteRepositoryTest.php @@ -29,7 +29,8 @@ use DI\NotFoundException; use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\Account\AccountToFavoriteRepository; +use SP\Domain\Account\In\AccountToFavoriteRepositoryInterface; +use SP\Infrastructure\Account\Repositories\AccountToFavoriteRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -41,7 +42,7 @@ use function SP\Tests\setupContext; class AccountToFavoriteRepositoryTest extends DatabaseTestCase { /** - * @var AccountToFavoriteRepository + * @var \SP\Domain\Account\In\AccountToFavoriteRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/AccountToTagRepositoryTest.php b/tests/SP/Repositories/AccountToTagRepositoryTest.php index c80f5a0a..74989af2 100644 --- a/tests/SP/Repositories/AccountToTagRepositoryTest.php +++ b/tests/SP/Repositories/AccountToTagRepositoryTest.php @@ -30,8 +30,9 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemData; -use SP\Repositories\Account\AccountToTagRepository; -use SP\Services\Account\AccountRequest; +use SP\Domain\Account\In\AccountToTagRepositoryInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Account\Repositories\AccountToTagRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -45,7 +46,7 @@ use function SP\Tests\setupContext; class AccountToTagRepositoryTest extends DatabaseTestCase { /** - * @var AccountToTagRepository + * @var AccountToTagRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/AccountToUserGroupRepositoryTest.php b/tests/SP/Repositories/AccountToUserGroupRepositoryTest.php index 92c3e4ff..42a393a3 100644 --- a/tests/SP/Repositories/AccountToUserGroupRepositoryTest.php +++ b/tests/SP/Repositories/AccountToUserGroupRepositoryTest.php @@ -30,8 +30,9 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemData; -use SP\Repositories\Account\AccountToUserGroupRepository; -use SP\Services\Account\AccountRequest; +use SP\Domain\Account\In\AccountToUserGroupRepositoryInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Account\Repositories\AccountToUserGroupRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -45,7 +46,7 @@ use function SP\Tests\setupContext; class AccountToUserGroupRepositoryTest extends DatabaseTestCase { /** - * @var AccountToUserGroupRepository + * @var AccountToUserGroupRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/AccountToUserRepositoryTest.php b/tests/SP/Repositories/AccountToUserRepositoryTest.php index 225061ff..f8444c27 100644 --- a/tests/SP/Repositories/AccountToUserRepositoryTest.php +++ b/tests/SP/Repositories/AccountToUserRepositoryTest.php @@ -30,8 +30,9 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemData; -use SP\Repositories\Account\AccountToUserRepository; -use SP\Services\Account\AccountRequest; +use SP\Domain\Account\In\AccountToUserRepositoryInterface; +use SP\Domain\Account\Services\AccountRequest; +use SP\Infrastructure\Account\Repositories\AccountToUserRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -45,7 +46,7 @@ use function SP\Tests\setupContext; class AccountToUserRepositoryTest extends DatabaseTestCase { /** - * @var AccountToUserRepository + * @var AccountToUserRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/AuthTokenRepositoryTest.php b/tests/SP/Repositories/AuthTokenRepositoryTest.php index e63e8ced..81ea0431 100644 --- a/tests/SP/Repositories/AuthTokenRepositoryTest.php +++ b/tests/SP/Repositories/AuthTokenRepositoryTest.php @@ -37,8 +37,8 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\AuthTokenData; use SP\DataModel\ItemSearchData; -use SP\Repositories\AuthToken\AuthTokenRepository; -use SP\Repositories\DuplicatedItemException; +use SP\Infrastructure\Auth\Repositories\AuthTokenRepository; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use SP\Util\Util; @@ -56,7 +56,7 @@ class AuthTokenRepositoryTest extends DatabaseTestCase const AUTH_TOKEN_PASS = 123456; /** - * @var AuthTokenRepository + * @var \SP\Infrastructure\Auth\Repositories\AuthTokenRepository */ private static $repository; diff --git a/tests/SP/Repositories/CategoryRepositoryTest.php b/tests/SP/Repositories/CategoryRepositoryTest.php index 5385f98f..6be43009 100644 --- a/tests/SP/Repositories/CategoryRepositoryTest.php +++ b/tests/SP/Repositories/CategoryRepositoryTest.php @@ -32,8 +32,9 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Category\CategoryRepository; -use SP\Repositories\DuplicatedItemException; +use SP\Domain\Category\In\CategoryRepositoryInterface; +use SP\Infrastructure\Category\Repositories\CategoryRepository; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -48,7 +49,7 @@ use function SP\Tests\setupContext; class CategoryRepositoryTest extends DatabaseTestCase { /** - * @var CategoryRepository + * @var CategoryRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/ClientRepositoryTest.php b/tests/SP/Repositories/ClientRepositoryTest.php index 71d80bba..d7f485fc 100644 --- a/tests/SP/Repositories/ClientRepositoryTest.php +++ b/tests/SP/Repositories/ClientRepositoryTest.php @@ -32,9 +32,9 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ClientData; use SP\DataModel\ItemSearchData; +use SP\Infrastructure\Client\Repositories\ClientRepository; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; use SP\Mvc\Model\QueryCondition; -use SP\Repositories\Client\ClientRepository; -use SP\Repositories\DuplicatedItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; diff --git a/tests/SP/Repositories/ConfigRepositoryTest.php b/tests/SP/Repositories/ConfigRepositoryTest.php index d552b61c..732ec144 100644 --- a/tests/SP/Repositories/ConfigRepositoryTest.php +++ b/tests/SP/Repositories/ConfigRepositoryTest.php @@ -30,7 +30,8 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ConfigData; -use SP\Repositories\Config\ConfigRepository; +use SP\Domain\Config\In\ConfigRepositoryInterface; +use SP\Infrastructure\Config\Repositories\ConfigRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -42,7 +43,7 @@ use function SP\Tests\setupContext; class ConfigRepositoryTest extends DatabaseTestCase { /** - * @var ConfigRepository + * @var ConfigRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/CustomFieldDefRepositoryTest.php b/tests/SP/Repositories/CustomFieldDefRepositoryTest.php index d75b5111..1c72ecbd 100644 --- a/tests/SP/Repositories/CustomFieldDefRepositoryTest.php +++ b/tests/SP/Repositories/CustomFieldDefRepositoryTest.php @@ -33,8 +33,9 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldDefinitionData; use SP\DataModel\ItemSearchData; -use SP\Repositories\CustomField\CustomFieldDefRepository; -use SP\Repositories\NoSuchItemException; +use SP\Domain\CustomField\In\CustomFieldDefRepositoryInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\CustomField\Repositories\CustomFieldDefRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -46,7 +47,7 @@ use function SP\Tests\setupContext; class CustomFieldDefRepositoryTest extends DatabaseTestCase { /** - * @var CustomFieldDefRepository + * @var CustomFieldDefRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/CustomFieldRepositoryTest.php b/tests/SP/Repositories/CustomFieldRepositoryTest.php index 0e600117..72760305 100644 --- a/tests/SP/Repositories/CustomFieldRepositoryTest.php +++ b/tests/SP/Repositories/CustomFieldRepositoryTest.php @@ -31,7 +31,8 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\CustomFieldData; -use SP\Repositories\CustomField\CustomFieldRepository; +use SP\Domain\CustomField\In\CustomFieldRepositoryInterface; +use SP\Infrastructure\CustomField\Repositories\CustomFieldRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -43,7 +44,7 @@ use function SP\Tests\setupContext; class CustomFieldRepositoryTest extends DatabaseTestCase { /** - * @var CustomFieldRepository + * @var CustomFieldRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/CustomFieldTypeRepositoryTest.php b/tests/SP/Repositories/CustomFieldTypeRepositoryTest.php index 3bd49648..14b0e4fc 100644 --- a/tests/SP/Repositories/CustomFieldTypeRepositoryTest.php +++ b/tests/SP/Repositories/CustomFieldTypeRepositoryTest.php @@ -31,7 +31,8 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldTypeData; -use SP\Repositories\CustomField\CustomFieldTypeRepository; +use SP\Domain\CustomField\In\CustomFieldTypeRepositoryInterface; +use SP\Infrastructure\CustomField\Repositories\CustomFieldTypeRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -43,7 +44,7 @@ use function SP\Tests\setupContext; class CustomFieldTypeRepositoryTest extends DatabaseTestCase { /** - * @var CustomFieldTypeRepository + * @var CustomFieldTypeRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/EventlogRepositoryTest.php b/tests/SP/Repositories/EventlogRepositoryTest.php index 65609c8e..639f3fc3 100644 --- a/tests/SP/Repositories/EventlogRepositoryTest.php +++ b/tests/SP/Repositories/EventlogRepositoryTest.php @@ -31,7 +31,8 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\EventlogData; use SP\DataModel\ItemSearchData; -use SP\Repositories\EventLog\EventlogRepository; +use SP\Domain\Security\In\EventlogRepositoryInterface; +use SP\Infrastructure\Security\Repositories\EventlogRepository; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -46,7 +47,7 @@ use function SP\Tests\setupContext; class EventlogRepositoryTest extends DatabaseTestCase { /** - * @var EventlogRepository + * @var EventlogRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/ItemPresetRepositoryTest.php b/tests/SP/Repositories/ItemPresetRepositoryTest.php index a0690ecd..113bd861 100644 --- a/tests/SP/Repositories/ItemPresetRepositoryTest.php +++ b/tests/SP/Repositories/ItemPresetRepositoryTest.php @@ -31,7 +31,8 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemPresetData; use SP\DataModel\ItemSearchData; -use SP\Repositories\ItemPreset\ItemPresetRepository; +use SP\Domain\ItemPreset\In\ItemPresetRepositoryInterface; +use SP\Infrastructure\ItemPreset\Repositories\ItemPresetRepository; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -44,7 +45,7 @@ use function SP\Tests\setupContext; class ItemPresetRepositoryTest extends DatabaseTestCase { /** - * @var ItemPresetRepository + * @var ItemPresetRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/NotificationRepositoryTest.php b/tests/SP/Repositories/NotificationRepositoryTest.php index 65df6eb0..c6e55c6d 100644 --- a/tests/SP/Repositories/NotificationRepositoryTest.php +++ b/tests/SP/Repositories/NotificationRepositoryTest.php @@ -32,7 +32,8 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Messages\NotificationMessage; use SP\DataModel\ItemSearchData; use SP\DataModel\NotificationData; -use SP\Repositories\Notification\NotificationRepository; +use SP\Domain\Notification\In\NotificationRepositoryInterface; +use SP\Infrastructure\Notification\Repositories\NotificationRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -44,7 +45,7 @@ use function SP\Tests\setupContext; class NotificationRepositoryTest extends DatabaseTestCase { /** - * @var NotificationRepository + * @var NotificationRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/PluginDataRepositoryTest.php b/tests/SP/Repositories/PluginDataRepositoryTest.php index a7923e11..91ae8545 100644 --- a/tests/SP/Repositories/PluginDataRepositoryTest.php +++ b/tests/SP/Repositories/PluginDataRepositoryTest.php @@ -32,8 +32,9 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; -use SP\Repositories\Plugin\PluginDataModel; -use SP\Repositories\Plugin\PluginDataRepository; +use SP\Domain\Plugin\In\PluginDataRepositoryInterface; +use SP\Infrastructure\Plugin\Repositories\PluginDataModel; +use SP\Infrastructure\Plugin\Repositories\PluginDataRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -45,7 +46,7 @@ use function SP\Tests\setupContext; class PluginDataRepositoryTest extends DatabaseTestCase { /** - * @var PluginDataRepository + * @var PluginDataRepositoryInterface */ private static $repository; @@ -85,7 +86,7 @@ class PluginDataRepositoryTest extends DatabaseTestCase $this->assertEquals(1, $result->getNumRows()); - /** @var PluginDataModel $itemData */ + /** @var \SP\Infrastructure\Plugin\Repositories\PluginDataModel $itemData */ $itemData = $result->getData(); $this->assertEquals($data->getData(), $itemData->getData()); @@ -176,7 +177,7 @@ class PluginDataRepositoryTest extends DatabaseTestCase public function testGetById() { $result = self::$repository->getById('Authenticator'); - /** @var PluginDataModel[] $data */ + /** @var \SP\Infrastructure\Plugin\Repositories\PluginDataModel[] $data */ $data = $result->getDataAsArray(); $this->assertEquals(2, $result->getNumRows()); @@ -249,7 +250,7 @@ class PluginDataRepositoryTest extends DatabaseTestCase $this->assertEquals(1, $result->getNumRows()); - /** @var PluginDataModel $itemData */ + /** @var \SP\Infrastructure\Plugin\Repositories\PluginDataModel $itemData */ $itemData = $result->getData(); $this->assertEquals($data->getName(), $itemData->getName()); @@ -287,7 +288,7 @@ class PluginDataRepositoryTest extends DatabaseTestCase public function testGetByIdBatch() { $result = self::$repository->getByIdBatch(['Authenticator', 'XML Exporter', 'Test']); - /** @var PluginDataModel[] $data */ + /** @var \SP\Infrastructure\Plugin\Repositories\PluginDataModel[] $data */ $data = $result->getDataAsArray(); $this->assertEquals(3, $result->getNumRows()); diff --git a/tests/SP/Repositories/PluginRepositoryTest.php b/tests/SP/Repositories/PluginRepositoryTest.php index 5ec68eeb..f49b595a 100644 --- a/tests/SP/Repositories/PluginRepositoryTest.php +++ b/tests/SP/Repositories/PluginRepositoryTest.php @@ -32,8 +32,9 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemData; use SP\DataModel\ItemSearchData; -use SP\Repositories\Plugin\PluginModel; -use SP\Repositories\Plugin\PluginRepository; +use SP\Domain\Plugin\In\PluginRepositoryInterface; +use SP\Infrastructure\Plugin\Repositories\PluginModel; +use SP\Infrastructure\Plugin\Repositories\PluginRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -45,7 +46,7 @@ use function SP\Tests\setupContext; class PluginRepositoryTest extends DatabaseTestCase { /** - * @var PluginRepository + * @var PluginRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/PublicLinkRepositoryTest.php b/tests/SP/Repositories/PublicLinkRepositoryTest.php index 2b19bf93..2ffa5866 100644 --- a/tests/SP/Repositories/PublicLinkRepositoryTest.php +++ b/tests/SP/Repositories/PublicLinkRepositoryTest.php @@ -34,8 +34,8 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\PublicLinkData; use SP\DataModel\PublicLinkListData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\PublicLink\PublicLinkRepository; +use SP\Infrastructure\Account\Repositories\PublicLinkRepository; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use function SP\Tests\setupContext; @@ -48,7 +48,7 @@ use function SP\Tests\setupContext; class PublicLinkRepositoryTest extends DatabaseTestCase { /** - * @var PublicLinkRepository + * @var \SP\Infrastructure\Account\Repositories\PublicLinkRepository */ private static $repository; diff --git a/tests/SP/Repositories/TagRepositoryTest.php b/tests/SP/Repositories/TagRepositoryTest.php index e7f51049..f0d341ab 100644 --- a/tests/SP/Repositories/TagRepositoryTest.php +++ b/tests/SP/Repositories/TagRepositoryTest.php @@ -33,8 +33,9 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ItemSearchData; use SP\DataModel\TagData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\Tag\TagRepository; +use SP\Domain\Tag\In\TagRepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Tag\Repositories\TagRepository; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -49,7 +50,7 @@ use function SP\Tests\setupContext; class TagRepositoryTest extends DatabaseTestCase { /** - * @var TagRepository + * @var TagRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/TrackRepositoryTest.php b/tests/SP/Repositories/TrackRepositoryTest.php index a85b229c..a0211429 100644 --- a/tests/SP/Repositories/TrackRepositoryTest.php +++ b/tests/SP/Repositories/TrackRepositoryTest.php @@ -31,8 +31,9 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\QueryException; use SP\DataModel\TrackData; -use SP\Repositories\Track\TrackRepository; -use SP\Repositories\Track\TrackRequest; +use SP\Domain\Security\In\TrackRepositoryInterface; +use SP\Infrastructure\Security\Repositories\TrackRepository; +use SP\Infrastructure\Security\Repositories\TrackRequest; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -44,7 +45,7 @@ use function SP\Tests\setupContext; class TrackRepositoryTest extends DatabaseTestCase { /** - * @var TrackRepository + * @var TrackRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/UserGroupRepositoryTest.php b/tests/SP/Repositories/UserGroupRepositoryTest.php index bd793376..6d960605 100644 --- a/tests/SP/Repositories/UserGroupRepositoryTest.php +++ b/tests/SP/Repositories/UserGroupRepositoryTest.php @@ -32,8 +32,9 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserGroupData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\UserGroup\UserGroupRepository; +use SP\Domain\User\In\UserGroupRepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\User\Repositories\UserGroupRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -47,7 +48,7 @@ use function SP\Tests\setupContext; class UserGroupRepositoryTest extends DatabaseTestCase { /** - * @var UserGroupRepository + * @var UserGroupRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/UserPassRecoverRepositoryTest.php b/tests/SP/Repositories/UserPassRecoverRepositoryTest.php index 20bbd158..99fafc80 100644 --- a/tests/SP/Repositories/UserPassRecoverRepositoryTest.php +++ b/tests/SP/Repositories/UserPassRecoverRepositoryTest.php @@ -31,7 +31,8 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; -use SP\Repositories\User\UserPassRecoverRepository; +use SP\Domain\User\In\UserPassRecoverRepositoryInterface; +use SP\Infrastructure\User\Repositories\UserPassRecoverRepository; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use function SP\Tests\setupContext; @@ -44,7 +45,7 @@ use function SP\Tests\setupContext; class UserPassRecoverRepositoryTest extends DatabaseTestCase { /** - * @var UserPassRecoverRepository + * @var UserPassRecoverRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/UserProfileRepositoryTest.php b/tests/SP/Repositories/UserProfileRepositoryTest.php index ccc480cd..1ef6ed99 100644 --- a/tests/SP/Repositories/UserProfileRepositoryTest.php +++ b/tests/SP/Repositories/UserProfileRepositoryTest.php @@ -33,8 +33,9 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\ProfileData; use SP\DataModel\UserProfileData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\UserProfile\UserProfileRepository; +use SP\Domain\User\In\UserProfileRepositoryInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\User\Repositories\UserProfileRepository; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -49,7 +50,7 @@ use function SP\Tests\setupContext; class UserProfileRepositoryTest extends DatabaseTestCase { /** - * @var UserProfileRepository + * @var UserProfileRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/UserRepositoryTest.php b/tests/SP/Repositories/UserRepositoryTest.php index 2b0c3118..8a98fdfb 100644 --- a/tests/SP/Repositories/UserRepositoryTest.php +++ b/tests/SP/Repositories/UserRepositoryTest.php @@ -36,9 +36,10 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserData; use SP\DataModel\UserPreferencesData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\User\UserRepository; -use SP\Services\User\UpdatePassRequest; +use SP\Domain\User\In\UserRepositoryInterface; +use SP\Domain\User\Services\UpdatePassRequest; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\User\Repositories\UserRepository; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -54,7 +55,7 @@ class UserRepositoryTest extends DatabaseTestCase { /** - * @var UserRepository + * @var UserRepositoryInterface */ private static $repository; diff --git a/tests/SP/Repositories/UserToUserGroupRepositoryTest.php b/tests/SP/Repositories/UserToUserGroupRepositoryTest.php index 395b9edd..3a49fb48 100644 --- a/tests/SP/Repositories/UserToUserGroupRepositoryTest.php +++ b/tests/SP/Repositories/UserToUserGroupRepositoryTest.php @@ -30,19 +30,20 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\UserToUserGroupData; -use SP\Repositories\UserGroup\UserToUserGroupRepository; +use SP\Domain\User\In\UserToUserGroupRepositoryInterface; +use SP\Infrastructure\User\Repositories\UserToUserGroupRepository; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; /** * Class UserToUserGroupRepositoryTest * - * @package SP\Tests\SP\Repositories + * @package SP\Tests\SP\Infrastructure\Common\Repositories */ class UserToUserGroupRepositoryTest extends DatabaseTestCase { /** - * @var UserToUserGroupRepository + * @var UserToUserGroupRepositoryInterface */ private static $repository; diff --git a/tests/SP/Services/Account/AccountAclServiceTest.php b/tests/SP/Services/Account/AccountAclServiceTest.php index ef2caf3f..a9188de8 100644 --- a/tests/SP/Services/Account/AccountAclServiceTest.php +++ b/tests/SP/Services/Account/AccountAclServiceTest.php @@ -28,6 +28,8 @@ use Closure; use DI\DependencyException; use DI\NotFoundException; use SP\Core\Acl\Acl; +use SP\Core\Acl\ActionsInterface; +use SP\Core\Application; use SP\Core\Context\ContextException; use SP\Core\Context\ContextInterface; use SP\Core\Context\StatelessContext; @@ -35,11 +37,12 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\Dto\AccountAclDto; use SP\DataModel\Dto\AccountDetailsResponse; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountAcl; -use SP\Services\Account\AccountAclService; -use SP\Services\Account\AccountService; -use SP\Services\User\UserLoginResponse; +use SP\Domain\Account\AccountAclServiceInterface; +use SP\Domain\Account\Services\AccountAcl; +use SP\Domain\Account\Services\AccountAclService; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -50,38 +53,23 @@ use function SP\Tests\setupContext; */ class AccountAclServiceTest extends DatabaseTestCase { - /** - * @var Closure - */ - private static $service; - /** - * @var AccountService - */ - private static $accountService; - /** - * @var StatelessContext - */ - private static $context; - /** - * @var array - */ - private static $actions = [ - Acl::ACCOUNT_SEARCH, - Acl::ACCOUNT_VIEW, - Acl::ACCOUNT_VIEW_PASS, - Acl::ACCOUNT_HISTORY_VIEW, - Acl::ACCOUNT_CREATE, - Acl::ACCOUNT_EDIT, - Acl::ACCOUNT_EDIT_PASS, - Acl::ACCOUNT_EDIT_RESTORE, - Acl::ACCOUNT_COPY, - Acl::ACCOUNT_COPY_PASS, - Acl::ACCOUNT_DELETE + private static Closure $service; + private static AccountService $accountService; + private static StatelessContext $context; + private static array $actions = [ + ActionsInterface::ACCOUNT_SEARCH, + ActionsInterface::ACCOUNT_VIEW, + ActionsInterface::ACCOUNT_VIEW_PASS, + ActionsInterface::ACCOUNT_HISTORY_VIEW, + ActionsInterface::ACCOUNT_CREATE, + ActionsInterface::ACCOUNT_EDIT, + ActionsInterface::ACCOUNT_EDIT_PASS, + ActionsInterface::ACCOUNT_EDIT_RESTORE, + ActionsInterface::ACCOUNT_COPY, + ActionsInterface::ACCOUNT_COPY_PASS, + ActionsInterface::ACCOUNT_DELETE, ]; - /** - * @var AccountDetailsResponse - */ - protected $account; + protected AccountDetailsResponse $account; /** * @throws NotFoundException @@ -98,8 +86,8 @@ class AccountAclServiceTest extends DatabaseTestCase // Es necesario utilizar una función anónima para evitar la fijación // de los datos del contexto - self::$service = function () use ($dic) { - return new AccountAclService($dic); + self::$service = static function () use ($dic) { + return new AccountAclService($dic, $dic->get(Application::class)); }; self::$accountService = $dic->get(AccountService::class); @@ -110,7 +98,7 @@ class AccountAclServiceTest extends DatabaseTestCase */ public function testSaveAclInCache() { - /** @var AccountAclService $service */ + /** @var AccountAclServiceInterface $service */ $service = self::$service->call($this); $accountAcl = new AccountAcl(10); @@ -150,7 +138,7 @@ class AccountAclServiceTest extends DatabaseTestCase */ public function testClearAcl() { - /** @var AccountAclService $service */ + /** @var \SP\Domain\Account\AccountAclServiceInterface $service */ $service = self::$service->call($this); $accountAcl = new AccountAcl(10); @@ -197,9 +185,9 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param bool $should + * @param bool $should * * @throws ConstraintException * @throws QueryException @@ -244,16 +232,16 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param AccountAcl $accountAclExample + * @param AccountAcl $accountAclExample * * @throws ConstraintException * @throws QueryException */ private function checkForUserByExample(AccountAclDto $accountAclDto, AccountAcl $accountAclExample) { - /** @var AccountAclService $service */ + /** @var AccountAclServiceInterface $service */ $service = self::$service->call($this); foreach (self::$actions as $action) { @@ -271,7 +259,10 @@ class AccountAclServiceTest extends DatabaseTestCase if ($action !== Acl::ACCOUNT_CREATE && $action !== Acl::ACCOUNT_COPY_PASS ) { - $this->assertEquals($accountAclExample->checkAccountAccess($action), $accountAcl->checkAccountAccess($action)); + $this->assertEquals( + $accountAclExample->checkAccountAccess($action), + $accountAcl->checkAccountAccess($action) + ); } if ($action === Acl::ACCOUNT_VIEW @@ -355,8 +346,8 @@ class AccountAclServiceTest extends DatabaseTestCase * @param $userId * @param $groupId * - * @param int $isAdminApp - * @param int $isAdminAcc + * @param int $isAdminApp + * @param int $isAdminAcc * * @return AccountAclDto * @throws ConstraintException @@ -489,17 +480,21 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param array $should Sets view and edit status - * @param bool $profile Sets profile action status - * @param bool $acl Sets ACL expected result + * @param array $should Sets view and edit status + * @param bool $profile Sets profile action status + * @param bool $acl Sets ACL expected result * * @throws ConstraintException * @throws QueryException */ - private function checkView(AccountAclDto $accountAclDto, $should = ['view' => true, 'edit' => true], $profile = true, $acl = true) - { + private function checkView( + AccountAclDto $accountAclDto, + $should = ['view' => true, 'edit' => true], + $profile = true, + $acl = true + ) { $userProfile = self::$context ->getUserProfile() ->reset() @@ -529,18 +524,22 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param array $should + * @param array $should * - * @param bool $profile - * @param bool $acl + * @param bool $profile + * @param bool $acl * * @throws ConstraintException * @throws QueryException */ - private function checkViewPass(AccountAclDto $accountAclDto, $should = ['view' => true, 'edit' => true], $profile = true, $acl = true) - { + private function checkViewPass( + AccountAclDto $accountAclDto, + $should = ['view' => true, 'edit' => true], + $profile = true, + $acl = true + ) { $userProfile = self::$context ->getUserProfile() ->reset() @@ -570,18 +569,22 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param array $should + * @param array $should * - * @param bool $profile - * @param bool $acl + * @param bool $profile + * @param bool $acl * * @throws ConstraintException * @throws QueryException */ - private function checkDelete(AccountAclDto $accountAclDto, $should = ['view' => true, 'edit' => true], $profile = true, $acl = true) - { + private function checkDelete( + AccountAclDto $accountAclDto, + $should = ['view' => true, 'edit' => true], + $profile = true, + $acl = true + ) { $userProfile = self::$context ->getUserProfile() ->reset() @@ -611,18 +614,22 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param array $should + * @param array $should * - * @param bool $profile - * @param bool $acl + * @param bool $profile + * @param bool $acl * * @throws ConstraintException * @throws QueryException */ - private function checkEditPass(AccountAclDto $accountAclDto, $should = ['view' => true, 'edit' => true], $profile = true, $acl = true) - { + private function checkEditPass( + AccountAclDto $accountAclDto, + $should = ['view' => true, 'edit' => true], + $profile = true, + $acl = true + ) { $userProfile = self::$context ->getUserProfile() ->reset() @@ -652,18 +659,22 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param array $should + * @param array $should * - * @param bool $profile - * @param bool $acl + * @param bool $profile + * @param bool $acl * * @throws ConstraintException * @throws QueryException */ - private function checkEditAndRestore(AccountAclDto $accountAclDto, $should = ['view' => true, 'edit' => true], $profile = true, $acl = true) - { + private function checkEditAndRestore( + AccountAclDto $accountAclDto, + $should = ['view' => true, 'edit' => true], + $profile = true, + $acl = true + ) { $userProfile = self::$context ->getUserProfile() ->reset() @@ -696,18 +707,22 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param array $should + * @param array $should * - * @param bool $profile - * @param bool $acl + * @param bool $profile + * @param bool $acl * * @throws ConstraintException * @throws QueryException */ - private function checkPermissions(AccountAclDto $accountAclDto, $should = ['view' => true, 'edit' => true], $profile = true, $acl = true) - { + private function checkPermissions( + AccountAclDto $accountAclDto, + $should = ['view' => true, 'edit' => true], + $profile = true, + $acl = true + ) { $userProfile = self::$context ->getUserProfile() ->reset() @@ -737,18 +752,22 @@ class AccountAclServiceTest extends DatabaseTestCase } /** - * @param AccountAclDto $accountAclDto + * @param AccountAclDto $accountAclDto * - * @param array $should + * @param array $should * - * @param bool $profile - * @param bool $acl + * @param bool $profile + * @param bool $acl * * @throws ConstraintException * @throws QueryException */ - private function checkViewFiles(AccountAclDto $accountAclDto, $should = ['view' => true, 'edit' => true], $profile = true, $acl = true) - { + private function checkViewFiles( + AccountAclDto $accountAclDto, + $should = ['view' => true, 'edit' => true], + $profile = true, + $acl = true + ) { $userProfile = self::$context ->getUserProfile() ->reset() @@ -782,7 +801,7 @@ class AccountAclServiceTest extends DatabaseTestCase */ public function testGetAclFromCache() { - /** @var AccountAclService $service */ + /** @var AccountAclServiceInterface $service */ $service = self::$service->call($this); $this->assertNull($service->getAclFromCache(1, 10)); diff --git a/tests/SP/Services/Account/AccountCryptServiceTest.php b/tests/SP/Services/Account/AccountCryptServiceTest.php index 7c5eb06f..e3864281 100644 --- a/tests/SP/Services/Account/AccountCryptServiceTest.php +++ b/tests/SP/Services/Account/AccountCryptServiceTest.php @@ -31,11 +31,12 @@ use SP\Core\Context\ContextException; use SP\Core\Crypt\Crypt; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountCryptService; -use SP\Services\Account\AccountService; -use SP\Services\Crypt\UpdateMasterPassRequest; -use SP\Services\ServiceException; +use SP\Domain\Account\AccountCryptServiceInterface; +use SP\Domain\Account\Services\AccountCryptService; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -54,7 +55,7 @@ class AccountCryptServiceTest extends DatabaseTestCase */ private static $accountService; /** - * @var AccountCryptService + * @var AccountCryptServiceInterface */ private static $service; @@ -77,7 +78,7 @@ class AccountCryptServiceTest extends DatabaseTestCase /** * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws CryptoException * @throws NoSuchItemException */ diff --git a/tests/SP/Services/Account/AccountFileServiceTest.php b/tests/SP/Services/Account/AccountFileServiceTest.php index a9c6221e..7098c70e 100644 --- a/tests/SP/Services/Account/AccountFileServiceTest.php +++ b/tests/SP/Services/Account/AccountFileServiceTest.php @@ -34,9 +34,9 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\FileData; use SP\DataModel\FileExtData; use SP\DataModel\ItemSearchData; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountFileService; -use SP\Services\ServiceException; +use SP\Domain\Account\Services\AccountFileService; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -48,7 +48,7 @@ use function SP\Tests\setupContext; class AccountFileServiceTest extends DatabaseTestCase { /** - * @var AccountFileService + * @var \SP\Domain\Services\AccountFileServiceInterface */ private static $service; diff --git a/tests/SP/Services/Account/AccountHistoryServiceTest.php b/tests/SP/Services/Account/AccountHistoryServiceTest.php index 533ac837..e77d7837 100644 --- a/tests/SP/Services/Account/AccountHistoryServiceTest.php +++ b/tests/SP/Services/Account/AccountHistoryServiceTest.php @@ -34,10 +34,11 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\AccountHistoryData; use SP\DataModel\Dto\AccountHistoryCreateDto; use SP\DataModel\ItemSearchData; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountHistoryService; -use SP\Services\Account\AccountPasswordRequest; -use SP\Services\ServiceException; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Account\Services\AccountHistoryService; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use function SP\Tests\setupContext; @@ -50,7 +51,7 @@ use function SP\Tests\setupContext; class AccountHistoryServiceTest extends DatabaseTestCase { /** - * @var AccountHistoryService + * @var AccountHistoryServiceInterface */ private static $service; diff --git a/tests/SP/Services/Account/AccountSearchServiceTest.php b/tests/SP/Services/Account/AccountSearchServiceTest.php index 56194d8c..229ab255 100644 --- a/tests/SP/Services/Account/AccountSearchServiceTest.php +++ b/tests/SP/Services/Account/AccountSearchServiceTest.php @@ -33,12 +33,13 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\UserPreferencesData; +use SP\Domain\Account\AccountSearchServiceInterface; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Domain\Account\Services\AccountSearchItem; +use SP\Domain\Account\Services\AccountSearchService; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Infrastructure\Database\QueryResult; use SP\Mvc\Model\QueryCondition; -use SP\Services\Account\AccountSearchFilter; -use SP\Services\Account\AccountSearchItem; -use SP\Services\Account\AccountSearchService; -use SP\Services\User\UserLoginResponse; -use SP\Storage\Database\QueryResult; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -50,7 +51,7 @@ use function SP\Tests\setupContext; class AccountSearchServiceTest extends DatabaseTestCase { /** - * @var AccountSearchService + * @var AccountSearchServiceInterface */ private static $service; /** diff --git a/tests/SP/Services/Account/AccountServiceTest.php b/tests/SP/Services/Account/AccountServiceTest.php index cf99c3a6..d42f648f 100644 --- a/tests/SP/Services/Account/AccountServiceTest.php +++ b/tests/SP/Services/Account/AccountServiceTest.php @@ -40,15 +40,16 @@ use SP\DataModel\AccountSearchVData; use SP\DataModel\AccountVData; use SP\DataModel\ItemSearchData; use SP\DataModel\ProfileData; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountBulkRequest; -use SP\Services\Account\AccountHistoryService; -use SP\Services\Account\AccountPasswordRequest; -use SP\Services\Account\AccountRequest; -use SP\Services\Account\AccountSearchFilter; -use SP\Services\Account\AccountService; -use SP\Services\ServiceException; -use SP\Services\User\UserLoginResponse; +use SP\Domain\Account\AccountHistoryServiceInterface; +use SP\Domain\Account\Services\AccountBulkRequest; +use SP\Domain\Account\Services\AccountHistoryService; +use SP\Domain\Account\Services\AccountPasswordRequest; +use SP\Domain\Account\Services\AccountRequest; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use stdClass; @@ -63,7 +64,7 @@ class AccountServiceTest extends DatabaseTestCase { const SECURE_KEY_PASSWORD = '12345678900'; /** - * @var AccountHistoryService + * @var AccountHistoryServiceInterface */ protected static $accountHistoryService; /** @@ -177,7 +178,7 @@ class AccountServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testDelete() { @@ -292,7 +293,7 @@ class AccountServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws CryptoException */ public function testGetPasswordEncrypted() @@ -646,7 +647,7 @@ class AccountServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws SPException */ public function testDeleteByIdBatch() diff --git a/tests/SP/Services/Account/AccountToFavoriteServiceTest.php b/tests/SP/Services/Account/AccountToFavoriteServiceTest.php index 1db8dffe..ece99042 100644 --- a/tests/SP/Services/Account/AccountToFavoriteServiceTest.php +++ b/tests/SP/Services/Account/AccountToFavoriteServiceTest.php @@ -29,7 +29,8 @@ use DI\NotFoundException; use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Services\Account\AccountToFavoriteService; +use SP\Domain\Account\AccountToFavoriteServiceInterface; +use SP\Domain\Account\Services\AccountToFavoriteService; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -41,7 +42,7 @@ use function SP\Tests\setupContext; class AccountToFavoriteServiceTest extends DatabaseTestCase { /** - * @var AccountToFavoriteService + * @var AccountToFavoriteServiceInterface */ private static $service; diff --git a/tests/SP/Services/Account/AccountToTagServiceTest.php b/tests/SP/Services/Account/AccountToTagServiceTest.php index 11864905..fd683885 100644 --- a/tests/SP/Services/Account/AccountToTagServiceTest.php +++ b/tests/SP/Services/Account/AccountToTagServiceTest.php @@ -29,7 +29,8 @@ use DI\NotFoundException; use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Services\Account\AccountToTagService; +use SP\Domain\Account\AccountToTagServiceInterface; +use SP\Domain\Account\Services\AccountToTagService; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -41,7 +42,7 @@ use function SP\Tests\setupContext; class AccountToTagServiceTest extends DatabaseTestCase { /** - * @var AccountToTagService + * @var AccountToTagServiceInterface */ private static $service; diff --git a/tests/SP/Services/Api/ApiRequestTest.php b/tests/SP/Services/Api/ApiRequestTest.php index b1c758fd..94af3b68 100644 --- a/tests/SP/Services/Api/ApiRequestTest.php +++ b/tests/SP/Services/Api/ApiRequestTest.php @@ -25,8 +25,8 @@ namespace SP\Tests\Services\Api; use PHPUnit\Framework\TestCase; -use SP\Services\Api\ApiRequest; -use SP\Services\Api\ApiRequestException; +use SP\Domain\Api\Services\ApiRequest; +use SP\Domain\Api\Services\ApiRequestException; use function SP\Tests\getResource; /** diff --git a/tests/SP/Services/Api/ApiServiceTest.php b/tests/SP/Services/Api/ApiServiceTest.php index ab7dd7f2..28d3d762 100644 --- a/tests/SP/Services/Api/ApiServiceTest.php +++ b/tests/SP/Services/Api/ApiServiceTest.php @@ -30,9 +30,10 @@ use DI\NotFoundException; use SP\Core\Acl\ActionsInterface; use SP\Core\Context\ContextException; use SP\Core\Exceptions\SPException; -use SP\Services\Api\ApiRequest; -use SP\Services\Api\ApiService; -use SP\Services\ServiceException; +use SP\Domain\Api\ApiServiceInterface; +use SP\Domain\Api\Services\ApiRequest; +use SP\Domain\Api\Services\ApiService; +use SP\Domain\Common\Services\ServiceException; use SP\Tests\DatabaseTestCase; use function SP\Tests\getResource; use function SP\Tests\setupContext; @@ -49,7 +50,7 @@ class ApiServiceTest extends DatabaseTestCase const DEMO_TOKEN = '12b9027d24efff7bfbaca8bd774a4c34b45de35e033d2b192a88f4dfaee5c233'; /** - * @var ApiService + * @var ApiServiceInterface */ private static $service; /** @@ -77,7 +78,7 @@ class ApiServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws SPException */ public function testSetup() @@ -132,7 +133,7 @@ class ApiServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws SPException */ public function testGetParamInt() @@ -168,7 +169,7 @@ class ApiServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws SPException */ public function testGetParamRaw() @@ -194,7 +195,7 @@ class ApiServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testGetMasterPass() { diff --git a/tests/SP/Services/AuthToken/AuthTokenServiceTest.php b/tests/SP/Services/AuthToken/AuthTokenServiceTest.php index 108d5a9d..83c57714 100644 --- a/tests/SP/Services/AuthToken/AuthTokenServiceTest.php +++ b/tests/SP/Services/AuthToken/AuthTokenServiceTest.php @@ -38,10 +38,10 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\AuthTokenData; use SP\DataModel\ItemSearchData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\AuthToken\AuthTokenService; -use SP\Services\ServiceException; +use SP\Domain\Auth\Services\AuthTokenService; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use SP\Util\Util; use stdClass; @@ -141,7 +141,7 @@ class AuthTokenServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws CryptoException * @throws ConstraintException * @throws QueryException diff --git a/tests/SP/Services/Backup/FileBackupServiceTest.php b/tests/SP/Services/Backup/FileBackupServiceTest.php index e3af676a..8ad4fc60 100644 --- a/tests/SP/Services/Backup/FileBackupServiceTest.php +++ b/tests/SP/Services/Backup/FileBackupServiceTest.php @@ -25,12 +25,12 @@ namespace SP\Tests\Services\Backup; use SP\Core\PhpExtensionChecker; -use SP\Services\Backup\BackupFiles; -use SP\Services\Backup\FileBackupService; -use SP\Storage\Database\Database; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\Database\MySQLHandler; -use SP\Storage\File\ArchiveHandler; +use SP\Domain\Export\Services\BackupFiles; +use SP\Domain\Export\Services\FileBackupService; +use SP\Infrastructure\Database\Database; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\Database\MySQLHandler; +use SP\Infrastructure\File\ArchiveHandler; use SP\Tests\UnitaryTestCase; /** @@ -44,7 +44,7 @@ class FileBackupServiceTest extends UnitaryTestCase private BackupFiles $backupFiles; /** - * @throws \SP\Services\ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testDoBackup(): void { diff --git a/tests/SP/Services/Category/CategoryServiceTest.php b/tests/SP/Services/Category/CategoryServiceTest.php index dd07bb96..4eef1956 100644 --- a/tests/SP/Services/Category/CategoryServiceTest.php +++ b/tests/SP/Services/Category/CategoryServiceTest.php @@ -32,10 +32,10 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CategoryData; use SP\DataModel\ItemSearchData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Category\CategoryService; -use SP\Services\ServiceException; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -48,7 +48,7 @@ use function SP\Tests\setupContext; class CategoryServiceTest extends DatabaseTestCase { /** - * @var CategoryService + * @var \SP\Domain\Category\CategoryServiceInterface */ private static $service; diff --git a/tests/SP/Services/Client/ClientServiceTest.php b/tests/SP/Services/Client/ClientServiceTest.php index e227ffbb..56ff2c4c 100644 --- a/tests/SP/Services/Client/ClientServiceTest.php +++ b/tests/SP/Services/Client/ClientServiceTest.php @@ -34,11 +34,11 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ClientData; use SP\DataModel\ItemSearchData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Client\ClientService; -use SP\Services\ServiceException; -use SP\Services\User\UserLoginResponse; +use SP\Domain\Client\Services\ClientService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -54,7 +54,7 @@ class ClientServiceTest extends DatabaseTestCase */ private static $setupUser; /** - * @var ClientService + * @var \SP\Domain\Client\ClientServiceInterface */ private static $service; diff --git a/tests/SP/Services/Config/ConfigBackupServiceTest.php b/tests/SP/Services/Config/ConfigBackupServiceTest.php index bc09b5d6..4bc316a7 100644 --- a/tests/SP/Services/Config/ConfigBackupServiceTest.php +++ b/tests/SP/Services/Config/ConfigBackupServiceTest.php @@ -27,13 +27,13 @@ namespace SP\Tests\Services\Config; use DI\DependencyException; use DI\NotFoundException; use PHPUnit\Framework\TestCase; -use SP\Config\Config; -use SP\Config\ConfigData; -use SP\Config\ConfigDataInterface; use SP\Core\Context\ContextException; -use SP\Services\Config\ConfigBackupService; -use SP\Services\ServiceException; -use SP\Storage\File\FileException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\Adapters\ConfigData; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Config\Services\ConfigBackupService; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Infrastructure\File\FileException; use function SP\Tests\getResource; use function SP\Tests\recreateDir; use function SP\Tests\saveResource; @@ -102,7 +102,7 @@ class ConfigBackupServiceTest extends TestCase $this->assertEquals($configData->getConfigVersion(), $data->getConfigVersion()); - $config = $dic->get(Config::class)->loadConfigFromFile(); + $config = $dic->get(ConfigFileService::class)->loadConfigFromFile(); $this->assertEquals($config->getConfigVersion(), $data->getConfigVersion()); $this->assertGreaterThanOrEqual($config->getConfigDate(), $data->getConfigDate()); diff --git a/tests/SP/Services/Config/ConfigServiceTest.php b/tests/SP/Services/Config/ConfigServiceTest.php index 54ba30c3..ef3ed6d5 100644 --- a/tests/SP/Services/Config/ConfigServiceTest.php +++ b/tests/SP/Services/Config/ConfigServiceTest.php @@ -31,9 +31,10 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\ConfigData; use SP\DataModel\Dto\ConfigRequest; -use SP\Repositories\NoSuchItemException; -use SP\Services\Config\ConfigService; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\ConfigServiceInterface; +use SP\Domain\Config\Services\ConfigService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -45,7 +46,7 @@ use function SP\Tests\setupContext; class ConfigServiceTest extends DatabaseTestCase { /** - * @var ConfigService + * @var ConfigServiceInterface */ private static $service; @@ -113,7 +114,7 @@ class ConfigServiceTest extends DatabaseTestCase * @throws NoSuchItemException * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testSave() { @@ -127,7 +128,7 @@ class ConfigServiceTest extends DatabaseTestCase * @throws NoSuchItemException * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testCreate() { diff --git a/tests/SP/Services/Crypt/MasterPassServiceTest.php b/tests/SP/Services/Crypt/MasterPassServiceTest.php index fbaf8342..d72381fe 100644 --- a/tests/SP/Services/Crypt/MasterPassServiceTest.php +++ b/tests/SP/Services/Crypt/MasterPassServiceTest.php @@ -32,12 +32,11 @@ use SP\Core\Context\ContextException; use SP\Core\Crypt\Crypt; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountService; -use SP\Services\Crypt\MasterPassService; -use SP\Services\Crypt\UpdateMasterPassRequest; -use SP\Services\CustomField\CustomFieldService; -use SP\Services\ServiceException; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Crypt\Services\MasterPassService; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; +use SP\Domain\CustomField\Services\CustomFieldService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use SP\Tests\Services\Account\AccountCryptServiceTest; use function SP\Tests\setupContext; @@ -50,7 +49,7 @@ use function SP\Tests\setupContext; class MasterPassServiceTest extends DatabaseTestCase { /** - * @var CustomFieldService + * @var \SP\Domain\CustomField\CustomFieldServiceInterface */ private static $customFieldService; /** @@ -58,7 +57,7 @@ class MasterPassServiceTest extends DatabaseTestCase */ private static $accountService; /** - * @var MasterPassService + * @var \SP\Domain\Crypt\MasterPassServiceInterface */ private static $service; @@ -178,7 +177,7 @@ class MasterPassServiceTest extends DatabaseTestCase /** * @throws NoSuchItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testCheckUserUpdateMPass() { @@ -188,7 +187,7 @@ class MasterPassServiceTest extends DatabaseTestCase /** * @throws NoSuchItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testCheckMasterPassword() { diff --git a/tests/SP/Services/Crypt/SecureSessionServiceTest.php b/tests/SP/Services/Crypt/SecureSessionServiceTest.php index 600155f1..8b7c7a98 100644 --- a/tests/SP/Services/Crypt/SecureSessionServiceTest.php +++ b/tests/SP/Services/Crypt/SecureSessionServiceTest.php @@ -30,7 +30,7 @@ use DI\NotFoundException; use PHPUnit\Framework\TestCase; use SP\Core\Context\ContextException; use SP\Core\Crypt\UUIDCookie; -use SP\Services\Crypt\SecureSessionService; +use SP\Domain\Crypt\Services\SecureSessionService; use function SP\Tests\setupContext; /** diff --git a/tests/SP/Services/Crypt/TemporaryMasterPassServiceTest.php b/tests/SP/Services/Crypt/TemporaryMasterPassServiceTest.php index 3d3546c0..f3403b3c 100644 --- a/tests/SP/Services/Crypt/TemporaryMasterPassServiceTest.php +++ b/tests/SP/Services/Crypt/TemporaryMasterPassServiceTest.php @@ -30,9 +30,8 @@ use DI\NotFoundException; use PHPUnit\Framework\TestCase; use SP\Core\Context\ContextException; use SP\Core\Context\ContextInterface; -use SP\Repositories\NoSuchItemException; -use SP\Services\Crypt\TemporaryMasterPassService; -use SP\Services\ServiceException; +use SP\Domain\Crypt\Services\TemporaryMasterPassService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use function SP\Tests\setupContext; /** @@ -47,7 +46,7 @@ class TemporaryMasterPassServiceTest extends TestCase */ private $context; /** - * @var TemporaryMasterPassService + * @var \SP\Domain\Crypt\TemporaryMasterPassServiceInterface */ private $service; @@ -67,7 +66,7 @@ class TemporaryMasterPassServiceTest extends TestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testCreate() { @@ -86,7 +85,7 @@ class TemporaryMasterPassServiceTest extends TestCase * * @throws CryptoException * @throws NoSuchItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testGetUsingKey($key) { @@ -102,7 +101,7 @@ class TemporaryMasterPassServiceTest extends TestCase * * @param $key * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testCheckTempMasterPass($key) { @@ -117,7 +116,7 @@ class TemporaryMasterPassServiceTest extends TestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testExpiredKey() { diff --git a/tests/SP/Services/CustomField/CustomFieldCryptServiceTest.php b/tests/SP/Services/CustomField/CustomFieldCryptServiceTest.php index 8eea239e..d23a1357 100644 --- a/tests/SP/Services/CustomField/CustomFieldCryptServiceTest.php +++ b/tests/SP/Services/CustomField/CustomFieldCryptServiceTest.php @@ -31,10 +31,11 @@ use SP\Core\Context\ContextException; use SP\Core\Crypt\Crypt; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Services\Crypt\UpdateMasterPassRequest; -use SP\Services\CustomField\CustomFieldCryptService; -use SP\Services\CustomField\CustomFieldService; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Crypt\Services\UpdateMasterPassRequest; +use SP\Domain\CustomField\CustomFieldCryptServiceInterface; +use SP\Domain\CustomField\Services\CustomFieldCryptService; +use SP\Domain\CustomField\Services\CustomFieldService; use SP\Tests\DatabaseTestCase; use SP\Tests\Services\Account\AccountCryptServiceTest; use function SP\Tests\setupContext; @@ -47,11 +48,11 @@ use function SP\Tests\setupContext; class CustomFieldCryptServiceTest extends DatabaseTestCase { /** - * @var CustomFieldService + * @var \SP\Domain\CustomField\CustomFieldServiceInterface */ private static $customFieldService; /** - * @var CustomFieldCryptService + * @var CustomFieldCryptServiceInterface */ private static $service; @@ -74,7 +75,7 @@ class CustomFieldCryptServiceTest extends DatabaseTestCase /** * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws CryptoException */ public function testUpdateMasterPassword() diff --git a/tests/SP/Services/CustomField/CustomFieldDefServiceTest.php b/tests/SP/Services/CustomField/CustomFieldDefServiceTest.php index ab245e9c..61bb0176 100644 --- a/tests/SP/Services/CustomField/CustomFieldDefServiceTest.php +++ b/tests/SP/Services/CustomField/CustomFieldDefServiceTest.php @@ -32,9 +32,9 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\DataModel\CustomFieldDefinitionData; use SP\DataModel\ItemSearchData; -use SP\Repositories\NoSuchItemException; -use SP\Services\CustomField\CustomFieldDefService; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\CustomField\Services\CustomFieldDefService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -66,7 +66,7 @@ class CustomFieldDefServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testDelete() { @@ -192,7 +192,7 @@ class CustomFieldDefServiceTest extends DatabaseTestCase * @throws ConstraintException * @throws NoSuchItemException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdate() { diff --git a/tests/SP/Services/CustomField/CustomFieldServiceTest.php b/tests/SP/Services/CustomField/CustomFieldServiceTest.php index c184a611..8f453bb9 100644 --- a/tests/SP/Services/CustomField/CustomFieldServiceTest.php +++ b/tests/SP/Services/CustomField/CustomFieldServiceTest.php @@ -34,9 +34,9 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\CustomFieldData; -use SP\Repositories\NoSuchItemException; -use SP\Services\CustomField\CustomFieldService; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\CustomField\Services\CustomFieldService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use SP\Tests\Services\Account\AccountCryptServiceTest; use function SP\Tests\setupContext; @@ -49,7 +49,7 @@ use function SP\Tests\setupContext; class CustomFieldServiceTest extends DatabaseTestCase { /** - * @var CustomFieldService + * @var \SP\Domain\CustomField\CustomFieldServiceInterface */ private static $service; @@ -85,7 +85,7 @@ class CustomFieldServiceTest extends DatabaseTestCase * @throws CryptoException * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdateMasterPass() { diff --git a/tests/SP/Services/Eventlog/EventlogServiceTest.php b/tests/SP/Services/Eventlog/EventlogServiceTest.php index 6b2aaa38..fc05cd16 100644 --- a/tests/SP/Services/Eventlog/EventlogServiceTest.php +++ b/tests/SP/Services/Eventlog/EventlogServiceTest.php @@ -32,7 +32,8 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\EventlogData; use SP\DataModel\ItemSearchData; -use SP\Services\EventLog\EventlogService; +use SP\Domain\Security\EventlogServiceInterface; +use SP\Domain\Security\Services\EventlogService; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -45,7 +46,7 @@ use function SP\Tests\setupContext; class EventlogServiceTest extends DatabaseTestCase { /** - * @var EventlogService + * @var EventlogServiceInterface */ private static $service; diff --git a/tests/SP/Services/Export/XmlExportServiceTest.php b/tests/SP/Services/Export/XmlExportServiceTest.php index 23d23243..390b5903 100644 --- a/tests/SP/Services/Export/XmlExportServiceTest.php +++ b/tests/SP/Services/Export/XmlExportServiceTest.php @@ -28,11 +28,12 @@ use Defuse\Crypto\Exception\CryptoException; use DI\DependencyException; use DI\NotFoundException; use SP\Core\Context\ContextException; -use SP\Services\Export\VerifyResult; -use SP\Services\Export\XmlExportService; -use SP\Services\Export\XmlVerifyService; -use SP\Services\ServiceException; -use SP\Storage\File\FileException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Export\Services\VerifyResult; +use SP\Domain\Export\Services\XmlExportService; +use SP\Domain\Export\Services\XmlVerifyService; +use SP\Domain\Export\XmlVerifyServiceInterface; +use SP\Infrastructure\File\FileException; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use function SP\Tests\setupContext; @@ -45,11 +46,11 @@ use function SP\Tests\setupContext; class XmlExportServiceTest extends DatabaseTestCase { /** - * @var XmlExportService + * @var \SP\Domain\Export\XmlExportServiceInterface */ private static $xmlExportService; /** - * @var XmlVerifyService + * @var XmlVerifyServiceInterface */ private static $xmlVerifyService; @@ -71,7 +72,7 @@ class XmlExportServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws FileException */ public function testDoExportWithoutPassword() @@ -88,7 +89,7 @@ class XmlExportServiceTest extends DatabaseTestCase * * @param $file * - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws FileException */ private function verifyExportWithoutPassword($file) @@ -120,7 +121,7 @@ class XmlExportServiceTest extends DatabaseTestCase /** * @throws CryptoException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws FileException */ public function testDoExportWithPassword() @@ -139,7 +140,7 @@ class XmlExportServiceTest extends DatabaseTestCase * @param $password * * @throws CryptoException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws FileException */ private function verifyExportWithPassword($file, $password) diff --git a/tests/SP/Services/Export/XmlVerifyServiceTest.php b/tests/SP/Services/Export/XmlVerifyServiceTest.php index 921508a0..18de66bc 100644 --- a/tests/SP/Services/Export/XmlVerifyServiceTest.php +++ b/tests/SP/Services/Export/XmlVerifyServiceTest.php @@ -29,11 +29,10 @@ use DI\NotFoundException; use DOMDocument; use PHPUnit\Framework\TestCase; use SP\Core\Context\ContextException; -use SP\Services\Export\VerifyResult; -use SP\Services\Export\XmlVerifyService; -use SP\Services\Import\ImportException; -use SP\Services\ServiceException; -use SP\Storage\File\FileException; +use SP\Domain\Export\Services\VerifyResult; +use SP\Domain\Export\Services\XmlVerifyService; +use SP\Domain\Import\Services\ImportException; +use SP\Infrastructure\File\FileException; use function SP\Tests\setupContext; /** @@ -44,7 +43,7 @@ use function SP\Tests\setupContext; class XmlVerifyServiceTest extends TestCase { /** - * @var XmlVerifyService + * @var \SP\Domain\Export\XmlVerifyServiceInterface */ private static $xmlVerifyService; @@ -63,7 +62,7 @@ class XmlVerifyServiceTest extends TestCase /** * @throws FileException * @throws ImportException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testVerifyEncrypted() { @@ -85,7 +84,7 @@ class XmlVerifyServiceTest extends TestCase /** * @throws FileException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws ImportException */ public function testVerify() diff --git a/tests/SP/Services/Import/CsvImportTest.php b/tests/SP/Services/Import/CsvImportTest.php index 4d96d508..b55e0b61 100644 --- a/tests/SP/Services/Import/CsvImportTest.php +++ b/tests/SP/Services/Import/CsvImportTest.php @@ -32,15 +32,15 @@ use SP\Core\Context\ContextException; use SP\Core\Crypt\Crypt; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Import\CsvImport; -use SP\Services\Import\FileImport; -use SP\Services\Import\ImportException; -use SP\Services\Import\ImportParams; -use SP\Storage\File\FileException; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Client\Services\ClientService; +use SP\Domain\Import\Services\CsvImport; +use SP\Domain\Import\Services\FileImport; +use SP\Domain\Import\Services\ImportException; +use SP\Domain\Import\Services\ImportParams; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\File\FileException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; diff --git a/tests/SP/Services/Import/KeepassImportTest.php b/tests/SP/Services/Import/KeepassImportTest.php index 74d83f05..eb7568f5 100644 --- a/tests/SP/Services/Import/KeepassImportTest.php +++ b/tests/SP/Services/Import/KeepassImportTest.php @@ -34,17 +34,17 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\AccountSearchVData; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountSearchFilter; -use SP\Services\Account\AccountService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Import\FileImport; -use SP\Services\Import\ImportException; -use SP\Services\Import\ImportParams; -use SP\Services\Import\KeepassImport; -use SP\Services\Import\XmlFileImport; -use SP\Storage\File\FileException; +use SP\Domain\Account\Services\AccountSearchFilter; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Client\Services\ClientService; +use SP\Domain\Import\Services\FileImport; +use SP\Domain\Import\Services\ImportException; +use SP\Domain\Import\Services\ImportParams; +use SP\Domain\Import\Services\KeepassImport; +use SP\Domain\Import\Services\XmlFileImport; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\File\FileException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; diff --git a/tests/SP/Services/Import/SyspassImportTest.php b/tests/SP/Services/Import/SyspassImportTest.php index 19af6799..506a7fae 100644 --- a/tests/SP/Services/Import/SyspassImportTest.php +++ b/tests/SP/Services/Import/SyspassImportTest.php @@ -32,16 +32,16 @@ use SP\Core\Context\ContextException; use SP\Core\Crypt\Crypt; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; -use SP\Repositories\NoSuchItemException; -use SP\Services\Account\AccountService; -use SP\Services\Category\CategoryService; -use SP\Services\Client\ClientService; -use SP\Services\Import\FileImport; -use SP\Services\Import\ImportException; -use SP\Services\Import\ImportParams; -use SP\Services\Import\SyspassImport; -use SP\Services\Import\XmlFileImport; -use SP\Storage\File\FileException; +use SP\Domain\Account\Services\AccountService; +use SP\Domain\Category\Services\CategoryService; +use SP\Domain\Client\Services\ClientService; +use SP\Domain\Import\Services\FileImport; +use SP\Domain\Import\Services\ImportException; +use SP\Domain\Import\Services\ImportParams; +use SP\Domain\Import\Services\SyspassImport; +use SP\Domain\Import\Services\XmlFileImport; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\File\FileException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; diff --git a/tests/SP/Services/Import/XmlFileImportTest.php b/tests/SP/Services/Import/XmlFileImportTest.php index 40f1e8c9..eed20f5d 100644 --- a/tests/SP/Services/Import/XmlFileImportTest.php +++ b/tests/SP/Services/Import/XmlFileImportTest.php @@ -25,10 +25,10 @@ namespace SP\Tests\Services\Import; use PHPUnit\Framework\TestCase; -use SP\Services\Import\FileImport; -use SP\Services\Import\ImportException; -use SP\Services\Import\XmlFileImport; -use SP\Storage\File\FileException; +use SP\Domain\Import\Services\FileImport; +use SP\Domain\Import\Services\ImportException; +use SP\Domain\Import\Services\XmlFileImport; +use SP\Infrastructure\File\FileException; /** * Class XmlFileImportTest diff --git a/tests/SP/Services/Import/XmlImportTest.php b/tests/SP/Services/Import/XmlImportTest.php index 7c0cf875..1a6933fa 100644 --- a/tests/SP/Services/Import/XmlImportTest.php +++ b/tests/SP/Services/Import/XmlImportTest.php @@ -27,12 +27,12 @@ namespace SP\Tests\Services\Import; use DI\Container; use SP\Core\Context\ContextException; use SP\Core\Exceptions\SPException; -use SP\Services\Import\FileImport; -use SP\Services\Import\ImportException; -use SP\Services\Import\ImportParams; -use SP\Services\Import\XmlFileImport; -use SP\Services\Import\XmlImport; -use SP\Storage\File\FileException; +use SP\Domain\Import\Services\FileImport; +use SP\Domain\Import\Services\ImportException; +use SP\Domain\Import\Services\ImportParams; +use SP\Domain\Import\Services\XmlFileImport; +use SP\Domain\Import\Services\XmlImport; +use SP\Infrastructure\File\FileException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; diff --git a/tests/SP/Services/Install/InstallerTest.php b/tests/SP/Services/Install/InstallerTest.php index b186dd20..be8c8b59 100644 --- a/tests/SP/Services/Install/InstallerTest.php +++ b/tests/SP/Services/Install/InstallerTest.php @@ -27,14 +27,15 @@ namespace SP\Tests\Services\Install; use Exception; use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\SPException; +use SP\Domain\Config\Services\ConfigService; +use SP\Domain\Install\Services\InstallData; +use SP\Domain\Install\Services\Installer; +use SP\Domain\User\Services\UserGroupService; +use SP\Domain\User\Services\UserProfileService; +use SP\Domain\User\Services\UserService; +use SP\Domain\User\UserProfileServiceInterface; use SP\Http\Request; -use SP\Services\Config\ConfigService; -use SP\Services\Install\DatabaseSetupInterface; -use SP\Services\Install\InstallData; -use SP\Services\Install\Installer; -use SP\Services\User\UserService; -use SP\Services\UserGroup\UserGroupService; -use SP\Services\UserProfile\UserProfileService; +use SP\Http\RequestInterface; use SP\Tests\UnitaryTestCase; use SP\Util\VersionUtil; @@ -46,27 +47,27 @@ use SP\Util\VersionUtil; class InstallerTest extends UnitaryTestCase { /** - * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Services\Install\DatabaseSetupInterface + * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Domain\Install\DatabaseSetupInterface */ private $databaseSetup; /** - * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Services\User\UserService + * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Domain\User\Services\UserService */ private $userService; /** - * @var \PHPUnit\Framework\MockObject\Stub|\SP\Http\Request + * @var \PHPUnit\Framework\MockObject\Stub|RequestInterface */ private $request; /** - * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Services\Config\ConfigService + * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Domain\Config\ConfigServiceInterface */ private $configService; /** - * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Services\UserGroup\UserGroupService + * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Domain\User\UserGroupServiceInterface */ private $userGroupService; /** - * @var \PHPUnit\Framework\MockObject\MockObject|\SP\Services\UserProfile\UserProfileService + * @var \PHPUnit\Framework\MockObject\MockObject|UserProfileServiceInterface */ private $userProfileService; @@ -110,7 +111,7 @@ class InstallerTest extends UnitaryTestCase } /** - * @return \SP\Services\Install\InstallData + * @return \SP\Domain\Install\Services\InstallData */ private function getInstallData(): InstallData { @@ -128,9 +129,9 @@ class InstallerTest extends UnitaryTestCase } /** - * @return \SP\Services\Install\Installer + * @return \SP\Domain\Install\InstallerInterface */ - private function getDefaultInstaller(): Installer + private function getDefaultInstaller(): \SP\Domain\Install\InstallerInterface { return new Installer( $this->request, @@ -458,7 +459,7 @@ class InstallerTest extends UnitaryTestCase */ protected function setUp(): void { - $this->databaseSetup = $this->createMock(DatabaseSetupInterface::class); + $this->databaseSetup = $this->createMock(\SP\Domain\Install\DatabaseSetupInterface::class); $this->userService = $this->createMock(UserService::class); $this->request = $this->createStub(Request::class); $this->configService = $this->createMock(ConfigService::class); diff --git a/tests/SP/Services/Install/MySQLTest.php b/tests/SP/Services/Install/MySQLTest.php index bc39b395..cc0a514c 100644 --- a/tests/SP/Services/Install/MySQLTest.php +++ b/tests/SP/Services/Install/MySQLTest.php @@ -25,14 +25,14 @@ namespace SP\Tests\Services\Install; use PDOException; -use SP\Config\ConfigDataInterface; use SP\Core\Exceptions\SPException; -use SP\Services\Install\InstallData; -use SP\Services\Install\MySQL; -use SP\Storage\Database\DatabaseFileInterface; -use SP\Storage\Database\DatabaseUtil; -use SP\Storage\Database\DBStorageInterface; -use SP\Storage\File\FileException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\Install\Services\InstallData; +use SP\Domain\Install\Services\MySQL; +use SP\Infrastructure\Database\DatabaseFileInterface; +use SP\Infrastructure\Database\DatabaseUtil; +use SP\Infrastructure\Database\DBStorageInterface; +use SP\Infrastructure\File\FileException; use SP\Tests\Stubs\Pdo; use SP\Tests\UnitaryTestCase; @@ -767,7 +767,7 @@ class MySQLTest extends UnitaryTestCase } /** - * @return \SP\Services\Install\InstallData + * @return \SP\Domain\Install\Services\InstallData */ private function getInstallData(): InstallData { diff --git a/tests/SP/Services/ItemPreset/ItemPresetServiceTest.php b/tests/SP/Services/ItemPreset/ItemPresetServiceTest.php index 4ebfe8cf..7f519021 100644 --- a/tests/SP/Services/ItemPreset/ItemPresetServiceTest.php +++ b/tests/SP/Services/ItemPreset/ItemPresetServiceTest.php @@ -33,9 +33,9 @@ use SP\Core\Exceptions\QueryException; use SP\DataModel\ItemPreset\AccountPermission; use SP\DataModel\ItemPresetData; use SP\DataModel\ItemSearchData; -use SP\Repositories\NoSuchItemException; -use SP\Services\ItemPreset\ItemPresetRequest; -use SP\Services\ItemPreset\ItemPresetService; +use SP\Domain\ItemPreset\Services\ItemPresetRequest; +use SP\Domain\ItemPreset\Services\ItemPresetService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; diff --git a/tests/SP/Services/Notification/NotificationServiceTest.php b/tests/SP/Services/Notification/NotificationServiceTest.php index 68f07299..a7fc6a93 100644 --- a/tests/SP/Services/Notification/NotificationServiceTest.php +++ b/tests/SP/Services/Notification/NotificationServiceTest.php @@ -33,10 +33,10 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Messages\NotificationMessage; use SP\DataModel\ItemSearchData; use SP\DataModel\NotificationData; -use SP\Repositories\NoSuchItemException; -use SP\Services\Notification\NotificationService; -use SP\Services\ServiceException; -use SP\Services\User\UserLoginResponse; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Notification\Services\NotificationService; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -52,7 +52,7 @@ class NotificationServiceTest extends DatabaseTestCase */ private static $context; /** - * @var NotificationService + * @var \SP\Domain\Notification\NotificationServiceInterface */ private static $service; diff --git a/tests/SP/Services/Plugin/PluginDataServiceTest.php b/tests/SP/Services/Plugin/PluginDataServiceTest.php index 6dec8146..aa2ce60d 100644 --- a/tests/SP/Services/Plugin/PluginDataServiceTest.php +++ b/tests/SP/Services/Plugin/PluginDataServiceTest.php @@ -32,10 +32,9 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Plugin\PluginDataModel; -use SP\Services\Plugin\PluginDataService; -use SP\Services\ServiceException; +use SP\Domain\Plugin\PluginDataServiceInterface; +use SP\Domain\Plugin\Services\PluginDataService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -47,7 +46,7 @@ use function SP\Tests\setupContext; class PluginDataServiceTest extends DatabaseTestCase { /** - * @var PluginDataService + * @var PluginDataServiceInterface */ private static $service; @@ -72,11 +71,11 @@ class PluginDataServiceTest extends DatabaseTestCase * @throws CryptoException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdate() { - $data = new PluginDataModel(); + $data = new \SP\Infrastructure\Plugin\Repositories\PluginDataModel(); $data->setItemId(1); $data->setName('Authenticator'); $data->setData('data_updated'); @@ -87,7 +86,7 @@ class PluginDataServiceTest extends DatabaseTestCase $this->assertEquals('data_updated', $itemData->getData()); - $data = new PluginDataModel(); + $data = new \SP\Infrastructure\Plugin\Repositories\PluginDataModel(); $data->setItemId(0); $data->setName('Authenticator'); $data->setData('data_updated'); @@ -100,11 +99,11 @@ class PluginDataServiceTest extends DatabaseTestCase * @throws CryptoException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdateUnkown() { - $data = new PluginDataModel(); + $data = new \SP\Infrastructure\Plugin\Repositories\PluginDataModel(); $data->setItemId(2); $data->setName('Test'); $data->setData('data'); @@ -164,11 +163,11 @@ class PluginDataServiceTest extends DatabaseTestCase * @throws CryptoException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testCreate() { - $data = new PluginDataModel(); + $data = new \SP\Infrastructure\Plugin\Repositories\PluginDataModel(); $data->setItemId(4); $data->setName('Authenticator'); $data->setData('data'); @@ -190,13 +189,13 @@ class PluginDataServiceTest extends DatabaseTestCase * @throws CryptoException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testCreateUnknown() { $this->expectException(ConstraintException::class); - $data = new PluginDataModel(); + $data = new \SP\Infrastructure\Plugin\Repositories\PluginDataModel(); $data->setItemId(4); $data->setName('Test'); $data->setData('data'); @@ -210,13 +209,13 @@ class PluginDataServiceTest extends DatabaseTestCase * @throws CryptoException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testGetByItemId() { $data = self::$service->getByItemId('Authenticator', 1); - $this->assertInstanceOf(PluginDataModel::class, $data); + $this->assertInstanceOf(\SP\Infrastructure\Plugin\Repositories\PluginDataModel::class, $data); $this->assertEquals(1, $data->getItemId()); $this->assertEquals('Authenticator', $data->getName()); $this->assertEquals('data_item1', $data->getData()); @@ -228,7 +227,7 @@ class PluginDataServiceTest extends DatabaseTestCase * @throws CryptoException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testGetByItemIdUnkown() { @@ -247,12 +246,12 @@ class PluginDataServiceTest extends DatabaseTestCase $result = self::$service->getById('Authenticator'); $this->assertCount(2, $result); - $this->assertInstanceOf(PluginDataModel::class, $result[0]); + $this->assertInstanceOf(\SP\Infrastructure\Plugin\Repositories\PluginDataModel::class, $result[0]); $this->assertEquals(1, $result[0]->getItemId()); $this->assertEquals('Authenticator', $result[0]->getName()); $this->assertEquals('data_item1', $result[0]->getData()); - $this->assertInstanceOf(PluginDataModel::class, $result[1]); + $this->assertInstanceOf(\SP\Infrastructure\Plugin\Repositories\PluginDataModel::class, $result[1]); $this->assertEquals(2, $result[1]->getItemId()); $this->assertEquals('Authenticator', $result[1]->getName()); $this->assertEquals('plugin_data', $result[1]->getData()); diff --git a/tests/SP/Services/Plugin/PluginOperationTest.php b/tests/SP/Services/Plugin/PluginOperationTest.php index fc23014e..bc7f6177 100644 --- a/tests/SP/Services/Plugin/PluginOperationTest.php +++ b/tests/SP/Services/Plugin/PluginOperationTest.php @@ -32,10 +32,10 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\NoSuchPropertyException; use SP\Core\Exceptions\QueryException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Plugin\Services\PluginDataService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Plugin\PluginOperation; -use SP\Repositories\NoSuchItemException; -use SP\Services\Plugin\PluginDataService; -use SP\Services\ServiceException; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -75,7 +75,7 @@ class PluginOperationTest extends DatabaseTestCase * @throws ConstraintException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdate() { @@ -101,7 +101,7 @@ class PluginOperationTest extends DatabaseTestCase * @throws ConstraintException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdateUnknown() { @@ -174,7 +174,7 @@ class PluginOperationTest extends DatabaseTestCase * @throws ConstraintException * @throws NoSuchPropertyException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testGetUnknown() { diff --git a/tests/SP/Services/Plugin/PluginServiceTest.php b/tests/SP/Services/Plugin/PluginServiceTest.php index b2c48009..4e09c02f 100644 --- a/tests/SP/Services/Plugin/PluginServiceTest.php +++ b/tests/SP/Services/Plugin/PluginServiceTest.php @@ -32,10 +32,11 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemData; use SP\DataModel\ItemSearchData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Plugin\PluginModel; -use SP\Services\Plugin\PluginService; -use SP\Services\ServiceException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Plugin\PluginServiceInterface; +use SP\Domain\Plugin\Services\PluginService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Plugin\Repositories\PluginModel; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -47,7 +48,7 @@ use function SP\Tests\setupContext; class PluginServiceTest extends DatabaseTestCase { /** - * @var PluginService + * @var PluginServiceInterface */ private static $service; diff --git a/tests/SP/Services/PublicLink/PublicLinkServiceTest.php b/tests/SP/Services/PublicLink/PublicLinkServiceTest.php index 44c7fc3b..e940b969 100644 --- a/tests/SP/Services/PublicLink/PublicLinkServiceTest.php +++ b/tests/SP/Services/PublicLink/PublicLinkServiceTest.php @@ -28,7 +28,6 @@ use Defuse\Crypto\Exception\CryptoException; use Defuse\Crypto\Exception\EnvironmentIsBrokenException; use DI\DependencyException; use DI\NotFoundException; -use SP\Config\ConfigDataInterface; use SP\Core\Context\ContextException; use SP\Core\Crypt\Vault; use SP\Core\Exceptions\ConstraintException; @@ -38,10 +37,12 @@ use SP\DataModel\AccountExtData; use SP\DataModel\ItemSearchData; use SP\DataModel\PublicLinkData; use SP\DataModel\PublicLinkListData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\PublicLink\PublicLinkService; -use SP\Services\ServiceException; +use SP\Domain\Account\PublicLinkServiceInterface; +use SP\Domain\Account\Services\PublicLinkService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use SP\Util\Util; @@ -59,7 +60,7 @@ class PublicLinkServiceTest extends DatabaseTestCase */ private static $salt; /** - * @var PublicLinkService + * @var PublicLinkServiceInterface */ private static $service; diff --git a/tests/SP/Services/Tag/TagServiceTest.php b/tests/SP/Services/Tag/TagServiceTest.php index d35aa206..1694f83f 100644 --- a/tests/SP/Services/Tag/TagServiceTest.php +++ b/tests/SP/Services/Tag/TagServiceTest.php @@ -32,10 +32,10 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\TagData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\ServiceException; -use SP\Services\Tag\TagService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Tag\Services\TagService; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -48,7 +48,7 @@ use function SP\Tests\setupContext; class TagServiceTest extends DatabaseTestCase { /** - * @var TagService + * @var \SP\Domain\Tag\TagServiceInterface */ private static $service; diff --git a/tests/SP/Services/Task/TaskServiceTest.php b/tests/SP/Services/Task/TaskServiceTest.php index 1282aa8b..bf728caf 100644 --- a/tests/SP/Services/Task/TaskServiceTest.php +++ b/tests/SP/Services/Task/TaskServiceTest.php @@ -26,11 +26,11 @@ namespace SP\Tests\Services\Task; use PHPUnit\Framework\TestCase; use SP\Core\Context\ContextException; -use SP\Services\ServiceException; -use SP\Services\Task\Task; -use SP\Services\Task\TaskFactory; -use SP\Services\Task\TaskService; -use SP\Storage\File\FileException; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Task\Services\Task; +use SP\Domain\Task\Services\TaskFactory; +use SP\Domain\Task\Services\TaskService; +use SP\Infrastructure\File\FileException; use function SP\Tests\setupContext; /** diff --git a/tests/SP/Services/Track/TrackServiceTest.php b/tests/SP/Services/Track/TrackServiceTest.php index f3624eb5..38b75a7c 100644 --- a/tests/SP/Services/Track/TrackServiceTest.php +++ b/tests/SP/Services/Track/TrackServiceTest.php @@ -32,10 +32,10 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\InvalidArgumentException; use SP\Core\Exceptions\QueryException; use SP\DataModel\TrackData; -use SP\Repositories\NoSuchItemException; -use SP\Repositories\Track\TrackRequest; -use SP\Services\ServiceException; -use SP\Services\Track\TrackService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Security\Services\TrackService; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; +use SP\Infrastructure\Security\Repositories\TrackRequest; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -47,7 +47,7 @@ use function SP\Tests\setupContext; class TrackServiceTest extends DatabaseTestCase { /** - * @var TrackService + * @var \SP\Domain\Security\TrackServiceInterface */ private static $service; @@ -87,7 +87,7 @@ class TrackServiceTest extends DatabaseTestCase * @throws ConstraintException * @throws InvalidArgumentException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testAdd() { diff --git a/tests/SP/Services/User/UserPassServiceTest.php b/tests/SP/Services/User/UserPassServiceTest.php index 3e9e377a..84292e6d 100644 --- a/tests/SP/Services/User/UserPassServiceTest.php +++ b/tests/SP/Services/User/UserPassServiceTest.php @@ -34,10 +34,11 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\UserLoginData; -use SP\Repositories\NoSuchItemException; -use SP\Services\User\UserLoginResponse; -use SP\Services\User\UserPassService; -use SP\Services\User\UserService; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Domain\User\Services\UserPassService; +use SP\Domain\User\Services\UserService; +use SP\Domain\User\UserPassServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; @@ -57,7 +58,7 @@ class UserPassServiceTest extends DatabaseTestCase private static $getUserLoginResponse; /** - * @var UserPassService + * @var \SP\Domain\Services\UserPassServiceInterface */ private static $service; diff --git a/tests/SP/Services/User/UserServiceTest.php b/tests/SP/Services/User/UserServiceTest.php index 19086954..6fc3b964 100644 --- a/tests/SP/Services/User/UserServiceTest.php +++ b/tests/SP/Services/User/UserServiceTest.php @@ -27,8 +27,6 @@ namespace SP\Tests\Services\User; use Defuse\Crypto\Exception\CryptoException; use DI\DependencyException; use DI\NotFoundException; -use SP\Config\ConfigData; -use SP\Config\ConfigDataInterface; use SP\Core\Context\ContextException; use SP\Core\Crypt\Hash; use SP\Core\Exceptions\ConstraintException; @@ -37,11 +35,12 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserData; use SP\DataModel\UserPreferencesData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\ServiceException; -use SP\Services\User\UserLoginRequest; -use SP\Services\User\UserService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\Config\In\ConfigDataInterface; +use SP\Domain\User\Services\UserLoginRequest; +use SP\Domain\User\Services\UserService; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -49,14 +48,14 @@ use function SP\Tests\setupContext; /** * Class UserServiceTest * - * @package SP\Tests\SP\Services\User + * @package SP\Tests\SP\Domain\User\Services */ class UserServiceTest extends DatabaseTestCase { private const CURRENT_MASTERPASS = '12345678900'; /** - * @var ConfigDataInterface + * @var \SP\Domain\Config\In\ConfigDataInterface */ private static $configData; @@ -159,7 +158,7 @@ class UserServiceTest extends DatabaseTestCase * @throws QueryException * @throws SPException * @throws DuplicatedItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdate() { @@ -200,7 +199,7 @@ class UserServiceTest extends DatabaseTestCase * @throws QueryException * @throws SPException * @throws DuplicatedItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdateDuplicatedLogin() { @@ -228,7 +227,7 @@ class UserServiceTest extends DatabaseTestCase * @throws QueryException * @throws SPException * @throws DuplicatedItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdateDuplicatedEmail() { @@ -256,7 +255,7 @@ class UserServiceTest extends DatabaseTestCase * @throws QueryException * @throws SPException * @throws DuplicatedItemException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdateUnknown() { @@ -299,7 +298,7 @@ class UserServiceTest extends DatabaseTestCase /** * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException * @throws SPException */ public function testUpdatePass() diff --git a/tests/SP/Services/UserGroup/UserGroupServiceTest.php b/tests/SP/Services/UserGroup/UserGroupServiceTest.php index 24de88f3..a5813bf5 100644 --- a/tests/SP/Services/UserGroup/UserGroupServiceTest.php +++ b/tests/SP/Services/UserGroup/UserGroupServiceTest.php @@ -32,23 +32,22 @@ use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\UserGroupData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\ServiceException; -use SP\Services\UserGroup\UserGroupService; +use SP\Domain\Common\Services\ServiceException; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; /** * Class UserGroupServiceTest * - * @package SP\Tests\SP\Services\UserGroup + * @package SP\Tests\SP\Domain\Common\Services\UserGroup */ class UserGroupServiceTest extends DatabaseTestCase { /** - * @var UserGroupService + * @var \SP\Domain\User\UserGroupServiceInterface */ private static $service; @@ -65,7 +64,7 @@ class UserGroupServiceTest extends DatabaseTestCase self::$loadFixtures = true; // Inicializar el servicio - self::$service = $dic->get(UserGroupService::class); + self::$service = $dic->get(\SP\Domain\User\Services\UserGroupService::class); } /** @@ -132,7 +131,7 @@ class UserGroupServiceTest extends DatabaseTestCase /** * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testDeleteByIdBatchUsed() { @@ -145,7 +144,7 @@ class UserGroupServiceTest extends DatabaseTestCase /** * @throws ConstraintException * @throws QueryException - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testDeleteByIdBatchUnknown() { @@ -173,7 +172,7 @@ class UserGroupServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testUpdateDuplicated() { @@ -221,7 +220,7 @@ class UserGroupServiceTest extends DatabaseTestCase } /** - * @throws ServiceException + * @throws \SP\Domain\Common\Services\ServiceException */ public function testCreateDuplicated() { diff --git a/tests/SP/Services/UserGroup/UserToUserGroupServiceTest.php b/tests/SP/Services/UserGroup/UserToUserGroupServiceTest.php index a4178503..faa38b9e 100644 --- a/tests/SP/Services/UserGroup/UserToUserGroupServiceTest.php +++ b/tests/SP/Services/UserGroup/UserToUserGroupServiceTest.php @@ -31,21 +31,22 @@ use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; use SP\DataModel\UserToUserGroupData; -use SP\Repositories\NoSuchItemException; -use SP\Services\UserGroup\UserToUserGroupService; +use SP\Domain\User\Services\UserToUserGroupService; +use SP\Domain\User\UserToUserGroupServiceInterface; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use function SP\Tests\setupContext; /** * Class UserToUserGroupServiceTest * - * @package SP\Tests\SP\Services\UserGroup + * @package SP\Tests\SP\Domain\Common\Services\UserGroup */ class UserToUserGroupServiceTest extends DatabaseTestCase { /** - * @var UserToUserGroupService + * @var UserToUserGroupServiceInterface */ private static $service; diff --git a/tests/SP/Services/UserPassRecover/UserPassRecoverServiceTest.php b/tests/SP/Services/UserPassRecover/UserPassRecoverServiceTest.php index ce752ebb..af9ced75 100644 --- a/tests/SP/Services/UserPassRecover/UserPassRecoverServiceTest.php +++ b/tests/SP/Services/UserPassRecover/UserPassRecoverServiceTest.php @@ -31,8 +31,9 @@ use SP\Core\Context\ContextException; use SP\Core\Exceptions\ConstraintException; use SP\Core\Exceptions\QueryException; use SP\Core\Exceptions\SPException; -use SP\Services\ServiceException; -use SP\Services\UserPassRecover\UserPassRecoverService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\User\Services\UserPassRecoverService; +use SP\Domain\User\UserPassRecoverServiceInterface; use SP\Tests\DatabaseTestCase; use SP\Util\PasswordUtil; use function SP\Tests\setupContext; @@ -40,12 +41,12 @@ use function SP\Tests\setupContext; /** * Class UserPassRecoverServiceTest * - * @package SP\Tests\SP\Services\UserPassRecover + * @package SP\Tests\SP\Domain\Common\Services\UserPassRecover */ class UserPassRecoverServiceTest extends DatabaseTestCase { /** - * @var UserPassRecoverService + * @var \SP\Domain\User\UserPassRecoverServiceInterface */ private static $service; diff --git a/tests/SP/Services/UserProfile/UserProfileServiceTest.php b/tests/SP/Services/UserProfile/UserProfileServiceTest.php index e0c11f21..bb86573e 100644 --- a/tests/SP/Services/UserProfile/UserProfileServiceTest.php +++ b/tests/SP/Services/UserProfile/UserProfileServiceTest.php @@ -33,10 +33,10 @@ use SP\Core\Exceptions\SPException; use SP\DataModel\ItemSearchData; use SP\DataModel\ProfileData; use SP\DataModel\UserProfileData; -use SP\Repositories\DuplicatedItemException; -use SP\Repositories\NoSuchItemException; -use SP\Services\ServiceException; -use SP\Services\UserProfile\UserProfileService; +use SP\Domain\Common\Services\ServiceException; +use SP\Domain\User\UserProfileServiceInterface; +use SP\Infrastructure\Common\Repositories\DuplicatedItemException; +use SP\Infrastructure\Common\Repositories\NoSuchItemException; use SP\Tests\DatabaseTestCase; use stdClass; use function SP\Tests\setupContext; @@ -44,12 +44,12 @@ use function SP\Tests\setupContext; /** * Class UserProfileServiceTest * - * @package SP\Tests\SP\Services\UserProfile + * @package SP\Tests\SP\Domain\Common\Services\UserProfile */ class UserProfileServiceTest extends DatabaseTestCase { /** - * @var UserProfileService + * @var UserProfileServiceInterface */ private static $service; @@ -66,7 +66,7 @@ class UserProfileServiceTest extends DatabaseTestCase self::$loadFixtures = true; // Inicializar el servicio - self::$service = $dic->get(UserProfileService::class); + self::$service = $dic->get(\SP\Domain\User\Services\UserProfileService::class); } /** diff --git a/tests/SP/Storage/ArchiveHandlerTest.php b/tests/SP/Storage/ArchiveHandlerTest.php index f88e672f..b283157c 100644 --- a/tests/SP/Storage/ArchiveHandlerTest.php +++ b/tests/SP/Storage/ArchiveHandlerTest.php @@ -28,8 +28,8 @@ use PHPUnit\Framework\TestCase; use RuntimeException; use SP\Core\Exceptions\CheckException; use SP\Core\PhpExtensionChecker; -use SP\Storage\File\ArchiveHandler; -use SP\Storage\File\FileException; +use SP\Infrastructure\File\ArchiveHandler; +use SP\Infrastructure\File\FileException; use UnexpectedValueException; /** diff --git a/tests/SP/Storage/FileCachePackedTest.php b/tests/SP/Storage/FileCachePackedTest.php index dd2110af..b9e83d54 100644 --- a/tests/SP/Storage/FileCachePackedTest.php +++ b/tests/SP/Storage/FileCachePackedTest.php @@ -26,8 +26,8 @@ namespace SP\Tests\Storage; use Faker\Factory; use PHPUnit\Framework\TestCase; -use SP\Storage\File\FileCachePacked; -use SP\Storage\File\FileException; +use SP\Infrastructure\File\FileCachePacked; +use SP\Infrastructure\File\FileException; use stdClass; /** diff --git a/tests/SP/Storage/FileCacheTest.php b/tests/SP/Storage/FileCacheTest.php index 202de27f..2adf4912 100644 --- a/tests/SP/Storage/FileCacheTest.php +++ b/tests/SP/Storage/FileCacheTest.php @@ -26,8 +26,8 @@ namespace SP\Tests\Storage; use Faker\Factory; use PHPUnit\Framework\TestCase; -use SP\Storage\File\FileCache; -use SP\Storage\File\FileException; +use SP\Infrastructure\File\FileCache; +use SP\Infrastructure\File\FileException; use stdClass; /** diff --git a/tests/SP/Storage/FileHandlerTest.php b/tests/SP/Storage/FileHandlerTest.php index 2c4b4f97..d4f0a5ee 100644 --- a/tests/SP/Storage/FileHandlerTest.php +++ b/tests/SP/Storage/FileHandlerTest.php @@ -25,13 +25,13 @@ namespace SP\Tests\Storage; use PHPUnit\Framework\TestCase; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; /** * Class FileHandlerTest * - * Tests unitarios para comprobar el funcionamiento de la clase SP\Storage\File\FileHandler + * Tests unitarios para comprobar el funcionamiento de la clase SP\Infrastructure\File\FileHandler * * @package SP\Tests */ diff --git a/tests/SP/Storage/XmlHandlerTest.php b/tests/SP/Storage/XmlHandlerTest.php index b70ce45b..98ee6da7 100644 --- a/tests/SP/Storage/XmlHandlerTest.php +++ b/tests/SP/Storage/XmlHandlerTest.php @@ -26,15 +26,15 @@ namespace SP\Tests\Storage; use PHPUnit\Framework\TestCase; use RuntimeException; -use SP\Storage\File\FileException; -use SP\Storage\File\FileHandler; -use SP\Storage\File\XmlHandler; +use SP\Infrastructure\File\FileException; +use SP\Infrastructure\File\FileHandler; +use SP\Infrastructure\File\XmlHandler; use stdClass; /** * Class XmlHandlerTest * - * Tests unitarios para comprobar el funcionamiento de la clase SP\Storage\File\XmlHandler + * Tests unitarios para comprobar el funcionamiento de la clase SP\Infrastructure\File\XmlHandler * * @package SP\Tests */ diff --git a/tests/SP/UnitaryTestCase.php b/tests/SP/UnitaryTestCase.php index 87c11dfa..40764464 100644 --- a/tests/SP/UnitaryTestCase.php +++ b/tests/SP/UnitaryTestCase.php @@ -29,23 +29,23 @@ use DG\BypassFinals; use Faker\Factory; use Faker\Generator; use PHPUnit\Framework\TestCase; -use SP\Config\Config; use SP\Core\Application; use SP\Core\Context\StatelessContext; use SP\Core\Events\EventDispatcher; -use SP\Services\Config\ConfigBackupService; -use SP\Services\User\UserLoginResponse; -use SP\Storage\File\FileCache; -use SP\Storage\File\XmlHandler; +use SP\Domain\Config\Services\ConfigBackupService; +use SP\Domain\Config\Services\ConfigFileService; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Infrastructure\File\FileCache; +use SP\Infrastructure\File\XmlHandler; /** * A class to test using a mocked Dependency Injection Container */ abstract class UnitaryTestCase extends TestCase { - protected static Generator $faker; - protected Config $config; - protected Application $application; + protected static Generator $faker; + protected ConfigFileService $config; + protected Application $application; public static function setUpBeforeClass(): void { @@ -82,7 +82,7 @@ abstract class UnitaryTestCase extends TestCase $context->initialize(); $context->setUserData($userLogin); - $config = new Config( + $config = new ConfigFileService( $this->createStub(XmlHandler::class), $this->createStub(FileCache::class), $context, diff --git a/tests/SP/bootstrap.php b/tests/SP/bootstrap.php index 34508a9a..fb7d57a3 100644 --- a/tests/SP/bootstrap.php +++ b/tests/SP/bootstrap.php @@ -32,10 +32,10 @@ use SP\Core\Context\ContextException; use SP\Core\Context\ContextInterface; use SP\Core\Exceptions\FileNotFoundException; use SP\DataModel\ProfileData; -use SP\Services\User\UserLoginResponse; -use SP\Storage\Database\DatabaseConnectionData; -use SP\Storage\Database\DBStorageInterface; -use SP\Storage\Database\MySQLHandler; +use SP\Domain\User\Services\UserLoginResponse; +use SP\Infrastructure\Database\DatabaseConnectionData; +use SP\Infrastructure\Database\DBStorageInterface; +use SP\Infrastructure\Database\MySQLHandler; use SP\Util\FileUtil; define('DEBUG', true);