diff --git a/.phpstorm.meta.php b/.phpstorm.meta.php
index eef24ddc..9111ee35 100644
--- a/.phpstorm.meta.php
+++ b/.phpstorm.meta.php
@@ -1,5 +1,28 @@
.
+ */
namespace PHPSTORM_META {
override(\Psr\Container\ContainerInterface::get(0), type(0));
-}
\ No newline at end of file
+ override(\SP\Infrastructure\Database\QueryResult::getData(0), type(0));
+}
diff --git a/app/modules/api/Controllers/Account/CreateController.php b/app/modules/api/Controllers/Account/CreateController.php
index 24359dbd..b537584b 100644
--- a/app/modules/api/Controllers/Account/CreateController.php
+++ b/app/modules/api/Controllers/Account/CreateController.php
@@ -51,7 +51,7 @@ final class CreateController extends AccountBase
$accountId = $this->accountService->create($accountRequest);
- $accountDetails = $this->accountService->getById($accountId)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($accountId)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'create.account',
diff --git a/app/modules/api/Controllers/Account/DeleteController.php b/app/modules/api/Controllers/Account/DeleteController.php
index feed5362..71fa367d 100644
--- a/app/modules/api/Controllers/Account/DeleteController.php
+++ b/app/modules/api/Controllers/Account/DeleteController.php
@@ -46,7 +46,7 @@ final class DeleteController extends AccountBase
$id = $this->apiService->getParamInt('id', true);
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$this->accountService->delete($id);
@@ -69,4 +69,4 @@ final class DeleteController extends AccountBase
$this->returnResponseException($e);
}
}
-}
\ No newline at end of file
+}
diff --git a/app/modules/api/Controllers/Account/EditController.php b/app/modules/api/Controllers/Account/EditController.php
index 8d743b32..e9e1dd8f 100644
--- a/app/modules/api/Controllers/Account/EditController.php
+++ b/app/modules/api/Controllers/Account/EditController.php
@@ -48,7 +48,7 @@ final class EditController extends AccountBase
$this->accountService->update($accountRequest);
- $accountDetails = $this->accountService->getById($accountRequest->id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($accountRequest->id)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'edit.account',
diff --git a/app/modules/api/Controllers/Account/EditPassController.php b/app/modules/api/Controllers/Account/EditPassController.php
index 8162c4a4..8686a418 100644
--- a/app/modules/api/Controllers/Account/EditPassController.php
+++ b/app/modules/api/Controllers/Account/EditPassController.php
@@ -50,7 +50,7 @@ final class EditPassController extends AccountBase
$this->accountService->editPassword($accountRequest);
- $accountDetails = $this->accountService->getById($accountRequest->id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($accountRequest->id)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'edit.account.pass',
diff --git a/app/modules/api/Controllers/Account/ViewController.php b/app/modules/api/Controllers/Account/ViewController.php
index ebcfd27d..4f42b22d 100644
--- a/app/modules/api/Controllers/Account/ViewController.php
+++ b/app/modules/api/Controllers/Account/ViewController.php
@@ -55,16 +55,14 @@ final class ViewController extends AccountBase
$this->apiService->requireMasterPass();
}
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$this->accountService->incrementViewCounter($id);
- $accountResponse = new AccountEnrichedDto($accountDetails);
-
- $this->accountService
- ->withUsersById($accountResponse)
- ->withUserGroupsById($accountResponse)
- ->withTagsById($accountResponse);
+ $accountEnrichedDto = new AccountEnrichedDto($accountDetails);
+ $accountEnrichedDto = $this->accountService->withUsers($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withUserGroups($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withTags($accountEnrichedDto);
$this->eventDispatcher->notifyEvent(
'show.account',
@@ -78,7 +76,7 @@ final class ViewController extends AccountBase
)
);
- $out = $this->fractal->createData(new Item($accountResponse, $this->accountAdapter));
+ $out = $this->fractal->createData(new Item($accountEnrichedDto, $this->accountAdapter));
if ($customFields) {
$this->fractal->parseIncludes(['customFields']);
diff --git a/app/modules/api/Controllers/Account/ViewPassController.php b/app/modules/api/Controllers/Account/ViewPassController.php
index 411cfa4d..d1251a0e 100644
--- a/app/modules/api/Controllers/Account/ViewPassController.php
+++ b/app/modules/api/Controllers/Account/ViewPassController.php
@@ -55,7 +55,7 @@ final class ViewPassController extends AccountBase
$this->accountService->incrementDecryptCounter($id);
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'show.account.pass',
@@ -76,4 +76,4 @@ final class ViewPassController extends AccountBase
$this->returnResponseException($e);
}
}
-}
\ No newline at end of file
+}
diff --git a/app/modules/web/Controllers/Account/CopyController.php b/app/modules/web/Controllers/Account/CopyController.php
index 2d2ee5fb..2a810270 100644
--- a/app/modules/web/Controllers/Account/CopyController.php
+++ b/app/modules/web/Controllers/Account/CopyController.php
@@ -42,13 +42,12 @@ final class CopyController extends AccountViewBase
public function copyAction(int $id): void
{
try {
- $accountDetailsResponse = $this->accountService->getById($id);
- $this->accountService
- ->withUsersById($accountDetailsResponse)
- ->withUserGroupsById($accountDetailsResponse)
- ->withTagsById($accountDetailsResponse);
+ $accountEnrichedDto = $this->accountService->getByIdEnriched($id);
+ $accountEnrichedDto = $this->accountService->withUsers($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withUserGroups($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withTags($accountEnrichedDto);
- $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_COPY);
+ $this->accountHelper->setViewForAccount($accountEnrichedDto, ActionsInterface::ACCOUNT_COPY);
$this->view->addTemplate('account');
$this->view->assign(
@@ -80,4 +79,4 @@ final class CopyController extends AccountViewBase
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
index 9bddbc76..07c16b13 100644
--- a/app/modules/web/Controllers/Account/DeleteController.php
+++ b/app/modules/web/Controllers/Account/DeleteController.php
@@ -67,12 +67,12 @@ final class DeleteController extends AccountControllerBase
public function deleteAction(?int $id = null): void
{
try {
- $accountDetailsResponse = $this->accountService->getById($id);
- $this->accountService
- ->withUsersById($accountDetailsResponse)
- ->withUserGroupsById($accountDetailsResponse);
+ $accountEnrichedDto = $this->accountService->getByIdEnriched($id);
+ $accountEnrichedDto = $this->accountService->withUsers($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withUserGroups($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withTags($accountEnrichedDto);
- $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_DELETE);
+ $this->accountHelper->setViewForAccount($accountEnrichedDto, ActionsInterface::ACCOUNT_DELETE);
$this->view->addTemplate('account');
$this->view->assign(
diff --git a/app/modules/web/Controllers/Account/EditController.php b/app/modules/web/Controllers/Account/EditController.php
index a03d3946..29fce6a2 100644
--- a/app/modules/web/Controllers/Account/EditController.php
+++ b/app/modules/web/Controllers/Account/EditController.php
@@ -43,13 +43,12 @@ final class EditController extends AccountViewBase
public function editAction(int $id): void
{
try {
- $accountDetailsResponse = $this->accountService->getById($id);
- $this->accountService
- ->withUsersById($accountDetailsResponse)
- ->withUserGroupsById($accountDetailsResponse)
- ->withTagsById($accountDetailsResponse);
+ $accountEnrichedDto = $this->accountService->getByIdEnriched($id);
+ $accountEnrichedDto = $this->accountService->withUsers($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withUserGroups($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withTags($accountEnrichedDto);
- $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_EDIT);
+ $this->accountHelper->setViewForAccount($accountEnrichedDto, ActionsInterface::ACCOUNT_EDIT);
$this->view->addTemplate('account');
$this->view->assign(
@@ -83,4 +82,4 @@ final class EditController extends AccountViewBase
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
index c5b44dae..52883218 100644
--- a/app/modules/web/Controllers/Account/EditPassController.php
+++ b/app/modules/web/Controllers/Account/EditPassController.php
@@ -47,12 +47,11 @@ final class EditPassController extends AccountViewBase
public function editPassAction(int $id): void
{
try {
- $accountDetailsResponse = $this->accountService->getById($id);
- $this->accountService
- ->withUsersById($accountDetailsResponse)
- ->withUserGroupsById($accountDetailsResponse);
+ $accountEnrichedDto = $this->accountService->getByIdEnriched($id);
+ $accountEnrichedDto = $this->accountService->withUsers($accountEnrichedDto);
+ $accountEnrichedDto = $this->accountService->withUserGroups($accountEnrichedDto);
- $this->accountHelper->setViewForAccount($accountDetailsResponse, ActionsInterface::ACCOUNT_EDIT_PASS);
+ $this->accountHelper->setViewForAccount($accountEnrichedDto, ActionsInterface::ACCOUNT_EDIT_PASS);
$this->view->addTemplate('account-editpass');
$this->view->assign(
@@ -84,4 +83,4 @@ final class EditPassController extends AccountViewBase
ErrorUtil::showExceptionInView($this->view, $e, 'account-editpass');
}
}
-}
\ No newline at end of file
+}
diff --git a/app/modules/web/Controllers/Account/RequestAccessController.php b/app/modules/web/Controllers/Account/RequestAccessController.php
index d38b8fef..17d3e40a 100644
--- a/app/modules/web/Controllers/Account/RequestAccessController.php
+++ b/app/modules/web/Controllers/Account/RequestAccessController.php
@@ -65,7 +65,7 @@ final class RequestAccessController extends ControllerBase
try {
$this->accountRequestHelper->setIsView(true);
$this->accountRequestHelper->setViewForRequest(
- $this->accountService->getById($id),
+ $this->accountService->getByIdEnriched($id),
ActionsInterface::ACCOUNT_REQUEST
);
diff --git a/app/modules/web/Controllers/Account/SaveCopyController.php b/app/modules/web/Controllers/Account/SaveCopyController.php
index 19684012..7d3e11f2 100644
--- a/app/modules/web/Controllers/Account/SaveCopyController.php
+++ b/app/modules/web/Controllers/Account/SaveCopyController.php
@@ -48,7 +48,7 @@ final class SaveCopyController extends AccountSaveBase
$accountId = $this->accountService->create($this->accountForm->getItemData());
- $accountDetails = $this->accountService->getById($accountId)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($accountId)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'create.account',
@@ -85,4 +85,4 @@ final class SaveCopyController extends AccountSaveBase
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
index a89cf096..ae4866a3 100644
--- a/app/modules/web/Controllers/Account/SaveCreateController.php
+++ b/app/modules/web/Controllers/Account/SaveCreateController.php
@@ -48,7 +48,7 @@ final class SaveCreateController extends AccountSaveBase
$accountId = $this->accountService->create($this->accountForm->getItemData());
- $accountDetails = $this->accountService->getById($accountId)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($accountId)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'create.account',
@@ -85,4 +85,4 @@ final class SaveCreateController extends AccountSaveBase
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
index ae6cd889..bc5a928f 100644
--- a/app/modules/web/Controllers/Account/SaveDeleteController.php
+++ b/app/modules/web/Controllers/Account/SaveDeleteController.php
@@ -72,7 +72,7 @@ final class SaveDeleteController extends AccountControllerBase
public function saveDeleteAction(int $id): bool
{
try {
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$this->accountService->delete($id);
diff --git a/app/modules/web/Controllers/Account/SaveEditController.php b/app/modules/web/Controllers/Account/SaveEditController.php
index a017487f..23827638 100644
--- a/app/modules/web/Controllers/Account/SaveEditController.php
+++ b/app/modules/web/Controllers/Account/SaveEditController.php
@@ -55,7 +55,7 @@ final class SaveEditController extends AccountSaveBase
$this->accountService->update($itemData);
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'edit.account',
@@ -92,4 +92,4 @@ final class SaveEditController extends AccountSaveBase
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
index 140ef194..1a09cf46 100644
--- a/app/modules/web/Controllers/Account/SaveEditPassController.php
+++ b/app/modules/web/Controllers/Account/SaveEditPassController.php
@@ -77,7 +77,7 @@ final class SaveEditPassController extends AccountControllerBase
$this->accountService->editPassword($this->accountForm->getItemData());
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'edit.account.pass',
diff --git a/app/modules/web/Controllers/Account/SaveEditRestoreController.php b/app/modules/web/Controllers/Account/SaveEditRestoreController.php
index 4c3fe4a7..eac8a894 100644
--- a/app/modules/web/Controllers/Account/SaveEditRestoreController.php
+++ b/app/modules/web/Controllers/Account/SaveEditRestoreController.php
@@ -70,9 +70,9 @@ final class SaveEditRestoreController extends AccountControllerBase
public function saveEditRestoreAction(int $historyId, int $id): bool
{
try {
- $this->accountService->editRestore($historyId, $id);
+ $this->accountService->restoreModified($historyId, $id);
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'edit.account.restore',
diff --git a/app/modules/web/Controllers/Account/SaveRequestController.php b/app/modules/web/Controllers/Account/SaveRequestController.php
index 8e4b523f..d2f07bb5 100644
--- a/app/modules/web/Controllers/Account/SaveRequestController.php
+++ b/app/modules/web/Controllers/Account/SaveRequestController.php
@@ -83,7 +83,7 @@ final class SaveRequestController extends AccountControllerBase
throw new ValidationException(__u('A description is needed'));
}
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$baseUrl = ($this->configData->getApplicationUrl() ?: BootstrapBase::$WEBURI).BootstrapBase::$SUBURI;
diff --git a/app/modules/web/Controllers/Account/ViewController.php b/app/modules/web/Controllers/Account/ViewController.php
index c7469c49..2518d5a0 100644
--- a/app/modules/web/Controllers/Account/ViewController.php
+++ b/app/modules/web/Controllers/Account/ViewController.php
@@ -46,9 +46,9 @@ final class ViewController extends AccountViewBase
try {
$this->view->addTemplate('account');
- $accountDetailsResponse = $this->accountService->getById($id);
+ $accountDetailsResponse = $this->accountService->getByIdEnriched($id);
$this->accountService
- ->withUsersById($accountDetailsResponse)
+ ->withUsers($accountDetailsResponse)
->withUserGroupsById($accountDetailsResponse)
->withTagsById($accountDetailsResponse);
@@ -85,4 +85,4 @@ final class ViewController extends AccountViewBase
ErrorUtil::showExceptionInView($this->view, $e, 'account');
}
}
-}
\ No newline at end of file
+}
diff --git a/app/modules/web/Controllers/AccountFile/UploadController.php b/app/modules/web/Controllers/AccountFile/UploadController.php
index 218ae986..a4ac6126 100644
--- a/app/modules/web/Controllers/AccountFile/UploadController.php
+++ b/app/modules/web/Controllers/AccountFile/UploadController.php
@@ -128,7 +128,7 @@ final class UploadController extends ControllerBase
$this->accountFileService->create($fileData);
- $account = $this->accountService->getById($accountId)->getAccountVData();
+ $account = $this->accountService->getByIdEnriched($accountId)->getAccountVData();
$this->eventDispatcher->notifyEvent(
'upload.accountFile',
diff --git a/app/modules/web/Controllers/AccountHistoryManager/RestoreController.php b/app/modules/web/Controllers/AccountHistoryManager/RestoreController.php
index 426bb761..84ddf361 100644
--- a/app/modules/web/Controllers/AccountHistoryManager/RestoreController.php
+++ b/app/modules/web/Controllers/AccountHistoryManager/RestoreController.php
@@ -76,9 +76,9 @@ final class RestoreController extends ControllerBase
$accountDetails = $this->accountHistoryService->getById($id);
if ($accountDetails->isModify) {
- $this->accountService->editRestore($id, $accountDetails->getAccountId());
+ $this->accountService->restoreModified($id, $accountDetails->getAccountId());
} else {
- $this->accountService->createFromHistory($accountDetails);
+ $this->accountService->restoreRemoved($accountDetails);
}
$this->eventDispatcher->notifyEvent(
diff --git a/app/modules/web/Controllers/AccountManager/DeleteController.php b/app/modules/web/Controllers/AccountManager/DeleteController.php
index 6a42c206..7f4770b5 100644
--- a/app/modules/web/Controllers/AccountManager/DeleteController.php
+++ b/app/modules/web/Controllers/AccountManager/DeleteController.php
@@ -87,7 +87,7 @@ final class DeleteController extends ControllerBase
return $this->returnJsonResponseData(JsonResponse::JSON_SUCCESS, __u('Accounts removed'));
}
- $accountDetails = $this->accountService->getById($id)->getAccountVData();
+ $accountDetails = $this->accountService->getByIdEnriched($id)->getAccountVData();
$this->accountService->delete($id);
diff --git a/app/modules/web/Controllers/AccountManager/SaveBulkEditController.php b/app/modules/web/Controllers/AccountManager/SaveBulkEditController.php
index a06d9dda..c0eeba8d 100644
--- a/app/modules/web/Controllers/AccountManager/SaveBulkEditController.php
+++ b/app/modules/web/Controllers/AccountManager/SaveBulkEditController.php
@@ -29,7 +29,7 @@ use SP\Core\Acl\ActionsInterface;
use SP\Core\Application;
use SP\Core\Events\Event;
use SP\Core\Events\EventMessage;
-use SP\Domain\Account\Dtos\AccountBulkRequest;
+use SP\Domain\Account\Dtos\AccountUpdateBulkDto;
use SP\Domain\Account\Ports\AccountHistoryServiceInterface;
use SP\Domain\Account\Ports\AccountPresetServiceInterface;
use SP\Domain\Account\Ports\AccountServiceInterface;
@@ -40,6 +40,7 @@ use SP\Modules\Web\Forms\AccountForm;
use SP\Mvc\Controller\ItemTrait;
use SP\Mvc\Controller\WebControllerHelper;
use SP\Util\Util;
+use function SP\processException;
/**
* Class AccountManagerController
@@ -74,24 +75,26 @@ final class SaveBulkEditController extends ControllerBase
* saveBulkEditAction
*
* @return bool
- * @throws \JsonException
+ * @throws \SP\Core\Exceptions\SPException
*/
public function saveBulkEditAction(): bool
{
try {
- $this->accountForm->validateFor(ActionsInterface::ACCOUNTMGR_BULK_EDIT, null);
+ $itemsId = Util::itemsIdAdapter($this->request->analyzeString('itemsId'));
- $request = new AccountBulkRequest(
- Util::itemsIdAdapter($this->request->analyzeString('itemsId')),
- $this->accountForm->getItemData()
+ $accountBulkDto = new AccountUpdateBulkDto(
+ array_map(function ($itemId) {
+ $this->accountForm->validateFor(ActionsInterface::ACCOUNTMGR_BULK_EDIT, $itemId);
+
+ return $this->accountForm->getItemData();
+ }, $itemsId)
);
- $request->setDeleteHistory($this->request->analyzeBool('delete_history', false));
- if ($request->isDeleteHistory()) {
- $this->accountHistoryService->deleteByAccountIdBatch($request->getItemsId());
+ if ($this->request->analyzeBool('delete_history', false)) {
+ $this->accountHistoryService->deleteByAccountIdBatch($itemsId);
}
- $this->accountService->updateBulk($request);
+ $this->accountService->updateBulk($accountBulkDto);
$this->eventDispatcher->notifyEvent(
'edit.account.bulk',
diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php
index 1740ac69..b1a4a111 100644
--- a/app/modules/web/Controllers/Helpers/Account/AccountHelper.php
+++ b/app/modules/web/Controllers/Helpers/Account/AccountHelper.php
@@ -140,14 +140,14 @@ final class AccountHelper extends AccountHelperBase
AccountEnrichedDto $accountDetailsResponse,
int $actionId
): void {
- $this->accountId = $accountDetailsResponse->getAccountVData()->getId();
+ $this->accountId = $accountDetailsResponse->getAccountDataView()->getId();
$this->actionId = $actionId;
$this->checkActionAccess();
$this->accountAcl = $this->checkAccess($accountDetailsResponse);
- $accountData = $accountDetailsResponse->getAccountVData();
+ $accountData = $accountDetailsResponse->getAccountDataView();
$accountActionsDto = new AccountActionsDto($this->accountId, null, $accountData->getParentId());
diff --git a/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php
index 30bd6a20..1f472d70 100644
--- a/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php
+++ b/app/modules/web/Controllers/Helpers/Account/AccountHistoryHelper.php
@@ -28,8 +28,8 @@ use SP\Core\Acl\AccountPermissionException;
use SP\Core\Acl\Acl;
use SP\Core\Application;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountHistoryData;
use SP\Domain\Account\Dtos\AccountAclDto;
+use SP\Domain\Account\Models\AccountHistory;
use SP\Domain\Account\Ports\AccountAclServiceInterface;
use SP\Domain\Account\Ports\AccountHistoryServiceInterface;
use SP\Domain\Account\Ports\AccountToUserGroupServiceInterface;
@@ -70,7 +70,7 @@ final class AccountHistoryHelper extends AccountHelperBase
}
/**
- * @param AccountHistoryData $accountHistoryData
+ * @param \SP\Domain\Account\Models\AccountHistory $accountHistoryData
* @param int $actionId
*
* @throws \SP\Core\Acl\AccountPermissionException
@@ -82,7 +82,7 @@ final class AccountHistoryHelper extends AccountHelperBase
* @throws \SP\Domain\User\Services\UpdatedMasterPassException
* @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
*/
- public function setView(AccountHistoryData $accountHistoryData, int $actionId): void
+ public function setView(AccountHistory $accountHistoryData, int $actionId): void
{
$this->actionId = $actionId;
$this->accountId = $accountHistoryData->getAccountId();
@@ -142,14 +142,14 @@ final class AccountHistoryHelper extends AccountHelperBase
/**
* Comprobar si el usuario dispone de acceso al módulo
*
- * @param AccountHistoryData $accountHistoryData
+ * @param AccountHistory $accountHistoryData
*
* @throws \SP\Core\Acl\AccountPermissionException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
* @throws \SP\Core\Exceptions\SPException
*/
- protected function checkAccess(AccountHistoryData $accountHistoryData): void
+ protected function checkAccess(AccountHistory $accountHistoryData): void
{
$acccountAclDto = AccountAclDto::makeFromAccountHistory(
$accountHistoryData,
diff --git a/app/modules/web/Controllers/Helpers/Account/AccountRequestHelper.php b/app/modules/web/Controllers/Helpers/Account/AccountRequestHelper.php
index fd885437..bef063ad 100644
--- a/app/modules/web/Controllers/Helpers/Account/AccountRequestHelper.php
+++ b/app/modules/web/Controllers/Helpers/Account/AccountRequestHelper.php
@@ -49,16 +49,16 @@ final class AccountRequestHelper extends AccountHelperBase
AccountEnrichedDto $accountDetailsResponse,
int $actionId
): bool {
- $this->accountId = $accountDetailsResponse->getAccountVData()->getId();
+ $this->accountId = $accountDetailsResponse->getAccountDataView()->getId();
$this->actionId = $actionId;
$this->accountAcl = new AccountAcl($actionId);
$this->checkActionAccess();
- $accountData = $accountDetailsResponse->getAccountVData();
+ $accountData = $accountDetailsResponse->getAccountDataView();
$this->view->assign('accountId', $accountData->getId());
- $this->view->assign('accountData', $accountDetailsResponse->getAccountVData());
+ $this->view->assign('accountData', $accountDetailsResponse->getAccountDataView());
$this->view->assign(
'accountActions',
$this->accountActionsHelper->getActionsForAccount(
diff --git a/app/modules/web/Controllers/Helpers/ItemPresetHelper.php b/app/modules/web/Controllers/Helpers/ItemPresetHelper.php
index c4ae2b5f..21d81f70 100644
--- a/app/modules/web/Controllers/Helpers/ItemPresetHelper.php
+++ b/app/modules/web/Controllers/Helpers/ItemPresetHelper.php
@@ -31,7 +31,7 @@ use SP\DataModel\ItemPreset\AccountPermission;
use SP\DataModel\ItemPreset\AccountPrivate;
use SP\DataModel\ItemPreset\Password;
use SP\DataModel\ItemPreset\SessionTimeout;
-use SP\DataModel\ItemPresetData;
+use SP\Domain\Account\Models\ItemPreset;
use SP\Domain\User\Ports\UserGroupServiceInterface;
use SP\Domain\User\Ports\UserProfileServiceInterface;
use SP\Domain\User\Ports\UserServiceInterface;
@@ -71,7 +71,7 @@ final class ItemPresetHelper extends HelperBase
/**
* @throws NoSuchPropertyException
*/
- public function makeAccountPermissionView(ItemPresetData $itemPresetData): void
+ public function makeAccountPermissionView(ItemPreset $itemPresetData): void
{
$accountPermission = $itemPresetData->hydrate(AccountPermission::class) ?? new AccountPermission();
@@ -101,7 +101,7 @@ final class ItemPresetHelper extends HelperBase
/**
* @throws NoSuchPropertyException
*/
- public function makeAccountPrivateView(ItemPresetData $itemPresetData): void
+ public function makeAccountPrivateView(ItemPreset $itemPresetData): void
{
$accountPrivate = $itemPresetData->hydrate(AccountPrivate::class) ?? new AccountPrivate();
@@ -115,7 +115,7 @@ final class ItemPresetHelper extends HelperBase
* @throws NoSuchPropertyException
* @throws InvalidArgumentException
*/
- public function makeSessionTimeoutView(ItemPresetData $itemPresetData): void
+ public function makeSessionTimeoutView(ItemPreset $itemPresetData): void
{
$sessionTimeout = $itemPresetData->hydrate(SessionTimeout::class)
?? new SessionTimeout($this->request->getClientAddress(), 3600);
@@ -129,7 +129,7 @@ final class ItemPresetHelper extends HelperBase
/**
* @throws NoSuchPropertyException
*/
- public function makeAccountPasswordView(ItemPresetData $itemPresetData): void
+ public function makeAccountPasswordView(ItemPreset $itemPresetData): void
{
$password = $itemPresetData->hydrate(Password::class) ?? new Password;
@@ -145,7 +145,7 @@ final class ItemPresetHelper extends HelperBase
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function setCommon(ItemPresetData $itemPresetData): void
+ public function setCommon(ItemPreset $itemPresetData): void
{
$this->users = SelectItemAdapter::factory($this->userService->getAllBasic());
$this->userGroups = SelectItemAdapter::factory($this->userGroupService->getAllBasic());
diff --git a/app/modules/web/Controllers/ItemPreset/ItemPresetViewBase.php b/app/modules/web/Controllers/ItemPreset/ItemPresetViewBase.php
index e6648883..8010c727 100644
--- a/app/modules/web/Controllers/ItemPreset/ItemPresetViewBase.php
+++ b/app/modules/web/Controllers/ItemPreset/ItemPresetViewBase.php
@@ -32,7 +32,7 @@ use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\InvalidArgumentException;
use SP\Core\Exceptions\NoSuchPropertyException;
use SP\Core\Exceptions\QueryException;
-use SP\DataModel\ItemPresetData;
+use SP\Domain\Account\Models\ItemPreset;
use SP\Domain\ItemPreset\Ports\ItemPresetInterface;
use SP\Infrastructure\Common\Repositories\NoSuchItemException;
use SP\Modules\Web\Controllers\ControllerBase;
@@ -79,7 +79,7 @@ abstract class ItemPresetViewBase extends ControllerBase
$itemPresetData = $id
? $this->itemPresetService->getById($id)
- : new ItemPresetData();
+ : new ItemPreset();
$this->itemPresetHelper->setCommon($itemPresetData);
diff --git a/app/modules/web/Forms/AccountForm.php b/app/modules/web/Forms/AccountForm.php
index 1bc563a4..1363f96d 100644
--- a/app/modules/web/Forms/AccountForm.php
+++ b/app/modules/web/Forms/AccountForm.php
@@ -26,23 +26,22 @@ namespace SP\Modules\Web\Forms;
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\Domain\Account\Dtos\AccountRequest;
+use SP\Domain\Account\Dtos\AccountCreateDto;
+use SP\Domain\Account\Dtos\AccountDto;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
use SP\Domain\Account\Ports\AccountPresetServiceInterface;
use SP\Http\RequestInterface;
+use SP\Util\Chainable;
+use function SP\__u;
/**
* Class AccountForm
- *
- * @package SP\Account
*/
final class AccountForm extends FormBase implements FormInterface
{
- private AccountPresetServiceInterface $accountPresetService;
- private AccountRequest $accountRequest;
+ private AccountPresetServiceInterface $accountPresetService;
+ private null|AccountCreateDto|AccountUpdateDto $accountDto = null;
public function __construct(
Application $application,
@@ -53,7 +52,6 @@ final class AccountForm extends FormBase implements FormInterface
parent::__construct($application, $request, $itemId);
$this->accountPresetService = $accountPresetService;
- $this->accountRequest = new AccountRequest();
}
/**
@@ -62,41 +60,47 @@ final class AccountForm extends FormBase implements FormInterface
* @param int $action
* @param int|null $id
*
- * @return AccountForm|FormInterface
- * @throws ValidationException
- * @throws ConstraintException
- * @throws NoSuchPropertyException
- * @throws QueryException
+ * @return \SP\Modules\Web\Forms\FormInterface
*/
public function validateFor(int $action, ?int $id = null): FormInterface
{
if ($id !== null) {
$this->itemId = $id;
}
-
+
+ $chain = new Chainable(fn() => $this->analyzeRequestData(), $this);
+
switch ($action) {
case ActionsInterface::ACCOUNT_EDIT_PASS:
- $this->analyzeRequestData();
- $this->checkPassword();
- $this->accountPresetService->checkPasswordPreset($this->accountRequest);
+ $this->accountDto = $chain->next(fn(AccountDto $dto) => $this->checkPassword($dto))
+ ->next(
+ fn(AccountDto $dto) => $this->accountPresetService->checkPasswordPreset(
+ $dto
+ )
+ )
+ ->resolve();
break;
case ActionsInterface::ACCOUNT_EDIT:
- $this->analyzeRequestData();
- $this->analyzeItems();
- $this->checkCommon();
+ $this->accountDto = $chain->next(fn(AccountDto $dto) => $this->analyzeItems($dto))
+ ->next(fn(AccountDto $dto) => $this->checkCommon($dto))
+ ->resolve();
break;
case ActionsInterface::ACCOUNT_CREATE:
case ActionsInterface::ACCOUNT_COPY:
- $this->analyzeRequestData();
- $this->analyzeItems();
- $this->checkCommon();
- $this->checkPassword();
- $this->accountPresetService->checkPasswordPreset($this->accountRequest);
+ $this->accountDto = $chain->next(fn(AccountDto $dto) => $this->analyzeItems($dto))
+ ->next(fn(AccountDto $dto) => $this->checkCommon($dto))
+ ->next(fn(AccountDto $dto) => $this->checkPassword($dto))
+ ->next(
+ fn(AccountDto $dto) => $this->accountPresetService->checkPasswordPreset(
+ $dto
+ )
+ )
+ ->resolve();
break;
case ActionsInterface::ACCOUNTMGR_BULK_EDIT:
- $this->analyzeRequestData();
- $this->analyzeItems();
- $this->analyzeBulkEdit();
+ $this->accountDto = $chain->next(fn(AccountDto $dto) => $this->analyzeItems($dto))
+ ->next(fn(AccountDto $dto) => $this->analyzeBulkEdit($dto))
+ ->resolve();
break;
}
@@ -106,111 +110,154 @@ final class AccountForm extends FormBase implements FormInterface
/**
* Analizar los datos de la petición HTTP
*
- * @return void
+ * @return \SP\Domain\Account\Dtos\AccountCreateDto|\SP\Domain\Account\Dtos\AccountUpdateDto
*/
- protected function analyzeRequestData(): void
+ private function analyzeRequestData(): AccountCreateDto|AccountUpdateDto
{
- $this->accountRequest->id = $this->itemId;
- $this->accountRequest->name = $this->request->analyzeString('name');
- $this->accountRequest->clientId = $this->request->analyzeInt('client_id');
- $this->accountRequest->categoryId = $this->request->analyzeInt('category_id');
- $this->accountRequest->login = $this->request->analyzeString('login');
- $this->accountRequest->url = $this->request->analyzeString('url');
- $this->accountRequest->notes = $this->request->analyzeUnsafeString('notes');
- $this->accountRequest->userEditId = $this->context->getUserData()->getId();
- $this->accountRequest->pass = $this->request->analyzeEncrypted('password');
- $this->accountRequest->isPrivate = (int)$this->request->analyzeBool('private_enabled', false);
- $this->accountRequest->isPrivateGroup = (int)$this->request->analyzeBool('private_group_enabled', false);
+ $name = $this->request->analyzeString('name');
+ $login = $this->request->analyzeString('login');
+ $clientId = $this->request->analyzeInt('client_id');
+ $categoryId = $this->request->analyzeInt('category_id');
+ $password = $this->request->analyzeEncrypted('password');
+ $userId = $this->request->analyzeInt('owner_id');
+ $url = $this->request->analyzeString('url');
+ $notes = $this->request->analyzeUnsafeString('notes');
+ $private = (int)$this->request->analyzeBool('private_enabled', false);
+ $privateGroup = (int)$this->request->analyzeBool('private_group_enabled', false);
+ $passDateChange = $this->request->analyzeInt('password_date_expire_unix');
+ $parentId = $this->request->analyzeInt('parent_account_id');
+ $userGroupId = $this->request->analyzeInt('main_usergroup_id');
- if ($this->request->analyzeInt('password_date_expire')) {
- $this->accountRequest->passDateChange = $this->request->analyzeInt('password_date_expire_unix');
+ if (null === $this->itemId) {
+ $accountDto = new AccountCreateDto(
+ $name,
+ $login,
+ $clientId,
+ $categoryId,
+ $password,
+ $userId,
+ null,
+ $url,
+ $notes,
+ $this->context->getUserData()->getId(),
+ $private,
+ $privateGroup,
+ $passDateChange,
+ $parentId,
+ $userGroupId
+ );
+ } else {
+ $accountDto = new AccountUpdateDto(
+ $this->itemId,
+ $name,
+ $login,
+ $clientId,
+ $categoryId,
+ $password,
+ $userId,
+ null,
+ $url,
+ $notes,
+ $this->context->getUserData()->getId(),
+ $private,
+ $privateGroup,
+ $passDateChange,
+ $parentId,
+ $userGroupId
+ );
}
- $this->accountRequest->parentId = $this->request->analyzeInt('parent_account_id');
- $this->accountRequest->userId = $this->request->analyzeInt('owner_id');
- $this->accountRequest->userGroupId = $this->request->analyzeInt('main_usergroup_id');
+ return $accountDto;
}
/**
* @throws ValidationException
*/
- private function checkPassword(): void
+ private function checkPassword(AccountDto $accountDto): void
{
- if ($this->accountRequest->parentId > 0) {
+ if ($accountDto->getParentId() > 0) {
return;
}
- if (!$this->accountRequest->pass) {
+ if (!$accountDto->getPass()) {
throw new ValidationException(__u('A key is needed'));
}
- if ($this->request->analyzeEncrypted('password_repeat') !== $this->accountRequest->pass) {
+ if ($this->request->analyzeEncrypted('password_repeat') !== $accountDto->getPass()) {
throw new ValidationException(__u('Passwords do not match'));
}
}
- private function analyzeItems(): void
+ private function analyzeItems(AccountDto $accountDto): AccountDto
{
if ($this->request->analyzeInt('other_users_view_update') === 1) {
- $this->accountRequest->usersView = $this->request->analyzeArray('other_users_view', null, []);
+ $accountDto = $accountDto->withUsersView($this->request->analyzeArray('other_users_view', null, []));
}
if ($this->request->analyzeInt('other_users_edit_update') === 1) {
- $this->accountRequest->usersEdit = $this->request->analyzeArray('other_users_edit', null, []);
+ $accountDto = $accountDto->withUsersEdit($this->request->analyzeArray('other_users_edit', null, []));
}
if ($this->request->analyzeInt('other_usergroups_view_update') === 1) {
- $this->accountRequest->userGroupsView = $this->request->analyzeArray('other_usergroups_view', null, []);
+ $accountDto =
+ $accountDto->withUserGroupsView($this->request->analyzeArray('other_usergroups_view', null, []));
}
if ($this->request->analyzeInt('other_usergroups_edit_update') === 1) {
- $this->accountRequest->userGroupsEdit = $this->request->analyzeArray('other_usergroups_edit', null, []);
+ $accountDto =
+ $accountDto->withUserGroupsEdit($this->request->analyzeArray('other_usergroups_edit', null, []));
}
if ($this->request->analyzeInt('tags_update') === 1) {
- $this->accountRequest->tags = $this->request->analyzeArray('tags', null, []);
+ $accountDto = $accountDto->withTags($this->request->analyzeArray('tags', null, []));
}
+
+ return $accountDto;
}
/**
* @throws ValidationException
*/
- private function checkCommon(): void
+ private function checkCommon(AccountDto $accountDto): AccountDto
{
- if (!$this->accountRequest->name) {
+ if (!$accountDto->getName()) {
throw new ValidationException(__u('An account name needed'));
}
- if (!$this->accountRequest->clientId) {
+ if (!$accountDto->getClientId()) {
throw new ValidationException(__u('A client name needed'));
}
- if (!$this->accountRequest->categoryId) {
+ if (!$accountDto->getCategoryId()) {
throw new ValidationException(__u('A category is needed'));
}
+
+ return $accountDto;
}
- private function analyzeBulkEdit(): void
+ private function analyzeBulkEdit(AccountDto $accountDto): AccountDto
{
if ($this->request->analyzeBool('clear_permission_users_view', false)) {
- $this->accountRequest->usersView = [];
+ $accountDto = $accountDto->withUsersView([]);
}
if ($this->request->analyzeBool('clear_permission_users_edit', false)) {
- $this->accountRequest->usersEdit = [];
+ $accountDto = $accountDto->withUsersEdit([]);
}
if ($this->request->analyzeBool('clear_permission_usergroups_view', false)) {
- $this->accountRequest->userGroupsView = [];
+ $accountDto = $accountDto->withUserGroupsView([]);
}
if ($this->request->analyzeBool('clear_permission_usergroups_edit', false)) {
- $this->accountRequest->userGroupsEdit = [];
+ $accountDto = $accountDto->withUserGroupsEdit([]);
}
+
+ return $accountDto;
}
- public function getItemData(): AccountRequest
+ public function getItemData(): AccountCreateDto|AccountUpdateDto|null
{
- return $this->accountRequest;
+ return $this->accountDto;
}
}
diff --git a/app/modules/web/Forms/FormBase.php b/app/modules/web/Forms/FormBase.php
index da8199f1..5f67e90e 100644
--- a/app/modules/web/Forms/FormBase.php
+++ b/app/modules/web/Forms/FormBase.php
@@ -28,7 +28,6 @@ use SP\Core\Application;
use SP\Core\Context\ContextInterface;
use SP\Domain\Config\Ports\ConfigDataInterface;
use SP\Domain\Config\Services\ConfigFileService;
-use SP\Http\Request;
use SP\Http\RequestInterface;
/**
@@ -38,11 +37,9 @@ use SP\Http\RequestInterface;
*/
abstract class FormBase
{
- protected ?int $itemId;
protected ConfigFileService $config;
protected ConfigDataInterface $configData;
protected ContextInterface $context;
- protected Request $request;
/**
* FormBase constructor.
@@ -53,14 +50,12 @@ abstract class FormBase
*/
public function __construct(
Application $application,
- RequestInterface $request,
- ?int $itemId = null
+ protected RequestInterface $request,
+ protected ?int $itemId = null
) {
$this->config = $application->getConfig();
$this->configData = $this->config->getConfigData();
$this->context = $application->getContext();
- $this->request = $request;
- $this->itemId = $itemId;
}
/**
@@ -70,9 +65,4 @@ abstract class FormBase
{
return $this->itemId;
}
-
- /**
- * Analizar los datos de la petición HTTP
- */
- abstract protected function analyzeRequestData();
}
diff --git a/app/modules/web/Forms/FormInterface.php b/app/modules/web/Forms/FormInterface.php
index dc03f446..e288eb53 100644
--- a/app/modules/web/Forms/FormInterface.php
+++ b/app/modules/web/Forms/FormInterface.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.
*
@@ -47,5 +47,5 @@ interface FormInterface
/**
* @return mixed
*/
- public function getItemData();
-}
\ No newline at end of file
+ public function getItemData(): mixed;
+}
diff --git a/app/modules/web/Forms/ItemsPresetForm.php b/app/modules/web/Forms/ItemsPresetForm.php
index ae7a9d70..f89de672 100644
--- a/app/modules/web/Forms/ItemsPresetForm.php
+++ b/app/modules/web/Forms/ItemsPresetForm.php
@@ -31,7 +31,7 @@ use SP\DataModel\ItemPreset\AccountPermission;
use SP\DataModel\ItemPreset\AccountPrivate;
use SP\DataModel\ItemPreset\Password;
use SP\DataModel\ItemPreset\SessionTimeout;
-use SP\DataModel\ItemPresetData;
+use SP\Domain\Account\Models\ItemPreset;
use SP\Domain\ItemPreset\Ports\ItemPresetInterface;
use SP\Domain\ItemPreset\Services\ItemPresetRequest;
use SP\Mvc\Controller\Validators\Validator;
@@ -79,7 +79,7 @@ final class ItemsPresetForm extends FormBase implements FormInterface
*/
protected function analyzeRequestData(): void
{
- $itemPresetData = new ItemPresetData();
+ $itemPresetData = new ItemPreset();
if ($this->itemId > 0) {
$itemPresetData->setId($this->itemId);
@@ -143,11 +143,10 @@ final class ItemsPresetForm extends FormBase implements FormInterface
*/
private function makePrivatePreset(): AccountPrivate
{
- $accountPrivate = new AccountPrivate();
- $accountPrivate->setPrivateUser($this->request->analyzeBool('private_user_enabled', false));
- $accountPrivate->setPrivateGroup($this->request->analyzeBool('private_group_enabled', false));
-
- return $accountPrivate;
+ return new AccountPrivate(
+ $this->request->analyzeBool('private_user_enabled', false),
+ $this->request->analyzeBool('private_group_enabled', false)
+ );
}
/**
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 ab3509e5..662b0bd1 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
@@ -52,7 +52,7 @@ $favoriteRouteOff = $_getvar('favoriteRouteOff');
getData()->getData() as $index => $accountSearchItem):
if ($index === 'count'): continue; endif;
- $accountSearchData = $accountSearchItem->getAccountSearchVData();
+ $accountSearchData = $accountSearchItem->getAccountSearchView();
?>
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 278c42ca..10d32a37 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
@@ -23,7 +23,7 @@
*/
/**
- * @var ItemPresetData $preset
+ * @var ItemPreset $preset
* @var ThemeIcons $icons
* @var \SP\Domain\Config\Ports\ConfigDataInterface $configData
* @var callable $_getvar
@@ -31,7 +31,7 @@
*/
use SP\Core\UI\ThemeIcons;
-use SP\DataModel\ItemPresetData;
+use SP\Domain\Account\Models\ItemPreset;
use SP\Mvc\View\Components\SelectItem;
$preset = $_getvar('preset');
diff --git a/lib/SP/Core/Acl/ActionsInterface.php b/lib/SP/Core/Acl/ActionsInterface.php
index 1f21c557..0b039d12 100644
--- a/lib/SP/Core/Acl/ActionsInterface.php
+++ b/lib/SP/Core/Acl/ActionsInterface.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.
*
@@ -31,159 +31,159 @@ namespace SP\Core\Acl;
*/
interface ActionsInterface
{
- public const ACCOUNT = 1;
- public const ACCOUNT_SEARCH = 2;
- public const ACCOUNT_VIEW = 3;
- public const ACCOUNT_CREATE = 4;
- public const ACCOUNT_EDIT = 5;
- public const ACCOUNT_DELETE = 6;
- public const ACCOUNT_VIEW_PASS = 7;
- public const ACCOUNT_EDIT_PASS = 8;
- public const ACCOUNT_EDIT_RESTORE = 9;
- public const ACCOUNT_COPY = 10;
- public const ACCOUNT_COPY_PASS = 11;
- public const ACCOUNT_REQUEST = 12;
- public const ACCOUNT_FILE = 20;
- public const ACCOUNT_FILE_VIEW = 21;
- public const ACCOUNT_FILE_UPLOAD = 22;
- public const ACCOUNT_FILE_DOWNLOAD = 23;
- public const ACCOUNT_FILE_DELETE = 24;
- public const ACCOUNT_FILE_SEARCH = 25;
- public const ACCOUNT_FILE_LIST = 26;
- public const ACCOUNT_FAVORITE = 30;
- public const ACCOUNT_FAVORITE_VIEW = 31;
- public const ACCOUNT_FAVORITE_ADD = 32;
- public const ACCOUNT_FAVORITE_DELETE = 33;
- public const ACCOUNT_HISTORY_VIEW = 40;
- public const ACCOUNT_HISTORY_VIEW_PASS = 41;
- public const ACCOUNT_HISTORY_COPY_PASS = 42;
- public const CATEGORY = 101;
- public const CATEGORY_SEARCH = 102;
- public const CATEGORY_VIEW = 103;
- public const CATEGORY_CREATE = 104;
- public const CATEGORY_EDIT = 105;
- public const CATEGORY_DELETE = 106;
- public const TAG = 201;
- public const TAG_SEARCH = 202;
- public const TAG_VIEW = 203;
- public const TAG_CREATE = 204;
- public const TAG_EDIT = 205;
- public const TAG_DELETE = 206;
- public const CLIENT = 301;
- public const CLIENT_SEARCH = 302;
- public const CLIENT_VIEW = 303;
- public const CLIENT_CREATE = 304;
- public const CLIENT_EDIT = 305;
- public const CLIENT_DELETE = 306;
- public const CUSTOMFIELD = 401;
- public const CUSTOMFIELD_SEARCH = 402;
- public const CUSTOMFIELD_VIEW = 403;
- public const CUSTOMFIELD_CREATE = 404;
- public const CUSTOMFIELD_EDIT = 405;
- public const CUSTOMFIELD_DELETE = 406;
- public const CUSTOMFIELD_VIEW_PASS = 407;
- public const PUBLICLINK = 501;
- public const PUBLICLINK_SEARCH = 502;
- public const PUBLICLINK_VIEW = 503;
- public const PUBLICLINK_CREATE = 504;
- public const PUBLICLINK_EDIT = 505;
- public const PUBLICLINK_DELETE = 506;
- public const PUBLICLINK_REFRESH = 507;
- public const FILE = 601;
- public const FILE_SEARCH = 602;
- public const FILE_VIEW = 603;
- public const FILE_UPLOAD = 604;
- public const FILE_DOWNLOAD = 605;
- public const FILE_DELETE = 606;
- public const USER = 701;
- public const USER_SEARCH = 702;
- public const USER_VIEW = 703;
- public const USER_CREATE = 704;
- public const USER_EDIT = 705;
- public const USER_DELETE = 706;
- public const USER_EDIT_PASS = 707;
- public const GROUP = 801;
- public const GROUP_SEARCH = 802;
- public const GROUP_VIEW = 803;
- public const GROUP_CREATE = 804;
- public const GROUP_EDIT = 805;
- public const GROUP_DELETE = 806;
- public const PROFILE = 901;
- public const PROFILE_SEARCH = 902;
- public const PROFILE_VIEW = 903;
- public const PROFILE_CREATE = 904;
- public const PROFILE_EDIT = 905;
- public const PROFILE_DELETE = 906;
- public const AUTHTOKEN = 1001;
- public const AUTHTOKEN_SEARCH = 1002;
- public const AUTHTOKEN_VIEW = 1003;
- public const AUTHTOKEN_CREATE = 1004;
- public const AUTHTOKEN_EDIT = 1005;
- public const AUTHTOKEN_DELETE = 1006;
- public const PLUGIN = 1101;
- public const PLUGIN_SEARCH = 1102;
- public const PLUGIN_VIEW = 1103;
- public const PLUGIN_CREATE = 1104;
- public const PLUGIN_ENABLE = 1105;
- public const PLUGIN_DISABLE = 1106;
- public const PLUGIN_RESET = 1107;
- public const PLUGIN_DELETE = 1108;
- public const WIKI = 1201;
- public const WIKI_SEARCH = 1202;
- public const WIKI_VIEW = 1203;
- public const WIKI_CREATE = 1204;
- public const WIKI_EDIT = 1205;
- public const WIKI_DELETE = 1206;
- public const ACCOUNTMGR = 1301;
- public const ACCOUNTMGR_SEARCH = 1302;
- public const ACCOUNTMGR_VIEW = 1303;
- public const ACCOUNTMGR_DELETE = 1304;
- public const ACCOUNTMGR_BULK_EDIT = 1305;
- public const ACCOUNTMGR_HISTORY = 1311;
- public const ACCOUNTMGR_HISTORY_SEARCH = 1312;
- public const ACCOUNTMGR_HISTORY_VIEW = 1313;
- public const ACCOUNTMGR_HISTORY_DELETE = 1314;
+ public const ACCOUNT = 1;
+ public const ACCOUNT_SEARCH = 2;
+ public const ACCOUNT_VIEW = 3;
+ public const ACCOUNT_CREATE = 4;
+ public const ACCOUNT_EDIT = 5;
+ public const ACCOUNT_DELETE = 6;
+ public const ACCOUNT_VIEW_PASS = 7;
+ public const ACCOUNT_EDIT_PASS = 8;
+ public const ACCOUNT_EDIT_RESTORE = 9;
+ public const ACCOUNT_COPY = 10;
+ public const ACCOUNT_COPY_PASS = 11;
+ public const ACCOUNT_REQUEST = 12;
+ public const ACCOUNT_FILE = 20;
+ public const ACCOUNT_FILE_VIEW = 21;
+ public const ACCOUNT_FILE_UPLOAD = 22;
+ public const ACCOUNT_FILE_DOWNLOAD = 23;
+ public const ACCOUNT_FILE_DELETE = 24;
+ public const ACCOUNT_FILE_SEARCH = 25;
+ public const ACCOUNT_FILE_LIST = 26;
+ public const ACCOUNT_FAVORITE = 30;
+ public const ACCOUNT_FAVORITE_VIEW = 31;
+ public const ACCOUNT_FAVORITE_ADD = 32;
+ public const ACCOUNT_FAVORITE_DELETE = 33;
+ public const ACCOUNT_HISTORY_VIEW = 40;
+ public const ACCOUNT_HISTORY_VIEW_PASS = 41;
+ public const ACCOUNT_HISTORY_COPY_PASS = 42;
+ public const CATEGORY = 101;
+ public const CATEGORY_SEARCH = 102;
+ public const CATEGORY_VIEW = 103;
+ public const CATEGORY_CREATE = 104;
+ public const CATEGORY_EDIT = 105;
+ public const CATEGORY_DELETE = 106;
+ public const TAG = 201;
+ public const TAG_SEARCH = 202;
+ public const TAG_VIEW = 203;
+ public const TAG_CREATE = 204;
+ public const TAG_EDIT = 205;
+ public const TAG_DELETE = 206;
+ public const CLIENT = 301;
+ public const CLIENT_SEARCH = 302;
+ public const CLIENT_VIEW = 303;
+ public const CLIENT_CREATE = 304;
+ public const CLIENT_EDIT = 305;
+ public const CLIENT_DELETE = 306;
+ public const CUSTOMFIELD = 401;
+ public const CUSTOMFIELD_SEARCH = 402;
+ public const CUSTOMFIELD_VIEW = 403;
+ public const CUSTOMFIELD_CREATE = 404;
+ public const CUSTOMFIELD_EDIT = 405;
+ public const CUSTOMFIELD_DELETE = 406;
+ public const CUSTOMFIELD_VIEW_PASS = 407;
+ public const PUBLICLINK = 501;
+ public const PUBLICLINK_SEARCH = 502;
+ public const PUBLICLINK_VIEW = 503;
+ public const PUBLICLINK_CREATE = 504;
+ public const PUBLICLINK_EDIT = 505;
+ public const PUBLICLINK_DELETE = 506;
+ public const PUBLICLINK_REFRESH = 507;
+ public const FILE = 601;
+ public const FILE_SEARCH = 602;
+ public const FILE_VIEW = 603;
+ public const FILE_UPLOAD = 604;
+ public const FILE_DOWNLOAD = 605;
+ public const FILE_DELETE = 606;
+ public const USER = 701;
+ public const USER_SEARCH = 702;
+ public const USER_VIEW = 703;
+ public const USER_CREATE = 704;
+ public const USER_EDIT = 705;
+ public const USER_DELETE = 706;
+ public const USER_EDIT_PASS = 707;
+ public const GROUP = 801;
+ public const GROUP_SEARCH = 802;
+ public const GROUP_VIEW = 803;
+ public const GROUP_CREATE = 804;
+ public const GROUP_EDIT = 805;
+ public const GROUP_DELETE = 806;
+ public const PROFILE = 901;
+ public const PROFILE_SEARCH = 902;
+ public const PROFILE_VIEW = 903;
+ public const PROFILE_CREATE = 904;
+ public const PROFILE_EDIT = 905;
+ public const PROFILE_DELETE = 906;
+ public const AUTHTOKEN = 1001;
+ public const AUTHTOKEN_SEARCH = 1002;
+ public const AUTHTOKEN_VIEW = 1003;
+ public const AUTHTOKEN_CREATE = 1004;
+ public const AUTHTOKEN_EDIT = 1005;
+ public const AUTHTOKEN_DELETE = 1006;
+ public const PLUGIN = 1101;
+ public const PLUGIN_SEARCH = 1102;
+ public const PLUGIN_VIEW = 1103;
+ public const PLUGIN_CREATE = 1104;
+ public const PLUGIN_ENABLE = 1105;
+ public const PLUGIN_DISABLE = 1106;
+ public const PLUGIN_RESET = 1107;
+ public const PLUGIN_DELETE = 1108;
+ public const WIKI = 1201;
+ public const WIKI_SEARCH = 1202;
+ public const WIKI_VIEW = 1203;
+ public const WIKI_CREATE = 1204;
+ public const WIKI_EDIT = 1205;
+ public const WIKI_DELETE = 1206;
+ public const ACCOUNTMGR = 1301;
+ public const ACCOUNTMGR_SEARCH = 1302;
+ public const ACCOUNTMGR_VIEW = 1303;
+ public const ACCOUNTMGR_DELETE = 1304;
+ public const ACCOUNTMGR_BULK_EDIT = 1305;
+ public const ACCOUNTMGR_HISTORY = 1311;
+ public const ACCOUNTMGR_HISTORY_SEARCH = 1312;
+ public const ACCOUNTMGR_HISTORY_VIEW = 1313;
+ public const ACCOUNTMGR_HISTORY_DELETE = 1314;
public const ACCOUNTMGR_HISTORY_RESTORE = 1315;
- public const NOTIFICATION = 1401;
- public const NOTIFICATION_SEARCH = 1402;
- public const NOTIFICATION_VIEW = 1403;
- public const NOTIFICATION_CREATE = 1404;
- public const NOTIFICATION_EDIT = 1405;
- public const NOTIFICATION_DELETE = 1406;
- public const NOTIFICATION_CHECK = 1407;
- public const CONFIG = 1501;
- public const CONFIG_GENERAL = 1502;
- public const CONFIG_ACCOUNT = 1510;
- public const CONFIG_WIKI = 1520;
- public const CONFIG_CRYPT = 1530;
- public const CONFIG_CRYPT_REFRESH = 1531;
- public const CONFIG_CRYPT_TEMPPASS = 1532;
- public const CONFIG_BACKUP = 1540;
- public const CONFIG_BACKUP_RUN = 1541;
- public const CONFIG_IMPORT = 1550;
- public const CONFIG_IMPORT_CSV = 1551;
- public const CONFIG_IMPORT_XML = 1552;
- public const CONFIG_EXPORT = 1560;
- public const CONFIG_EXPORT_RUN = 1561;
- public const CONFIG_MAIL = 1570;
- public const CONFIG_LDAP = 1580;
- public const CONFIG_LDAP_SYNC = 1581;
- public const EVENTLOG = 1701;
- public const EVENTLOG_SEARCH = 1702;
- public const EVENTLOG_CLEAR = 1703;
- public const ITEMPRESET = 1801;
- public const ITEMPRESET_SEARCH = 1802;
- public const ITEMPRESET_VIEW = 1803;
- public const ITEMPRESET_CREATE = 1804;
- public const ITEMPRESET_EDIT = 1805;
- public const ITEMPRESET_DELETE = 1806;
- public const TRACK = 1901;
- public const TRACK_SEARCH = 1902;
- public const TRACK_UNLOCK = 1903;
- public const TRACK_CLEAR = 1904;
- public const ITEMS_MANAGE = 5001;
- public const ACCESS_MANAGE = 5002;
- public const SECURITY_MANAGE = 5003;
- public const USERSETTINGS = 5010;
- public const USERSETTINGS_GENERAL = 5011;
-}
\ No newline at end of file
+ public const NOTIFICATION = 1401;
+ public const NOTIFICATION_SEARCH = 1402;
+ public const NOTIFICATION_VIEW = 1403;
+ public const NOTIFICATION_CREATE = 1404;
+ public const NOTIFICATION_EDIT = 1405;
+ public const NOTIFICATION_DELETE = 1406;
+ public const NOTIFICATION_CHECK = 1407;
+ public const CONFIG = 1501;
+ public const CONFIG_GENERAL = 1502;
+ public const CONFIG_ACCOUNT = 1510;
+ public const CONFIG_WIKI = 1520;
+ public const CONFIG_CRYPT = 1530;
+ public const CONFIG_CRYPT_REFRESH = 1531;
+ public const CONFIG_CRYPT_TEMPPASS = 1532;
+ public const CONFIG_BACKUP = 1540;
+ public const CONFIG_BACKUP_RUN = 1541;
+ public const CONFIG_IMPORT = 1550;
+ public const CONFIG_IMPORT_CSV = 1551;
+ public const CONFIG_IMPORT_XML = 1552;
+ public const CONFIG_EXPORT = 1560;
+ public const CONFIG_EXPORT_RUN = 1561;
+ public const CONFIG_MAIL = 1570;
+ public const CONFIG_LDAP = 1580;
+ public const CONFIG_LDAP_SYNC = 1581;
+ public const EVENTLOG = 1701;
+ public const EVENTLOG_SEARCH = 1702;
+ public const EVENTLOG_CLEAR = 1703;
+ public const ITEMPRESET = 1801;
+ public const ITEMPRESET_SEARCH = 1802;
+ public const ITEMPRESET_VIEW = 1803;
+ public const ITEMPRESET_CREATE = 1804;
+ public const ITEMPRESET_EDIT = 1805;
+ public const ITEMPRESET_DELETE = 1806;
+ public const TRACK = 1901;
+ public const TRACK_SEARCH = 1902;
+ public const TRACK_UNLOCK = 1903;
+ public const TRACK_CLEAR = 1904;
+ public const ITEMS_MANAGE = 5001;
+ public const ACCESS_MANAGE = 5002;
+ public const SECURITY_MANAGE = 5003;
+ public const USERSETTINGS = 5010;
+ public const USERSETTINGS_GENERAL = 5011;
+}
diff --git a/lib/SP/DataModel/AccountExtData.php b/lib/SP/DataModel/AccountExtData.php
index 616157ea..7915533b 100644
--- a/lib/SP/DataModel/AccountExtData.php
+++ b/lib/SP/DataModel/AccountExtData.php
@@ -33,9 +33,6 @@ use SP\Domain\Account\Adapters\AccountData;
*/
class AccountExtData extends AccountData
{
- protected array $usersId = [];
- protected array $userGroupsId = [];
- protected array $tags = [];
protected ?string $categoryName = null;
protected ?string $clientName = null;
protected ?string $userGroupName = null;
@@ -43,7 +40,6 @@ class AccountExtData extends AccountData
protected ?string $userLogin = null;
protected ?string $userEditName = null;
protected ?string $userEditLogin = null;
- protected ?string $publicLinkHash = null;
public function getUserEditName(): ?string
{
diff --git a/lib/SP/DataModel/AccountSearchVData.php b/lib/SP/DataModel/AccountSearchVData.php
index b0b8feb9..f5ac1183 100644
--- a/lib/SP/DataModel/AccountSearchVData.php
+++ b/lib/SP/DataModel/AccountSearchVData.php
@@ -24,14 +24,14 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
/**
* Class AccountSearchData
*
* @package SP\DataModel
*/
-class AccountSearchVData extends DataModel
+class AccountSearchVData extends Model
{
public ?string $publicLinkHash = null;
protected ?int $id = 0;
diff --git a/lib/SP/DataModel/AccountToUserGroupData.php b/lib/SP/DataModel/AccountToUserGroupData.php
index cce3f1dd..f938eb08 100644
--- a/lib/SP/DataModel/AccountToUserGroupData.php
+++ b/lib/SP/DataModel/AccountToUserGroupData.php
@@ -24,7 +24,7 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
defined('APP_ROOT') || die();
@@ -33,7 +33,7 @@ defined('APP_ROOT') || die();
*
* @package SP\DataModel
*/
-class AccountToUserGroupData extends DataModel
+class AccountToUserGroupData extends Model
{
/**
* @var int
diff --git a/lib/SP/DataModel/AccountVData.php b/lib/SP/DataModel/AccountVData.php
index 70f79601..d68d349a 100644
--- a/lib/SP/DataModel/AccountVData.php
+++ b/lib/SP/DataModel/AccountVData.php
@@ -24,14 +24,14 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
/**
* Class AccountVData
*
* @package SP\DataModel
*/
-class AccountVData extends DataModel
+class AccountVData extends Model
{
protected ?int $id = null;
protected ?int $userId = null;
diff --git a/lib/SP/DataModel/AuthTokenData.php b/lib/SP/DataModel/AuthTokenData.php
index ee0fd031..f28460ac 100644
--- a/lib/SP/DataModel/AuthTokenData.php
+++ b/lib/SP/DataModel/AuthTokenData.php
@@ -25,15 +25,15 @@
namespace SP\DataModel;
use SP\Core\Crypt\Vault;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
/**
* Class AuthTokenData
*
* @package SP\DataModel
*/
-class AuthTokenData extends DataModel implements DataModelInterface
+class AuthTokenData extends Model implements DataModelInterface
{
/**
* @var int
diff --git a/lib/SP/DataModel/CategoryData.php b/lib/SP/DataModel/CategoryData.php
index 37be52ed..ef711a05 100644
--- a/lib/SP/DataModel/CategoryData.php
+++ b/lib/SP/DataModel/CategoryData.php
@@ -24,8 +24,8 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
defined('APP_ROOT') || die();
@@ -34,7 +34,7 @@ defined('APP_ROOT') || die();
*
* @package SP\DataModel
*/
-class CategoryData extends DataModel implements DataModelInterface
+class CategoryData extends Model implements DataModelInterface
{
public ?int $id = null;
public ?string $name = null;
diff --git a/lib/SP/DataModel/ClientData.php b/lib/SP/DataModel/ClientData.php
index dde9463f..50cfaf88 100644
--- a/lib/SP/DataModel/ClientData.php
+++ b/lib/SP/DataModel/ClientData.php
@@ -24,8 +24,8 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
defined('APP_ROOT') || die();
@@ -34,7 +34,7 @@ defined('APP_ROOT') || die();
*
* @package SP\DataModel
*/
-class ClientData extends DataModel implements DataModelInterface
+class ClientData extends Model implements DataModelInterface
{
public ?int $id = null;
public ?string $name = null;
diff --git a/lib/SP/DataModel/CustomFieldBaseData.php b/lib/SP/DataModel/CustomFieldBaseData.php
index eb0c7ccd..0894e8cd 100644
--- a/lib/SP/DataModel/CustomFieldBaseData.php
+++ b/lib/SP/DataModel/CustomFieldBaseData.php
@@ -24,7 +24,7 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
defined('APP_ROOT') || die();
@@ -33,7 +33,7 @@ defined('APP_ROOT') || die();
*
* @package SP\DataModel
*/
-class CustomFieldBaseData extends DataModel
+class CustomFieldBaseData extends Model
{
/**
* @var int
diff --git a/lib/SP/DataModel/CustomFieldTypeData.php b/lib/SP/DataModel/CustomFieldTypeData.php
index 4a8c2531..018f48ae 100644
--- a/lib/SP/DataModel/CustomFieldTypeData.php
+++ b/lib/SP/DataModel/CustomFieldTypeData.php
@@ -25,15 +25,15 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
/**
* Class CustomFieldTypeData
*
* @package SP\DataModel
*/
-class CustomFieldTypeData extends DataModel implements DataModelInterface
+class CustomFieldTypeData extends Model implements DataModelInterface
{
/**
* @var int
diff --git a/lib/SP/DataModel/EventlogData.php b/lib/SP/DataModel/EventlogData.php
index b1d52751..339200e9 100644
--- a/lib/SP/DataModel/EventlogData.php
+++ b/lib/SP/DataModel/EventlogData.php
@@ -24,14 +24,14 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
/**
* Class EventlogData
*
* @package SP\DataModel
*/
-class EventlogData extends DataModel
+class EventlogData extends Model
{
/**
* @var int
diff --git a/lib/SP/DataModel/FileData.php b/lib/SP/DataModel/FileData.php
index 238a93db..b5c1ce3f 100644
--- a/lib/SP/DataModel/FileData.php
+++ b/lib/SP/DataModel/FileData.php
@@ -24,15 +24,15 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
/**
* Class FileData
*
* @package SP\DataModel
*/
-class FileData extends DataModel implements DataModelInterface
+class FileData extends Model implements DataModelInterface
{
protected ?int $id = null;
protected ?int $accountId = null;
@@ -41,7 +41,7 @@ class FileData extends DataModel implements DataModelInterface
protected ?string $content = null;
protected ?string $extension = null;
protected ?string $thumb = null;
- protected ?int $size;
+ protected ?int $size = null;
public function getId(): ?int
{
diff --git a/lib/SP/DataModel/ItemData.php b/lib/SP/DataModel/ItemData.php
index 01c6663a..0a4eb52b 100644
--- a/lib/SP/DataModel/ItemData.php
+++ b/lib/SP/DataModel/ItemData.php
@@ -24,15 +24,15 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
/**
* Class ItemData
*
* @package SP\DataModel
*/
-class ItemData extends DataModel implements DataModelInterface
+class ItemData extends Model implements DataModelInterface
{
protected ?int $id = null;
protected ?string $name = null;
diff --git a/lib/SP/DataModel/ItemPreset/AccountPrivate.php b/lib/SP/DataModel/ItemPreset/AccountPrivate.php
index 0789a51f..61b3592a 100644
--- a/lib/SP/DataModel/ItemPreset/AccountPrivate.php
+++ b/lib/SP/DataModel/ItemPreset/AccountPrivate.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.
*
@@ -29,46 +29,25 @@ namespace SP\DataModel\ItemPreset;
*
* @package SP\DataModel
*/
-class AccountPrivate
+final class AccountPrivate
{
/**
- * @var bool
+ * @param bool|null $privateUser
+ * @param bool|null $privateGroup
*/
- private $privateUser = false;
- /**
- * @var bool
- */
- private $privateGroup = false;
+ public function __construct(private ?bool $privateUser = false, private ?bool $privateGroup = false)
+ {
+ $this->privateUser = $privateUser;
+ $this->privateGroup = $privateGroup;
+ }
- /**
- * @return bool
- */
public function isPrivateUser(): bool
{
return $this->privateUser;
}
- /**
- * @param bool $privateUser
- */
- public function setPrivateUser(bool $privateUser)
- {
- $this->privateUser = $privateUser;
- }
-
- /**
- * @return bool
- */
public function isPrivateGroup(): bool
{
return $this->privateGroup;
}
-
- /**
- * @param bool $privateGroup
- */
- public function setPrivateGroup(bool $privateGroup)
- {
- $this->privateGroup = $privateGroup;
- }
-}
\ No newline at end of file
+}
diff --git a/lib/SP/DataModel/PublicLinkData.php b/lib/SP/DataModel/PublicLinkData.php
index 33da3bb5..cab8dc86 100644
--- a/lib/SP/DataModel/PublicLinkData.php
+++ b/lib/SP/DataModel/PublicLinkData.php
@@ -24,30 +24,30 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
/**
* Class PublicLinkData
*
* @package SP\DataModel
*/
-class PublicLinkData extends DataModel implements DataModelInterface
+class PublicLinkData extends Model implements DataModelInterface
{
- protected ?int $id;
- protected ?int $itemId;
- protected ?string $hash;
- protected ?int $userId;
- protected ?int $typeId;
- protected ?bool $notify;
- protected ?int $dateAdd;
- protected ?int $dateUpdate;
- protected ?int $dateExpire;
- protected ?int $countViews;
- protected ?int $totalCountViews;
- protected ?int $maxCountViews;
- protected ?string $useInfo;
- protected ?string $data;
+ protected ?int $id = null;
+ protected ?int $itemId = null;
+ protected ?string $hash = null;
+ protected ?int $userId = null;
+ protected ?int $typeId = null;
+ protected ?bool $notify = null;
+ protected ?int $dateAdd = null;
+ protected ?int $dateUpdate = null;
+ protected ?int $dateExpire = null;
+ protected ?int $countViews = null;
+ protected ?int $totalCountViews = null;
+ protected ?int $maxCountViews = null;
+ protected ?string $useInfo = null;
+ protected ?string $data = null;
public function getData(): ?string
{
diff --git a/lib/SP/DataModel/TagData.php b/lib/SP/DataModel/TagData.php
index 92433f37..861bec84 100644
--- a/lib/SP/DataModel/TagData.php
+++ b/lib/SP/DataModel/TagData.php
@@ -24,8 +24,8 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
defined('APP_ROOT') || die();
@@ -34,7 +34,7 @@ defined('APP_ROOT') || die();
*
* @package SP\Mgmt\Tags
*/
-class TagData extends DataModel implements DataModelInterface
+class TagData extends Model implements DataModelInterface
{
/**
* @var int
diff --git a/lib/SP/DataModel/TrackData.php b/lib/SP/DataModel/TrackData.php
index b8affb15..a6b2235b 100644
--- a/lib/SP/DataModel/TrackData.php
+++ b/lib/SP/DataModel/TrackData.php
@@ -25,7 +25,7 @@
namespace SP\DataModel;
use SP\Core\Exceptions\InvalidArgumentException;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
use SP\Http\Address;
/**
@@ -33,7 +33,7 @@ use SP\Http\Address;
*
* @package SP\DataModel
*/
-class TrackData extends DataModel
+class TrackData extends Model
{
/**
* @var int
diff --git a/lib/SP/DataModel/UserGroupData.php b/lib/SP/DataModel/UserGroupData.php
index 44b8b67e..9df6ada4 100644
--- a/lib/SP/DataModel/UserGroupData.php
+++ b/lib/SP/DataModel/UserGroupData.php
@@ -24,8 +24,8 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
defined('APP_ROOT') || die();
@@ -34,7 +34,7 @@ defined('APP_ROOT') || die();
*
* @package SP\DataModel
*/
-class UserGroupData extends DataModel implements DataModelInterface
+class UserGroupData extends Model implements DataModelInterface
{
public int $id = 0;
public ?string $name = null;
diff --git a/lib/SP/DataModel/UserPassData.php b/lib/SP/DataModel/UserPassData.php
index a64f51e5..4a72a6ac 100644
--- a/lib/SP/DataModel/UserPassData.php
+++ b/lib/SP/DataModel/UserPassData.php
@@ -24,14 +24,14 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
/**
* Class UserPassData
*
* @package SP\DataModel
*/
-class UserPassData extends DataModel
+class UserPassData extends Model
{
protected ?int $id = null;
protected ?string $pass = null;
diff --git a/lib/SP/DataModel/UserPassRecoverData.php b/lib/SP/DataModel/UserPassRecoverData.php
index 36b15343..b157a1e7 100644
--- a/lib/SP/DataModel/UserPassRecoverData.php
+++ b/lib/SP/DataModel/UserPassRecoverData.php
@@ -24,14 +24,14 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
/**
* Class UserPassRecoverData
*
* @package SP\DataModel
*/
-class UserPassRecoverData extends DataModel
+class UserPassRecoverData extends Model
{
/**
* @var int
diff --git a/lib/SP/DataModel/UserProfileData.php b/lib/SP/DataModel/UserProfileData.php
index 07c63574..5685a6e0 100644
--- a/lib/SP/DataModel/UserProfileData.php
+++ b/lib/SP/DataModel/UserProfileData.php
@@ -24,8 +24,8 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
defined('APP_ROOT') || die();
@@ -34,7 +34,7 @@ defined('APP_ROOT') || die();
*
* @package SP\DataModel
*/
-class UserProfileData extends DataModel implements DataModelInterface
+class UserProfileData extends Model implements DataModelInterface
{
protected ?int $id = null;
protected ?string $name = null;
diff --git a/lib/SP/DataModel/UserToUserGroupData.php b/lib/SP/DataModel/UserToUserGroupData.php
index f2d16b57..9f83f93d 100644
--- a/lib/SP/DataModel/UserToUserGroupData.php
+++ b/lib/SP/DataModel/UserToUserGroupData.php
@@ -24,7 +24,7 @@
namespace SP\DataModel;
-use SP\Domain\Common\Adapters\DataModel;
+use SP\Domain\Common\Models\Model;
defined('APP_ROOT') || die();
@@ -33,7 +33,7 @@ defined('APP_ROOT') || die();
*
* @package SP\DataModel
*/
-class UserToUserGroupData extends DataModel
+class UserToUserGroupData extends Model
{
/**
* @var int
diff --git a/lib/SP/Domain/Account/Adapters/AccountAdapter.php b/lib/SP/Domain/Account/Adapters/AccountAdapter.php
index 1bba1527..7c8d25c5 100644
--- a/lib/SP/Domain/Account/Adapters/AccountAdapter.php
+++ b/lib/SP/Domain/Account/Adapters/AccountAdapter.php
@@ -69,7 +69,7 @@ final class AccountAdapter extends Adapter implements AccountAdapterInterface
public function transform(AccountEnrichedDto $data): array
{
- $account = $data->getAccountVData();
+ $account = $data->getAccountDataView();
return [
'id' => (int)$account->getId(),
diff --git a/lib/SP/Domain/Account/Adapters/AccountData.php b/lib/SP/Domain/Account/Adapters/AccountData.php
index 0a409b71..9b25ef7e 100644
--- a/lib/SP/Domain/Account/Adapters/AccountData.php
+++ b/lib/SP/Domain/Account/Adapters/AccountData.php
@@ -24,13 +24,13 @@
namespace SP\Domain\Account\Adapters;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
/**
* Class AccountData
*/
-class AccountData extends DataModel implements DataModelInterface
+class AccountData extends Model implements DataModelInterface
{
protected ?int $id = null;
protected ?int $userId = null;
@@ -56,11 +56,6 @@ class AccountData extends DataModel implements DataModelInterface
protected ?bool $otherUserGroupEdit = false;
protected ?bool $otherUserEdit = false;
- public function __construct(?array $properties = [])
- {
- parent::__construct($properties);
- }
-
public function getDateAdd(): ?int
{
return $this->dateAdd;
diff --git a/lib/SP/Domain/Account/Adapters/AccountPassData.php b/lib/SP/Domain/Account/Adapters/AccountPassData.php
index 07e2708d..dd0594dc 100644
--- a/lib/SP/Domain/Account/Adapters/AccountPassData.php
+++ b/lib/SP/Domain/Account/Adapters/AccountPassData.php
@@ -24,13 +24,12 @@
namespace SP\Domain\Account\Adapters;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
/**
* Class AccountPassData
*/
-class AccountPassData extends DataModel implements DataModelInterface
+class AccountPassData extends \SP\Domain\Common\Models\Model implements DataModelInterface
{
protected ?int $id = null;
protected ?string $name = null;
diff --git a/lib/SP/Domain/Account/Dtos/AccountAclDto.php b/lib/SP/Domain/Account/Dtos/AccountAclDto.php
index a595d69f..3126f047 100644
--- a/lib/SP/Domain/Account/Dtos/AccountAclDto.php
+++ b/lib/SP/Domain/Account/Dtos/AccountAclDto.php
@@ -26,6 +26,7 @@ namespace SP\Domain\Account\Dtos;
use SP\DataModel\AccountSearchVData;
use SP\DataModel\ItemData;
+use SP\Domain\Account\Models\AccountSearchView;
use SP\Domain\Common\Dtos\ItemDataTrait;
/**
@@ -66,11 +67,11 @@ final class AccountAclDto
{
return new self(
$accountDetailsResponse->getId(),
- $accountDetailsResponse->getAccountVData()->getUserId(),
+ $accountDetailsResponse->getAccountDataView()->getUserId(),
$accountDetailsResponse->getUsers(),
- $accountDetailsResponse->getAccountVData()->getUserGroupId(),
+ $accountDetailsResponse->getAccountDataView()->getUserGroupId(),
$accountDetailsResponse->getUserGroups(),
- strtotime($accountDetailsResponse->getAccountVData()->getDateEdit())
+ strtotime($accountDetailsResponse->getAccountDataView()->getDateEdit())
);
}
@@ -90,7 +91,7 @@ final class AccountAclDto
}
/**
- * @param AccountSearchVData $accountSearchVData
+ * @param AccountSearchView $accountSearchView
*
* @param array $users
* @param array $userGroups
@@ -98,17 +99,17 @@ final class AccountAclDto
* @return AccountAclDto
*/
public static function makeFromAccountSearch(
- AccountSearchVData $accountSearchVData,
+ AccountSearchView $accountSearchView,
array $users,
array $userGroups
): AccountAclDto {
return new self(
- $accountSearchVData->getId(),
- $accountSearchVData->getUserId(),
+ $accountSearchView->getId(),
+ $accountSearchView->getUserId(),
$users,
- $accountSearchVData->getUserGroupId(),
+ $accountSearchView->getUserGroupId(),
$userGroups,
- strtotime($accountSearchVData->getDateEdit())
+ strtotime($accountSearchView->getDateEdit())
);
}
diff --git a/lib/SP/Domain/Account/Dtos/AccountBulkRequest.php b/lib/SP/Domain/Account/Dtos/AccountBulkRequest.php
deleted file mode 100644
index ce154244..00000000
--- a/lib/SP/Domain/Account/Dtos/AccountBulkRequest.php
+++ /dev/null
@@ -1,75 +0,0 @@
-.
- */
-
-namespace SP\Domain\Account\Dtos;
-
-/**
- * Class AccountBulkRequest
- *
- * @package SP\Domain\Account\Services
- */
-final class AccountBulkRequest
-{
- private bool $deleteHistory = false;
-
- /**
- * AccountBulkRequest constructor.
- *
- * @param int[] $itemsId
- * @param AccountRequest $accountRequest
- */
- public function __construct(private array $itemsId, private AccountRequest $accountRequest)
- {
- $this->setUp();
- }
-
- private function setUp(): void
- {
- $this->accountRequest->changeUserGroup = $this->accountRequest->userGroupId > 0;
- $this->accountRequest->changePermissions = true;
- }
-
- public function isDeleteHistory(): bool
- {
- return $this->deleteHistory;
- }
-
- public function setDeleteHistory(bool $deleteHistory): void
- {
- $this->deleteHistory = $deleteHistory;
- }
-
- public function getItemsId(): array
- {
- return $this->itemsId;
- }
-
- public function getAccountRequestForId(int $id): AccountRequest
- {
- $request = clone $this->accountRequest;
- $request->id = $id;
-
- return $request;
- }
-}
diff --git a/lib/SP/DataModel/AccountHistoryData.php b/lib/SP/Domain/Account/Dtos/AccountCreateDto.php
similarity index 71%
rename from lib/SP/DataModel/AccountHistoryData.php
rename to lib/SP/Domain/Account/Dtos/AccountCreateDto.php
index 050a2e62..955b16f1 100644
--- a/lib/SP/DataModel/AccountHistoryData.php
+++ b/lib/SP/Domain/Account/Dtos/AccountCreateDto.php
@@ -22,21 +22,12 @@
* along with sysPass. If not, see .
*/
-namespace SP\DataModel;
+namespace SP\Domain\Account\Dtos;
/**
- * Class AccountHistoryData
- *
- * @package SP\DataModel
+ * Class AccountCreateDto
*/
-class AccountHistoryData extends AccountExtData
+final class AccountCreateDto extends AccountDto
{
- protected int $isModify = 0;
- protected int $isDeleted = 0;
- protected ?int $accountId = null;
- public function getAccountId(): ?int
- {
- return $this->accountId;
- }
-}
\ No newline at end of file
+}
diff --git a/lib/SP/Domain/Account/Dtos/AccountDto.php b/lib/SP/Domain/Account/Dtos/AccountDto.php
new file mode 100644
index 00000000..c234b85a
--- /dev/null
+++ b/lib/SP/Domain/Account/Dtos/AccountDto.php
@@ -0,0 +1,281 @@
+.
+ */
+
+namespace SP\Domain\Account\Dtos;
+
+use SP\Domain\Account\Models\Account;
+use SP\Domain\Common\Dtos\Dto;
+
+/**
+ * Class AccountDto
+ */
+abstract class AccountDto extends Dto
+{
+ public function __construct(
+ protected ?string $name = null,
+ protected ?string $login = null,
+ protected ?int $clientId = null,
+ protected ?int $categoryId = null,
+ protected ?string $pass = null,
+ protected ?int $userId = null,
+ protected ?string $key = null,
+ protected ?string $url = null,
+ protected ?string $notes = null,
+ protected ?int $userEditId = null,
+ protected ?bool $isPrivate = null,
+ protected ?bool $isPrivateGroup = null,
+ protected ?int $passDateChange = null,
+ protected ?int $parentId = null,
+ protected ?int $userGroupId = null,
+ protected ?bool $otherUserEdit = null,
+ protected ?bool $otherUserGroupEdit = null,
+ protected ?array $usersView = null,
+ protected ?array $usersEdit = null,
+ protected ?array $userGroupsView = null,
+ protected ?array $userGroupsEdit = null,
+ protected ?array $tags = null
+ ) {}
+
+ public static function fromAccount(Account $account): static
+ {
+ return new static(
+ name : $account->getName(),
+ login : $account->getLogin(),
+ clientId : $account->getClientId(),
+ categoryId : $account->getCategoryId(),
+ pass : $account->getPass(),
+ userId : $account->getUserId(),
+ key : $account->getKey(),
+ url : $account->getUrl(),
+ notes : $account->getNotes(),
+ userEditId : $account->getUserEditId(),
+ isPrivate : $account->getIsPrivate(),
+ isPrivateGroup : $account->getIsPrivateGroup(),
+ passDateChange : $account->getPassDateChange(),
+ parentId : $account->getParentId(),
+ userGroupId : $account->getUserGroupId(),
+ otherUserEdit : $account->getOtherUserEdit(),
+ otherUserGroupEdit: $account->getOtherUserGroupEdit(),
+ );
+ }
+
+ public function getName(): ?string
+ {
+ return $this->name;
+ }
+
+ public function getLogin(): ?string
+ {
+ return $this->login;
+ }
+
+ public function getClientId(): ?int
+ {
+ return $this->clientId;
+ }
+
+ public function getCategoryId(): ?int
+ {
+ return $this->categoryId;
+ }
+
+ public function getPass(): ?string
+ {
+ return $this->pass;
+ }
+
+ public function getUserId(): ?int
+ {
+ return $this->userId;
+ }
+
+ public function getKey(): ?string
+ {
+ return $this->key;
+ }
+
+ public function getUrl(): ?string
+ {
+ return $this->url;
+ }
+
+ public function getNotes(): ?string
+ {
+ return $this->notes;
+ }
+
+ public function getUserEditId(): ?int
+ {
+ return $this->userEditId;
+ }
+
+ public function getIsPrivate(): ?bool
+ {
+ return $this->isPrivate;
+ }
+
+ public function getIsPrivateGroup(): ?bool
+ {
+ return $this->isPrivateGroup;
+ }
+
+ public function getPassDateChange(): ?int
+ {
+ return $this->passDateChange;
+ }
+
+ public function getParentId(): ?int
+ {
+ return $this->parentId;
+ }
+
+ public function getUserGroupId(): ?int
+ {
+ return $this->userGroupId;
+ }
+
+ public function getOtherUserEdit(): ?bool
+ {
+ return $this->otherUserEdit;
+ }
+
+ public function getOtherUserGroupEdit(): ?bool
+ {
+ return $this->otherUserGroupEdit;
+ }
+
+ public function withUserId(int $userId): static
+ {
+ $self = clone $this;
+ $self->userId = $userId;
+
+ return $self;
+ }
+
+ public function withUserGroupId(int $userGroupId): static
+ {
+ $self = clone $this;
+ $self->userGroupId = $userGroupId;
+
+ return $self;
+ }
+
+ public function withPrivate(bool $isPrivate): static
+ {
+ $self = clone $this;
+ $self->isPrivate = (int)$isPrivate;
+
+ return $self;
+ }
+
+ public function withPrivateGroup(bool $isPrivateGroup): static
+ {
+ $self = clone $this;
+ $self->isPrivateGroup = (int)$isPrivateGroup;
+
+ return $self;
+ }
+
+ public function withEncryptedPassword(EncryptedPassword $encryptedPassword): static
+ {
+ $self = clone $this;
+ $self->pass = $encryptedPassword->getPass();
+ $self->key = $encryptedPassword->getKey();
+
+ return $self;
+ }
+
+ public function withUsersView(array $users): static
+ {
+ $self = clone $this;
+ $self->usersView = $users;
+
+ return $self;
+ }
+
+ public function withUsersEdit(array $users): static
+ {
+ $self = clone $this;
+ $self->usersEdit = $users;
+
+ return $self;
+ }
+
+ public function withUserGroupsView(array $userGroups): static
+ {
+ $self = clone $this;
+ $self->userGroupsView = $userGroups;
+
+ return $self;
+ }
+
+ public function withUserGroupsEdit(array $userGroups): static
+ {
+ $self = clone $this;
+ $self->userGroupsEdit = $userGroups;
+
+ return $self;
+ }
+
+ public function withTags(array $tags): static
+ {
+ $self = clone $this;
+ $self->tags = $tags;
+
+ return $self;
+ }
+
+ public function withPassDateChange(int $passDateChange): static
+ {
+ $self = clone $this;
+ $self->passDateChange = $passDateChange;
+
+ return $self;
+ }
+
+ public function getUsersView(): ?array
+ {
+ return $this->usersView;
+ }
+
+ public function getUsersEdit(): ?array
+ {
+ return $this->usersEdit;
+ }
+
+ public function getUserGroupsView(): ?array
+ {
+ return $this->userGroupsView;
+ }
+
+ public function getUserGroupsEdit(): ?array
+ {
+ return $this->userGroupsEdit;
+ }
+
+ public function getTags(): ?array
+ {
+ return $this->tags;
+ }
+}
diff --git a/lib/SP/Domain/Account/Dtos/AccountEnrichedDto.php b/lib/SP/Domain/Account/Dtos/AccountEnrichedDto.php
index 1fb6b575..d7a1832f 100644
--- a/lib/SP/Domain/Account/Dtos/AccountEnrichedDto.php
+++ b/lib/SP/Domain/Account/Dtos/AccountEnrichedDto.php
@@ -24,16 +24,19 @@
namespace SP\Domain\Account\Dtos;
-use SP\DataModel\AccountVData;
use SP\DataModel\ItemData;
+use SP\Domain\Account\Models\AccountDataView;
+use SP\Domain\Account\Models\AccountSearchView;
+use SP\Domain\Common\Dtos\ItemDataTrait;
/**
* Class AccountEnrichedDto
*/
class AccountEnrichedDto
{
- private int $id;
- private AccountVData $accountVData;
+ use ItemDataTrait;
+
+ private int $id;
/**
* @var ItemData[] Los usuarios secundarios de la cuenta.
*/
@@ -50,12 +53,11 @@ class AccountEnrichedDto
/**
* AccountDetailsResponse constructor.
*
- * @param AccountVData $accountVData
+ * @param \SP\Domain\Account\Models\AccountDataView $accountDataView
*/
- public function __construct(AccountVData $accountVData)
+ public function __construct(private AccountDataView $accountDataView)
{
- $this->id = $accountVData->getId();
- $this->accountVData = $accountVData;
+ $this->id = $accountDataView->getId();
}
/**
@@ -66,6 +68,45 @@ class AccountEnrichedDto
return $this->id;
}
+ /**
+ * @param ItemData[] $users
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ */
+ public function withUsers(array $users): AccountEnrichedDto
+ {
+ $self = clone $this;
+ $self->users = self::buildFromItemData($users);
+
+ return $self;
+ }
+
+ /**
+ * @param ItemData[] $groups
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ */
+ public function withUserGroups(array $groups): AccountEnrichedDto
+ {
+ $self = clone $this;
+ $self->userGroups = self::buildFromItemData($groups);
+
+ return $self;
+ }
+
+ /**
+ * @param ItemData[] $tags
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ */
+ public function withTags(array $tags): AccountEnrichedDto
+ {
+ $self = clone $this;
+ $self->tags = self::buildFromItemData($tags);
+
+ return $self;
+ }
+
/**
* @return ItemData[]
*/
@@ -74,14 +115,6 @@ class AccountEnrichedDto
return $this->users;
}
- /**
- * @param ItemData[] $users
- */
- public function setUsers(array $users): void
- {
- $this->users = $users;
- }
-
/**
* @return ItemData[]
*/
@@ -90,14 +123,6 @@ class AccountEnrichedDto
return $this->userGroups;
}
- /**
- * @param ItemData[] $userGroups
- */
- public function setUserGroups(array $userGroups): void
- {
- $this->userGroups = $userGroups;
- }
-
/**
* @return ItemData[]
*/
@@ -106,19 +131,8 @@ class AccountEnrichedDto
return $this->tags;
}
- /**
- * @param ItemData[] $tags
- */
- public function setTags(array $tags): void
+ public function getAccountDataView(): AccountDataView
{
- $this->tags = $tags;
- }
-
- /**
- * @return AccountVData
- */
- public function getAccountVData(): AccountVData
- {
- return $this->accountVData;
+ return $this->accountDataView;
}
}
diff --git a/lib/SP/Domain/Account/Dtos/AccountHistoryCreateDto.php b/lib/SP/Domain/Account/Dtos/AccountHistoryCreateDto.php
index 8b2b24df..0735bde3 100644
--- a/lib/SP/Domain/Account/Dtos/AccountHistoryCreateDto.php
+++ b/lib/SP/Domain/Account/Dtos/AccountHistoryCreateDto.php
@@ -24,7 +24,7 @@
namespace SP\Domain\Account\Dtos;
-use SP\Domain\Account\Adapters\AccountData;
+use SP\Domain\Account\Models\Account;
/**
* Class AccountHistoryCreateDto
@@ -32,7 +32,7 @@ use SP\Domain\Account\Adapters\AccountData;
class AccountHistoryCreateDto
{
public function __construct(
- private AccountData $accountData,
+ private Account $account,
private bool $isModify,
private bool $isDelete,
private string $masterPassHash
@@ -53,8 +53,8 @@ class AccountHistoryCreateDto
return $this->masterPassHash;
}
- public function getAccountData(): AccountData
+ public function getAccount(): Account
{
- return $this->accountData;
+ return $this->account;
}
}
diff --git a/lib/SP/Domain/Account/Dtos/AccountHistoryDto.php b/lib/SP/Domain/Account/Dtos/AccountHistoryDto.php
new file mode 100644
index 00000000..ebb48d26
--- /dev/null
+++ b/lib/SP/Domain/Account/Dtos/AccountHistoryDto.php
@@ -0,0 +1,119 @@
+.
+ */
+
+namespace SP\Domain\Account\Dtos;
+
+/**
+ * Class AccountHistoryDto
+ */
+final class AccountHistoryDto extends AccountDto
+{
+ public function __construct(
+ protected ?int $accountId = null,
+ protected ?int $isDelete = null,
+ protected ?int $isModify = null,
+ protected ?int $dateAdd = null,
+ protected ?int $dateEdit = null,
+ protected ?int $passDate = null,
+ protected ?int $countView = null,
+ protected ?int $countDecrypt = null,
+ ?string $name = null,
+ ?string $login = null,
+ ?int $clientId = null,
+ ?int $categoryId = null,
+ ?string $pass = null,
+ ?int $userId = null,
+ ?string $key = null,
+ ?string $url = null,
+ ?string $notes = null,
+ ?int $userEditId = null,
+ ?bool $isPrivate = null,
+ ?bool $isPrivateGroup = null,
+ ?int $passDateChange = null,
+ ?int $parentId = null,
+ ?int $userGroupId = null,
+ ?bool $otherUserEdit = null,
+ ?bool $otherUserGroupEdit = null
+ ) {
+ parent::__construct(
+ $name,
+ $login,
+ $clientId,
+ $categoryId,
+ $pass,
+ $userId,
+ $key,
+ $url,
+ $notes,
+ $userEditId,
+ $isPrivate,
+ $isPrivateGroup,
+ $passDateChange,
+ $parentId,
+ $userGroupId,
+ $otherUserGroupEdit,
+ $otherUserEdit
+ );
+ }
+
+ public function getAccountId(): ?int
+ {
+ return $this->accountId;
+ }
+
+ public function getIsDelete(): ?int
+ {
+ return $this->isDelete;
+ }
+
+ public function getIsModify(): ?int
+ {
+ return $this->isModify;
+ }
+
+ public function getDateAdd(): ?int
+ {
+ return $this->dateAdd;
+ }
+
+ public function getDateEdit(): ?int
+ {
+ return $this->dateEdit;
+ }
+
+ public function getPassDate(): ?int
+ {
+ return $this->passDate;
+ }
+
+ public function getCountView(): ?int
+ {
+ return $this->countView;
+ }
+
+ public function getCountDecrypt(): ?int
+ {
+ return $this->countDecrypt;
+ }
+}
diff --git a/lib/SP/Domain/Account/Dtos/AccountUpdateBulkDto.php b/lib/SP/Domain/Account/Dtos/AccountUpdateBulkDto.php
new file mode 100644
index 00000000..c3f7f24b
--- /dev/null
+++ b/lib/SP/Domain/Account/Dtos/AccountUpdateBulkDto.php
@@ -0,0 +1,52 @@
+.
+ */
+
+namespace SP\Domain\Account\Dtos;
+
+/**
+ * Class AccountBulkRequest
+ */
+final class AccountUpdateBulkDto
+{
+ /**
+ * AccountBulkRequest constructor.
+ *
+ * @param AccountUpdateDto[] $accountUpdateDto
+ */
+ public function __construct(array $accountsId, private array $accountUpdateDto)
+ {
+ $accountUpdateDto = array_combine($accountsId, $this->accountUpdateDto);
+
+ $this->accountUpdateDto =
+ array_filter($accountUpdateDto, static fn($dto) => $dto instanceof AccountUpdateDto);
+ }
+
+ /**
+ * @return \SP\Domain\Account\Dtos\AccountUpdateDto[]
+ */
+ public function getAccountUpdateDto(): array
+ {
+ return $this->accountUpdateDto;
+ }
+}
diff --git a/lib/SP/Domain/Account/Dtos/AccountUpdateDto.php b/lib/SP/Domain/Account/Dtos/AccountUpdateDto.php
new file mode 100644
index 00000000..625623b2
--- /dev/null
+++ b/lib/SP/Domain/Account/Dtos/AccountUpdateDto.php
@@ -0,0 +1,33 @@
+.
+ */
+
+namespace SP\Domain\Account\Dtos;
+
+/**
+ * Class AccountUpdateDto
+ */
+final class AccountUpdateDto extends AccountDto
+{
+
+}
diff --git a/lib/SP/Domain/Account/Dtos/EncryptedPassword.php b/lib/SP/Domain/Account/Dtos/EncryptedPassword.php
index e5ab90c4..95782491 100644
--- a/lib/SP/Domain/Account/Dtos/EncryptedPassword.php
+++ b/lib/SP/Domain/Account/Dtos/EncryptedPassword.php
@@ -29,7 +29,7 @@ namespace SP\Domain\Account\Dtos;
*/
final class EncryptedPassword
{
- public function __construct(private string $pass, private string $key) {}
+ public function __construct(private string $pass, private string $key, private ?string $hash = null) {}
public function getPass(): string
{
@@ -40,4 +40,9 @@ final class EncryptedPassword
{
return $this->key;
}
+
+ public function getHash(): ?string
+ {
+ return $this->hash;
+ }
}
diff --git a/lib/SP/Domain/Account/Models/Account.php b/lib/SP/Domain/Account/Models/Account.php
new file mode 100644
index 00000000..ebaf729e
--- /dev/null
+++ b/lib/SP/Domain/Account/Models/Account.php
@@ -0,0 +1,174 @@
+.
+ */
+
+namespace SP\Domain\Account\Models;
+
+use SP\Domain\Common\Models\Model;
+
+/**
+ * Class Account
+ */
+final class Account extends Model
+{
+ use AccountUseCases;
+
+ protected ?int $id = null;
+ protected ?int $userId = null;
+ protected ?int $userGroupId = null;
+ protected ?int $userEditId = null;
+ protected ?string $name = null;
+ protected ?int $clientId = null;
+ protected ?int $categoryId = null;
+ protected ?string $login = null;
+ protected ?string $url = null;
+ protected ?string $pass = null;
+ protected ?string $key = null;
+ protected ?string $notes = null;
+ protected ?int $dateAdd = null;
+ protected ?int $dateEdit = null;
+ protected ?int $countView = null;
+ protected ?int $countDecrypt = null;
+ protected ?int $isPrivate = null;
+ protected ?int $isPrivateGroup = null;
+ protected ?int $passDate = null;
+ protected ?int $passDateChange = null;
+ protected ?int $parentId = null;
+ protected ?int $otherUserGroupEdit = null;
+ protected ?int $otherUserEdit = null;
+
+ public function getUserId(): ?int
+ {
+ return $this->userId;
+ }
+
+ public function getUserGroupId(): ?int
+ {
+ return $this->userGroupId;
+ }
+
+ public function getName(): ?string
+ {
+ return $this->name;
+ }
+
+ public function getClientId(): ?int
+ {
+ return $this->clientId;
+ }
+
+ public function getLogin(): ?string
+ {
+ return $this->login;
+ }
+
+ public function getUrl(): ?string
+ {
+ return $this->url;
+ }
+
+ public function getNotes(): ?string
+ {
+ return $this->notes;
+ }
+
+ public function getIsPrivate(): ?int
+ {
+ return $this->isPrivate;
+ }
+
+ public function getIsPrivateGroup(): ?int
+ {
+ return $this->isPrivateGroup;
+ }
+
+ public function getPassDateChange(): ?int
+ {
+ return $this->passDateChange;
+ }
+
+ public function getParentId(): ?int
+ {
+ return $this->parentId;
+ }
+
+ public function getOtherUserEdit(): ?int
+ {
+ return $this->otherUserEdit;
+ }
+
+ public function getOtherUserGroupEdit(): ?int
+ {
+ return $this->otherUserGroupEdit;
+ }
+
+ public function getPass(): ?string
+ {
+ return $this->pass;
+ }
+
+ public function getKey(): ?string
+ {
+ return $this->key;
+ }
+
+ public function getId(): ?int
+ {
+ return $this->id;
+ }
+
+ public function getUserEditId(): ?int
+ {
+ return $this->userEditId;
+ }
+
+ public function getCategoryId(): ?int
+ {
+ return $this->categoryId;
+ }
+
+ public function getDateAdd(): ?int
+ {
+ return $this->dateAdd;
+ }
+
+ public function getDateEdit(): ?int
+ {
+ return $this->dateEdit;
+ }
+
+ public function getCountView(): ?int
+ {
+ return $this->countView;
+ }
+
+ public function getCountDecrypt(): ?int
+ {
+ return $this->countDecrypt;
+ }
+
+ public function getPassDate(): ?int
+ {
+ return $this->passDate;
+ }
+}
diff --git a/lib/SP/Domain/Account/Models/AccountDataView.php b/lib/SP/Domain/Account/Models/AccountDataView.php
new file mode 100644
index 00000000..ef5a562f
--- /dev/null
+++ b/lib/SP/Domain/Account/Models/AccountDataView.php
@@ -0,0 +1,218 @@
+.
+ */
+
+namespace SP\Domain\Account\Models;
+
+use SP\Domain\Common\Models\Model;
+
+/**
+ * Class AccountDataView
+ */
+final class AccountDataView extends Model
+{
+ protected ?int $id = null;
+ protected ?string $name = null;
+ protected ?int $categoryId = null;
+ protected ?int $userId = null;
+ protected ?int $clientId = null;
+ protected ?int $userGroupId = null;
+ protected ?int $userEditId = null;
+ protected ?string $login = null;
+ protected ?string $url = null;
+ protected ?string $notes = null;
+ protected ?int $countView = null;
+ protected ?int $countDecrypt = null;
+ protected ?int $dateAdd = null;
+ protected ?int $dateEdit = null;
+ protected ?int $otherUserEdit = null;
+ protected ?int $otherUserGroupEdit = null;
+ protected ?int $isPrivate = null;
+ protected ?int $isPrivateGroup = null;
+ protected ?int $passDate = null;
+ protected ?int $passDateChange = null;
+ protected ?int $parentId = null;
+ protected ?string $categoryName = null;
+ protected ?string $clientName = null;
+ protected ?string $userGroupName = null;
+ protected ?string $userName = null;
+ protected ?string $userLogin = null;
+ protected ?string $userEditName = null;
+ protected ?string $userEditLogin = null;
+ protected ?string $publicLinkHash = null;
+
+ public function getCategoryName(): ?string
+ {
+ return $this->categoryName;
+ }
+
+ public function getClientName(): ?string
+ {
+ return $this->clientName;
+ }
+
+ public function getUserGroupName(): ?string
+ {
+ return $this->userGroupName;
+ }
+
+ public function getUserName(): ?string
+ {
+ return $this->userName;
+ }
+
+ public function getUserLogin(): ?string
+ {
+ return $this->userLogin;
+ }
+
+ public function getUserEditName(): ?string
+ {
+ return $this->userEditName;
+ }
+
+ public function getUserEditLogin(): ?string
+ {
+ return $this->userEditLogin;
+ }
+
+ public function getPublicLinkHash(): ?string
+ {
+ return $this->publicLinkHash;
+ }
+
+ public function getUserId(): ?int
+ {
+ return $this->userId;
+ }
+
+ public function getUserGroupId(): ?int
+ {
+ return $this->userGroupId;
+ }
+
+ public function getName(): ?string
+ {
+ return $this->name;
+ }
+
+ public function getClientId(): ?int
+ {
+ return $this->clientId;
+ }
+
+ public function getLogin(): ?string
+ {
+ return $this->login;
+ }
+
+ public function getUrl(): ?string
+ {
+ return $this->url;
+ }
+
+ public function getNotes(): ?string
+ {
+ return $this->notes;
+ }
+
+ public function getIsPrivate(): ?int
+ {
+ return $this->isPrivate;
+ }
+
+ public function getIsPrivateGroup(): ?int
+ {
+ return $this->isPrivateGroup;
+ }
+
+ public function getPassDateChange(): ?int
+ {
+ return $this->passDateChange;
+ }
+
+ public function getParentId(): ?int
+ {
+ return $this->parentId;
+ }
+
+ public function getOtherUserEdit(): ?int
+ {
+ return $this->otherUserEdit;
+ }
+
+ public function getOtherUserGroupEdit(): ?int
+ {
+ return $this->otherUserGroupEdit;
+ }
+
+ public function getPass(): ?string
+ {
+ return $this->pass;
+ }
+
+ public function getKey(): ?string
+ {
+ return $this->key;
+ }
+
+ public function getId(): ?int
+ {
+ return $this->id;
+ }
+
+ public function getUserEditId(): ?int
+ {
+ return $this->userEditId;
+ }
+
+ public function getCategoryId(): ?int
+ {
+ return $this->categoryId;
+ }
+
+ public function getDateAdd(): ?int
+ {
+ return $this->dateAdd;
+ }
+
+ public function getDateEdit(): ?int
+ {
+ return $this->dateEdit;
+ }
+
+ public function getCountView(): ?int
+ {
+ return $this->countView;
+ }
+
+ public function getCountDecrypt(): ?int
+ {
+ return $this->countDecrypt;
+ }
+
+ public function getPassDate(): ?int
+ {
+ return $this->passDate;
+ }
+}
diff --git a/lib/SP/Domain/Account/Models/AccountHistory.php b/lib/SP/Domain/Account/Models/AccountHistory.php
new file mode 100644
index 00000000..1069892d
--- /dev/null
+++ b/lib/SP/Domain/Account/Models/AccountHistory.php
@@ -0,0 +1,190 @@
+.
+ */
+
+namespace SP\Domain\Account\Models;
+
+use SP\Domain\Common\Models\Model;
+
+/**
+ * Class AccountHistory
+ */
+final class AccountHistory extends Model
+{
+ protected ?int $id = null;
+ protected ?int $userId = null;
+ protected ?int $userGroupId = null;
+ protected ?int $userEditId = null;
+ protected ?string $name = null;
+ protected ?int $clientId = null;
+ protected ?int $categoryId = null;
+ protected ?string $login = null;
+ protected ?string $url = null;
+ protected ?string $pass = null;
+ protected ?string $key = null;
+ protected ?string $notes = null;
+ protected ?int $dateAdd = null;
+ protected ?int $dateEdit = null;
+ protected ?int $countView = null;
+ protected ?int $countDecrypt = null;
+ protected ?int $isPrivate = null;
+ protected ?int $isPrivateGroup = null;
+ protected ?int $passDate = null;
+ protected ?int $passDateChange = null;
+ protected ?int $parentId = null;
+ protected ?int $otherUserGroupEdit = null;
+ protected ?int $otherUserEdit = null;
+ protected ?int $isModify = null;
+ protected ?int $isDeleted = null;
+ protected ?int $accountId = null;
+
+ public function getAccountId(): ?int
+ {
+ return $this->accountId;
+ }
+
+ public function getId(): ?int
+ {
+ return $this->id;
+ }
+
+ public function getUserId(): ?int
+ {
+ return $this->userId;
+ }
+
+ public function getUserGroupId(): ?int
+ {
+ return $this->userGroupId;
+ }
+
+ public function getUserEditId(): ?int
+ {
+ return $this->userEditId;
+ }
+
+ public function getName(): ?string
+ {
+ return $this->name;
+ }
+
+ public function getClientId(): ?int
+ {
+ return $this->clientId;
+ }
+
+ public function getCategoryId(): ?int
+ {
+ return $this->categoryId;
+ }
+
+ public function getLogin(): ?string
+ {
+ return $this->login;
+ }
+
+ public function getUrl(): ?string
+ {
+ return $this->url;
+ }
+
+ public function getPass(): ?string
+ {
+ return $this->pass;
+ }
+
+ public function getKey(): ?string
+ {
+ return $this->key;
+ }
+
+ public function getNotes(): ?string
+ {
+ return $this->notes;
+ }
+
+ public function getDateAdd(): ?int
+ {
+ return $this->dateAdd;
+ }
+
+ public function getDateEdit(): ?int
+ {
+ return $this->dateEdit;
+ }
+
+ public function getCountView(): ?int
+ {
+ return $this->countView;
+ }
+
+ public function getCountDecrypt(): ?int
+ {
+ return $this->countDecrypt;
+ }
+
+ public function getIsPrivate(): ?int
+ {
+ return $this->isPrivate;
+ }
+
+ public function getIsPrivateGroup(): ?int
+ {
+ return $this->isPrivateGroup;
+ }
+
+ public function getPassDate(): ?int
+ {
+ return $this->passDate;
+ }
+
+ public function getPassDateChange(): ?int
+ {
+ return $this->passDateChange;
+ }
+
+ public function getParentId(): ?int
+ {
+ return $this->parentId;
+ }
+
+ public function getOtherUserGroupEdit(): ?int
+ {
+ return $this->otherUserGroupEdit;
+ }
+
+ public function getOtherUserEdit(): ?int
+ {
+ return $this->otherUserEdit;
+ }
+
+ public function getIsModify(): ?int
+ {
+ return $this->isModify;
+ }
+
+ public function getIsDeleted(): ?int
+ {
+ return $this->isDeleted;
+ }
+}
diff --git a/lib/SP/Domain/Account/Models/AccountSearchView.php b/lib/SP/Domain/Account/Models/AccountSearchView.php
new file mode 100644
index 00000000..32ad91fe
--- /dev/null
+++ b/lib/SP/Domain/Account/Models/AccountSearchView.php
@@ -0,0 +1,196 @@
+.
+ */
+
+namespace SP\Domain\Account\Models;
+
+use SP\Domain\Common\Models\Model;
+
+/**
+ * Class AccountSearchView
+ */
+final class AccountSearchView extends Model
+{
+ protected ?int $id = null;
+ protected ?int $clientId = null;
+ protected ?int $categoryId = null;
+ protected ?string $name = null;
+ protected ?string $login = null;
+ protected ?string $url = null;
+ protected ?string $notes = null;
+ protected ?int $userId = null;
+ protected ?int $userGroupId = null;
+ protected ?int $otherUserEdit = null;
+ protected ?int $otherUserGroupEdit = null;
+ protected ?int $isPrivate = null;
+ protected ?int $isPrivateGroup = null;
+ protected ?int $passDate = null;
+ protected ?int $passDateChange = null;
+ protected ?int $parentId = null;
+ protected ?int $countView = null;
+ protected ?int $dateEdit = null;
+ protected ?string $userName = null;
+ protected ?string $userLogin = null;
+ protected ?string $userGroupName = null;
+ protected ?string $categoryName = null;
+ protected ?string $clientName = null;
+ protected ?int $num_files = null;
+ protected ?string $publicLinkHash = null;
+ protected ?string $publicLinkDateExpire = null;
+ protected ?string $publicLinkTotalCountViews = null;
+
+ public function getClientId(): ?int
+ {
+ return $this->clientId;
+ }
+
+ public function getCategoryId(): ?int
+ {
+ return $this->categoryId;
+ }
+
+ public function getLogin(): ?string
+ {
+ return $this->login;
+ }
+
+ public function getUrl(): ?string
+ {
+ return $this->url;
+ }
+
+ public function getNotes(): ?string
+ {
+ return $this->notes;
+ }
+
+ public function getUserId(): ?int
+ {
+ return $this->userId;
+ }
+
+ public function getUserGroupId(): ?int
+ {
+ return $this->userGroupId;
+ }
+
+ public function getOtherUserEdit(): ?int
+ {
+ return $this->otherUserEdit;
+ }
+
+ public function getOtherUserGroupEdit(): ?int
+ {
+ return $this->otherUserGroupEdit;
+ }
+
+ public function getIsPrivate(): ?int
+ {
+ return $this->isPrivate;
+ }
+
+ public function getIsPrivateGroup(): ?int
+ {
+ return $this->isPrivateGroup;
+ }
+
+ public function getPassDate(): ?int
+ {
+ return $this->passDate;
+ }
+
+ public function getPassDateChange(): ?int
+ {
+ return $this->passDateChange;
+ }
+
+ public function getParentId(): ?int
+ {
+ return $this->parentId;
+ }
+
+ public function getCountView(): ?int
+ {
+ return $this->countView;
+ }
+
+ public function getDateEdit(): ?int
+ {
+ return $this->dateEdit;
+ }
+
+ public function getUserLogin(): ?string
+ {
+ return $this->userLogin;
+ }
+
+ public function getNumFiles(): ?int
+ {
+ return $this->num_files;
+ }
+
+ public function getPublicLinkHash(): ?string
+ {
+ return $this->publicLinkHash;
+ }
+
+ public function getPublicLinkDateExpire(): ?string
+ {
+ return $this->publicLinkDateExpire;
+ }
+
+ public function getPublicLinkTotalCountViews(): ?string
+ {
+ return $this->publicLinkTotalCountViews;
+ }
+
+ public function getId(): ?int
+ {
+ return $this->id;
+ }
+
+ public function getName(): ?string
+ {
+ return $this->name;
+ }
+
+ public function getClientName(): ?string
+ {
+ return $this->clientName;
+ }
+
+ public function getCategoryName(): ?string
+ {
+ return $this->categoryName;
+ }
+
+ public function getUserName(): ?string
+ {
+ return $this->userName;
+ }
+
+ public function getUserGroupName(): ?string
+ {
+ return $this->userGroupName;
+ }
+}
diff --git a/lib/SP/Domain/Account/Models/AccountUseCases.php b/lib/SP/Domain/Account/Models/AccountUseCases.php
new file mode 100644
index 00000000..910a30de
--- /dev/null
+++ b/lib/SP/Domain/Account/Models/AccountUseCases.php
@@ -0,0 +1,118 @@
+.
+ */
+
+namespace SP\Domain\Account\Models;
+
+use SP\Domain\Account\Dtos\AccountCreateDto;
+use SP\Domain\Account\Dtos\AccountDto;
+use SP\Domain\Account\Dtos\AccountHistoryDto;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
+
+/**
+ * Trait AccountUseCases
+ */
+trait AccountUseCases
+{
+ public static function create(AccountCreateDto $accountCreateDto): Account
+ {
+ $account = new Account();
+ $account->passDate = time();
+ self::buildCommon($accountCreateDto, $account);
+
+ return $account;
+ }
+
+ /**
+ * @param \SP\Domain\Account\Dtos\AccountCreateDto $accountDto
+ * @param \SP\Domain\Account\Models\Account $account
+ *
+ * @return void
+ */
+ private static function buildCommon(AccountDto $accountDto, Account $account): void
+ {
+ $account->userId = $accountDto->getUserId();
+ $account->userGroupId = $accountDto->getUserGroupId();
+ $account->userGroupId = $accountDto->getUserGroupId();
+ $account->name = $accountDto->getName();
+ $account->clientId = $accountDto->getClientId();
+ $account->login = $accountDto->getLogin();
+ $account->url = $accountDto->getUrl();
+ $account->notes = $accountDto->getNotes();
+ $account->isPrivate = (int)$accountDto->getIsPrivate();
+ $account->isPrivateGroup = (int)$accountDto->getIsPrivateGroup();
+ $account->passDateChange = $accountDto->getPassDateChange();
+ $account->parentId = $accountDto->getParentId();
+ $account->otherUserEdit = (int)$accountDto->getOtherUserEdit();
+ $account->otherUserGroupEdit = (int)$accountDto->getOtherUserGroupEdit();
+ }
+
+ public static function update(AccountUpdateDto $accountUpdateDto): Account
+ {
+ $account = new Account();
+ self::buildCommon($accountUpdateDto, $account);
+
+ return $account;
+ }
+
+ public static function updatePassword(AccountUpdateDto $accountUpdateDto): Account
+ {
+ $account = new Account();
+ $account->pass = $accountUpdateDto->getPass();
+ $account->key = $accountUpdateDto->getKey();
+ $account->passDate = time();
+ $account->userEditId = $accountUpdateDto->getUserEditId();
+ $account->passDateChange = $accountUpdateDto->getPassDateChange();
+
+ return $account;
+ }
+
+ public static function restoreRemoved(AccountHistoryDto $accountHistoryDto, int $userEditId): Account
+ {
+ $account = new Account();
+ $account->pass = $accountHistoryDto->getPass();
+ $account->key = $accountHistoryDto->getKey();
+ $account->userEditId = $userEditId;
+ $account->passDate = $accountHistoryDto->getPassDate();
+ $account->dateAdd = $accountHistoryDto->getDateAdd();
+ $account->dateEdit = $accountHistoryDto->getDateEdit();
+ $account->countView = $accountHistoryDto->getCountView();
+ $account->countDecrypt = $accountHistoryDto->getCountDecrypt();
+
+ self::buildCommon($accountHistoryDto, $account);
+
+ return $account;
+ }
+
+ public static function restoreModified(AccountHistoryDto $accountHistoryDto, int $userEditId): Account
+ {
+ $account = new Account();
+ $account->pass = $accountHistoryDto->getPass();
+ $account->key = $accountHistoryDto->getKey();
+ $account->userEditId = $userEditId;
+
+ self::buildCommon($accountHistoryDto, $account);
+
+ return $account;
+ }
+}
diff --git a/lib/SP/DataModel/ItemPresetData.php b/lib/SP/Domain/Account/Models/ItemPreset.php
similarity index 90%
rename from lib/SP/DataModel/ItemPresetData.php
rename to lib/SP/Domain/Account/Models/ItemPreset.php
index 103cce2b..fdf66b92 100644
--- a/lib/SP/DataModel/ItemPresetData.php
+++ b/lib/SP/Domain/Account/Models/ItemPreset.php
@@ -22,17 +22,16 @@
* along with sysPass. If not, see .
*/
-namespace SP\DataModel;
+namespace SP\Domain\Account\Models;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\HydratableInterface;
+use SP\Domain\Common\Models\Model;
+use SP\Domain\Common\Models\SerializedModel;
/**
- * Class ItemPresetData
- *
- * @package SP\DataModel
+ * Class ItemPreset
*/
-class ItemPresetData extends DataModel implements HydratableInterface
+class ItemPreset extends Model implements HydratableInterface
{
use SerializedModel;
diff --git a/lib/SP/Domain/Account/Ports/AccountHistoryRepositoryInterface.php b/lib/SP/Domain/Account/Ports/AccountHistoryRepositoryInterface.php
index 3ec9defc..497040d4 100644
--- a/lib/SP/Domain/Account/Ports/AccountHistoryRepositoryInterface.php
+++ b/lib/SP/Domain/Account/Ports/AccountHistoryRepositoryInterface.php
@@ -27,6 +27,7 @@ namespace SP\Domain\Account\Ports;
use SP\DataModel\ItemSearchData;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
use SP\Domain\Account\Dtos\AccountPasswordRequest;
+use SP\Domain\Account\Dtos\EncryptedPassword;
use SP\Domain\Common\Ports\RepositoryInterface;
use SP\Infrastructure\Database\QueryResult;
@@ -72,11 +73,12 @@ interface AccountHistoryRepositoryInterface extends RepositoryInterface
/**
* Actualiza la clave de una cuenta en la BBDD.
*
- * @param \SP\Domain\Account\Dtos\AccountPasswordRequest $request
+ * @param int $accountId
+ * @param \SP\Domain\Account\Dtos\EncryptedPassword $encryptedPassword
*
* @return bool
*/
- public function updatePassword(AccountPasswordRequest $request): bool;
+ public function updatePassword(int $accountId, EncryptedPassword $encryptedPassword): bool;
/**
* Elimina los datos de una cuenta en la BBDD.
diff --git a/lib/SP/Domain/Account/Ports/AccountHistoryServiceInterface.php b/lib/SP/Domain/Account/Ports/AccountHistoryServiceInterface.php
index 6960699a..c3fca687 100644
--- a/lib/SP/Domain/Account/Ports/AccountHistoryServiceInterface.php
+++ b/lib/SP/Domain/Account/Ports/AccountHistoryServiceInterface.php
@@ -27,11 +27,12 @@ namespace SP\Domain\Account\Ports;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountHistoryData;
-use SP\DataModel\ItemData;
use SP\DataModel\ItemSearchData;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
use SP\Domain\Account\Dtos\AccountPasswordRequest;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
+use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\AccountHistory;
use SP\Domain\Common\Services\ServiceException;
use SP\Infrastructure\Common\Repositories\NoSuchItemException;
use SP\Infrastructure\Database\QueryResult;
@@ -48,7 +49,7 @@ interface AccountHistoryServiceInterface
*
* @throws NoSuchItemException
*/
- public function getById(int $id): AccountHistoryData;
+ public function getById(int $id): AccountHistory;
/**
* Obtiene el listado del histórico de una cuenta.
@@ -114,5 +115,5 @@ interface AccountHistoryServiceInterface
* @throws SPException
* @throws ConstraintException
*/
- public function updatePasswordMasterPass(AccountPasswordRequest $accountPasswordRequest): void;
+ public function updatePasswordMasterPass(int $accountId, EncryptedPassword $encryptedPassword): void;
}
diff --git a/lib/SP/Domain/Account/Ports/AccountItemsServiceInterface.php b/lib/SP/Domain/Account/Ports/AccountItemsServiceInterface.php
new file mode 100644
index 00000000..184b9ffd
--- /dev/null
+++ b/lib/SP/Domain/Account/Ports/AccountItemsServiceInterface.php
@@ -0,0 +1,54 @@
+.
+ */
+
+namespace SP\Domain\Account\Ports;
+
+use SP\Core\Exceptions\ConstraintException;
+use SP\Core\Exceptions\QueryException;
+use SP\Domain\Account\Dtos\AccountCreateDto;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
+
+/**
+ * Class AccountItemsService
+ */
+interface AccountItemsServiceInterface
+{
+ /**
+ * Updates external items for the account
+ *
+ * @throws QueryException
+ * @throws ConstraintException
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function updateItems(
+ bool $userCanChangePermissions,
+ int $accountId,
+ AccountUpdateDto $accountUpdateDto
+ ): void;
+
+ /**
+ * Adds external items to the account
+ */
+ public function addItems(bool $userCanChangePermissions, int $accountId, AccountCreateDto $accountCreateDto): void;
+}
diff --git a/lib/SP/Domain/Account/Ports/AccountPresetServiceInterface.php b/lib/SP/Domain/Account/Ports/AccountPresetServiceInterface.php
index 3282f5e6..455a0ea5 100644
--- a/lib/SP/Domain/Account/Ports/AccountPresetServiceInterface.php
+++ b/lib/SP/Domain/Account/Ports/AccountPresetServiceInterface.php
@@ -28,7 +28,7 @@ use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\NoSuchPropertyException;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\ValidationException;
-use SP\Domain\Account\Dtos\AccountRequest;
+use SP\Domain\Account\Dtos\AccountDto;
/**
* Class AccountPreset
@@ -43,5 +43,12 @@ interface AccountPresetServiceInterface
* @throws NoSuchPropertyException
* @throws QueryException
*/
- public function checkPasswordPreset(AccountRequest $accountRequest): void;
+ public function checkPasswordPreset(AccountDto $accountDto): AccountDto;
+
+ /**
+ * @throws QueryException
+ * @throws ConstraintException
+ * @throws NoSuchPropertyException
+ */
+ public function addPresetPermissions(int $accountId): void;
}
diff --git a/lib/SP/Domain/Account/Ports/AccountRepositoryInterface.php b/lib/SP/Domain/Account/Ports/AccountRepositoryInterface.php
index e6b653d5..a4e8bd9a 100644
--- a/lib/SP/Domain/Account/Ports/AccountRepositoryInterface.php
+++ b/lib/SP/Domain/Account/Ports/AccountRepositoryInterface.php
@@ -26,19 +26,16 @@ namespace SP\Domain\Account\Ports;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountHistoryData;
use SP\DataModel\ItemSearchData;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
-use SP\Domain\Account\Dtos\AccountRequest;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\Account;
use SP\Domain\Common\Ports\RepositoryInterface;
use SP\Infrastructure\Database\QueryResult;
/**
* Class AccountRepository
*
- * @package Services
+ * @package SP\Domain\Account\Ports
*/
interface AccountRepositoryInterface extends RepositoryInterface
{
@@ -48,102 +45,107 @@ interface AccountRepositoryInterface extends RepositoryInterface
* @throws QueryException
* @throws ConstraintException
*/
- public function getTotalNumAccounts(): SimpleModel;
+ public function getTotalNumAccounts(): QueryResult;
/**
- * @param int $id
+ * @param int $accountId
*
* @return QueryResult
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function getPasswordForId(int $id): QueryResult;
+ public function getPasswordForId(int $accountId): QueryResult;
/**
- * @param int $id
+ * @param int $accountId
*
* @return QueryResult
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function getPasswordHistoryForId(int $id): QueryResult;
+ public function getPasswordHistoryForId(int $accountId): QueryResult;
/**
* Incrementa el contador de vista de clave de una cuenta en la BBDD
*
- * @param int $id
+ * @param int $accountId
*
- * @return bool
+ * @return QueryResult
* @throws ConstraintException
* @throws QueryException
*/
- public function incrementDecryptCounter(int $id): bool;
+ public function incrementDecryptCounter(int $accountId): QueryResult;
/**
* Actualiza la clave de una cuenta en la BBDD.
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
- *
- * @return int
- * @throws ConstraintException
- * @throws QueryException
- */
- public function editPassword(AccountRequest $accountRequest): int;
-
- /**
- * Actualiza la clave de una cuenta en la BBDD.
- *
- * @param \SP\Domain\Account\Dtos\AccountPasswordRequest $request
- *
- * @return bool
- * @throws ConstraintException
- * @throws QueryException
- */
- public function updatePassword(AccountPasswordRequest $request): bool;
-
- /**
- * Restaurar una cuenta desde el histórico.
- *
- * @param \SP\DataModel\AccountHistoryData $accountHistoryData
- * @param int $userId User's Id
- *
- * @return bool
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- public function editRestore(AccountHistoryData $accountHistoryData, 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
+ * @param int $accountId
+ * @param \SP\Domain\Account\Models\Account $account
*
* @return QueryResult
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function getDataForLink(int $id): QueryResult;
+ public function editPassword(int $accountId, Account $account): QueryResult;
+
+ /**
+ * Actualiza la clave de una cuenta en la BBDD.
+ *
+ * @param int $accountId
+ * @param \SP\Domain\Account\Dtos\EncryptedPassword $encryptedPassword
+ *
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function updatePassword(int $accountId, EncryptedPassword $encryptedPassword): QueryResult;
+
+ /**
+ * Restaurar una cuenta desde el histórico.
+ *
+ * @param int $accountId
+ * @param \SP\Domain\Account\Models\Account $account
+ *
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function restoreModified(int $accountId, Account $account): QueryResult;
+
+ /**
+ * Updates an item for bulk action
+ *
+ * @param int $accountId
+ * @param \SP\Domain\Account\Models\Account $account
+ * @param bool $changeOwner
+ * @param bool $changeUserGroup
+ *
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function updateBulk(int $accountId, Account $account, bool $changeOwner, bool $changeUserGroup): QueryResult;
+
+ /**
+ * Incrementa el contador de visitas de una cuenta en la BBDD
+ *
+ * @param int $accountId
+ *
+ * @return QueryResult
+ * @throws ConstraintException
+ * @throws QueryException
+ */
+ public function incrementViewCounter(int $accountId): QueryResult;
+
+ /**
+ * Obtener los datos de una cuenta.
+ *
+ * @param int $accountId
+ *
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function getDataForLink(int $accountId): QueryResult;
/**
* @param int|null $accountId
@@ -175,43 +177,55 @@ interface AccountRepositoryInterface extends RepositoryInterface
/**
* Crea una nueva cuenta en la BBDD
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
+ * @param \SP\Domain\Account\Models\Account $account
*
- * @return int
- * @throws ConstraintException
- * @throws QueryException
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
*/
- public function create(AccountRequest $accountRequest): int;
+ public function create(Account $account): QueryResult;
/**
* Elimina los datos de una cuenta en la BBDD.
*
- * @param int $id
+ * @param int $accountId
*
- * @return bool
+ * @return QueryResult
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function delete(int $id): bool;
+ public function delete(int $accountId): QueryResult;
/**
* Updates an item
*
- * @param AccountRequest $accountRequest
+ * @param int $accountId
+ * @param \SP\Domain\Account\Models\Account $account
+ * @param bool $changeOwner
+ * @param bool $changeUserGroup
*
- * @return int
- * @throws SPException
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function update(AccountRequest $accountRequest): int;
+ public function update(int $accountId, Account $account, bool $changeOwner, bool $changeUserGroup): QueryResult;
+
+ /**
+ * Returns the item for given id with referential data
+ *
+ * @param int $accountId
+ *
+ * @return QueryResult
+ */
+ public function getByIdEnriched(int $accountId): QueryResult;
/**
* Returns the item for given id
*
- * @param int $id
+ * @param int $accountId
*
* @return QueryResult
*/
- public function getById(int $id): QueryResult;
+ public function getById(int $accountId): QueryResult;
/**
* Returns all the items
@@ -223,13 +237,13 @@ interface AccountRepositoryInterface extends RepositoryInterface
/**
* Deletes all the items for given ids
*
- * @param array $ids
+ * @param array $accountsId
*
- * @return int
+ * @return QueryResult
* @throws ConstraintException
* @throws QueryException
*/
- public function deleteByIdBatch(array $ids): int;
+ public function deleteByIdBatch(array $accountsId): QueryResult;
/**
* Searches for items by a given filter
@@ -240,4 +254,14 @@ interface AccountRepositoryInterface extends RepositoryInterface
*/
public function search(ItemSearchData $itemSearchData): QueryResult;
+ /**
+ * Create an account from deleted
+ *
+ * @param \SP\Domain\Account\Models\Account $account
+ *
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function createRemoved(Account $account): QueryResult;
}
diff --git a/lib/SP/Domain/Account/Ports/AccountServiceInterface.php b/lib/SP/Domain/Account/Ports/AccountServiceInterface.php
index 20de13d3..ad2d4a25 100644
--- a/lib/SP/Domain/Account/Ports/AccountServiceInterface.php
+++ b/lib/SP/Domain/Account/Ports/AccountServiceInterface.php
@@ -25,20 +25,20 @@
namespace SP\Domain\Account\Ports;
use SP\Core\Exceptions\ConstraintException;
-use SP\Core\Exceptions\NoSuchPropertyException;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountExtData;
-use SP\DataModel\AccountHistoryData;
use SP\DataModel\ItemSearchData;
use SP\Domain\Account\Adapters\AccountData;
-use SP\Domain\Account\Adapters\AccountPassData;
-use SP\Domain\Account\Dtos\AccountBulkRequest;
+use SP\Domain\Account\Dtos\AccountCreateDto;
use SP\Domain\Account\Dtos\AccountEnrichedDto;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
-use SP\Domain\Account\Dtos\AccountRequest;
+use SP\Domain\Account\Dtos\AccountHistoryDto;
+use SP\Domain\Account\Dtos\AccountUpdateBulkDto;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
+use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\Account;
+use SP\Domain\Account\Models\AccountDataView;
+use SP\Domain\Common\Models\Simple;
use SP\Domain\Common\Services\ServiceException;
-use SP\Infrastructure\Common\Repositories\NoSuchItemException;
use SP\Infrastructure\Database\QueryResult;
/**
@@ -49,90 +49,124 @@ use SP\Infrastructure\Database\QueryResult;
interface AccountServiceInterface
{
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param \SP\Domain\Account\Dtos\AccountEnrichedDto $accountEnrichedDto
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
*/
- public function withUsersById(AccountEnrichedDto $accountDetailsResponse): AccountServiceInterface;
+ public function withUsers(AccountEnrichedDto $accountEnrichedDto): AccountEnrichedDto;
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param \SP\Domain\Account\Dtos\AccountEnrichedDto $accountEnrichedDto
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
*/
- public function withUserGroupsById(AccountEnrichedDto $accountDetailsResponse): AccountServiceInterface;
+ public function withUserGroups(AccountEnrichedDto $accountEnrichedDto): AccountEnrichedDto;
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param \SP\Domain\Account\Dtos\AccountEnrichedDto $accountEnrichedDto
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
*/
- public function withTagsById(AccountEnrichedDto $accountDetailsResponse): AccountServiceInterface;
+ public function withTags(AccountEnrichedDto $accountEnrichedDto): AccountEnrichedDto;
/**
+ * @param int $id The account ID
+ *
+ * @return bool
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
public function incrementViewCounter(int $id): bool;
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param int $id The account ID
+ *
+ * @return bool
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
*/
public function incrementDecryptCounter(int $id): bool;
/**
+ * @param int $id The account ID
+ *
+ * @return \SP\Domain\Account\Models\Account
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
* @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
*/
- public function getPasswordForId(int $id): AccountPassData;
+ public function getPasswordForId(int $id): Account;
/**
- * @param \SP\DataModel\AccountHistoryData $data
+ * @param \SP\Domain\Account\Dtos\AccountHistoryDto $accountHistoryDto
*
- * @return int
+ * @return void
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function createFromHistory(AccountHistoryData $data): int;
+ public function restoreRemoved(AccountHistoryDto $accountHistoryDto): void;
/**
- * @throws QueryException
- * @throws SPException
- * @throws ConstraintException
- * @throws NoSuchPropertyException
+ * @param \SP\Domain\Account\Dtos\AccountCreateDto $accountCreateDto
+ *
+ * @return int
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\NoSuchPropertyException
*/
- public function create(AccountRequest $accountRequest): int;
+ public function create(AccountCreateDto $accountCreateDto): int;
/**
- * @throws QueryException
- * @throws NoSuchItemException
- * @throws ConstraintException
+ * @param int $id The account ID
+ *
+ * @return \SP\Domain\Account\Models\AccountDataView
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\ConstraintException
*/
- public function getById(int $id): AccountEnrichedDto;
+ public function getByIdEnriched(int $id): AccountDataView;
+
+ /**
+ * @param int $id The account ID
+ *
+ * @return \SP\Domain\Account\Models\Account
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ */
+ public function getById(int $id): Account;
/**
* Updates external items for the account
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
+ * @param int $id The account ID
+ * @param \SP\Domain\Account\Dtos\AccountUpdateDto $accountUpdateDto
*
* @throws \SP\Domain\Common\Services\ServiceException
*/
- public function update(AccountRequest $accountRequest): void;
+ public function update(int $id, AccountUpdateDto $accountUpdateDto): void;
/**
* Update accounts in bulk mode
*
- * @param \SP\Domain\Account\Dtos\AccountBulkRequest $request
+ * @param \SP\Domain\Account\Dtos\AccountUpdateBulkDto $accountUpdateBulkDto
*
* @throws \SP\Domain\Common\Services\ServiceException
*/
- public function updateBulk(AccountBulkRequest $request): void;
+ public function updateBulk(AccountUpdateBulkDto $accountUpdateBulkDto): void;
/**
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
+ * @param int $id The account ID
+ * @param \SP\Domain\Account\Dtos\AccountUpdateDto $accountUpdateDto
*
* @throws \SP\Domain\Common\Services\ServiceException
*/
- public function editPassword(AccountRequest $accountRequest): void;
+ public function editPassword(int $id, AccountUpdateDto $accountUpdateDto): void;
/**
* Updates an already encrypted password data from a master password changing action
@@ -140,48 +174,59 @@ interface AccountServiceInterface
* @throws ConstraintException
* @throws QueryException
*/
- public function updatePasswordMasterPass(AccountPasswordRequest $accountRequest): void;
+ public function updatePasswordMasterPass(int $id, EncryptedPassword $encryptedPassword): void;
/**
- * @param int $historyId
- * @param int $accountId
+ * @param \SP\Domain\Account\Dtos\AccountHistoryDto $accountHistoryDto
*
* @throws \SP\Domain\Common\Services\ServiceException
* @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
*/
- public function editRestore(int $historyId, int $accountId): void;
+ public function restoreModified(AccountHistoryDto $accountHistoryDto): void;
/**
+ * @param int $id The account ID
+ *
+ * @return \SP\Domain\Account\Ports\AccountServiceInterface
* @throws \SP\Domain\Common\Services\ServiceException
*/
public function delete(int $id): AccountServiceInterface;
/**
- * @param int[] $ids
+ * @param int[] $ids The accounts ID
*
* @throws SPException
* @throws ServiceException
*/
- public function deleteByIdBatch(array $ids): AccountServiceInterface;
+ public function deleteByIdBatch(array $ids): void;
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param int|null $id The account ID
+ *
+ * @return array
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
*/
- public function getForUser(?int $accountId = null): array;
+ public function getForUser(?int $id = null): array;
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param int $id The account ID
+ *
+ * @return array
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
*/
- public function getLinked(int $accountId): array;
+ public function getLinked(int $id): array;
/**
- * @throws QueryException
- * @throws ConstraintException
- * @throws NoSuchItemException
+ * @param int $id The account ID
+ *
+ * @return \SP\Domain\Common\Models\Simple
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
*/
- public function getPasswordHistoryForId(int $id): AccountPassData;
+ public function getPasswordHistoryForId(int $id): Simple;
/**
* @return AccountData[]
@@ -206,11 +251,14 @@ interface AccountServiceInterface
/**
* Obtener los datos de una cuenta.
*
+ * @param int $id The account ID
+ *
+ * @return \SP\Domain\Common\Models\Simple
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
* @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
*/
- public function getDataForLink(int $id): AccountExtData;
+ public function getDataForLink(int $id): Simple;
/**
* Obtener los datos relativos a la clave de todas las cuentas.
diff --git a/lib/SP/Domain/Account/Ports/AccountToTagRepositoryInterface.php b/lib/SP/Domain/Account/Ports/AccountToTagRepositoryInterface.php
index b53e8b00..5e6c0c27 100644
--- a/lib/SP/Domain/Account/Ports/AccountToTagRepositoryInterface.php
+++ b/lib/SP/Domain/Account/Ports/AccountToTagRepositoryInterface.php
@@ -26,6 +26,7 @@ namespace SP\Domain\Account\Ports;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
+use SP\Domain\Account\Dtos\AccountDto;
use SP\Domain\Account\Dtos\AccountRequest;
use SP\Domain\Common\Ports\RepositoryInterface;
use SP\Infrastructure\Database\QueryResult;
@@ -62,10 +63,11 @@ interface AccountToTagRepositoryInterface extends RepositoryInterface
/**
* Actualizar las etiquetas de una cuenta
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
+ * @param int $accountId
+ * @param array $tags
*
- * @throws ConstraintException
- * @throws QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
*/
- public function add(AccountRequest $accountRequest): void;
+ public function add(int $accountId, array $tags): void;
}
diff --git a/lib/SP/Domain/Account/Ports/AccountToUserGroupRepositoryInterface.php b/lib/SP/Domain/Account/Ports/AccountToUserGroupRepositoryInterface.php
index 868b753c..7114af9f 100644
--- a/lib/SP/Domain/Account/Ports/AccountToUserGroupRepositoryInterface.php
+++ b/lib/SP/Domain/Account/Ports/AccountToUserGroupRepositoryInterface.php
@@ -86,7 +86,7 @@ interface AccountToUserGroupRepositoryInterface extends RepositoryInterface
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function addByType(int $accountId, array $items, bool $isEdit): void;
+ public function addByType(int $accountId, array $items, bool $isEdit = false): void;
/**
* @param $id int
diff --git a/lib/SP/Domain/Account/Ports/AccountToUserRepositoryInterface.php b/lib/SP/Domain/Account/Ports/AccountToUserRepositoryInterface.php
index b8313bca..d6469bee 100644
--- a/lib/SP/Domain/Account/Ports/AccountToUserRepositoryInterface.php
+++ b/lib/SP/Domain/Account/Ports/AccountToUserRepositoryInterface.php
@@ -59,7 +59,7 @@ interface AccountToUserRepositoryInterface extends RepositoryInterface
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function addByType(int $accountId, array $items, bool $isEdit): void;
+ public function addByType(int $accountId, array $items, bool $isEdit = false): void;
/**
* Eliminar la asociación de grupos con cuentas.
diff --git a/lib/SP/Domain/Account/Search/AccountSearchDataBuilder.php b/lib/SP/Domain/Account/Search/AccountSearchDataBuilder.php
index 7e5975eb..33df3ab3 100644
--- a/lib/SP/Domain/Account/Search/AccountSearchDataBuilder.php
+++ b/lib/SP/Domain/Account/Search/AccountSearchDataBuilder.php
@@ -28,6 +28,8 @@ use SP\Core\Acl\ActionsInterface;
use SP\Core\Application;
use SP\DataModel\AccountSearchVData;
use SP\Domain\Account\Dtos\AccountAclDto;
+use SP\Domain\Account\Models\AccountDataView;
+use SP\Domain\Account\Models\AccountSearchView;
use SP\Domain\Account\Ports\AccountAclServiceInterface;
use SP\Domain\Account\Ports\AccountCacheServiceInterface;
use SP\Domain\Account\Ports\AccountSearchDataBuilderInterface;
@@ -118,50 +120,50 @@ final class AccountSearchDataBuilder extends Service implements AccountSearchDat
return array_map(
/**
- * @param AccountSearchVData $accountSearchData
+ * @param AccountSearchView $accountSearchView
*
* @return \SP\Domain\Account\Services\AccountSearchItem
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
* @throws \SP\Core\Exceptions\SPException
*/
- function (AccountSearchVData $accountSearchData) use ($maxTextLength, $accountLinkEnabled, $favorites) {
+ function (AccountSearchView $accountSearchView) use ($maxTextLength, $accountLinkEnabled, $favorites) {
$cache = $this->accountCacheService->getCacheForAccount(
- $accountSearchData->getId(),
- (int)strtotime($accountSearchData->getDateEdit())
+ $accountSearchView->getId(),
+ (int)strtotime($accountSearchView->getDateEdit())
);
// Obtener la ACL de la cuenta
$accountAcl = $this->accountAclService->getAcl(
ActionsInterface::ACCOUNT_SEARCH,
AccountAclDto::makeFromAccountSearch(
- $accountSearchData,
+ $accountSearchView,
$cache->getUsers(),
$cache->getUserGroups()
)
);
$tags = $this->accountToTagRepository
- ->getTagsByAccountId($accountSearchData->getId())
+ ->getTagsByAccountId($accountSearchView->getId())
->getDataAsArray();
- $users = !$accountSearchData->getIsPrivate() ? $cache->getUsers() : null;
- $userGroups = !$accountSearchData->getIsPrivate() ? $cache->getUserGroups() : null;
+ $users = !$accountSearchView->getIsPrivate() ? $cache->getUsers() : null;
+ $userGroups = !$accountSearchView->getIsPrivate() ? $cache->getUserGroups() : null;
return new AccountSearchItem(
- $accountSearchData,
+ $accountSearchView,
$accountAcl,
$this->configData,
$tags,
$maxTextLength,
- isset($favorites[$accountSearchData->getId()]),
+ isset($favorites[$accountSearchView->getId()]),
$users,
$userGroups,
- $this->pickAccountColor($accountSearchData->getClientId()),
+ $this->pickAccountColor($accountSearchView->getClientId()),
$accountLinkEnabled
);
},
- $queryResult->getDataAsArray(AccountSearchVData::class)
+ $queryResult->getDataAsArray(AccountSearchView::class)
);
}
diff --git a/lib/SP/Domain/Account/Services/AccountCryptService.php b/lib/SP/Domain/Account/Services/AccountCryptService.php
index 1e134e4d..b3b55be1 100644
--- a/lib/SP/Domain/Account/Services/AccountCryptService.php
+++ b/lib/SP/Domain/Account/Services/AccountCryptService.php
@@ -31,7 +31,7 @@ use SP\Core\Events\Event;
use SP\Core\Events\EventMessage;
use SP\Core\Exceptions\CryptException;
use SP\Core\Exceptions\SPException;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
use SP\Domain\Account\Dtos\EncryptedPassword;
use SP\Domain\Account\Ports\AccountCryptServiceInterface;
use SP\Domain\Account\Ports\AccountHistoryServiceInterface;
@@ -74,7 +74,7 @@ final class AccountCryptService extends Service implements AccountCryptServiceIn
new Event(
$this,
EventMessage::factory()
- ->addDescription(__u('Update Master Password'))
+ ->addDescription(__u('Update Master Password'))
)
);
@@ -92,8 +92,8 @@ final class AccountCryptService extends Service implements AccountCryptServiceIn
$eventMessage = $this->processAccounts(
$this->accountService->getAccountsPassData(),
- function (AccountPasswordRequest $request) {
- $this->accountService->updatePasswordMasterPass($request);
+ function (int $accountId, EncryptedPassword $encryptedPassword) {
+ $this->accountService->updatePasswordMasterPass($accountId, $encryptedPassword);
},
$updateMasterPassRequest
);
@@ -115,6 +115,13 @@ final class AccountCryptService extends Service implements AccountCryptServiceIn
}
}
+ /**
+ * @param \SP\Domain\Account\Models\Account[] $accounts
+ * @param callable $passUpdater
+ * @param \SP\Domain\Crypt\Services\UpdateMasterPassRequest $updateMasterPassRequest
+ *
+ * @return \SP\Core\Events\EventMessage
+ */
private function processAccounts(
array $accounts,
callable $passUpdater,
@@ -146,7 +153,7 @@ final class AccountCryptService extends Service implements AccountCryptServiceIn
foreach ($accounts as $account) {
// No realizar cambios si está en modo demo
if ($configData->isDemoEnabled()) {
- $accountsOk[] = $account->id;
+ $accountsOk[] = $account->getId();
continue;
}
@@ -180,30 +187,24 @@ final class AccountCryptService extends Service implements AccountCryptServiceIn
if (isset($account->mPassHash) && $account->mPassHash !== $currentMasterPassHash) {
$eventMessage->addDescription(__u('The record\'s master password does not match'));
- $eventMessage->addDetail($account->name, $account->id);
+ $eventMessage->addDetail($account->getName(), $account->getId());
continue;
}
try {
$encryptedPassword = $this->getPasswordEncrypted(
$this->crypt->decrypt(
- $account->pass,
- $account->key,
+ $account->getPass(),
+ $account->getKey(),
$updateMasterPassRequest->getCurrentMasterPass()
),
$updateMasterPassRequest->getNewMasterPass()
);
- $request = new AccountPasswordRequest(
- $account->id,
- $encryptedPassword,
- $updateMasterPassRequest->getHash()
- );
-
// Call the specific updater
- $passUpdater($request);
+ $passUpdater($account->getId(), $encryptedPassword);
- $accountsOk[] = $account->id;
+ $accountsOk[] = $account->getId();
$counter++;
} catch (SPException $e) {
$this->eventDispatcher->notifyEvent('exception', new Event($e));
@@ -211,7 +212,7 @@ final class AccountCryptService extends Service implements AccountCryptServiceIn
$errorCount++;
$eventMessage->addDescription(__u('Error while updating the account\'s password'));
- $eventMessage->addDetail($account->name, $account->id);
+ $eventMessage->addDetail($account->getName(), $account->getId());
}
}
@@ -268,7 +269,7 @@ final class AccountCryptService extends Service implements AccountCryptServiceIn
new Event(
$this,
EventMessage::factory()
- ->addDescription(__u('Update Master Password (H)'))
+ ->addDescription(__u('Update Master Password (H)'))
)
);
@@ -286,8 +287,8 @@ final class AccountCryptService extends Service implements AccountCryptServiceIn
$eventMessage = $this->processAccounts(
$this->accountHistoryService->getAccountsPassData(),
- function (AccountPasswordRequest $request) {
- $this->accountHistoryService->updatePasswordMasterPass($request);
+ function (int $accountId, EncryptedPassword $encryptedPassword) {
+ $this->accountHistoryService->updatePasswordMasterPass($accountId, $encryptedPassword);
},
$updateMasterPassRequest
);
diff --git a/lib/SP/Domain/Account/Services/AccountFileService.php b/lib/SP/Domain/Account/Services/AccountFileService.php
index a1bb5e6b..846127fc 100644
--- a/lib/SP/Domain/Account/Services/AccountFileService.php
+++ b/lib/SP/Domain/Account/Services/AccountFileService.php
@@ -84,6 +84,7 @@ final class AccountFileService extends Service implements AccountFileServiceInte
* @param int $id
*
* @return \SP\DataModel\FileExtData|null
+ * @throws \SP\Core\Exceptions\SPException
*/
public function getById(int $id): ?FileExtData
{
diff --git a/lib/SP/Domain/Account/Services/AccountHistoryService.php b/lib/SP/Domain/Account/Services/AccountHistoryService.php
index 41f138d4..1a05e2cc 100644
--- a/lib/SP/Domain/Account/Services/AccountHistoryService.php
+++ b/lib/SP/Domain/Account/Services/AccountHistoryService.php
@@ -25,10 +25,10 @@
namespace SP\Domain\Account\Services;
use SP\Core\Application;
-use SP\DataModel\AccountHistoryData;
use SP\DataModel\ItemSearchData;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
+use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\AccountHistory;
use SP\Domain\Account\Ports\AccountHistoryRepositoryInterface;
use SP\Domain\Account\Ports\AccountHistoryServiceInterface;
use SP\Domain\Common\Services\Service;
@@ -56,7 +56,7 @@ final class AccountHistoryService extends Service implements AccountHistoryServi
*
* @throws NoSuchItemException
*/
- public function getById(int $id): AccountHistoryData
+ public function getById(int $id): AccountHistory
{
$results = $this->accountHistoryRepository->getById($id);
@@ -150,13 +150,14 @@ final class AccountHistoryService extends Service implements AccountHistoryServi
}
/**
- * @param \SP\Domain\Account\Dtos\AccountPasswordRequest $accountPasswordRequest
+ * @param int $accountId
+ * @param \SP\Domain\Account\Dtos\EncryptedPassword $encryptedPassword
*
* @throws \SP\Domain\Common\Services\ServiceException
*/
- public function updatePasswordMasterPass(AccountPasswordRequest $accountPasswordRequest): void
+ public function updatePasswordMasterPass(int $accountId, EncryptedPassword $encryptedPassword): void
{
- if (!$this->accountHistoryRepository->updatePassword($accountPasswordRequest)) {
+ if (!$this->accountHistoryRepository->updatePassword($accountId, $encryptedPassword)) {
throw new ServiceException(__u('Error while updating the password'));
}
}
diff --git a/lib/SP/Domain/Account/Services/AccountItemsService.php b/lib/SP/Domain/Account/Services/AccountItemsService.php
new file mode 100644
index 00000000..a18d8172
--- /dev/null
+++ b/lib/SP/Domain/Account/Services/AccountItemsService.php
@@ -0,0 +1,177 @@
+.
+ */
+
+namespace SP\Domain\Account\Services;
+
+use SP\Core\Application;
+use SP\Core\Exceptions\ConstraintException;
+use SP\Core\Exceptions\QueryException;
+use SP\Core\Exceptions\SPException;
+use SP\Domain\Account\Dtos\AccountCreateDto;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
+use SP\Domain\Account\Ports\AccountItemsServiceInterface;
+use SP\Domain\Account\Ports\AccountToTagRepositoryInterface;
+use SP\Domain\Account\Ports\AccountToUserGroupRepositoryInterface;
+use SP\Domain\Account\Ports\AccountToUserRepositoryInterface;
+use SP\Domain\Common\Services\Service;
+use function SP\processException;
+
+/**
+ * Class AccountItemsService
+ */
+final class AccountItemsService extends Service implements AccountItemsServiceInterface
+{
+ public function __construct(
+ Application $application,
+ private AccountToUserGroupRepositoryInterface $accountToUserGroupRepository,
+ private AccountToUserRepositoryInterface $accountToUserRepository,
+ private AccountToTagRepositoryInterface $accountToTagRepository,
+ ) {
+ parent::__construct($application);
+ }
+
+ /**
+ * Updates external items for the account
+ *
+ * @throws QueryException
+ * @throws ConstraintException
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function updateItems(
+ bool $userCanChangePermissions,
+ int $accountId,
+ AccountUpdateDto $accountUpdateDto
+ ): void {
+ if ($userCanChangePermissions) {
+ if (null === $accountUpdateDto->getUserGroupsView()) {
+ $this->accountToUserGroupRepository->deleteTypeByAccountId($accountId, false);
+ } elseif (count($accountUpdateDto->getUserGroupsView()) > 0) {
+ $this->accountToUserGroupRepository->transactionAware(
+ function () use ($accountUpdateDto, $accountId) {
+ $this->accountToUserGroupRepository
+ ->deleteTypeByAccountId($accountId, false);
+ $this->accountToUserGroupRepository
+ ->addByType($accountId, $accountUpdateDto->getUserGroupsView());
+ },
+ $this
+ );
+ }
+
+ if (null === $accountUpdateDto->getUserGroupsEdit()) {
+ $this->accountToUserGroupRepository->deleteTypeByAccountId($accountId, true);
+ } elseif (count($accountUpdateDto->getUserGroupsEdit()) > 0) {
+ $this->accountToUserGroupRepository->transactionAware(
+ function () use ($accountUpdateDto, $accountId) {
+ $this->accountToUserGroupRepository
+ ->deleteTypeByAccountId($accountId, true);
+ $this->accountToUserGroupRepository
+ ->addByType($accountId, $accountUpdateDto->getUserGroupsEdit(), true);
+ },
+ $this
+ );
+ }
+
+ if (null === $accountUpdateDto->getUsersView()) {
+ $this->accountToUserRepository->deleteTypeByAccountId($accountId, false);
+ } elseif (count($accountUpdateDto->getUsersView()) > 0) {
+ $this->accountToUserRepository->transactionAware(
+ function () use ($accountUpdateDto, $accountId) {
+ $this->accountToUserRepository
+ ->deleteTypeByAccountId($accountId, false);
+ $this->accountToUserRepository
+ ->addByType($accountId, $accountUpdateDto->getUsersView());
+ },
+ $this
+ );
+ }
+
+ if (null === $accountUpdateDto->getUsersEdit()) {
+ $this->accountToUserRepository->deleteTypeByAccountId($accountId, true);
+ } elseif (count($accountUpdateDto->getUsersEdit()) > 0) {
+ $this->accountToUserRepository->transactionAware(
+ function () use ($accountUpdateDto, $accountId) {
+ $this->accountToUserRepository
+ ->deleteTypeByAccountId($accountId, true);
+ $this->accountToUserRepository
+ ->addByType($accountId, $accountUpdateDto->getUsersEdit(), true);
+ },
+ $this
+ );
+ }
+ }
+
+ if (null === $accountUpdateDto->getTags()) {
+ $this->accountToTagRepository->deleteByAccountId($accountId);
+ } elseif (count($accountUpdateDto->getTags()) > 0) {
+ $this->accountToTagRepository->transactionAware(
+ function () use ($accountUpdateDto, $accountId) {
+ $this->accountToTagRepository->deleteByAccountId($accountId);
+ $this->accountToTagRepository->add($accountId, $accountUpdateDto->getTags());
+ },
+ $this
+ );
+ }
+ }
+
+ /**
+ * Adds external items to the account
+ */
+ public function addItems(bool $userCanChangePermissions, int $accountId, AccountCreateDto $accountCreateDto): void
+ {
+ try {
+ if ($userCanChangePermissions) {
+ if (null !== $accountCreateDto->getUserGroupsView()
+ && count($accountCreateDto->getUserGroupsView()) > 0) {
+ $this->accountToUserGroupRepository->addByType(
+ $accountId,
+ $accountCreateDto->getUserGroupsView()
+ );
+ }
+
+ if (null !== $accountCreateDto->getUserGroupsEdit()
+ && count($accountCreateDto->getUserGroupsEdit()) > 0) {
+ $this->accountToUserGroupRepository->addByType(
+ $accountId,
+ $accountCreateDto->getUserGroupsEdit(),
+ true
+ );
+ }
+
+ if (null !== $accountCreateDto->getUsersView() && count($accountCreateDto->getUsersView()) > 0) {
+ $this->accountToUserRepository->addByType($accountId, $accountCreateDto->getUsersView());
+ }
+
+ if (null !== $accountCreateDto->getUsersEdit() && count($accountCreateDto->getUsersEdit()) > 0) {
+ $this->accountToUserRepository->addByType($accountId, $accountCreateDto->getUsersEdit(), true);
+ }
+ }
+
+ if (null !== $accountCreateDto->getTags() && count($accountCreateDto->getTags()) > 0) {
+ $this->accountToTagRepository->add($accountId, $accountCreateDto->getTags());
+ }
+ } catch (SPException $e) {
+ processException($e);
+ }
+ }
+}
diff --git a/lib/SP/Domain/Account/Services/AccountPresetService.php b/lib/SP/Domain/Account/Services/AccountPresetService.php
index 6152e77b..7f285afa 100644
--- a/lib/SP/Domain/Account/Services/AccountPresetService.php
+++ b/lib/SP/Domain/Account/Services/AccountPresetService.php
@@ -24,13 +24,18 @@
namespace SP\Domain\Account\Services;
+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\DataModel\ItemPreset\AccountPermission;
use SP\DataModel\ItemPreset\Password;
-use SP\Domain\Account\Dtos\AccountRequest;
+use SP\Domain\Account\Dtos\AccountDto;
use SP\Domain\Account\Ports\AccountPresetServiceInterface;
+use SP\Domain\Account\Ports\AccountToUserGroupRepositoryInterface;
+use SP\Domain\Account\Ports\AccountToUserRepositoryInterface;
+use SP\Domain\Common\Services\Service;
use SP\Domain\Config\Ports\ConfigDataInterface;
use SP\Domain\ItemPreset\Ports\ItemPresetInterface;
use SP\Domain\ItemPreset\Ports\ItemPresetServiceInterface;
@@ -41,13 +46,18 @@ use SP\Mvc\Controller\Validators\ValidatorInterface;
*
* @package SP\Domain\Account\Services
*/
-final class AccountPresetService implements AccountPresetServiceInterface
+final class AccountPresetService extends Service implements AccountPresetServiceInterface
{
public function __construct(
+ Application $application,
private ItemPresetServiceInterface $itemPresetService,
+ private AccountToUserGroupRepositoryInterface $accountToUserGroupRepository,
+ private AccountToUserRepositoryInterface $accountToUserRepository,
private ConfigDataInterface $configData,
private ValidatorInterface $validator
- ) {}
+ ) {
+ parent::__construct($application);
+ }
/**
* @throws ValidationException
@@ -55,25 +65,64 @@ final class AccountPresetService implements AccountPresetServiceInterface
* @throws NoSuchPropertyException
* @throws QueryException
*/
- public function checkPasswordPreset(AccountRequest $accountRequest): void
+ public function checkPasswordPreset(AccountDto $accountDto): AccountDto
{
$itemPreset = $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PASSWORD);
if ($itemPreset !== null && $itemPreset->getFixed() === 1) {
$passwordPreset = $itemPreset->hydrate(Password::class);
- $this->validator->validate($passwordPreset, $accountRequest->pass);
+ $this->validator->validate($passwordPreset, $accountDto->getPass());
if ($this->configData->isAccountExpireEnabled()) {
$expireTimePreset = $passwordPreset->getExpireTime();
if ($expireTimePreset > 0
- && ($accountRequest->passDateChange === 0
- || $accountRequest->passDateChange < time() + $expireTimePreset)
+ && ($accountDto->getPassDateChange() === 0
+ || $accountDto->getPassDateChange() < time() + $expireTimePreset)
) {
- $accountRequest->passDateChange = time() + $expireTimePreset;
+ return $accountDto->withPassDateChange(time() + $expireTimePreset);
}
}
}
+
+ return $accountDto;
+ }
+
+ /**
+ * @throws QueryException
+ * @throws ConstraintException
+ * @throws NoSuchPropertyException
+ */
+ public function addPresetPermissions(int $accountId): void
+ {
+ $itemPresetData =
+ $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PERMISSION);
+
+ if ($itemPresetData !== null && $itemPresetData->getFixed()) {
+ $userData = $this->context->getUserData();
+ $accountPermission = $itemPresetData->hydrate(AccountPermission::class);
+
+ $usersView = array_diff($accountPermission->getUsersView(), [$userData->getId()]);
+ $usersEdit = array_diff($accountPermission->getUsersEdit(), [$userData->getId()]);
+ $userGroupsView = array_diff($accountPermission->getUserGroupsView(), [$userData->getUserGroupId()]);
+ $userGroupsEdit = array_diff($accountPermission->getUserGroupsEdit(), [$userData->getUserGroupId()]);
+
+ if (count($usersView) > 0) {
+ $this->accountToUserRepository->addByType($accountId, $usersView);
+ }
+
+ if (count($usersEdit) > 0) {
+ $this->accountToUserRepository->addByType($accountId, $usersEdit, true);
+ }
+
+ if (count($userGroupsView) > 0) {
+ $this->accountToUserGroupRepository->addByType($accountId, $userGroupsView);
+ }
+
+ if (count($userGroupsEdit) > 0) {
+ $this->accountToUserGroupRepository->addByType($accountId, $userGroupsEdit, true);
+ }
+ }
}
}
diff --git a/lib/SP/Domain/Account/Services/AccountSearchItem.php b/lib/SP/Domain/Account/Services/AccountSearchItem.php
index 5049c2d4..3ea5dc2a 100644
--- a/lib/SP/Domain/Account/Services/AccountSearchItem.php
+++ b/lib/SP/Domain/Account/Services/AccountSearchItem.php
@@ -25,16 +25,14 @@
namespace SP\Domain\Account\Services;
use SP\Core\Bootstrap\BootstrapBase;
-use SP\DataModel\AccountSearchVData;
use SP\DataModel\ItemData;
+use SP\Domain\Account\Models\AccountSearchView;
use SP\Domain\Common\Dtos\ItemDataTrait;
use SP\Domain\Config\Ports\ConfigDataInterface;
use SP\Html\Html;
/**
* Class AccountSearchItem para contener los datos de cada cuenta en la búsqueda
- *
- * @package SP\Controller
*/
final class AccountSearchItem
{
@@ -51,7 +49,7 @@ final class AccountSearchItem
public static bool $isDemoMode = false;
public function __construct(
- protected AccountSearchVData $accountSearchVData,
+ protected AccountSearchView $accountSearchView,
private AccountAcl $accountAcl,
private ConfigDataInterface $configData,
private array $tags,
@@ -108,39 +106,39 @@ final class AccountSearchItem
public function getShortUrl(): string
{
- return Html::truncate($this->accountSearchVData->getUrl(), $this->textMaxLength);
+ return Html::truncate($this->accountSearchView->getUrl(), $this->textMaxLength);
}
public function isUrlIslink(): bool
{
- return preg_match('#^\w+://#', $this->accountSearchVData->getUrl()) === 1;
+ return preg_match('#^\w+://#', $this->accountSearchView->getUrl()) === 1;
}
public function getShortLogin(): string
{
- return Html::truncate($this->accountSearchVData->getLogin(), $this->textMaxLength);
+ return Html::truncate($this->accountSearchView->getLogin(), $this->textMaxLength);
}
public function getShortClientName(): string
{
- return Html::truncate($this->accountSearchVData->getClientName(), $this->textMaxLength / 3);
+ return Html::truncate($this->accountSearchView->getClientName(), $this->textMaxLength / 3);
}
public function getClientLink(): ?string
{
return self::$wikiEnabled
- ? $this->configData->getWikiSearchurl().$this->accountSearchVData->getClientName()
+ ? $this->configData->getWikiSearchurl().$this->accountSearchView->getClientName()
: null;
}
public function getPublicLink(): ?string
{
if (self::$publicLinkEnabled
- && $this->accountSearchVData->getPublicLinkHash() !== null
+ && $this->accountSearchView->getPublicLinkHash() !== null
) {
$baseUrl = ($this->configData->getApplicationUrl() ?: BootstrapBase::$WEBURI).BootstrapBase::$SUBURI;
- return PublicLinkService::getLinkForHash($baseUrl, $this->accountSearchVData->getPublicLinkHash());
+ return PublicLinkService::getLinkForHash($baseUrl, $this->accountSearchView->getPublicLinkHash());
}
return null;
@@ -169,12 +167,12 @@ final class AccountSearchItem
public function getAccesses(): array
{
$accesses = [
- '(G*) '.$this->accountSearchVData->getUserGroupName().'',
- '(U*) '.$this->accountSearchVData->getUserLogin().'',
+ '(G*) '.$this->accountSearchView->getUserGroupName().'',
+ '(U*) '.$this->accountSearchView->getUserLogin().'',
];
- $userLabel = $this->accountSearchVData->getOtherUserEdit() === 1 ? 'U+' : 'U';
- $userGroupLabel = $this->accountSearchVData->getOtherUserGroupEdit() === 1 ? 'G+' : 'G';
+ $userLabel = $this->accountSearchView->getOtherUserEdit() === 1 ? 'U+' : 'U';
+ $userGroupLabel = $this->accountSearchView->getOtherUserGroupEdit() === 1 ? 'G+' : 'G';
foreach ($this->userGroups ?? [] as $group) {
$accesses[] = sprintf(
@@ -198,7 +196,7 @@ final class AccountSearchItem
public function getNumFiles(): int
{
return $this->configData->isFilesEnabled()
- ? $this->accountSearchVData->getNumFiles()
+ ? $this->accountSearchView->getNumFiles()
: 0;
}
@@ -222,15 +220,15 @@ final class AccountSearchItem
return $this->accountAcl->isShowDelete();
}
- public function getAccountSearchVData(): AccountSearchVData
+ public function getAccountSearchView(): AccountSearchView
{
- return $this->accountSearchVData;
+ return $this->accountSearchView;
}
public function getShortNotes(): string
{
- if ($this->accountSearchVData->getNotes()) {
- return nl2br(htmlspecialchars(Html::truncate($this->accountSearchVData->getNotes(), 300), ENT_QUOTES));
+ if ($this->accountSearchView->getNotes()) {
+ return nl2br(htmlspecialchars(Html::truncate($this->accountSearchView->getNotes(), 300), ENT_QUOTES));
}
return '';
@@ -242,8 +240,8 @@ final class AccountSearchItem
public function isPasswordExpired(): bool
{
return $this->configData->isAccountExpireEnabled()
- && $this->accountSearchVData->getPassDateChange() > 0
- && time() > $this->accountSearchVData->getPassDateChange();
+ && $this->accountSearchView->getPassDateChange() > 0
+ && time() > $this->accountSearchView->getPassDateChange();
}
/**
@@ -256,6 +254,6 @@ final class AccountSearchItem
public function isWikiMatch(string $wikiFilter): bool
{
- return preg_match('/^'.$wikiFilter.'/i', $this->accountSearchVData->getName()) === 1;
+ return preg_match('/^'.$wikiFilter.'/i', $this->accountSearchView->getName()) === 1;
}
}
diff --git a/lib/SP/Domain/Account/Services/AccountService.php b/lib/SP/Domain/Account/Services/AccountService.php
index f2d67a46..fa1de5e2 100644
--- a/lib/SP/Domain/Account/Services/AccountService.php
+++ b/lib/SP/Domain/Account/Services/AccountService.php
@@ -29,36 +29,38 @@ use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\NoSuchPropertyException;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountExtData;
-use SP\DataModel\AccountHistoryData;
-use SP\DataModel\ItemPreset\AccountPermission;
use SP\DataModel\ItemPreset\AccountPrivate;
use SP\DataModel\ItemSearchData;
use SP\DataModel\ProfileData;
use SP\Domain\Account\Adapters\AccountData;
-use SP\Domain\Account\Adapters\AccountPassData;
-use SP\Domain\Account\Dtos\AccountBulkRequest;
+use SP\Domain\Account\Dtos\AccountCreateDto;
use SP\Domain\Account\Dtos\AccountEnrichedDto;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
-use SP\Domain\Account\Dtos\AccountRequest;
+use SP\Domain\Account\Dtos\AccountHistoryDto;
+use SP\Domain\Account\Dtos\AccountUpdateBulkDto;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
+use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\Account;
+use SP\Domain\Account\Models\AccountDataView;
use SP\Domain\Account\Ports\AccountCryptServiceInterface;
use SP\Domain\Account\Ports\AccountHistoryServiceInterface;
+use SP\Domain\Account\Ports\AccountItemsServiceInterface;
+use SP\Domain\Account\Ports\AccountPresetServiceInterface;
use SP\Domain\Account\Ports\AccountRepositoryInterface;
use SP\Domain\Account\Ports\AccountServiceInterface;
use SP\Domain\Account\Ports\AccountToTagRepositoryInterface;
use SP\Domain\Account\Ports\AccountToUserGroupRepositoryInterface;
use SP\Domain\Account\Ports\AccountToUserRepositoryInterface;
+use SP\Domain\Common\Models\Simple;
use SP\Domain\Common\Services\Service;
use SP\Domain\Common\Services\ServiceException;
-use SP\Domain\Common\Services\ServiceItemTrait;
use SP\Domain\Config\Ports\ConfigServiceInterface;
use SP\Domain\ItemPreset\Ports\ItemPresetInterface;
use SP\Domain\ItemPreset\Ports\ItemPresetServiceInterface;
+use SP\Domain\User\Services\UserLoginResponse;
use SP\Infrastructure\Common\Repositories\NoSuchItemException;
use SP\Infrastructure\Database\QueryResult;
use function SP\__u;
-use function SP\logger;
/**
* Class AccountService
@@ -67,8 +69,6 @@ use function SP\logger;
*/
final class AccountService extends Service implements AccountServiceInterface
{
- use ServiceItemTrait;
-
public function __construct(
Application $application,
private AccountRepositoryInterface $accountRepository,
@@ -77,6 +77,8 @@ final class AccountService extends Service implements AccountServiceInterface
private AccountToTagRepositoryInterface $accountToTagRepository,
private ItemPresetServiceInterface $itemPresetService,
private AccountHistoryServiceInterface $accountHistoryService,
+ private AccountItemsServiceInterface $accountItemsService,
+ private AccountPresetServiceInterface $accountPresetService,
private ConfigServiceInterface $configService,
private AccountCryptServiceInterface $accountCryptService
) {
@@ -84,45 +86,50 @@ final class AccountService extends Service implements AccountServiceInterface
}
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param \SP\Domain\Account\Dtos\AccountEnrichedDto $accountEnrichedDto
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function withUsersById(AccountEnrichedDto $accountDetailsResponse): AccountServiceInterface
+ public function withUsers(AccountEnrichedDto $accountEnrichedDto): AccountEnrichedDto
{
- $accountDetailsResponse->setUsers(
- $this->accountToUserRepository->getUsersByAccountId($accountDetailsResponse->getId())
- ->getDataAsArray()
+ return $accountEnrichedDto->withUsers(
+ $this->accountToUserRepository->getUsersByAccountId($accountEnrichedDto->getId())->getDataAsArray()
);
-
- return $this;
}
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param \SP\Domain\Account\Dtos\AccountEnrichedDto $accountEnrichedDto
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function withUserGroupsById(AccountEnrichedDto $accountDetailsResponse): AccountServiceInterface
+ public function withUserGroups(AccountEnrichedDto $accountEnrichedDto): AccountEnrichedDto
{
- $accountDetailsResponse->setUserGroups(
- $this->accountToUserGroupRepository->getUserGroupsByAccountId($accountDetailsResponse->getId())
+ return $accountEnrichedDto->withUserGroups(
+ $this->accountToUserGroupRepository
+ ->getUserGroupsByAccountId($accountEnrichedDto->getId())
->getDataAsArray()
);
-
- return $this;
}
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param \SP\Domain\Account\Dtos\AccountEnrichedDto $accountEnrichedDto
+ *
+ * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function withTagsById(AccountEnrichedDto $accountDetailsResponse): AccountServiceInterface
+ public function withTags(AccountEnrichedDto $accountEnrichedDto): AccountEnrichedDto
{
- $accountDetailsResponse->setTags(
- $this->accountToTagRepository->getTagsByAccountId($accountDetailsResponse->getId())
- ->getDataAsArray()
+ return $accountEnrichedDto->withTags(
+ $this->accountToTagRepository->getTagsByAccountId($accountEnrichedDto->getId())->getDataAsArray()
);
-
- return $this;
}
/**
@@ -131,7 +138,7 @@ final class AccountService extends Service implements AccountServiceInterface
*/
public function incrementViewCounter(int $id): bool
{
- return $this->accountRepository->incrementViewCounter($id);
+ return $this->accountRepository->incrementViewCounter($id)->getAffectedNumRows() === 1;
}
/**
@@ -140,15 +147,16 @@ final class AccountService extends Service implements AccountServiceInterface
*/
public function incrementDecryptCounter(int $id): bool
{
- return $this->accountRepository->incrementDecryptCounter($id);
+ return $this->accountRepository->incrementDecryptCounter($id)->getAffectedNumRows() === 1;
}
/**
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
* @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function getPasswordForId(int $id): AccountPassData
+ public function getPasswordForId(int $id): Account
{
$result = $this->accountRepository->getPasswordForId($id);
@@ -156,121 +164,78 @@ final class AccountService extends Service implements AccountServiceInterface
throw new NoSuchItemException(__u('Account not found'));
}
- return $result->getData();
- }
-
- /**
- * @param \SP\DataModel\AccountHistoryData $data
- *
- * @return int
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- 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
- * @throws ConstraintException
- * @throws NoSuchPropertyException
- */
- public function create(AccountRequest $accountRequest): int
- {
- $userData = $this->context->getUserData();
-
- $accountRequest->changePermissions = AccountAclService::getShowPermission(
- $userData,
- $this->context->getUserProfile()
- );
-
- if (empty($accountRequest->userGroupId)
- || !$accountRequest->changePermissions
- ) {
- $accountRequest->userGroupId = $userData->getUserGroupId();
- }
-
- if (empty($accountRequest->userId)
- || !$accountRequest->changePermissions
- ) {
- $accountRequest->userId = $userData->getId();
- }
-
- if (empty($accountRequest->key)) {
- $encryptedPassword = $this->accountCryptService->getPasswordEncrypted($accountRequest->pass);
-
- $accountRequest->pass = $encryptedPassword->getPass();
- $accountRequest->key = $encryptedPassword->getKey();
- }
-
- $this->setPresetPrivate($accountRequest);
-
- $accountRequest->id = $this->accountRepository->create($accountRequest);
-
- $this->addItems($accountRequest);
-
- $this->addPresetPermissions($accountRequest->id);
-
- return $accountRequest->id;
- }
-
- /**
- * @throws QueryException
- * @throws ConstraintException
- * @throws NoSuchPropertyException
- * @throws NoSuchItemException
- */
- private function setPresetPrivate(AccountRequest $accountRequest): void
- {
- $userData = $this->context->getUserData();
- $itemPreset = $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE);
-
- if ($itemPreset !== null
- && $itemPreset->getFixed()
- ) {
- $accountPrivate = $itemPreset->hydrate(AccountPrivate::class);
-
- $userId = $accountRequest->userId;
-
- if ($userId === null && $accountRequest->id > 0) {
- $userId = $this->getById($accountRequest->id)->getAccountVData()->getUserId();
- }
-
- if ($userData->getId() === $userId) {
- $accountRequest->isPrivate = (int)$accountPrivate->isPrivateUser();
- }
-
- if ($userData->getUserGroupId() === $accountRequest->userGroupId) {
- $accountRequest->isPrivateGroup = (int)$accountPrivate->isPrivateGroup();
- }
- }
+ return $result->getData(Account::class);
}
/**
* @param int $id
*
- * @return \SP\Domain\Account\Dtos\AccountEnrichedDto
+ * @return \SP\Domain\Account\Models\AccountDataView
+ * @throws \SP\Core\Exceptions\SPException
* @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
*/
- public function getById(int $id): AccountEnrichedDto
+ public function getByIdEnriched(int $id): AccountDataView
+ {
+ $result = $this->accountRepository->getByIdEnriched($id);
+
+ if ($result->getNumRows() === 0) {
+ throw new NoSuchItemException(__u('The account doesn\'t exist'));
+ }
+
+ return $result->getData(AccountDataView::class);
+ }
+
+ /**
+ * Update accounts in bulk mode
+ *
+ * @param \SP\Domain\Account\Dtos\AccountUpdateBulkDto $accountUpdateBulkDto
+ *
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function updateBulk(AccountUpdateBulkDto $accountUpdateBulkDto): void
+ {
+ $this->accountRepository->transactionAware(
+ function () use ($accountUpdateBulkDto) {
+ $userData = $this->context->getUserData();
+ $userProfile = $this->context->getUserProfile() ?? new ProfileData();
+
+ $userCanChangePermissions = AccountAclService::getShowPermission($userData, $userProfile);
+
+ foreach ($accountUpdateBulkDto->getAccountUpdateDto() as $accountId => $accountUpdateDto) {
+ if ($userCanChangePermissions) {
+ $account = $this->getById($accountId);
+
+ $changeOwner = $this->userCanChangeOwner($userData, $userProfile, $account);
+ $changeUserGroup = $this->userCanChangeGroup($userData, $userProfile, $account);
+ } else {
+ $changeOwner = false;
+ $changeUserGroup = false;
+ }
+
+ $this->addHistory($accountId);
+
+ $this->accountRepository->updateBulk(
+ $accountId,
+ Account::update($accountUpdateDto),
+ $changeOwner,
+ $changeUserGroup
+ );
+
+ $this->accountItemsService->updateItems($accountId, $userCanChangePermissions, $accountUpdateDto);
+ }
+ },
+ $this
+ );
+ }
+
+ /**
+ * @param int $id
+ *
+ * @return \SP\Domain\Account\Models\Account
+ * @throws \SP\Core\Exceptions\SPException
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ */
+ public function getById(int $id): Account
{
$result = $this->accountRepository->getById($id);
@@ -278,136 +243,39 @@ final class AccountService extends Service implements AccountServiceInterface
throw new NoSuchItemException(__u('The account doesn\'t exist'));
}
- return new AccountEnrichedDto($result->getData());
+ return $result->getData(Account::class);
}
/**
- * Adds external items to the account
- */
- private function addItems(AccountRequest $accountRequest): void
- {
- try {
- if ($accountRequest->changePermissions) {
- if (is_array($accountRequest->userGroupsView)
- && count($accountRequest->userGroupsView) !== 0
- ) {
- $this->accountToUserGroupRepository->addByType($accountRequest, false);
- }
-
- if (is_array($accountRequest->userGroupsEdit)
- && count($accountRequest->userGroupsEdit) !== 0
- ) {
- $this->accountToUserGroupRepository->addByType($accountRequest, true);
- }
-
- if (is_array($accountRequest->usersView)
- && count($accountRequest->usersView) !== 0
- ) {
- $this->accountToUserRepository->addByType($accountRequest, false);
- }
-
- if (is_array($accountRequest->usersEdit)
- && count($accountRequest->usersEdit) !== 0
- ) {
- $this->accountToUserRepository->addByType($accountRequest, true);
- }
- }
-
- if (is_array($accountRequest->tags)
- && count($accountRequest->tags) !== 0
- ) {
- $this->accountToTagRepository->add($accountRequest);
- }
- } catch (SPException $e) {
- logger($e->getMessage());
- }
- }
-
- /**
- * @throws QueryException
- * @throws ConstraintException
- * @throws NoSuchPropertyException
- */
- private function addPresetPermissions(int $accountId): void
- {
- $itemPresetData =
- $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PERMISSION);
-
- if ($itemPresetData !== null
- && $itemPresetData->getFixed()
- ) {
- $userData = $this->context->getUserData();
- $accountPermission = $itemPresetData->hydrate(AccountPermission::class);
-
- $usersView = array_diff($accountPermission->getUsersView(), [$userData->getId()]);
- $usersEdit = array_diff($accountPermission->getUsersEdit(), [$userData->getId()]);
- $userGroupsView = array_diff($accountPermission->getUserGroupsView(), [$userData->getUserGroupId()]);
- $userGroupsEdit = array_diff($accountPermission->getUserGroupsEdit(), [$userData->getUserGroupId()]);
-
- if (count($usersView) !== 0) {
- $this->accountToUserRepository->addByType($accountId, $usersView, false);
- }
-
- if (count($usersEdit) !== 0) {
- $this->accountToUserRepository->addByType($accountId, $usersEdit, true);
- }
-
- if (count($userGroupsView) !== 0) {
- $this->accountToUserGroupRepository->addByType($accountId, $userGroupsView, false);
- }
-
- if (count($userGroupsEdit) !== 0) {
- $this->accountToUserGroupRepository->addByType($accountId, $userGroupsEdit, true);
- }
- }
- }
-
- /**
- * Updates external items for the account
+ * @param \SP\Domain\User\Services\UserLoginResponse $userData
+ * @param \SP\DataModel\ProfileData $userProfile
+ * @param \SP\Domain\Account\Models\Account $account
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
- *
- * @throws \SP\Domain\Common\Services\ServiceException
+ * @return bool
*/
- public function update(AccountRequest $accountRequest): void
- {
- $this->accountRepository->transactionAware(
- function () use ($accountRequest) {
- $userData = $this->context->getUserData();
- $userProfile = $this->context->getUserProfile() ?? new ProfileData();
+ protected function userCanChangeOwner(
+ UserLoginResponse $userData,
+ ProfileData $userProfile,
+ Account $account
+ ): bool {
+ return $userData->getIsAdminApp() || $userData->getIsAdminAcc()
+ || ($userProfile->isAccPermission() && $userData->getId() === $account->getUserId());
+ }
- $accountRequest->changePermissions =
- AccountAclService::getShowPermission($userData, $userProfile);
-
- if ($accountRequest->changePermissions) {
- $account = $this->getById($accountRequest->id)->getAccountVData();
-
- $accountRequest->changeOwner = $accountRequest->userId > 0
- && ($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()));
- }
-
- $this->addHistory($accountRequest->id);
-
- $this->setPresetPrivate($accountRequest);
-
- $this->accountRepository->update($accountRequest);
-
- $this->updateItems($accountRequest);
-
- $this->addPresetPermissions($accountRequest->id);
- }
- );
+ /**
+ * @param \SP\Domain\User\Services\UserLoginResponse $userData
+ * @param \SP\DataModel\ProfileData $userProfile
+ * @param \SP\Domain\Account\Models\Account $account
+ *
+ * @return bool
+ */
+ protected function userCanChangeGroup(
+ UserLoginResponse $userData,
+ ProfileData $userProfile,
+ Account $account
+ ): bool {
+ return $this->userCanChangeOwner($userData, $userProfile, $account)
+ || ($userProfile->isAccPermission() && $userData->getUserGroupId() === $account->getUserGroupId());
}
/**
@@ -415,12 +283,13 @@ final class AccountService extends Service implements AccountServiceInterface
* @throws QueryException
* @throws ServiceException
* @throws ConstraintException
+ * @throws \SP\Core\Exceptions\SPException
*/
- private function addHistory(int $accountId, bool $isDelete = false): int
+ private function addHistory(int $accountId, bool $isDelete = false): void
{
- return $this->accountHistoryService->create(
+ $this->accountHistoryService->create(
new AccountHistoryCreateDto(
- $accountId,
+ $this->getById($accountId),
!$isDelete,
$isDelete,
$this->configService->getByParam('masterPwd')
@@ -429,177 +298,221 @@ final class AccountService extends Service implements AccountServiceInterface
}
/**
- * Updates external items for the account
+ * @param \SP\Domain\Account\Dtos\AccountCreateDto $accountCreateDto
*
- * @throws QueryException
- * @throws ConstraintException
+ * @return int
* @throws \SP\Domain\Common\Services\ServiceException
*/
- private function updateItems(AccountRequest $accountRequest): void
+ public function create(AccountCreateDto $accountCreateDto): int
{
- if ($accountRequest->changePermissions) {
- if ($accountRequest->userGroupsView !== null) {
- if (count($accountRequest->userGroupsView) > 0) {
- $this->accountToUserGroupRepository->transactionAware(
- function () use ($accountRequest) {
- $this->accountToUserGroupRepository
- ->deleteTypeByAccountId($accountRequest->id, false);
- $this->accountToUserGroupRepository
- ->addByType($accountRequest->id, $accountRequest->userGroupsView, false);
- }
- );
- } else {
- $this->accountToUserGroupRepository->deleteTypeByAccountId($accountRequest->id, false);
- }
- }
+ return $this->accountRepository->transactionAware(
+ function () use ($accountCreateDto) {
+ $userData = $this->context->getUserData();
- if ($accountRequest->userGroupsEdit !== null) {
- if (count($accountRequest->userGroupsEdit) > 0) {
- $this->accountToUserGroupRepository->transactionAware(
- function () use ($accountRequest) {
- $this->accountToUserGroupRepository
- ->deleteTypeByAccountId($accountRequest->id, true);
- $this->accountToUserGroupRepository
- ->addByType($accountRequest->id, $accountRequest->userGroupsEdit, true);
- }
- );
- } else {
- $this->accountToUserGroupRepository->deleteTypeByAccountId($accountRequest->id, true);
- }
- }
+ $userCanChangePermissions =
+ AccountAclService::getShowPermission($userData, $this->context->getUserProfile());
- if ($accountRequest->usersView !== null) {
- if (count($accountRequest->usersView) > 0) {
- $this->accountToUserRepository->transactionAware(
- function () use ($accountRequest) {
- $this->accountToUserRepository
- ->deleteTypeByAccountId($accountRequest->id, false);
- $this->accountToUserRepository
- ->addByType($accountRequest->id, $accountRequest->usersView, false);
- }
- );
- } else {
- $this->accountToUserRepository->deleteTypeByAccountId($accountRequest->id, false);
+ if (!$userCanChangePermissions) {
+ $accountCreateDto = AccountService::buildWithUserData($userData, $accountCreateDto);
}
- }
- if ($accountRequest->usersEdit !== null) {
- if (count($accountRequest->usersEdit) > 0) {
- $this->accountToUserRepository->transactionAware(
- function () use ($accountRequest) {
- $this->accountToUserRepository
- ->deleteTypeByAccountId($accountRequest->id, true);
- $this->accountToUserRepository
- ->addByType($accountRequest->id, $accountRequest->usersEdit, true);
- }
- );
- } else {
- $this->accountToUserRepository->deleteTypeByAccountId($accountRequest->id, true);
- }
- }
- }
-
- if ($accountRequest->tags !== null) {
- if (count($accountRequest->tags) > 0) {
- $this->accountToTagRepository->transactionAware(
- function () use ($accountRequest) {
- $this->accountToTagRepository->deleteByAccountId($accountRequest->id);
- $this->accountToTagRepository->add($accountRequest);
- }
+ $accountCreateDto = $accountCreateDto->withEncryptedPassword(
+ $this->accountCryptService->getPasswordEncrypted($accountCreateDto->getPass())
);
- } else {
- $this->accountToTagRepository->deleteByAccountId($accountRequest->id);
- }
- }
- }
- /**
- * Update accounts in bulk mode
- *
- * @param \SP\Domain\Account\Dtos\AccountBulkRequest $request
- *
- * @throws \SP\Domain\Common\Services\ServiceException
- */
- public function updateBulk(AccountBulkRequest $request): void
- {
- $this->accountRepository->transactionAware(
- function () use ($request) {
- foreach ($request->getItemsId() as $itemId) {
- $accountRequest = $request->getAccountRequestForId($itemId);
+ $accountCreateDto = $this->setPresetPrivate($accountCreateDto);
- $this->addHistory($accountRequest->id);
+ $accountId = $this->accountRepository->create(Account::create($accountCreateDto))->getLastId();
- $this->accountRepository->updateBulk($accountRequest);
+ $this->accountItemsService->addItems($userCanChangePermissions, $accountId, $accountCreateDto);
- $this->updateItems($accountRequest);
- }
- }
+ $this->accountPresetService->addPresetPermissions($accountId);
+
+ return $accountId;
+ },
+ $this
);
}
/**
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
+ * @param \SP\Domain\User\Services\UserLoginResponse $userData
+ * @param \SP\Domain\Account\Dtos\AccountCreateDto $accountCreateDto
+ *
+ * @return \SP\Domain\Account\Dtos\AccountCreateDto
+ */
+ private static function buildWithUserData(
+ UserLoginResponse $userData,
+ AccountCreateDto $accountCreateDto
+ ): AccountCreateDto {
+ return $accountCreateDto->withUserGroupId($userData->getUserGroupId())->withUserId($userData->getId());
+ }
+
+ /**
+ * @throws QueryException
+ * @throws ConstraintException
+ * @throws NoSuchPropertyException
+ * @throws NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ private function setPresetPrivate(
+ AccountCreateDto|AccountUpdateDto $accountDto,
+ ?int $accountId = null
+ ): AccountCreateDto|AccountUpdateDto {
+ $userData = $this->context->getUserData();
+ $itemPreset = $this->itemPresetService->getForCurrentUser(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE);
+
+ if ($itemPreset !== null && $itemPreset->getFixed()) {
+ $accountPrivate = $itemPreset->hydrate(AccountPrivate::class);
+
+ if ($accountDto instanceof AccountUpdateDto && null !== $accountId) {
+ $account = $this->getById($accountId);
+ $accountDto =
+ $accountDto->withUserId($account->getUserId())->withUserGroupId($account->getUserGroupId());
+ }
+
+ $privateUser = $userData->getId() === $accountDto->getUserId()
+ && $accountPrivate->isPrivateUser();
+ $privateGroup = $userData->getUserGroupId() === $accountDto->getUserGroupId()
+ && $accountPrivate->isPrivateGroup();
+
+ return $accountDto->withPrivate($privateUser)->withPrivateGroup($privateGroup);
+ }
+
+ return $accountDto;
+ }
+
+ /**
+ * Updates external items for the account
+ *
+ * @param int $id
+ * @param \SP\Domain\Account\Dtos\AccountUpdateDto $accountUpdateDto
*
* @throws \SP\Domain\Common\Services\ServiceException
*/
- public function editPassword(AccountRequest $accountRequest): void
+ public function update(int $id, AccountUpdateDto $accountUpdateDto): void
{
$this->accountRepository->transactionAware(
- function () use ($accountRequest) {
- $this->addHistory($accountRequest->id);
+ function () use ($id, $accountUpdateDto) {
+ $userData = $this->context->getUserData();
+ $userProfile = $this->context->getUserProfile() ?? new ProfileData();
- $pass = $this->getPasswordEncrypted($accountRequest->pass);
+ $userCanChangePermissions = AccountAclService::getShowPermission($userData, $userProfile);
- $accountRequest->pass = $pass['pass'];
- $accountRequest->key = $pass['key'];
+ if ($userCanChangePermissions) {
+ $account = $this->getById($id);
- $this->accountRepository->editPassword($accountRequest);
- }
+ $changeOwner = $this->userCanChangeOwner($userData, $userProfile, $account);
+ $changeUserGroup = $this->userCanChangeGroup($userData, $userProfile, $account);
+ } else {
+ $changeOwner = false;
+ $changeUserGroup = false;
+ }
+
+ $this->addHistory($id);
+
+ $accountUpdateDto = $this->setPresetPrivate($accountUpdateDto, $id);
+
+ $this->accountRepository->update(
+ $id,
+ Account::update($accountUpdateDto),
+ $changeOwner,
+ $changeUserGroup
+ );
+
+ $this->accountItemsService->updateItems($userCanChangePermissions, $id, $accountUpdateDto);
+
+ $this->accountPresetService->addPresetPermissions($id);
+ },
+ $this
+ );
+ }
+
+ /**
+ * @param int $id
+ * @param \SP\Domain\Account\Dtos\AccountUpdateDto $accountUpdateDto
+ *
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function editPassword(int $id, AccountUpdateDto $accountUpdateDto): void
+ {
+ $this->accountRepository->transactionAware(
+ function () use ($id, $accountUpdateDto) {
+ $this->addHistory($id);
+
+ $encryptedPassword = $this->accountCryptService->getPasswordEncrypted($accountUpdateDto->getPass());
+
+ $this->accountRepository->editPassword(
+ $id,
+ Account::updatePassword($accountUpdateDto->withEncryptedPassword($encryptedPassword))
+ );
+ },
+ $this
);
}
/**
* Updates an already encrypted password data from a master password changing action
*
- * @param \SP\Domain\Account\Dtos\AccountPasswordRequest $accountRequest
+ * @param int $id
+ * @param \SP\Domain\Account\Dtos\EncryptedPassword $encryptedPassword
*
* @return void
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
* @throws \SP\Domain\Common\Services\ServiceException
*/
- public function updatePasswordMasterPass(AccountPasswordRequest $accountRequest): void
+ public function updatePasswordMasterPass(int $id, EncryptedPassword $encryptedPassword): void
{
- if (!$this->accountRepository->updatePassword($accountRequest)) {
+ $result = $this->accountRepository->updatePassword($id, $encryptedPassword);
+
+ if ($result->getAffectedNumRows() === 0) {
throw new ServiceException(__u('Error while updating the password'));
}
}
/**
- * @param int $historyId
- * @param int $accountId
+ * @param \SP\Domain\Account\Dtos\AccountHistoryDto $accountHistoryDto
*
* @throws \SP\Domain\Common\Services\ServiceException
- * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
*/
- public function editRestore(int $historyId, int $accountId): void
+ public function restoreModified(AccountHistoryDto $accountHistoryDto): void
{
- $accountHistoryData = $this->accountHistoryService->getById($historyId);
-
$this->accountRepository->transactionAware(
- function () use ($historyId, $accountId, $accountHistoryData) {
- $this->addHistory($accountId);
+ function () use ($accountHistoryDto) {
+ $this->addHistory($accountHistoryDto->getAccountId());
- if (!$this->accountRepository->editRestore(
- $accountHistoryData,
- $this->context->getUserData()->getId()
- )) {
+ $result = $this->accountRepository->restoreModified(
+ $accountHistoryDto->getAccountId(),
+ Account::restoreModified($accountHistoryDto, $this->context->getUserData()->getId())
+ );
+
+ if ($result->getAffectedNumRows() === 0) {
throw new ServiceException(__u('Error on restoring the account'));
}
- }
+ },
+ $this
);
}
+ /**
+ * @param \SP\Domain\Account\Dtos\AccountHistoryDto $accountHistoryDto
+ *
+ * @return void
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function restoreRemoved(AccountHistoryDto $accountHistoryDto): void
+ {
+ $result = $this->accountRepository->createRemoved(
+ Account::restoreRemoved($accountHistoryDto, $this->context->getUserData()->getId())
+ );
+
+ if ($result->getAffectedNumRows() === 0) {
+ throw new ServiceException(__u('Error on restoring the account'));
+ }
+ }
+
/**
* @throws \SP\Domain\Common\Services\ServiceException
*/
@@ -609,10 +522,11 @@ final class AccountService extends Service implements AccountServiceInterface
function () use ($id) {
$this->addHistory($id, 1);
- if ($this->accountRepository->delete($id)) {
+ if ($this->accountRepository->delete($id)->getAffectedNumRows() === 0) {
throw new NoSuchItemException(__u('Account not found'));
}
- }
+ },
+ $this
);
return $this;
@@ -624,39 +538,46 @@ final class AccountService extends Service implements AccountServiceInterface
* @throws SPException
* @throws ServiceException
*/
- public function deleteByIdBatch(array $ids): AccountServiceInterface
+ public function deleteByIdBatch(array $ids): void
{
- if ($this->accountRepository->deleteByIdBatch($ids) === 0) {
+ if ($this->accountRepository->deleteByIdBatch($ids)->getAffectedNumRows() === 0) {
throw new ServiceException(__u('Error while deleting the accounts'));
}
-
- return $this;
}
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param int|null $id
+ *
+ * @return array
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function getForUser(?int $accountId = null): array
+ public function getForUser(?int $id = null): array
{
- return $this->accountRepository->getForUser($accountId)->getDataAsArray();
+ return $this->accountRepository->getForUser($id)->getDataAsArray();
}
/**
- * @throws QueryException
- * @throws ConstraintException
+ * @param int $id
+ *
+ * @return array
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function getLinked(int $accountId): array
+ public function getLinked(int $id): array
{
- return $this->accountRepository->getLinked($accountId)->getDataAsArray();
+ return $this->accountRepository->getLinked($id)->getDataAsArray();
}
/**
* @throws QueryException
* @throws ConstraintException
* @throws NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function getPasswordHistoryForId(int $id): AccountPassData
+ public function getPasswordHistoryForId(int $id): Simple
{
$result = $this->accountRepository->getPasswordHistoryForId($id);
@@ -664,11 +585,12 @@ final class AccountService extends Service implements AccountServiceInterface
throw new NoSuchItemException(__u('The account doesn\'t exist'));
}
- return $result->getData();
+ return $result->getData(Simple::class);
}
/**
* @return AccountData[]
+ * @throws \SP\Core\Exceptions\SPException
*/
public function getAllBasic(): array
{
@@ -690,10 +612,13 @@ final class AccountService extends Service implements AccountServiceInterface
*
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
*/
public function getTotalNumAccounts(): int
{
- return (int)$this->accountRepository->getTotalNumAccounts()->num;
+ $data = $this->accountRepository->getTotalNumAccounts()->getData(Simple::class);
+
+ return (int)$data->num;
}
/**
@@ -702,8 +627,9 @@ final class AccountService extends Service implements AccountServiceInterface
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
* @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function getDataForLink(int $id): AccountExtData
+ public function getDataForLink(int $id): Simple
{
$result = $this->accountRepository->getDataForLink($id);
@@ -711,17 +637,19 @@ final class AccountService extends Service implements AccountServiceInterface
throw new NoSuchItemException(__u('The account doesn\'t exist'));
}
- return $result->getData();
+ return $result->getData(Simple::class);
}
/**
* Obtener los datos relativos a la clave de todas las cuentas.
*
- * @throws QueryException
- * @throws ConstraintException
+ * @return \SP\Domain\Common\Models\Simple[]
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
*/
public function getAccountsPassData(): array
{
- return $this->accountRepository->getAccountsPassData()->getDataAsArray();
+ return $this->accountRepository->getAccountsPassData()->getDataAsArray(Simple::class);
}
}
diff --git a/lib/SP/Domain/Common/Adapters/DataModel.php b/lib/SP/Domain/Common/Adapters/DataModel.php
deleted file mode 100644
index a986020e..00000000
--- a/lib/SP/Domain/Common/Adapters/DataModel.php
+++ /dev/null
@@ -1,101 +0,0 @@
-.
- */
-
-namespace SP\Domain\Common\Adapters;
-
-use JsonSerializable;
-
-/**
- * Class DataModel
- */
-abstract class DataModel implements JsonSerializable
-{
- private array $properties;
-
- public function __construct(?array $properties = [])
- {
- $this->assignProperties($properties);
- }
-
- private function assignProperties(array $properties): void
- {
- foreach ($properties as $property => $value) {
- $this->{$property} = $value;
- }
- }
-
- final public static function buildFromSimpleModel(SimpleModel $model): static
- {
- return new static($model->toArray());
- }
-
- final public function toArray(): array
- {
- if (count($this->properties) !== 0) {
- return $this->properties;
- }
-
- return get_object_vars($this);
- }
-
- final public function __get(string $name): mixed
- {
- if (property_exists($this, $name)) {
- return $this->{$name};
- }
-
- return $this->properties[$name] ?? null;
- }
-
- final public function __set(string $name, mixed $value = null): void
- {
- if (is_numeric($value)) {
- $value = (int)$value;
- }
-
- if (property_exists($this, $name)) {
- $this->{$name} = $value;
- } else {
- $this->properties[$name] = $value;
- }
- }
-
- final public function __isset(string $name): bool
- {
- return property_exists($this, $name) || isset($this->properties[$name]);
- }
-
- /**
- * Specify data which should be serialized to JSON
- *
- * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
- * @return array data which can be serialized by json_encode,
- * which is a value of any type other than a resource.
- * @since 5.4.0
- */
- public function jsonSerialize(): array
- {
- return $this->toArray();
- }
-}
diff --git a/lib/SP/Domain/Common/Dtos/Dto.php b/lib/SP/Domain/Common/Dtos/Dto.php
new file mode 100644
index 00000000..a5c7b25a
--- /dev/null
+++ b/lib/SP/Domain/Common/Dtos/Dto.php
@@ -0,0 +1,69 @@
+.
+ */
+
+namespace SP\Domain\Common\Dtos;
+
+/**
+ * Class Dto
+ */
+abstract class Dto
+{
+ protected array $reservedProperties = [];
+
+ /**
+ * Expose any property. This allows to get any property from dynamic calls.
+ *
+ * @param string $property
+ *
+ * @return mixed
+ */
+ public function get(string $property): mixed
+ {
+ if (property_exists($this, $property) && !in_array($property, $this->reservedProperties)) {
+ return $this->{$property};
+ }
+
+ return null;
+ }
+
+ /**
+ * Set any property. This allows to set any property from dynamic calls.
+ *
+ * @param string $property
+ * @param mixed $value
+ *
+ * @return \SP\Domain\Common\Dtos\Dto|null Returns a new instance with the property set.
+ */
+ public function set(string $property, mixed $value): static|null
+ {
+ if (property_exists($this, $property) && !in_array($property, $this->reservedProperties)) {
+ $self = clone $this;
+ $self->{$property} = $value;
+
+ return $self;
+ }
+
+ return null;
+ }
+}
diff --git a/lib/SP/Domain/Common/Models/Model.php b/lib/SP/Domain/Common/Models/Model.php
new file mode 100644
index 00000000..7fe888eb
--- /dev/null
+++ b/lib/SP/Domain/Common/Models/Model.php
@@ -0,0 +1,198 @@
+.
+ */
+
+namespace SP\Domain\Common\Models;
+
+use JsonSerializable;
+
+/**
+ * Class DataModel
+ */
+abstract class Model implements JsonSerializable
+{
+ private ?array $fields = null;
+ /**
+ * Dynamically declared properties must not be class' properties
+ */
+ private array $properties = [];
+
+ public function __construct(?array $properties = [])
+ {
+ $this->assignProperties($properties);
+ }
+
+ private function assignProperties(array $properties): void
+ {
+ $selfProperties = array_intersect_key($properties, $this->getClassProperties());
+
+ foreach ($selfProperties as $property => $value) {
+ $this->{$property} = $value;
+ }
+
+ $this->properties = array_diff_key($properties, $selfProperties);
+ }
+
+ /**
+ * @return array
+ */
+ private function getClassProperties(): array
+ {
+ return array_filter(
+ get_object_vars($this),
+ fn($key) => $key !== 'properties' && $key !== 'fields',
+ ARRAY_FILTER_USE_KEY
+ );
+ }
+
+ /**
+ * Build a new concrete object from a simple model
+ *
+ * @param \SP\Domain\Common\Models\Simple $model
+ *
+ * @return static
+ */
+ final public static function buildFromSimpleModel(Simple $model): static
+ {
+ return new static($model->toArray(null, null, true));
+ }
+
+ /**
+ * @param array|null $only Include only these properties
+ * @param array|null $filter Filter out these properties
+ * @param bool $includeOuter
+ *
+ * @return array
+ */
+ final public function toArray(?array $only = null, ?array $filter = null, bool $includeOuter = false): array
+ {
+ $fields = $this->getClassProperties();
+
+ if ($includeOuter) {
+ $fields = array_merge($fields, $this->properties);
+ }
+
+ if (null !== $only) {
+ $fields = array_intersect_key($fields, array_flip($only));
+ }
+
+ if (null !== $filter) {
+ $fields = array_diff_key($fields, array_flip($filter));
+ }
+
+ $this->fields = array_keys($fields);
+
+ return $fields;
+ }
+
+ /**
+ * Get columns name for this model
+ *
+ * @param array|null $filter
+ *
+ * @return array
+ */
+ final public static function getCols(?array $filter = null): array
+ {
+ $self = new static();
+
+ return array_keys($self->toArray(null, $filter, false));
+ }
+
+ /**
+ * Create a new object with properties changed
+ *
+ * @param array $properties
+ *
+ * @return $this
+ */
+ final public function mutate(array $properties): static
+ {
+ return new static(array_merge($this->toArray(), $properties));
+ }
+
+ /**
+ * Convert the model to its string representation.
+ *
+ * @return string
+ * @throws \JsonException
+ */
+ public function __toString()
+ {
+ return $this->toJson();
+ }
+
+ /**
+ * Convert the model instance to JSON.
+ *
+ * @param int $options
+ *
+ * @return string
+ * @throws \JsonException
+ */
+ public function toJson(int $options = 0): string
+ {
+ return json_encode($this->jsonSerialize(), $options & JSON_THROW_ON_ERROR);
+ }
+
+ /**
+ * Specify data which should be serialized to JSON
+ *
+ * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
+ * @return array data which can be serialized by json_encode,
+ * which is a value of any type other than a resource.
+ * @since 5.4.0
+ */
+ public function jsonSerialize(): array
+ {
+ return $this->toArray();
+ }
+
+ public function getFields(): ?array
+ {
+ return $this->fields;
+ }
+
+ /**
+ * @param string $name
+ *
+ * @return void
+ */
+ public function __get(string $name)
+ {
+ if (array_key_exists($name, $this->properties)) {
+ return $this->properties[$name];
+ }
+ }
+
+ /**
+ * @param string $name
+ * @param $value
+ *
+ * @return void
+ */
+ public function __set(string $name, $value): void
+ {
+ $this->properties[$name] = $value;
+ }
+}
diff --git a/lib/SP/DataModel/SerializedModel.php b/lib/SP/Domain/Common/Models/SerializedModel.php
similarity index 97%
rename from lib/SP/DataModel/SerializedModel.php
rename to lib/SP/Domain/Common/Models/SerializedModel.php
index b3e81b75..0b5c60a8 100644
--- a/lib/SP/DataModel/SerializedModel.php
+++ b/lib/SP/Domain/Common/Models/SerializedModel.php
@@ -22,7 +22,7 @@
* along with sysPass. If not, see .
*/
-namespace SP\DataModel;
+namespace SP\Domain\Common\Models;
use SP\Core\Exceptions\NoSuchPropertyException;
use SP\Util\Util;
diff --git a/lib/SP/Domain/Common/Adapters/SimpleModel.php b/lib/SP/Domain/Common/Models/Simple.php
similarity index 82%
rename from lib/SP/Domain/Common/Adapters/SimpleModel.php
rename to lib/SP/Domain/Common/Models/Simple.php
index 23f7396e..d26f8919 100644
--- a/lib/SP/Domain/Common/Adapters/SimpleModel.php
+++ b/lib/SP/Domain/Common/Models/Simple.php
@@ -22,16 +22,15 @@
* along with sysPass. If not, see .
*/
-namespace SP\Domain\Common\Adapters;
+namespace SP\Domain\Common\Models;
/**
- * Class SimpleModel
+ * Class Simple
*
- * This model does not contain any properties, they will be set on $properties property.
+ * This model does not contain any properties.
*
* It's intended to be used when returned non-well defined objects from the repository.
*/
-final class SimpleModel extends DataModel
+final class Simple extends Model
{
-
}
diff --git a/lib/SP/Domain/Common/Ports/RepositoryInterface.php b/lib/SP/Domain/Common/Ports/RepositoryInterface.php
index 07fc3451..ce3553e9 100644
--- a/lib/SP/Domain/Common/Ports/RepositoryInterface.php
+++ b/lib/SP/Domain/Common/Ports/RepositoryInterface.php
@@ -29,7 +29,7 @@ use Closure;
/**
* Interface RepositoryItemInterface
*
- * @package SP\Domain\Common\In
+ * @package SP\Domain\Common\Ports
*/
interface RepositoryInterface
{
@@ -37,10 +37,11 @@ interface RepositoryInterface
* Bubbles a Closure in a database transaction
*
* @param \Closure $closure
+ * @param object $newThis
*
* @return mixed
* @throws \SP\Domain\Common\Services\ServiceException
* @throws \Exception
*/
- public function transactionAware(Closure $closure): mixed;
+ public function transactionAware(Closure $closure, object $newThis): mixed;
}
diff --git a/lib/SP/Domain/ItemPreset/Ports/ItemPresetServiceInterface.php b/lib/SP/Domain/ItemPreset/Ports/ItemPresetServiceInterface.php
index 40c3b3b9..11dfd189 100644
--- a/lib/SP/Domain/ItemPreset/Ports/ItemPresetServiceInterface.php
+++ b/lib/SP/Domain/ItemPreset/Ports/ItemPresetServiceInterface.php
@@ -26,8 +26,8 @@ namespace SP\Domain\ItemPreset\Ports;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
-use SP\DataModel\ItemPresetData;
use SP\DataModel\ItemSearchData;
+use SP\Domain\Account\Models\ItemPreset;
use SP\Domain\ItemPreset\Services\ItemPresetRequest;
use SP\Domain\ItemPreset\Services\ItemPresetService;
use SP\Infrastructure\Common\Repositories\NoSuchItemException;
@@ -68,12 +68,12 @@ interface ItemPresetServiceInterface
* @throws ConstraintException
* @throws QueryException
*/
- public function getById(int $id): ItemPresetData;
+ public function getById(int $id): ItemPreset;
/**
* Returns all the items
*
- * @return ItemPresetData[]
+ * @return ItemPreset[]
* @throws ConstraintException
* @throws QueryException
*/
@@ -91,13 +91,13 @@ interface ItemPresetServiceInterface
* @throws ConstraintException
* @throws QueryException
*/
- public function getForCurrentUser(string $type): ?ItemPresetData;
+ public function getForCurrentUser(string $type): ?ItemPreset;
/**
* @throws ConstraintException
* @throws QueryException
*/
- public function getForUser(string $type, int $userId, int $userGroupId, int $userProfileId): ?ItemPresetData;
+ public function getForUser(string $type, int $userId, int $userGroupId, int $userProfileId): ?ItemPreset;
/**
* @param int[] $ids
diff --git a/lib/SP/Domain/ItemPreset/Services/ItemPresetRequest.php b/lib/SP/Domain/ItemPreset/Services/ItemPresetRequest.php
index 5bcd091a..ddf0de2f 100644
--- a/lib/SP/Domain/ItemPreset/Services/ItemPresetRequest.php
+++ b/lib/SP/Domain/ItemPreset/Services/ItemPresetRequest.php
@@ -24,7 +24,7 @@
namespace SP\Domain\ItemPreset\Services;
-use SP\DataModel\ItemPresetData;
+use SP\Domain\Account\Models\ItemPreset;
/**
* Class ItemPresetRequest
@@ -33,19 +33,19 @@ use SP\DataModel\ItemPresetData;
*/
final class ItemPresetRequest
{
- private ItemPresetData $itemPresetData;
- private $data;
+ private ItemPreset $itemPresetData;
+ private $data;
/**
* ItemPresetRequest constructor.
*/
- public function __construct(ItemPresetData $itemPresetData, $data)
+ public function __construct(ItemPreset $itemPresetData, $data)
{
$this->itemPresetData = $itemPresetData;
$this->data = $data;
}
- public function getItemPresetData(): ItemPresetData
+ public function getItemPresetData(): ItemPreset
{
return $this->itemPresetData;
}
@@ -58,10 +58,10 @@ final class ItemPresetRequest
return $this->data;
}
- public function prepareToPersist(): ItemPresetData
+ public function prepareToPersist(): ItemPreset
{
$this->itemPresetData->setData(serialize($this->data));
return $this->itemPresetData;
}
-}
\ No newline at end of file
+}
diff --git a/lib/SP/Domain/ItemPreset/Services/ItemPresetService.php b/lib/SP/Domain/ItemPreset/Services/ItemPresetService.php
index d988f965..83fee36e 100644
--- a/lib/SP/Domain/ItemPreset/Services/ItemPresetService.php
+++ b/lib/SP/Domain/ItemPreset/Services/ItemPresetService.php
@@ -28,8 +28,8 @@ 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\Domain\Account\Models\ItemPreset;
use SP\Domain\Common\Services\Service;
use SP\Domain\Common\Services\ServiceException;
use SP\Domain\ItemPreset\Ports\ItemPresetRepositoryInterface;
@@ -95,7 +95,7 @@ final class ItemPresetService extends Service implements ItemPresetServiceInterf
* @throws ConstraintException
* @throws QueryException
*/
- public function getById(int $id): ItemPresetData
+ public function getById(int $id): ItemPreset
{
$result = $this->itemPresetRepository->getById($id);
@@ -109,7 +109,7 @@ final class ItemPresetService extends Service implements ItemPresetServiceInterf
/**
* Returns all the items
*
- * @return ItemPresetData[]
+ * @return \SP\Domain\Account\Models\ItemPreset[]
* @throws ConstraintException
* @throws QueryException
*/
@@ -133,7 +133,7 @@ final class ItemPresetService extends Service implements ItemPresetServiceInterf
* @throws ConstraintException
* @throws QueryException
*/
- public function getForCurrentUser(string $type): ?ItemPresetData
+ public function getForCurrentUser(string $type): ?ItemPreset
{
$userData = $this->context->getUserData();
@@ -154,7 +154,7 @@ final class ItemPresetService extends Service implements ItemPresetServiceInterf
int $userId,
int $userGroupId,
int $userProfileId
- ): ?ItemPresetData {
+ ): ?ItemPreset {
$result = $this->itemPresetRepository->getByFilter(
$type,
$userId,
diff --git a/lib/SP/Infrastructure/Account/Repositories/AccountHistoryRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountHistoryRepository.php
index b84d2244..ada90cbc 100644
--- a/lib/SP/Infrastructure/Account/Repositories/AccountHistoryRepository.php
+++ b/lib/SP/Infrastructure/Account/Repositories/AccountHistoryRepository.php
@@ -28,7 +28,7 @@ use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
use SP\DataModel\ItemSearchData;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
+use SP\Domain\Account\Dtos\EncryptedPassword;
use SP\Domain\Account\Ports\AccountHistoryRepositoryInterface;
use SP\Infrastructure\Common\Repositories\Repository;
use SP\Infrastructure\Common\Repositories\RepositoryItemTrait;
@@ -84,7 +84,7 @@ final class AccountHistoryRepository extends Repository implements AccountHistor
*/
public function create(AccountHistoryCreateDto $dto): int
{
- $accountData = $dto->getAccountData();
+ $accountData = $dto->getAccount();
$query = $this->queryFactory
->newInsert()
@@ -382,24 +382,25 @@ final class AccountHistoryRepository extends Repository implements AccountHistor
/**
* Actualiza la clave de una cuenta en la BBDD.
*
- * @param \SP\Domain\Account\Dtos\AccountPasswordRequest $request
+ * @param int $accountId
+ * @param \SP\Domain\Account\Dtos\EncryptedPassword $encryptedPassword
*
* @return bool
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function updatePassword(AccountPasswordRequest $request): bool
+ public function updatePassword(int $accountId, EncryptedPassword $encryptedPassword): bool
{
$query = $this->queryFactory
->newUpdate()
->table('AccountHistory')
->cols([
- 'pass' => $request->getEncryptedPassword()->getPass(),
- 'key' => $request->getEncryptedPassword()->getKey(),
- 'mPassHash' => $request->getHash(),
+ 'pass' => $encryptedPassword->getPass(),
+ 'key' => $encryptedPassword->getKey(),
+ 'mPassHash' => $encryptedPassword->getHash(),
])
->where('id = :id')
- ->bindValues(['id' => $request->getId()]);
+ ->bindValues(['id' => $accountId]);
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while updating the password'));
diff --git a/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php
index 2f2bba68..a7008094 100644
--- a/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php
+++ b/lib/SP/Infrastructure/Account/Repositories/AccountRepository.php
@@ -29,21 +29,19 @@ use SP\Core\Context\ContextInterface;
use SP\Core\Events\EventDispatcherInterface;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
-use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountHistoryData;
use SP\DataModel\ItemSearchData;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
-use SP\Domain\Account\Dtos\AccountRequest;
+use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\Account;
+use SP\Domain\Account\Models\AccountDataView;
+use SP\Domain\Account\Models\AccountSearchView;
use SP\Domain\Account\Ports\AccountFilterUserInterface;
use SP\Domain\Account\Ports\AccountRepositoryInterface;
-use SP\Domain\Common\Adapters\SimpleModel;
use SP\Infrastructure\Common\Repositories\Repository;
use SP\Infrastructure\Common\Repositories\RepositoryItemTrait;
use SP\Infrastructure\Database\DatabaseInterface;
use SP\Infrastructure\Database\QueryData;
use SP\Infrastructure\Database\QueryResult;
use function SP\__u;
-use function SP\logger;
/**
* Class AccountRepository
@@ -54,39 +52,35 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
{
use RepositoryItemTrait;
- private AccountFilterUserInterface $accountFilterUser;
-
public function __construct(
DatabaseInterface $database,
ContextInterface $session,
QueryFactory $queryFactory,
EventDispatcherInterface $eventDispatcher,
- AccountFilterUserInterface $accountFilterUser
+ private AccountFilterUserInterface $accountFilterUser
) {
parent::__construct($database, $session, $eventDispatcher, $queryFactory);
-
- $this->accountFilterUser = $accountFilterUser;
}
/**
* Devolver el número total de cuentas
*/
- public function getTotalNumAccounts(): SimpleModel
+ public function getTotalNumAccounts(): QueryResult
{
$query = $this->queryFactory
->newSelect()
->cols(['SUM(n) AS num'])
->fromSubSelect('SELECT COUNT(*) AS n FROM Account UNION SELECT COUNT(*) AS n FROM AccountHistory', 'a');
- return $this->db->doSelect(QueryData::build($query))->getData();
+ return $this->db->doSelect(QueryData::build($query));
}
/**
- * @param int $id
+ * @param int $accountId
*
* @return QueryResult
*/
- public function getPasswordForId(int $id): QueryResult
+ public function getPasswordForId(int $accountId): QueryResult
{
$query = $this->accountFilterUser
->buildFilter()
@@ -99,18 +93,18 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
'Account.parentId',
])
->where('Account.id = :id')
- ->bindValues(['id' => $id])
+ ->bindValues(['id' => $accountId])
->limit(1);
- return $this->db->doSelect(QueryData::build($query));
+ return $this->db->doSelect(QueryData::build($query)->setMapClassName(Account::class));
}
/**
- * @param int $id
+ * @param int $accountId
*
* @return QueryResult
*/
- public function getPasswordHistoryForId(int $id): QueryResult
+ public function getPasswordHistoryForId(int $accountId): QueryResult
{
$query = $this->accountFilterUser
->buildFilterHistory()
@@ -123,8 +117,8 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
'AccountHistory.parentId',
'AccountHistory.mPassHash',
])
- ->where('AccountHistory.id = :id')
- ->bindValues(['id' => $id]);
+ ->where('AccountHistory.accountId = :accountId')
+ ->bindValues(['accountId' => $accountId]);
return $this->db->doSelect(QueryData::build($query));
}
@@ -132,317 +126,318 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
/**
* Incrementa el contador de vista de clave de una cuenta en la BBDD
*
- * @param int $id
+ * @param int $accountId
*
- * @return bool
- * @throws ConstraintException
- * @throws QueryException
+ * @return \SP\Infrastructure\Database\QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
*/
- public function incrementDecryptCounter(int $id): bool
+ public function incrementDecryptCounter(int $accountId): QueryResult
{
$query = $this->queryFactory
->newUpdate()
->table('Account')
->set('countDecrypt', '(countDecrypt + 1)')
->where('id = :id')
- ->bindValues(['id' => $id]);
+ ->bindValues(['id' => $accountId]);
- return $this->db->doQuery(QueryData::build($query))->getAffectedNumRows() === 1;
+ return $this->db->doQuery(QueryData::build($query));
}
/**
* Crea una nueva cuenta en la BBDD
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
+ * @param \SP\Domain\Account\Models\Account $account
*
- * @return int
- * @throws ConstraintException
- * @throws QueryException
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
*/
- public function create(AccountRequest $accountRequest): int
+ public function create(Account $account): QueryResult
{
$query = $this->queryFactory
->newInsert()
->into('Account')
- ->cols([
- 'clientId' => $accountRequest->clientId,
- 'categoryId' => $accountRequest->categoryId,
- 'name' => $accountRequest->name,
- 'login' => $accountRequest->login,
- 'url' => $accountRequest->url,
- 'pass' => $accountRequest->pass,
- 'key' => $accountRequest->key,
- 'notes' => $accountRequest->notes,
- 'userId' => $accountRequest->userId,
- 'userGroupId' => $accountRequest->userGroupId,
- 'userEditId' => $accountRequest->userId,
- 'isPrivate' => $accountRequest->isPrivate,
- 'isPrivateGroup' => $accountRequest->isPrivateGroup,
- 'passDateChange' => $accountRequest->passDateChange,
- 'parentId' => $accountRequest->parentId,
- ])
+ ->cols($account->toArray(null, ['countDecrypt', 'countView', 'dateAdd', 'dateEdit', 'id']))
->set('dateAdd', 'NOW()')
->set('passDate', 'UNIX_TIMESTAMP()');
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while creating the account'));
- return $this->db->doQuery($queryData)->getLastId();
+ return $this->db->doQuery($queryData);
+ }
+
+ /**
+ * Create an account from deleted
+ *
+ * @param \SP\Domain\Account\Models\Account $account
+ *
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function createRemoved(Account $account): QueryResult
+ {
+ $query = $this->queryFactory
+ ->newInsert()
+ ->into('Account')
+ ->cols($account->toArray(null, ['id']));
+
+ $queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while creating the account'));
+
+ return $this->db->doQuery($queryData);
}
/**
* Actualiza la clave de una cuenta en la BBDD.
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
+ * @param int $accountId
+ * @param \SP\Domain\Account\Models\Account $account
*
- * @return int
- * @throws ConstraintException
- * @throws QueryException
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
*/
- public function editPassword(AccountRequest $accountRequest): int
+ public function editPassword(int $accountId, Account $account): QueryResult
{
$query = $this->queryFactory
->newUpdate()
->table('Account')
- ->cols([
- 'pass' => $accountRequest->pass,
- 'key' => $accountRequest->key,
- 'userEditId' => $accountRequest->userEditId,
- 'passDateChange' => $accountRequest->passDateChange,
- ])
+ ->cols($account->toArray(['pass', 'key', 'userEditId', 'passDateChange']))
->set('dateEdit', 'NOW()')
->set('passDate', 'UNIX_TIMESTAMP()')
->where('id = :id')
- ->bindValues(['id' => $accountRequest->id]);
+ ->bindValues(['id' => $accountId]);
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while updating the password'));
- return $this->db->doQuery($queryData)->getAffectedNumRows();
+ return $this->db->doQuery($queryData);
}
/**
* Actualiza la clave de una cuenta en la BBDD.
*
- * @param AccountPasswordRequest $request
+ * @param int $accountId
+ * @param \SP\Domain\Account\Dtos\EncryptedPassword $encryptedPassword
*
- * @return bool
- * @throws ConstraintException
- * @throws QueryException
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
*/
- public function updatePassword(AccountPasswordRequest $request): bool
+ public function updatePassword(int $accountId, EncryptedPassword $encryptedPassword): QueryResult
{
$query = $this->queryFactory
->newUpdate()
->table('Account')
- ->cols(
- [
- 'pass' => $request->getEncryptedPassword()->getPass(),
- 'key' => $request->getEncryptedPassword()->getKey(),
- ]
- )
+ ->cols(['pass' => $encryptedPassword->getPass(), 'key' => $encryptedPassword->getKey()])
->where('id = :id')
- ->bindValues(['id' => $request->getId()]);
+ ->bindValues(['id' => $accountId]);
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while updating the password'));
- return $this->db->doQuery($queryData)->getAffectedNumRows() === 1;
+ return $this->db->doQuery($queryData);
}
/**
* Restaurar una cuenta desde el histórico.
*
- * @param \SP\DataModel\AccountHistoryData $accountHistoryData
- * @param int $userId User's Id
+ * @param int $accountId
+ * @param \SP\Domain\Account\Models\Account $account
*
- * @return bool
+ * @return QueryResult
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function editRestore(AccountHistoryData $accountHistoryData, int $userId): bool
+ public function restoreModified(int $accountId, Account $account): QueryResult
{
$query = $this->queryFactory
->newUpdate()
->table('Account')
- ->cols([
- 'clientId' => $accountHistoryData->getClientId(),
- 'categoryId' => $accountHistoryData->getCategoryId(),
- 'name' => $accountHistoryData->getName(),
- 'login' => $accountHistoryData->getLogin(),
- 'url' => $accountHistoryData->getUrl(),
- 'notes' => $accountHistoryData->getNotes(),
- 'userGroupId' => $accountHistoryData->getUserGroupId(),
- 'userEditId' => $userId,
- 'pass' => $accountHistoryData->getPass(),
- 'key' => $accountHistoryData->getKey(),
- 'passDate' => $accountHistoryData->getPassDate(),
- 'passDateChange' => $accountHistoryData->getPassDateChange(),
- 'parentId' => $accountHistoryData->getParentId(),
- 'isPrivate' => $accountHistoryData->getIsPrivate(),
- 'isPrivateGroup' => $accountHistoryData->getIsPrivateGroup(),
- ])
+ ->cols(
+ $account->toArray(
+ null,
+ [
+ 'passDate',
+ 'dateAdd',
+ 'countDecrypt',
+ 'countView',
+ 'dateEdit',
+ 'id',
+ ]
+ )
+ )
->set('dateEdit', 'NOW()')
->where('id = :id')
- ->bindValues(['id' => $accountHistoryData->getAccountId()]);
+ ->bindValues(['id' => $accountId]);
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error on restoring the account'));
- return $this->db->doQuery($queryData)->getAffectedNumRows() === 1;
+ return $this->db->doQuery($queryData);
}
/**
* Elimina los datos de una cuenta en la BBDD.
*
- * @param int $id
+ * @param int $accountId
*
- * @return bool
+ * @return QueryResult
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function delete(int $id): bool
+ public function delete(int $accountId): QueryResult
{
$query = $this->queryFactory
->newDelete()
->from('Account')
->where('id = :id')
- ->bindValues(['id' => $id]);
+ ->bindValues(['id' => $accountId]);
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while deleting the account'));
- return $this->db->doQuery($queryData)->getAffectedNumRows() === 1;
+ return $this->db->doQuery($queryData);
}
/**
* Updates an item
*
- * @param AccountRequest $accountRequest
+ * @param int $accountId
+ * @param \SP\Domain\Account\Models\Account $account
+ * @param bool $changeOwner
+ * @param bool $changeUserGroup
*
- * @return int
- * @throws SPException
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
*/
- public function update(AccountRequest $accountRequest): int
+ public function update(int $accountId, Account $account, bool $changeOwner, bool $changeUserGroup): QueryResult
{
$query = $this->queryFactory
->newUpdate()
->table('Account')
->where('id = :id')
- ->cols([
- 'clientId' => $accountRequest->clientId,
- 'categoryId' => $accountRequest->categoryId,
- 'name' => $accountRequest->name,
- 'login' => $accountRequest->login,
- 'url' => $accountRequest->url,
- 'notes' => $accountRequest->notes,
- 'userEditId' => $accountRequest->userEditId,
- 'passDateChange' => $accountRequest->passDateChange,
- 'isPrivate' => $accountRequest->isPrivate,
- 'isPrivateGroup' => $accountRequest->isPrivateGroup,
- 'parentId' => $accountRequest->parentId,
- ])
+ ->cols(
+ $account->toArray(
+ null,
+ [
+ 'passDate',
+ 'dateAdd',
+ 'key',
+ 'pass',
+ 'countDecrypt',
+ 'countView',
+ 'dateEdit',
+ 'userGroupId',
+ 'userId',
+ 'id',
+ ]
+ )
+ )
->set('dateEdit', 'NOW()')
- ->bindValues(['id' => $accountRequest->id]);
+ ->bindValues(['id' => $accountId]);
- if ($accountRequest->changeUserGroup) {
- $query->col('userGroupId', $accountRequest->userGroupId);
+ if ($changeUserGroup) {
+ $query->col('userGroupId', $account->getUserGroupId());
}
- if ($accountRequest->changeOwner) {
- $query->col('userId', $accountRequest->userId);
+ if ($changeOwner) {
+ $query->col('userId', $account->getUserId());
}
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while updating the account'));
- return $this->db->doQuery($queryData)->getAffectedNumRows();
+ return $this->db->doQuery($queryData);
}
/**
* Updates an item for bulk action
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $itemData
+ * @param int $accountId
+ * @param \SP\Domain\Account\Models\Account $account
+ * @param bool $changeOwner
+ * @param bool $changeUserGroup
*
- * @return int
- * @throws SPException
+ * @return QueryResult
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
*/
- public function updateBulk(AccountRequest $itemData): int
+ public function updateBulk(int $accountId, Account $account, bool $changeOwner, bool $changeUserGroup): QueryResult
{
+ $optional = ['clientId', 'categoryId', 'passDateChange'];
+
+ if ($changeOwner) {
+ $optional[] = 'userId';
+ }
+
+ if ($changeUserGroup) {
+ $optional[] = 'userGroupId';
+ }
+
+ $cols = array_filter($account->toArray($optional), fn($value) => !empty($value));
+
+ if (count($cols) === 0) {
+ return new QueryResult();
+ }
+
$query = $this->queryFactory
->newUpdate()
->table('Account')
- ->cols([
- 'userEditId' => $itemData->userEditId,
- ])
+ ->cols(
+ array_merge(
+ $cols,
+ ['userEditId' => $account->getUserEditId(),]
+ )
+ )
->set('dateEdit', 'NOW()')
->where('id = :id')
- ->bindValues(['id' => $itemData->id]);
-
- $optional = ['clientId', 'categoryId', 'userId', 'userGroupId', 'passDateChange'];
-
- $optionalCount = 0;
-
- foreach ($optional as $field) {
- if (!empty($itemData->{$field})) {
- $query->col($field, $itemData->{$field});
- $optionalCount++;
- } else {
- logger(sprintf('Field \'%s\' not found in $itemData', $field), 'ERROR');
- }
- }
-
- if ($optionalCount === 0) {
- return 0;
- }
+ ->bindValues(['id' => $accountId]);
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while updating the account'));
- return $this->db->doQuery($queryData)->getAffectedNumRows();
+ return $this->db->doQuery($queryData);
+ }
+
+ /**
+ * Returns the item for given id with referential data
+ *
+ * @param int $accountId
+ *
+ * @return QueryResult
+ */
+ public function getByIdEnriched(int $accountId): QueryResult
+ {
+ $query = $this->queryFactory
+ ->newSelect()
+ ->from('account_data_v')
+ ->cols(AccountDataView::getCols())
+ ->where('id = :id')
+ ->bindValues(['id' => $accountId])
+ ->limit(1);
+
+ $queryData = QueryData::buildWithMapper($query, AccountDataView::class)
+ ->setOnErrorMessage(__u('Error while retrieving account\'s data'));
+
+ return $this->db->doSelect($queryData);
}
/**
* Returns the item for given id
*
- * @param int $id
+ * @param int $accountId
*
* @return QueryResult
*/
- public function getById(int $id): QueryResult
+ public function getById(int $accountId): QueryResult
{
$query = $this->queryFactory
->newSelect()
- ->from('account_data_v')
- ->cols([
- 'id',
- 'name',
- 'categoryId',
- 'userId',
- 'clientId',
- 'userGroupId',
- 'userEditId',
- 'login',
- 'url',
- 'notes',
- 'countView',
- 'countDecrypt',
- 'dateAdd',
- 'dateEdit',
- 'otherUserEdit',
- 'otherUserGroupEdit',
- 'isPrivate',
- 'isPrivateGroup',
- 'passDate',
- 'passDateChange',
- 'parentId',
- 'categoryName',
- 'clientName',
- 'userGroupName',
- 'userName',
- 'userLogin',
- 'userEditName',
- 'userEditLogin',
- 'publicLinkHash',
- ])
+ ->from('Account')
+ ->cols(Account::getCols())
->where('id = :id')
- ->bindValues(['id' => $id])
+ ->bindValues(['id' => $accountId])
->limit(1);
- $queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while retrieving account\'s data'));
+ $queryData = QueryData::buildWithMapper($query, Account::class)
+ ->setOnErrorMessage(__u('Error while retrieving account\'s data'));
return $this->db->doSelect($queryData);
}
@@ -457,56 +452,34 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
$query = $this->queryFactory
->newSelect()
->from('Account')
- ->cols([
- 'id',
- 'name',
- 'categoryId',
- 'userId',
- 'clientId',
- 'userGroupId',
- 'userEditId',
- 'login',
- 'url',
- 'notes',
- 'countView',
- 'countDecrypt',
- 'dateAdd',
- 'dateEdit',
- 'otherUserEdit',
- 'otherUserGroupEdit',
- 'isPrivate',
- 'isPrivateGroup',
- 'passDate',
- 'passDateChange',
- 'parentId',
- ]);
+ ->cols(Account::getCols(['pass', 'key']));
- return $this->db->doSelect(QueryData::build($query));
+ return $this->db->doSelect(QueryData::buildWithMapper($query, Account::class));
}
/**
* Deletes all the items for given ids
*
- * @param array $ids
+ * @param array $accountsId
*
- * @return int
+ * @return QueryResult
* @throws ConstraintException
* @throws QueryException
*/
- public function deleteByIdBatch(array $ids): int
+ public function deleteByIdBatch(array $accountsId): QueryResult
{
- if (count($ids) === 0) {
- return 0;
+ if (count($accountsId) === 0) {
+ return new QueryResult();
}
$query = $this->queryFactory
->newDelete()
->from('Account')
- ->where(sprintf('id IN (%s)', $this->buildParamsFromArray($ids)), ...$ids);
+ ->where(sprintf('id IN (%s)', $this->buildParamsFromArray($accountsId)), ...$accountsId);
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while deleting the accounts'));
- return $this->db->doQuery($queryData)->getAffectedNumRows();
+ return $this->db->doQuery($queryData);
}
/**
@@ -521,25 +494,17 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
$query = $this->queryFactory
->newSelect()
->from('account_search_v')
- ->cols([
- 'id',
- 'name',
- 'clientName',
- 'categoryName',
- 'userName',
- 'userGroupName',
-
- ])
+ ->cols(AccountSearchView::getCols())
->orderBy(['name ASC', 'clientName ASC'])
->limit($itemSearchData->getLimitCount())
->offset($itemSearchData->getLimitStart());
if (!empty($itemSearchData->getSeachString())) {
$query->where('name LIKE :name')
- ->orWhere('clientName LIKE :clientName')
- ->orWhere('categoryName LIKE :categoryName')
- ->orWhere('userName LIKE :userName')
- ->orWhere('userGroupName LIKE :userGroupName');
+ ->orWhere('clientName LIKE :clientName')
+ ->orWhere('categoryName LIKE :categoryName')
+ ->orWhere('userName LIKE :userName')
+ ->orWhere('userGroupName LIKE :userGroupName');
$search = '%'.$itemSearchData->getSeachString().'%';
@@ -552,44 +517,42 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
]);
}
- return $this->db->doSelect(QueryData::build($query), true);
+ return $this->db->doSelect(QueryData::buildWithMapper($query, AccountSearchView::class), true);
}
/**
* Incrementa el contador de visitas de una cuenta en la BBDD
*
- * @param int $id
+ * @param int $accountId
*
- * @return bool
+ * @return QueryResult
* @throws ConstraintException
* @throws QueryException
*/
- public function incrementViewCounter(int $id): bool
+ public function incrementViewCounter(int $accountId): QueryResult
{
$query = $this->queryFactory
->newUpdate()
->table('Account')
->set('countView', '(countView + 1)')
->where('id = :id')
- ->bindValues(['id' => $id]);
+ ->bindValues(['id' => $accountId]);
- return $this->db->doQuery(QueryData::build($query))->getAffectedNumRows() === 1;
+ return $this->db->doQuery(QueryData::build($query));
}
/**
* Obtener los datos de una cuenta.
*
- * @param int $id
+ * @param int $accountId
*
* @return QueryResult
*/
- public function getDataForLink(int $id): QueryResult
+ public function getDataForLink(int $accountId): QueryResult
{
$query = $this->queryFactory
->newSelect()
->from('Account')
- ->join('INNER', 'Client', 'Account.clientId = Client.id')
- ->join('INNER', 'Category', 'Account.categoryId = Category.id')
->cols([
'Account.name',
'Account.login',
@@ -600,8 +563,10 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
'Client.name AS clientName',
'Category.name AS categoryName',
])
+ ->join('INNER', 'Client', 'Account.clientId = Client.id')
+ ->join('INNER', 'Category', 'Account.categoryId = Category.id')
->where('Account.id = :id')
- ->bindValues(['id' => $id]);
+ ->bindValues(['id' => $accountId]);
$queryData = QueryData::build($query)->setOnErrorMessage(__u('Error while retrieving account\'s data'));
@@ -617,14 +582,12 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
{
$query = $this->accountFilterUser
->buildFilter()
- ->cols(
- [
- 'Account.id',
- 'Account.name',
- 'C.name AS clientName',
- ]
- )
- ->join('LEFT', 'Client AS C', 'Account.clientId = C.id')
+ ->cols([
+ 'Account.id',
+ 'Account.name',
+ 'Client.name AS clientName',
+ ])
+ ->join('INNER', 'Client', 'Account.clientId = Client.id')
->orderBy(['Account.name ASC']);
if ($accountId) {
@@ -646,13 +609,11 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
{
$query = $this->accountFilterUser
->buildFilter()
- ->cols(
- [
- 'Account.id',
- 'Account.name',
- 'Client.name AS clientName',
- ]
- )
+ ->cols([
+ 'Account.id',
+ 'Account.name',
+ 'Client.name AS clientName',
+ ])
->join('INNER', 'Client', 'Account.clientId = Client.id')
->where('Account.parentId = :parentId')
->bindValues(['parentId' => $accountId])
@@ -671,16 +632,14 @@ final class AccountRepository extends Repository implements AccountRepositoryInt
$query = $this->queryFactory
->newSelect()
->from('Account')
- ->cols(
- [
- 'id',
- 'name',
- 'pass',
- 'key',
- ]
- )
+ ->cols([
+ 'id',
+ 'name',
+ 'pass',
+ 'key',
+ ])
->where('BIT_LENGTH(pass) > 0');
- return $this->db->doSelect(QueryData::build($query));
+ return $this->db->doSelect(QueryData::buildWithMapper($query, Account::class));
}
}
diff --git a/lib/SP/Infrastructure/Account/Repositories/AccountToTagRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountToTagRepository.php
index dc0f5d72..629bd66c 100644
--- a/lib/SP/Infrastructure/Account/Repositories/AccountToTagRepository.php
+++ b/lib/SP/Infrastructure/Account/Repositories/AccountToTagRepository.php
@@ -24,6 +24,7 @@
namespace SP\Infrastructure\Account\Repositories;
+use SP\Domain\Account\Dtos\AccountDto;
use SP\Domain\Account\Dtos\AccountRequest;
use SP\Domain\Account\Ports\AccountToTagRepositoryInterface;
use SP\Infrastructure\Common\Repositories\Repository;
@@ -92,20 +93,21 @@ final class AccountToTagRepository extends Repository implements AccountToTagRep
/**
* Actualizar las etiquetas de una cuenta
*
- * @param \SP\Domain\Account\Dtos\AccountRequest $accountRequest
+ * @param int $accountId
+ * @param array $tags
*
* @return void
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function add(AccountRequest $accountRequest): void
+ public function add(int $accountId, array $tags): void
{
- foreach ($accountRequest->tags as $tag) {
+ foreach ($tags as $tag) {
$query = $this->queryFactory
->newInsert()
->into('AccountToTag')
->cols([
- 'accountId' => $accountRequest->id,
+ 'accountId' => $accountId,
'tagId' => $tag,
]);
diff --git a/lib/SP/Infrastructure/Account/Repositories/AccountToUserGroupRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountToUserGroupRepository.php
index c6fe5efe..42964975 100644
--- a/lib/SP/Infrastructure/Account/Repositories/AccountToUserGroupRepository.php
+++ b/lib/SP/Infrastructure/Account/Repositories/AccountToUserGroupRepository.php
@@ -150,7 +150,7 @@ final class AccountToUserGroupRepository extends Repository implements AccountTo
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function addByType(int $accountId, array $items, bool $isEdit): void
+ public function addByType(int $accountId, array $items, bool $isEdit = false): void
{
$values = array_map(static function ($item) use ($accountId, $isEdit) {
return [$accountId, (int)$item, (int)$isEdit];
diff --git a/lib/SP/Infrastructure/Account/Repositories/AccountToUserRepository.php b/lib/SP/Infrastructure/Account/Repositories/AccountToUserRepository.php
index eaf2e748..b6664108 100644
--- a/lib/SP/Infrastructure/Account/Repositories/AccountToUserRepository.php
+++ b/lib/SP/Infrastructure/Account/Repositories/AccountToUserRepository.php
@@ -82,7 +82,7 @@ final class AccountToUserRepository extends Repository implements AccountToUserR
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function addByType(int $accountId, array $items, bool $isEdit): void
+ public function addByType(int $accountId, array $items, bool $isEdit = false): void
{
$values = array_map(static function ($item) use ($accountId, $isEdit) {
return [$accountId, (int)$item, (int)$isEdit];
diff --git a/lib/SP/Infrastructure/Common/Repositories/Repository.php b/lib/SP/Infrastructure/Common/Repositories/Repository.php
index 1ee4d03b..42de3b5b 100644
--- a/lib/SP/Infrastructure/Common/Repositories/Repository.php
+++ b/lib/SP/Infrastructure/Common/Repositories/Repository.php
@@ -31,6 +31,7 @@ use SP\Core\Context\ContextInterface;
use SP\Core\Events\Event;
use SP\Core\Events\EventDispatcherInterface;
use SP\Core\Events\EventMessage;
+use SP\Core\Exceptions\SPException;
use SP\Domain\Common\Ports\RepositoryInterface;
use SP\Domain\Common\Services\ServiceException;
use SP\Infrastructure\Database\DatabaseInterface;
@@ -44,22 +45,12 @@ use function SP\logger;
*/
abstract class Repository implements RepositoryInterface
{
- protected ContextInterface $context;
- protected DatabaseInterface $db;
- protected QueryFactory $queryFactory;
- protected EventDispatcherInterface $eventDispatcher;
-
public function __construct(
- DatabaseInterface $database,
- ContextInterface $session,
- EventDispatcherInterface $eventDispatcher,
- QueryFactory $queryFactory
+ protected DatabaseInterface $db,
+ protected ContextInterface $context,
+ protected EventDispatcherInterface $eventDispatcher,
+ protected QueryFactory $queryFactory
) {
- $this->db = $database;
- $this->context = $session;
- $this->queryFactory = $queryFactory;
- $this->eventDispatcher = $eventDispatcher;
-
if (method_exists($this, 'initialize')) {
$this->initialize();
}
@@ -69,16 +60,16 @@ abstract class Repository implements RepositoryInterface
* Bubbles a Closure in a database transaction
*
* @param \Closure $closure
+ * @param object $newThis
*
* @return mixed
* @throws \SP\Domain\Common\Services\ServiceException
- * @throws \Exception
*/
- final public function transactionAware(Closure $closure): mixed
+ final public function transactionAware(Closure $closure, object $newThis): mixed
{
if ($this->db->beginTransaction()) {
try {
- $result = $closure->call($this);
+ $result = $closure->call($newThis);
$this->db->endTransaction();
@@ -92,8 +83,9 @@ abstract class Repository implements RepositoryInterface
'database.rollback',
new Event($this, EventMessage::factory()->addDescription(__u('Rollback')))
);
+ $this->eventDispatcher->notifyEvent('exception', new Event($e));
- throw $e;
+ throw new ServiceException(__u('Rollback'), SPException::ERROR, null, $e->getCode(), $e);
}
} else {
throw new ServiceException(__u('Unable to start a transaction'));
diff --git a/lib/SP/Infrastructure/Database/QueryData.php b/lib/SP/Infrastructure/Database/QueryData.php
index a6a04d00..86217081 100644
--- a/lib/SP/Infrastructure/Database/QueryData.php
+++ b/lib/SP/Infrastructure/Database/QueryData.php
@@ -27,7 +27,7 @@ namespace SP\Infrastructure\Database;
use Aura\SqlQuery\Common\Select;
use Aura\SqlQuery\QueryInterface;
use SP\Core\Exceptions\QueryException;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
use function SP\__u;
/**
@@ -37,19 +37,10 @@ use function SP\__u;
*/
final class QueryData
{
- protected array $params = [];
- protected QueryInterface $query;
- protected ?string $mapClassName = SimpleModel::class;
- 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 $onErrorMessage = null;
+ protected string $mapClassName = Simple::class;
+ protected ?string $onErrorMessage = null;
- public function __construct(QueryInterface $query)
+ public function __construct(private QueryInterface $query)
{
$this->query = $query;
}
@@ -59,33 +50,36 @@ final class QueryData
return new self($query);
}
+ public static function buildWithMapper(QueryInterface $query, string $class): QueryData
+ {
+ $self = new self($query);
+ $self->mapClassName = self::checkClassOrDefault($class);
+
+ return $self;
+ }
+
+ private static function checkClassOrDefault(string $class): string
+ {
+ return class_exists($class) ? $class : Simple::class;
+ }
+
public function getQuery(): QueryInterface
{
return $this->query;
}
- public function getMapClassName(): ?string
+ public function getMapClassName(): string
{
return $this->mapClassName;
}
- public function setMapClassName(string $mapClassName): QueryData
+ public function setMapClassName(string $class): QueryData
{
- $this->mapClassName = $mapClassName;
+ $this->mapClassName = self::checkClassOrDefault($class);
return $this;
}
- public function isUseKeyPair(): bool
- {
- return $this->useKeyPair;
- }
-
- public function addParams(array $params): void
- {
- $this->params = array_merge($this->params, $params);
- }
-
/**
* @throws \SP\Core\Exceptions\QueryException
*/
diff --git a/lib/SP/Infrastructure/Database/QueryResult.php b/lib/SP/Infrastructure/Database/QueryResult.php
index 324676c9..811a3368 100644
--- a/lib/SP/Infrastructure/Database/QueryResult.php
+++ b/lib/SP/Infrastructure/Database/QueryResult.php
@@ -70,24 +70,45 @@ class QueryResult
}
/**
- * @return mixed|null
+ * @template T
+ *
+ * @param class-string|null $dataType
+ *
+ * @return T|mixed|null
+ *
+ * @throws \SP\Core\Exceptions\SPException
*/
- public function getData(): mixed
+ public function getData(?string $dataType = null): mixed
{
+ $this->checkDataType($dataType);
+
return $this->numRows === 1 ? $this->data[0] : null;
}
/**
- * @param string|null $dataType Expected data's type
+ * @param string|null $dataType
*
- * @return array
+ * @return void
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ private function checkDataType(?string $dataType = null): void
+ {
+ if (null !== $dataType && $this->dataType !== null && $dataType !== $this->dataType) {
+ throw new SPException(sprintf(__u('Invalid data\'s type: %s - Expected: %s'), $dataType, $this->dataType));
+ }
+ }
+
+ /**
+ * @template T
+ *
+ * @param class-string|null $dataType
+ *
+ * @return T[]
* @throws \SP\Core\Exceptions\SPException
*/
public function getDataAsArray(?string $dataType = null): array
{
- if (null !== $dataType && $this->dataType !== null && $dataType !== $this->dataType) {
- throw new SPException(__u('Invalid data\'s type'));
- }
+ $this->checkDataType($dataType);
return $this->data ?? [];
}
diff --git a/lib/SP/Infrastructure/ItemPreset/Repositories/ItemPresetRepository.php b/lib/SP/Infrastructure/ItemPreset/Repositories/ItemPresetRepository.php
index 8d0c5ccd..add8cdf9 100644
--- a/lib/SP/Infrastructure/ItemPreset/Repositories/ItemPresetRepository.php
+++ b/lib/SP/Infrastructure/ItemPreset/Repositories/ItemPresetRepository.php
@@ -27,8 +27,8 @@ 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\Domain\Account\Models\ItemPreset;
use SP\Domain\Common\Ports\RepositoryInterface;
use SP\Domain\ItemPreset\Ports\ItemPresetRepositoryInterface;
use SP\Infrastructure\Common\Repositories\Repository;
@@ -48,7 +48,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface, It
/**
* Creates an item
*
- * @param ItemPresetData $itemData
+ * @param ItemPreset $itemData
*
* @return int
* @throws ConstraintException
@@ -86,7 +86,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface, It
/**
* Updates an item
*
- * @param ItemPresetData $itemData
+ * @param ItemPreset $itemData
*
* @return int
* @throws ConstraintException
@@ -154,7 +154,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface, It
public function getById(int $id): QueryResult
{
$queryData = new QueryData();
- $queryData->setMapClassName(ItemPresetData::class);
+ $queryData->setMapClassName(ItemPreset::class);
$queryData->setQuery(
'SELECT id, type, userId, userGroupId, userProfileId, `fixed`, priority, `data`
FROM ItemPreset WHERE id = ? LIMIT 1'
@@ -183,7 +183,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface, It
int $userProfileId
): QueryResult {
$queryData = new QueryData();
- $queryData->setMapClassName(ItemPresetData::class);
+ $queryData->setMapClassName(ItemPreset::class);
$queryData->setQuery(
'SELECT id, type, userId, userGroupId, userProfileId, `fixed`, priority, `data`,
IF(userId IS NOT NULL, priority + 3,
@@ -217,7 +217,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface, It
public function getAll(): QueryResult
{
$queryData = new QueryData();
- $queryData->setMapClassName(ItemPresetData::class);
+ $queryData->setMapClassName(ItemPreset::class);
$queryData->setQuery(
'SELECT id, type, userId, userGroupId, userProfileId, `fixed`, priority, `data`
FROM ItemPreset'
@@ -242,7 +242,7 @@ class ItemPresetRepository extends Repository implements RepositoryInterface, It
}
$queryData = new QueryData();
- $queryData->setMapClassName(ItemPresetData::class);
+ $queryData->setMapClassName(ItemPreset::class);
$queryData->setQuery(
'SELECT type, userId, userGroupId, userProfileId, `fixed`, priority, `data`
FROM ItemPreset WHERE id IN ('.$this->buildParamsFromArray($ids).')'
diff --git a/lib/SP/Infrastructure/Plugin/Repositories/PluginDataModel.php b/lib/SP/Infrastructure/Plugin/Repositories/PluginDataModel.php
index cf596829..c6f62e31 100644
--- a/lib/SP/Infrastructure/Plugin/Repositories/PluginDataModel.php
+++ b/lib/SP/Infrastructure/Plugin/Repositories/PluginDataModel.php
@@ -25,8 +25,8 @@
namespace SP\Infrastructure\Plugin\Repositories;
use SP\DataModel\EncryptedModel;
-use SP\DataModel\SerializedModel;
use SP\Domain\Common\Adapters\HydratableInterface;
+use SP\Domain\Common\Models\SerializedModel;
/**
* Class PluginData
diff --git a/lib/SP/Infrastructure/Plugin/Repositories/PluginModel.php b/lib/SP/Infrastructure/Plugin/Repositories/PluginModel.php
index f1efaeba..59c8e87a 100644
--- a/lib/SP/Infrastructure/Plugin/Repositories/PluginModel.php
+++ b/lib/SP/Infrastructure/Plugin/Repositories/PluginModel.php
@@ -24,15 +24,15 @@
namespace SP\Infrastructure\Plugin\Repositories;
-use SP\Domain\Common\Adapters\DataModel;
use SP\Domain\Common\Adapters\DataModelInterface;
+use SP\Domain\Common\Models\Model;
/**
* Class PluginData
*
* @package SP\DataModel
*/
-class PluginModel extends DataModel implements DataModelInterface
+class PluginModel extends Model implements DataModelInterface
{
/**
* @var int
diff --git a/lib/SP/Util/Chainable.php b/lib/SP/Util/Chainable.php
new file mode 100644
index 00000000..20218506
--- /dev/null
+++ b/lib/SP/Util/Chainable.php
@@ -0,0 +1,52 @@
+.
+ */
+
+namespace SP\Util;
+
+use Closure;
+
+/**
+ * Class Chainable
+ */
+final class Chainable
+{
+ private array $args;
+
+ public function __construct(private Closure $next, private object $bindTo, ...$args)
+ {
+ $this->args = $args;
+ }
+
+ public function next(Closure $next): Chainable
+ {
+ $resolved = $this->next->call($this->bindTo, ...$this->args);
+
+ return new self($next, $this->bindTo, $resolved);
+ }
+
+ public function resolve(): mixed
+ {
+ return $this->next->call($this->bindTo, ...$this->args);
+ }
+}
diff --git a/lib/SP/Util/Util.php b/lib/SP/Util/Util.php
index 3c81b775..6a6a5b78 100644
--- a/lib/SP/Util/Util.php
+++ b/lib/SP/Util/Util.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.
*
@@ -147,7 +147,7 @@ final class Util
*
* @return mixed
*/
- public static function unserialize(string $dstClass, $serialized, ?string $srcClass = null)
+ public static function unserialize(string $dstClass, string|object $serialized, ?string $srcClass = null): mixed
{
if (!is_object($serialized)) {
$match = preg_match_all('/O:\d+:"(?P[^"]++)"/', $serialized, $matches);
diff --git a/tests/SP/Domain/Account/Adapters/AccountAdapterTest.php b/tests/SP/Domain/Account/Adapters/AccountAdapterTest.php
index 464d1b0f..ece4df64 100644
--- a/tests/SP/Domain/Account/Adapters/AccountAdapterTest.php
+++ b/tests/SP/Domain/Account/Adapters/AccountAdapterTest.php
@@ -48,7 +48,7 @@ class AccountAdapterTest extends UnitaryTestCase
$this->config->getConfigData(),
$this->createStub(CustomFieldServiceInterface::class)
);
- $accountData = $dataGenerator->buildAccountEnrichedData();
+ $accountData = $dataGenerator->buildAccountEnrichedDto();
$out = $adapter->transform($accountData);
@@ -66,7 +66,7 @@ class AccountAdapterTest extends UnitaryTestCase
$out['userGroups']
);
- $accountVData = $accountData->getAccountVData();
+ $accountVData = $accountData->getAccountDataView();
$this->assertEquals($accountVData->getName(), $out['name']);
$this->assertEquals($accountVData->getClientId(), $out['clientId']);
@@ -107,15 +107,15 @@ class AccountAdapterTest extends UnitaryTestCase
$customFieldData = CustomFieldGenerator::factory()->buildSimpleModel();
$customFieldsService = $this->createStub(CustomFieldServiceInterface::class);
$customFieldsService->expects(self::once())
- ->method('getForModuleAndItemId')
- ->willReturn([$customFieldData]);
+ ->method('getForModuleAndItemId')
+ ->willReturn([$customFieldData]);
$adapter = new AccountAdapter($this->config->getConfigData(), $customFieldsService);
$fractal = new Manager();
$fractal->parseIncludes('customFields');
$out = $fractal->createData(
- new Item(AccountDataGenerator::factory()->buildAccountEnrichedData(), $adapter)
+ new Item(AccountDataGenerator::factory()->buildAccountEnrichedDto(), $adapter)
)->toArray();
$this->assertArrayHasKey('customFields', $out['data']);
diff --git a/tests/SP/Domain/Account/Search/AccountSearchDataBuilderTest.php b/tests/SP/Domain/Account/Search/AccountSearchDataBuilderTest.php
index 00afe322..322df4b7 100644
--- a/tests/SP/Domain/Account/Search/AccountSearchDataBuilderTest.php
+++ b/tests/SP/Domain/Account/Search/AccountSearchDataBuilderTest.php
@@ -62,8 +62,7 @@ class AccountSearchDataBuilderTest extends UnitaryTestCase
public function testBuildFrom(): void
{
$accountSearchVData =
- array_map(static fn() => AccountSearchVData::buildFromSimpleModel(AccountDataGenerator::factory()
- ->builAccountSearchVData()), range(0, 4));
+ array_map(static fn() => AccountDataGenerator::factory()->builAccountSearchView(), range(0, 4));
$numResults = count($accountSearchVData);
$queryResult = new QueryResult($accountSearchVData);
@@ -101,8 +100,7 @@ class AccountSearchDataBuilderTest extends UnitaryTestCase
public function testBuildFromWithColorCacheException(): void
{
$accountSearchVData =
- array_map(static fn() => AccountSearchVData::buildFromSimpleModel(AccountDataGenerator::factory()
- ->builAccountSearchVData()), range(0, 4));
+ array_map(static fn() => AccountDataGenerator::factory()->builAccountSearchView(), range(0, 4));
$numResults = count($accountSearchVData);
$queryResult = new QueryResult($accountSearchVData);
diff --git a/tests/SP/Domain/Account/Services/AccountAclServiceTest.php b/tests/SP/Domain/Account/Services/AccountAclServiceTest.php
index 789f65b3..6747f065 100644
--- a/tests/SP/Domain/Account/Services/AccountAclServiceTest.php
+++ b/tests/SP/Domain/Account/Services/AccountAclServiceTest.php
@@ -32,7 +32,7 @@ use SP\DataModel\ItemData;
use SP\Domain\Account\Dtos\AccountAclDto;
use SP\Domain\Account\Services\AccountAcl;
use SP\Domain\Account\Services\AccountAclService;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
use SP\Domain\User\Ports\UserToUserGroupServiceInterface;
use SP\Infrastructure\File\FileCacheInterface;
use SP\Infrastructure\File\FileException;
@@ -776,9 +776,9 @@ class AccountAclServiceTest extends UnitaryTestCase
*/
return [
[1, 2, 2, true, true],
- [1, 3, 0, true, true],
+ [1, 3, 0, true, true],
[1, 3, 1, true, true],
- [1, 3, 2, true, true],
+ [1, 3, 2, true, true],
[1, 4, 0, false, false],
[1, 4, 3, false, false],
[1, 4, 4, false, false],
@@ -786,11 +786,11 @@ class AccountAclServiceTest extends UnitaryTestCase
[2, 2, 2, true, true],
[2, 2, 3, true, true],
[2, 3, 0, false, false],
- [2, 3, 3, true, true],
+ [2, 3, 3, true, true],
[2, 4, 0, false, false],
[2, 4, 1, true, true],
- [2, 4, 2, true, true],
- [2, 4, 3, true, true],
+ [2, 4, 2, true, true],
+ [2, 4, 3, true, true],
[2, 4, 4, false, false],
[3, 1, 1, false, false],
[3, 1, 2, false, false],
@@ -817,9 +817,9 @@ class AccountAclServiceTest extends UnitaryTestCase
$userToUserGroupService = $this->createMock(UserToUserGroupServiceInterface::class);
$userToUserGroupService->method('getGroupsForUser')
->willReturnMap([
- [1, [new SimpleModel(['userGroupId' => 2])]],
- [2, [new SimpleModel(['userGroupId' => 1])]],
- [3, [new SimpleModel(['userGroupId' => 2])]],
+ [1, [new Simple(['userGroupId' => 2])]],
+ [2, [new Simple(['userGroupId' => 1])]],
+ [3, [new Simple(['userGroupId' => 2])]],
[4, []],
]);
diff --git a/tests/SP/Domain/Account/Services/AccountCryptServiceTest.php b/tests/SP/Domain/Account/Services/AccountCryptServiceTest.php
index 03224368..80ef0e5f 100644
--- a/tests/SP/Domain/Account/Services/AccountCryptServiceTest.php
+++ b/tests/SP/Domain/Account/Services/AccountCryptServiceTest.php
@@ -58,11 +58,11 @@ class AccountCryptServiceTest extends UnitaryTestCase
{
$task = $this->createMock(TaskInterface::class);
$task->method('getUid')
- ->willReturn(self::$faker->uuid);
+ ->willReturn(self::$faker->uuid);
$task->method('getTaskId')
- ->willReturn((string)self::$faker->randomNumber());
+ ->willReturn((string)self::$faker->randomNumber());
$task->method('registerSession')
- ->willReturnSelf();
+ ->willReturnSelf();
$request =
new UpdateMasterPassRequest(
@@ -71,23 +71,23 @@ class AccountCryptServiceTest extends UnitaryTestCase
self::$faker->sha1,
TaskFactory::register($task)
);
- $accountData = array_map(static fn() => AccountDataGenerator::factory()->buildAccountData(), range(0, 9));
+ $accountData = array_map(static fn() => AccountDataGenerator::factory()->buildAccount(), range(0, 9));
$this->accountService->expects(self::once())
- ->method('getAccountsPassData')
- ->willReturn($accountData);
+ ->method('getAccountsPassData')
+ ->willReturn($accountData);
$this->accountService->expects(self::exactly(10))
- ->method('updatePasswordMasterPass');
+ ->method('updatePasswordMasterPass');
$this->crypt->expects(self::exactly(10))
- ->method('decrypt');
+ ->method('decrypt');
$this->crypt->expects(self::exactly(10))
- ->method('makeSecuredKey')
- ->willReturn(self::$faker->password);
+ ->method('makeSecuredKey')
+ ->willReturn(self::$faker->password);
$this->crypt->expects(self::exactly(10))
- ->method('encrypt')
- ->willReturn(self::$faker->password);
+ ->method('encrypt')
+ ->willReturn(self::$faker->password);
$task->expects(self::exactly(2))
- ->method('writeJsonStatusAndFlush');
+ ->method('writeJsonStatusAndFlush');
$this->accountCryptService->updateMasterPassword($request);
}
@@ -105,16 +105,16 @@ class AccountCryptServiceTest extends UnitaryTestCase
);
$this->accountService->expects(self::once())
- ->method('getAccountsPassData')
- ->willReturn([]);
+ ->method('getAccountsPassData')
+ ->willReturn([]);
$this->accountService->expects(self::never())
- ->method('updatePasswordMasterPass');
+ ->method('updatePasswordMasterPass');
$this->crypt->expects(self::never())
- ->method('decrypt');
+ ->method('decrypt');
$this->crypt->expects(self::never())
- ->method('makeSecuredKey');
+ ->method('makeSecuredKey');
$this->crypt->expects(self::never())
- ->method('encrypt');
+ ->method('encrypt');
$this->accountCryptService->updateMasterPassword($request);
}
@@ -125,14 +125,14 @@ class AccountCryptServiceTest extends UnitaryTestCase
public function testUpdateMasterPasswordDoesNotThrowException(): void
{
$request = new UpdateMasterPassRequest(self::$faker->password, self::$faker->password, self::$faker->sha1);
- $accountData = array_map(static fn() => AccountDataGenerator::factory()->buildAccountData(), range(0, 9));
+ $accountData = array_map(static fn() => AccountDataGenerator::factory()->buildAccount(), range(0, 9));
$this->accountService->expects(self::once())
- ->method('getAccountsPassData')
- ->willReturn($accountData);
+ ->method('getAccountsPassData')
+ ->willReturn($accountData);
$this->crypt->expects(self::exactly(10))
- ->method('decrypt')
- ->willThrowException(new SPException('test'));
+ ->method('decrypt')
+ ->willThrowException(new SPException('test'));
$this->accountCryptService->updateMasterPassword($request);
}
@@ -145,8 +145,8 @@ class AccountCryptServiceTest extends UnitaryTestCase
$request = new UpdateMasterPassRequest(self::$faker->password, self::$faker->password, self::$faker->sha1);
$this->accountService->expects(self::once())
- ->method('getAccountsPassData')
- ->willThrowException(new \RuntimeException('test'));
+ ->method('getAccountsPassData')
+ ->willThrowException(new \RuntimeException('test'));
$this->expectException(ServiceException::class);
$this->expectExceptionMessage('Error while updating the accounts\' passwords');
@@ -162,30 +162,29 @@ class AccountCryptServiceTest extends UnitaryTestCase
{
$task = $this->createMock(TaskInterface::class);
$task->method('getUid')
- ->willReturn(self::$faker->uuid);
+ ->willReturn(self::$faker->uuid);
$task->method('getTaskId')
- ->willReturn((string)self::$faker->randomNumber());
+ ->willReturn((string)self::$faker->randomNumber());
$task->method('registerSession')
- ->willReturnSelf();
+ ->willReturnSelf();
- $request =
- new UpdateMasterPassRequest(
- self::$faker->password,
- self::$faker->password,
- self::$faker->sha1,
- TaskFactory::register($task)
- );
- $accountData = array_map(static fn() => AccountDataGenerator::factory()->buildAccountData(), range(0, 9));
+ $request = new UpdateMasterPassRequest(
+ self::$faker->password,
+ self::$faker->password,
+ self::$faker->sha1,
+ TaskFactory::register($task)
+ );
+ $accountData = array_map(static fn() => AccountDataGenerator::factory()->buildAccount(), range(0, 9));
$this->accountHistoryService->expects(self::once())
- ->method('getAccountsPassData')
- ->willReturn($accountData);
+ ->method('getAccountsPassData')
+ ->willReturn($accountData);
$this->accountHistoryService->expects(self::exactly(10))
- ->method('updatePasswordMasterPass');
+ ->method('updatePasswordMasterPass');
$this->crypt->expects(self::exactly(10))
- ->method('decrypt');
+ ->method('decrypt');
$task->expects(self::exactly(2))
- ->method('writeJsonStatusAndFlush');
+ ->method('writeJsonStatusAndFlush');
$this->accountCryptService->updateHistoryMasterPassword($request);
}
@@ -203,16 +202,16 @@ class AccountCryptServiceTest extends UnitaryTestCase
);
$this->accountHistoryService->expects(self::once())
- ->method('getAccountsPassData')
- ->willReturn([]);
+ ->method('getAccountsPassData')
+ ->willReturn([]);
$this->accountHistoryService->expects(self::never())
- ->method('updatePasswordMasterPass');
+ ->method('updatePasswordMasterPass');
$this->crypt->expects(self::never())
- ->method('decrypt');
+ ->method('decrypt');
$this->crypt->expects(self::never())
- ->method('makeSecuredKey');
+ ->method('makeSecuredKey');
$this->crypt->expects(self::never())
- ->method('encrypt');
+ ->method('encrypt');
$this->accountCryptService->updateHistoryMasterPassword($request);
}
@@ -225,9 +224,8 @@ class AccountCryptServiceTest extends UnitaryTestCase
$request = new UpdateMasterPassRequest(self::$faker->password, self::$faker->password, self::$faker->sha1);
$this->accountHistoryService->expects(self::once())
- ->method('getAccountsPassData')
- ->willThrowException(new \RuntimeException('test'));
-
+ ->method('getAccountsPassData')
+ ->willThrowException(new \RuntimeException('test'));
$this->expectException(ServiceException::class);
$this->expectExceptionMessage('Error while updating the accounts\' passwords in history');
@@ -241,14 +239,14 @@ class AccountCryptServiceTest extends UnitaryTestCase
public function testUpdateHistoryMasterPasswordDoesNotThrowException(): void
{
$request = new UpdateMasterPassRequest(self::$faker->password, self::$faker->password, self::$faker->sha1);
- $accountData = array_map(static fn() => AccountDataGenerator::factory()->buildAccountData(), range(0, 9));
+ $accountData = array_map(static fn() => AccountDataGenerator::factory()->buildAccount(), range(0, 9));
$this->accountHistoryService->expects(self::once())
- ->method('getAccountsPassData')
- ->willReturn($accountData);
+ ->method('getAccountsPassData')
+ ->willReturn($accountData);
$this->crypt->expects(self::exactly(10))
- ->method('decrypt')
- ->willThrowException(new SPException('test'));
+ ->method('decrypt')
+ ->willThrowException(new SPException('test'));
$this->accountCryptService->updateHistoryMasterPassword($request);
}
@@ -263,14 +261,14 @@ class AccountCryptServiceTest extends UnitaryTestCase
$masterPass = self::$faker->password;
$this->crypt->expects(self::once())
- ->method('makeSecuredKey')
- ->with($masterPass)
- ->willReturn($key);
+ ->method('makeSecuredKey')
+ ->with($masterPass)
+ ->willReturn($key);
$this->crypt->expects(self::once())
- ->method('encrypt')
- ->with($pass)
- ->willReturn($pass);
+ ->method('encrypt')
+ ->with($pass)
+ ->willReturn($pass);
$out = $this->accountCryptService->getPasswordEncrypted($pass, $masterPass);
@@ -287,10 +285,10 @@ class AccountCryptServiceTest extends UnitaryTestCase
$this->context->setTrasientKey('_masterpass', '');
$this->crypt->expects(self::never())
- ->method('makeSecuredKey');
+ ->method('makeSecuredKey');
$this->crypt->expects(self::never())
- ->method('encrypt');
+ ->method('encrypt');
$this->expectException(ServiceException::class);
$this->expectExceptionMessage('Error while retrieving master password from context');
@@ -304,10 +302,10 @@ class AccountCryptServiceTest extends UnitaryTestCase
public function testGetPasswordEncryptedThrowsExceptionWithEmptyMasterPassword(): void
{
$this->crypt->expects(self::never())
- ->method('makeSecuredKey');
+ ->method('makeSecuredKey');
$this->crypt->expects(self::never())
- ->method('encrypt');
+ ->method('encrypt');
$this->expectException(ServiceException::class);
$this->expectExceptionMessage('Master password not set');
@@ -321,12 +319,12 @@ class AccountCryptServiceTest extends UnitaryTestCase
public function testGetPasswordEncryptedThrowsExceptionWithLongPass(): void
{
$this->crypt->expects(self::once())
- ->method('makeSecuredKey')
- ->willReturn(self::$faker->password);
+ ->method('makeSecuredKey')
+ ->willReturn(self::$faker->password);
$this->crypt->expects(self::once())
- ->method('encrypt')
- ->willReturn(self::$faker->text(1500));
+ ->method('encrypt')
+ ->willReturn(self::$faker->text(1500));
$this->expectException(ServiceException::class);
$this->expectExceptionMessage('Internal error');
@@ -340,12 +338,12 @@ class AccountCryptServiceTest extends UnitaryTestCase
public function testGetPasswordEncryptedThrowsExceptionWithLongKey(): void
{
$this->crypt->expects(self::once())
- ->method('makeSecuredKey')
- ->willReturn(self::$faker->text(1500));
+ ->method('makeSecuredKey')
+ ->willReturn(self::$faker->text(1500));
$this->crypt->expects(self::once())
- ->method('encrypt')
- ->willReturn(self::$faker->password);
+ ->method('encrypt')
+ ->willReturn(self::$faker->password);
$this->expectException(ServiceException::class);
$this->expectExceptionMessage('Internal error');
diff --git a/tests/SP/Domain/Account/Services/AccountFileServiceTest.php b/tests/SP/Domain/Account/Services/AccountFileServiceTest.php
index fc3e6d65..08df4813 100644
--- a/tests/SP/Domain/Account/Services/AccountFileServiceTest.php
+++ b/tests/SP/Domain/Account/Services/AccountFileServiceTest.php
@@ -74,7 +74,6 @@ class AccountFileServiceTest extends UnitaryTestCase
public function testCreateWithThumbnail(): void
{
$fileData = FileData::buildFromSimpleModel(FileDataGenerator::factory()->buildFileData());
- $fileData->type = 'image/jpeg';
$this->accountFileRepository
->expects(self::once())
diff --git a/tests/SP/Domain/Account/Services/AccountHistoryServiceTest.php b/tests/SP/Domain/Account/Services/AccountHistoryServiceTest.php
index 803b975c..23aa6f60 100644
--- a/tests/SP/Domain/Account/Services/AccountHistoryServiceTest.php
+++ b/tests/SP/Domain/Account/Services/AccountHistoryServiceTest.php
@@ -25,12 +25,10 @@
namespace SP\Tests\Domain\Account\Services;
use PHPUnit\Framework\MockObject\MockObject;
-use SP\DataModel\AccountHistoryData;
use SP\DataModel\ItemSearchData;
-use SP\Domain\Account\Adapters\AccountData;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\AccountHistory;
use SP\Domain\Account\Ports\AccountHistoryRepositoryInterface;
use SP\Domain\Account\Services\AccountHistoryService;
use SP\Domain\Common\Services\ServiceException;
@@ -52,7 +50,7 @@ class AccountHistoryServiceTest extends UnitaryTestCase
public function testCreate()
{
- $accountData = AccountData::buildFromSimpleModel(AccountDataGenerator::factory()->buildAccountData());
+ $accountData = AccountDataGenerator::factory()->buildAccount();
$dto = new AccountHistoryCreateDto(
$accountData,
self::$faker->boolean,
@@ -130,7 +128,7 @@ class AccountHistoryServiceTest extends UnitaryTestCase
{
$id = self::$faker->randomNumber();
$accountHistoryData =
- AccountHistoryData::buildFromSimpleModel(AccountDataGenerator::factory()->buildAccountHistoryData());
+ AccountHistory::buildFromSimpleModel(AccountDataGenerator::factory()->buildAccountHistoryData());
$queryResult = new QueryResult([$accountHistoryData]);
$this->accountHistoryRepository->expects(self::once())->method('getById')->with($id)->willReturn($queryResult);
@@ -178,17 +176,15 @@ class AccountHistoryServiceTest extends UnitaryTestCase
*/
public function testUpdatePasswordMasterPass()
{
- $accountPasswordRequest = new AccountPasswordRequest(
- self::$faker->randomNumber(),
- new EncryptedPassword(self::$faker->password, self::$faker->password),
- );
+ $id = self::$faker->randomNumber();
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password, self::$faker->sha1);
$this->accountHistoryRepository->expects(self::once())
- ->method('updatePassword')
- ->with($accountPasswordRequest)
- ->willReturn(true);
+ ->method('updatePassword')
+ ->with($id, $encryptedPassword)
+ ->willReturn(true);
- $this->accountHistoryService->updatePasswordMasterPass($accountPasswordRequest);
+ $this->accountHistoryService->updatePasswordMasterPass($id, $encryptedPassword);
}
/**
@@ -196,20 +192,18 @@ class AccountHistoryServiceTest extends UnitaryTestCase
*/
public function testUpdatePasswordMasterPassError()
{
- $accountPasswordRequest = new AccountPasswordRequest(
- self::$faker->randomNumber(),
- new EncryptedPassword(self::$faker->password, self::$faker->password),
- );
+ $id = self::$faker->randomNumber();
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password, self::$faker->sha1);
$this->accountHistoryRepository->expects(self::once())
- ->method('updatePassword')
- ->with($accountPasswordRequest)
- ->willReturn(false);
+ ->method('updatePassword')
+ ->with($id, $encryptedPassword)
+ ->willReturn(false);
$this->expectException(ServiceException::class);
$this->expectExceptionMessage('Error while updating the password');
- $this->accountHistoryService->updatePasswordMasterPass($accountPasswordRequest);
+ $this->accountHistoryService->updatePasswordMasterPass($id, $encryptedPassword);
}
protected function setUp(): void
diff --git a/tests/SP/Domain/Account/Services/AccountPresetServiceTest.php b/tests/SP/Domain/Account/Services/AccountPresetServiceTest.php
index f01b09eb..831afff4 100644
--- a/tests/SP/Domain/Account/Services/AccountPresetServiceTest.php
+++ b/tests/SP/Domain/Account/Services/AccountPresetServiceTest.php
@@ -27,12 +27,13 @@ namespace SP\Tests\Domain\Account\Services;
use PHPUnit\Framework\MockObject\MockObject;
use SP\Core\Exceptions\ValidationException;
use SP\DataModel\ItemPreset\Password;
-use SP\DataModel\ItemPresetData;
-use SP\Domain\Account\Dtos\AccountRequest;
+use SP\Domain\Account\Ports\AccountToUserGroupRepositoryInterface;
+use SP\Domain\Account\Ports\AccountToUserRepositoryInterface;
use SP\Domain\Account\Services\AccountPresetService;
use SP\Domain\ItemPreset\Ports\ItemPresetInterface;
use SP\Domain\ItemPreset\Ports\ItemPresetServiceInterface;
use SP\Mvc\Controller\Validators\ValidatorInterface;
+use SP\Tests\Generators\AccountDataGenerator;
use SP\Tests\Generators\ItemPresetDataGenerator;
use SP\Tests\UnitaryTestCase;
@@ -59,10 +60,8 @@ class AccountPresetServiceTest extends UnitaryTestCase
$this->config->getConfigData()->setAccountExpireEnabled(true);
$itemPresetDataGenerator = ItemPresetDataGenerator::factory();
- $itemPreset = ItemPresetData::buildFromSimpleModel(
- $itemPresetDataGenerator->buildItemPresetData($itemPresetDataGenerator->buildPasswordPreset())
- );
- $itemPreset->fixed = 1;
+ $itemPreset = $itemPresetDataGenerator->buildItemPresetData($itemPresetDataGenerator->buildPassword())
+ ->mutate(['fixed' => 1]);
$this->itemPresetService
->expects(self::once())
@@ -74,30 +73,7 @@ class AccountPresetServiceTest extends UnitaryTestCase
->method('validate')
->with(self::callback(static fn($password) => $password instanceof Password));
- $this->accountPresetService->checkPasswordPreset($this->buildAccountRequest());
- }
-
- private function buildAccountRequest(): AccountRequest
- {
- $accountRequest = new AccountRequest();
- $accountRequest->id = self::$faker->randomNumber();
- $accountRequest->name = self::$faker->name;
- $accountRequest->login = self::$faker->userName;
- $accountRequest->url = self::$faker->url;
- $accountRequest->notes = self::$faker->text;
- $accountRequest->userEditId = self::$faker->randomNumber();
- $accountRequest->passDateChange = self::$faker->unixTime;
- $accountRequest->clientId = self::$faker->randomNumber();
- $accountRequest->categoryId = self::$faker->randomNumber();
- $accountRequest->isPrivate = self::$faker->numberBetween(0, 1);
- $accountRequest->isPrivateGroup = self::$faker->numberBetween(0, 1);
- $accountRequest->parentId = self::$faker->randomNumber();
- $accountRequest->userId = self::$faker->randomNumber();
- $accountRequest->userGroupId = self::$faker->randomNumber();
- $accountRequest->key = self::$faker->password;
- $accountRequest->pass = self::$faker->password(10, 10);
-
- return $accountRequest;
+ $this->accountPresetService->checkPasswordPreset(AccountDataGenerator::factory()->buildAccountCreateDto());
}
/**
@@ -111,10 +87,8 @@ class AccountPresetServiceTest extends UnitaryTestCase
$this->config->getConfigData()->setAccountExpireEnabled(true);
$itemPresetDataGenerator = ItemPresetDataGenerator::factory();
- $itemPreset = ItemPresetData::buildFromSimpleModel(
- $itemPresetDataGenerator->buildItemPresetData($itemPresetDataGenerator->buildPasswordPreset())
- );
- $itemPreset->fixed = 1;
+ $itemPreset = $itemPresetDataGenerator->buildItemPresetData($itemPresetDataGenerator->buildPassword())
+ ->mutate(['fixed' => 1]);
$this->itemPresetService
->expects(self::once())
@@ -129,7 +103,7 @@ class AccountPresetServiceTest extends UnitaryTestCase
$this->expectException(ValidationException::class);
- $this->accountPresetService->checkPasswordPreset($this->buildAccountRequest());
+ $this->accountPresetService->checkPasswordPreset(AccountDataGenerator::factory()->buildAccountCreateDto());
}
/**
@@ -141,11 +115,8 @@ class AccountPresetServiceTest extends UnitaryTestCase
public function testCheckPasswordPresetWithoutFixed(): void
{
$itemPresetDataGenerator = ItemPresetDataGenerator::factory();
- $itemPreset = ItemPresetData::buildFromSimpleModel(
- $itemPresetDataGenerator->buildItemPresetData($itemPresetDataGenerator->buildPasswordPreset())
- );
-
- $itemPreset->fixed = 0;
+ $itemPreset = $itemPresetDataGenerator->buildItemPresetData($itemPresetDataGenerator->buildPassword())
+ ->mutate(['fixed' => 0]);
$this->itemPresetService
->expects(self::once())
@@ -156,7 +127,7 @@ class AccountPresetServiceTest extends UnitaryTestCase
->expects(self::never())
->method('validate');
- $this->accountPresetService->checkPasswordPreset($this->buildAccountRequest());
+ $this->accountPresetService->checkPasswordPreset(AccountDataGenerator::factory()->buildAccountCreateDto());
}
/**
@@ -168,12 +139,9 @@ class AccountPresetServiceTest extends UnitaryTestCase
public function testCheckPasswordPresetWithPassDateChangeModified(): void
{
$itemPresetDataGenerator = ItemPresetDataGenerator::factory();
- $passwordPreset = $itemPresetDataGenerator->buildPasswordPreset();
+ $passwordPreset = $itemPresetDataGenerator->buildPassword();
- $itemPreset = ItemPresetData::buildFromSimpleModel(
- $itemPresetDataGenerator->buildItemPresetData($passwordPreset)
- );
- $itemPreset->fixed = 1;
+ $itemPreset = $itemPresetDataGenerator->buildItemPresetData($passwordPreset)->mutate(['fixed' => 1]);
$this->itemPresetService
->expects(self::once())
@@ -184,12 +152,12 @@ class AccountPresetServiceTest extends UnitaryTestCase
->expects(self::once())
->method('validate');
- $accountRequest = $this->buildAccountRequest();
- $accountRequest->passDateChange = 0;
+ $accountDto = AccountDataGenerator::factory()->buildAccountCreateDto();
+ $accountDto = $accountDto->set('passDateChange', 0);
- $this->accountPresetService->checkPasswordPreset($accountRequest);
+ $out = $this->accountPresetService->checkPasswordPreset($accountDto);
- $this->assertGreaterThan(0, $accountRequest->passDateChange);
+ $this->assertGreaterThan(0, $out->getPassDateChange());
}
protected function setUp(): void
@@ -201,8 +169,17 @@ class AccountPresetServiceTest extends UnitaryTestCase
$this->itemPresetService = $this->createMock(ItemPresetServiceInterface::class);
$this->passwordValidator = $this->createMock(ValidatorInterface::class);
+ $this->accountToUserGroupRepository = $this->createMock(AccountToUserGroupRepositoryInterface::class);
+ $this->accountToUserRepository = $this->createMock(AccountToUserRepositoryInterface::class);
$this->accountPresetService =
- new AccountPresetService($this->itemPresetService, $configData, $this->passwordValidator);
+ new AccountPresetService(
+ $this->application,
+ $this->itemPresetService,
+ $this->accountToUserGroupRepository,
+ $this->accountToUserRepository,
+ $configData,
+ $this->passwordValidator
+ );
}
}
diff --git a/tests/SP/Domain/Account/Services/AccountServiceTest.php b/tests/SP/Domain/Account/Services/AccountServiceTest.php
new file mode 100644
index 00000000..bce04c21
--- /dev/null
+++ b/tests/SP/Domain/Account/Services/AccountServiceTest.php
@@ -0,0 +1,1330 @@
+.
+ */
+
+namespace SP\Tests\Domain\Account\Services;
+
+use PHPUnit\Framework\Constraint\Callback;
+use PHPUnit\Framework\MockObject\MockObject;
+use SP\DataModel\ItemPreset\AccountPrivate;
+use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
+use SP\Domain\Account\Dtos\AccountUpdateBulkDto;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
+use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\Account;
+use SP\Domain\Account\Models\ItemPreset;
+use SP\Domain\Account\Ports\AccountCryptServiceInterface;
+use SP\Domain\Account\Ports\AccountHistoryServiceInterface;
+use SP\Domain\Account\Ports\AccountItemsServiceInterface;
+use SP\Domain\Account\Ports\AccountPresetServiceInterface;
+use SP\Domain\Account\Ports\AccountRepositoryInterface;
+use SP\Domain\Account\Ports\AccountToTagRepositoryInterface;
+use SP\Domain\Account\Ports\AccountToUserGroupRepositoryInterface;
+use SP\Domain\Account\Ports\AccountToUserRepositoryInterface;
+use SP\Domain\Account\Services\AccountService;
+use SP\Domain\Common\Models\Simple;
+use SP\Domain\Common\Services\ServiceException;
+use SP\Domain\Config\Ports\ConfigServiceInterface;
+use SP\Domain\ItemPreset\Ports\ItemPresetInterface;
+use SP\Domain\ItemPreset\Ports\ItemPresetServiceInterface;
+use SP\Infrastructure\Common\Repositories\NoSuchItemException;
+use SP\Infrastructure\Database\QueryResult;
+use SP\Tests\Generators\AccountDataGenerator;
+use SP\Tests\Generators\ItemSearchDataGenerator;
+use SP\Tests\Stubs\AccountRepositoryStub;
+use SP\Tests\UnitaryTestCase;
+
+/**
+ * Class AccountServiceTest
+ *
+ * @group unitary
+ */
+class AccountServiceTest extends UnitaryTestCase
+{
+ private AccountRepositoryInterface|MockObject $accountRepository;
+ private AccountToUserGroupRepositoryInterface|MockObject $accountToUserGroupRepository;
+ private AccountToUserRepositoryInterface|MockObject $accountToUserRepository;
+ private AccountToTagRepositoryInterface|MockObject $accountToTagRepository;
+ private ItemPresetServiceInterface|MockObject $itemPresetService;
+ private AccountHistoryServiceInterface|MockObject $accountHistoryService;
+ private ConfigServiceInterface|MockObject $configService;
+ private AccountCryptServiceInterface|MockObject $accountCryptService;
+ private AccountPresetServiceInterface|MockObject $accountPresetService;
+ private AccountItemsServiceInterface|MockObject $accountItemsService;
+ private AccountService $accountService;
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdate()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountUpdateDto = $accountDataGenerator->buildAccountUpdateDto();
+
+ $this->context->getUserData()->setIsAdminApp(true);
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountHistoryService->expects(self::once())->method('create');
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn(null);
+ $this->accountRepository->expects(self::exactly(2))->method('getById')
+ ->with($id)
+ ->willReturn(new QueryResult([$accountDataGenerator->buildAccount()]));
+ $this->accountRepository->expects(self::once())->method('update')
+ ->with($id, Account::update($accountUpdateDto), true, true);
+ $this->accountItemsService->expects(self::once())->method('updateItems')
+ ->with(true, $id, $accountUpdateDto);
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->update($id, $accountUpdateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateUserCannotChangePermissionsWithoutAdminApp()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountUpdateDto = $accountDataGenerator->buildAccountUpdateDto();
+
+ $this->context->getUserData()->setIsAdminApp(false);
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountHistoryService->expects(self::once())->method('create');
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn(null);
+ $this->accountRepository->expects(self::once())->method('getById')
+ ->with($id)
+ ->willReturn(new QueryResult([$accountDataGenerator->buildAccount()]));
+ $this->accountRepository->expects(self::once())->method('update')
+ ->with($id, Account::update($accountUpdateDto), false, false);
+ $this->accountItemsService->expects(self::once())->method('updateItems')
+ ->with(false, $id, $accountUpdateDto);
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->update($id, $accountUpdateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateUserCanChangePermissionsWithAdminAcc()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountUpdateDto = $accountDataGenerator->buildAccountUpdateDto();
+
+ $this->context->getUserData()->setIsAdminApp(false);
+ $this->context->getUserData()->setIsAdminAcc(true);
+ $this->context->getUserProfile()->setAccPermission(false);
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountHistoryService->expects(self::once())->method('create');
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn(null);
+ $this->accountRepository->expects(self::exactly(2))->method('getById')
+ ->with($id)
+ ->willReturn(new QueryResult([$accountDataGenerator->buildAccount()]));
+ $this->accountRepository->expects(self::once())->method('update')
+ ->with($id, Account::update($accountUpdateDto), true, true);
+ $this->accountItemsService->expects(self::once())->method('updateItems')
+ ->with(true, $id, $accountUpdateDto);
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->update($id, $accountUpdateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateUserCanChangePermissionsWithProfilePermission()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountUpdateDto = $accountDataGenerator->buildAccountUpdateDto();
+
+ $this->context->getUserData()->setIsAdminApp(false);
+ $this->context->getUserData()->setIsAdminAcc(false);
+ $this->context->getUserProfile()->setAccPermission(true);
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountHistoryService->expects(self::once())->method('create');
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn(null);
+ $this->accountRepository->expects(self::exactly(2))->method('getById')
+ ->with($id)
+ ->willReturn(new QueryResult([$accountDataGenerator->buildAccount()]));
+ $this->accountRepository->expects(self::once())->method('update')
+ ->with($id, Account::update($accountUpdateDto), false, false);
+ $this->accountItemsService->expects(self::once())->method('updateItems')
+ ->with(true, $id, $accountUpdateDto);
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->update($id, $accountUpdateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateWithPresetPrivateForUser()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountUpdateDto = $accountDataGenerator->buildAccountUpdateDto();
+ $itemPreset = new ItemPreset([
+ 'id' => self::$faker->randomNumber(),
+ 'type' => self::$faker->colorName,
+ 'userId' => self::$faker->randomNumber(),
+ 'userGroupId' => self::$faker->randomNumber(),
+ 'userProfileId' => self::$faker->randomNumber(),
+ 'fixed' => 1,
+ 'priority' => self::$faker->randomNumber(),
+ 'data' => serialize(new AccountPrivate(true, true)),
+ ]);
+
+ $userData = $this->context->getUserData();
+ $userData->setIsAdminApp(true);
+ $userData->setId($accountUpdateDto->getUserId());
+ $userData->setUserGroupId($accountUpdateDto->getUserGroupId());
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountHistoryService->expects(self::once())->method('create');
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn($itemPreset);
+ $account = new Account(
+ [
+ 'userId' => $accountUpdateDto->getUserId(),
+ 'userGroupId' => self::$faker->randomNumber(),
+ ]
+ );
+
+ $this->accountRepository->expects(self::exactly(3))->method('getById')
+ ->with($id)
+ ->willReturnOnConsecutiveCalls(
+ new QueryResult([$accountDataGenerator->buildAccount()]),
+ new QueryResult([$accountDataGenerator->buildAccount()]),
+ new QueryResult([$account]),
+ );
+ $this->accountRepository->expects(self::once())->method('update')
+ ->with(
+ $id,
+ new Callback(function (Account $account) {
+ return $account->getIsPrivate() === 1 && $account->getIsPrivateGroup() === 0;
+ }),
+ true,
+ true
+ );
+ $this->accountItemsService->expects(self::once())->method('updateItems')
+ ->with(
+ true,
+ $id,
+ $accountUpdateDto->withPrivate(true)
+ ->withPrivateGroup(false)
+ ->withUserGroupId($account->getUserGroupId())
+ );
+
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->update($id, $accountUpdateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateWithPresetPrivateForGroup()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountUpdateDto = $accountDataGenerator->buildAccountUpdateDto();
+ $itemPreset = new ItemPreset([
+ 'id' => self::$faker->randomNumber(),
+ 'type' => self::$faker->colorName,
+ 'userId' => self::$faker->randomNumber(),
+ 'userGroupId' => self::$faker->randomNumber(),
+ 'userProfileId' => self::$faker->randomNumber(),
+ 'fixed' => 1,
+ 'priority' => self::$faker->randomNumber(),
+ 'data' => serialize(new AccountPrivate(true, true)),
+ ]);
+
+ $userData = $this->context->getUserData();
+ $userData->setIsAdminApp(true);
+ $userData->setId($accountUpdateDto->getUserId());
+ $userData->setUserGroupId($accountUpdateDto->getUserGroupId());
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountHistoryService->expects(self::once())->method('create');
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn($itemPreset);
+ $account = new Account(
+ [
+ 'userId' => self::$faker->randomNumber(),
+ 'userGroupId' => $accountUpdateDto->getUserGroupId(),
+ ]
+ );
+
+ $this->accountRepository->expects(self::exactly(3))->method('getById')
+ ->with($id)
+ ->willReturnOnConsecutiveCalls(
+ new QueryResult([$accountDataGenerator->buildAccount()]),
+ new QueryResult([$accountDataGenerator->buildAccount()]),
+ new QueryResult([$account]),
+ );
+ $this->accountRepository->expects(self::once())->method('update')
+ ->with(
+ $id,
+ new Callback(function (Account $account) {
+ return $account->getIsPrivate() === 0 && $account->getIsPrivateGroup() === 1;
+ }),
+ true,
+ true
+ );
+ $this->accountItemsService->expects(self::once())->method('updateItems')
+ ->with(
+ true,
+ $id,
+ $accountUpdateDto->withPrivate(false)
+ ->withPrivateGroup(true)
+ ->withUserId($account->getUserId())
+ );
+
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->update($id, $accountUpdateDto);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetLinked()
+ {
+ $id = self::$faker->randomNumber();
+
+ $this->accountRepository->expects(self::once())->method('getLinked')->with($id);
+
+ $this->accountService->getLinked($id);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetForUser()
+ {
+ $id = self::$faker->randomNumber();
+
+ $this->accountRepository->expects(self::once())->method('getForUser')->with($id);
+
+ $this->accountService->getForUser($id);
+ }
+
+ /**
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetPasswordForId()
+ {
+ $account = AccountDataGenerator::factory()->buildAccount();
+
+ $this->accountRepository->expects(self::once())->method('getPasswordForId')
+ ->with($account->getId())->willReturn(new QueryResult([$account]));
+
+ $this->assertEquals($account, $this->accountService->getPasswordForId($account->getId()));
+ }
+
+ /**
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetPasswordForIdNotFound()
+ {
+ $account = AccountDataGenerator::factory()->buildAccount();
+
+ $this->accountRepository->expects(self::once())->method('getPasswordForId')
+ ->with($account->getId())->willReturn(new QueryResult([]));
+
+ $this->expectException(NoSuchItemException::class);
+ $this->expectExceptionMessage('Account not found');
+
+ $this->accountService->getPasswordForId($account->getId());
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdatePasswordMasterPass()
+ {
+ $id = self::$faker->randomNumber();
+
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password);
+
+ $result = new QueryResult();
+ $result->setAffectedNumRows(1);
+
+ $this->accountRepository->expects(self::once())->method('updatePassword')
+ ->with($id, $encryptedPassword)
+ ->willReturn($result);
+
+ $this->accountService->updatePasswordMasterPass($id, $encryptedPassword);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdatePasswordMasterPassError()
+ {
+ $id = self::$faker->randomNumber();
+
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password);
+
+ $result = new QueryResult();
+ $result->setAffectedNumRows(0);
+
+ $this->accountRepository->expects(self::once())->method('updatePassword')
+ ->with($id, $encryptedPassword)
+ ->willReturn($result);
+
+ $this->expectException(ServiceException::class);
+ $this->expectExceptionMessage('Error while updating the password');
+
+ $this->accountService->updatePasswordMasterPass($id, $encryptedPassword);
+ }
+
+ /**
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetById()
+ {
+ $id = self::$faker->randomNumber();
+ $account = AccountDataGenerator::factory()->buildAccount();
+ $result = new QueryResult([$account]);
+
+ $this->accountRepository->expects(self::once())->method('getById')
+ ->with($id)->willReturn($result);
+
+ $this->assertEquals($account, $this->accountService->getById($id));
+ }
+
+ /**
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetByIdNotFound()
+ {
+ $id = self::$faker->randomNumber();
+ $result = new QueryResult([]);
+
+ $this->accountRepository->expects(self::once())->method('getById')
+ ->with($id)->willReturn($result);
+
+ $this->expectException(NoSuchItemException::class);
+ $this->expectExceptionMessage('The account doesn\'t exist');
+
+ $this->accountService->getById($id);
+ }
+
+ /**
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetByIdEnriched()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataView = AccountDataGenerator::factory()->builAccountDataView();
+ $result = new QueryResult([$accountDataView]);
+
+ $this->accountRepository->expects(self::once())->method('getByIdEnriched')
+ ->with($id)->willReturn($result);
+
+ $this->assertEquals($accountDataView, $this->accountService->getByIdEnriched($id));
+ }
+
+ /**
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetByIdEnrichedError()
+ {
+ $id = self::$faker->randomNumber();
+ $result = new QueryResult([]);
+
+ $this->accountRepository->expects(self::once())->method('getByIdEnriched')
+ ->with($id)->willReturn($result);
+
+ $this->expectException(NoSuchItemException::class);
+ $this->expectExceptionMessage('The account doesn\'t exist');
+
+ $this->accountService->getByIdEnriched($id);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateBulk()
+ {
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accounts = array_map(fn() => $accountDataGenerator->buildAccountUpdateDto(), range(0, 4));
+ $accountsId = range(0, 4);
+ $accountUpdateBulkDto = new AccountUpdateBulkDto($accountsId, $accounts);
+
+ $this->context->getUserData()->setIsAdminApp(true);
+
+ $consecutive = array_merge($accountsId, $accountsId);
+ sort($consecutive);
+
+ $this->accountRepository->expects(self::exactly(count($consecutive)))->method('getById')
+ ->withConsecutive(...array_map(fn($v) => [$v], $consecutive))
+ ->willReturn(new QueryResult([$accountDataGenerator->buildAccount()]));
+ $this->configService->expects(self::exactly(count($accountsId)))->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountItemsService->expects(self::exactly(count($accountsId)))->method('updateItems')
+ ->withConsecutive(...array_map(fn($v) => [$v, true, $accounts[$v]], $accountsId));
+
+ $this->accountService->updateBulk($accountUpdateBulkDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateBulkCannotChangePermissionsWithoutAdminApp()
+ {
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accounts = array_map(fn() => $accountDataGenerator->buildAccountUpdateDto(), range(0, 4));
+ $accountsId = range(0, 4);
+ $accountUpdateBulkDto = new AccountUpdateBulkDto($accountsId, $accounts);
+
+ $this->context->getUserData()->setIsAdminApp(false);
+
+ $this->accountRepository->expects(self::exactly(count($accountsId)))->method('getById')
+ ->withConsecutive(...array_map(fn($v) => [$v], $accountsId))
+ ->willReturn(new QueryResult([$accountDataGenerator->buildAccount()]));
+ $this->configService->expects(self::exactly(count($accountsId)))->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountItemsService->expects(self::exactly(count($accountsId)))->method('updateItems')
+ ->withConsecutive(...array_map(fn($v) => [$v, false, $accounts[$v]], $accountsId));
+
+ $this->accountService->updateBulk($accountUpdateBulkDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateBulkCanChangePermissionsWithAdminAcc()
+ {
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accounts = array_map(fn() => $accountDataGenerator->buildAccountUpdateDto(), range(0, 4));
+ $accountsId = range(0, 4);
+ $accountUpdateBulkDto = new AccountUpdateBulkDto($accountsId, $accounts);
+
+ $this->context->getUserData()->setIsAdminApp(false);
+ $this->context->getUserData()->setIsAdminAcc(true);
+ $this->context->getUserProfile()->setAccPermission(false);
+
+ $consecutive = array_merge($accountsId, $accountsId);
+ sort($consecutive);
+
+ $this->accountRepository->expects(self::exactly(count($consecutive)))->method('getById')
+ ->withConsecutive(...array_map(fn($v) => [$v], $consecutive))
+ ->willReturn(new QueryResult([$accountDataGenerator->buildAccount()]));
+ $this->configService->expects(self::exactly(count($accountsId)))->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountItemsService->expects(self::exactly(count($accountsId)))->method('updateItems')
+ ->withConsecutive(...array_map(fn($v) => [$v, true, $accounts[$v]], $accountsId));
+
+ $this->accountService->updateBulk($accountUpdateBulkDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testUpdateBulkCanChangePermissionsWithProfilePermission()
+ {
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accounts = array_map(fn() => $accountDataGenerator->buildAccountUpdateDto(), range(0, 4));
+ $accountsId = range(0, 4);
+ $accountUpdateBulkDto = new AccountUpdateBulkDto($accountsId, $accounts);
+
+ $this->context->getUserData()->setIsAdminApp(false);
+ $this->context->getUserData()->setIsAdminAcc(false);
+ $this->context->getUserProfile()->setAccPermission(true);
+
+ $consecutive = array_merge($accountsId, $accountsId);
+ sort($consecutive);
+
+ $this->accountRepository->expects(self::exactly(count($consecutive)))->method('getById')
+ ->withConsecutive(...array_map(fn($v) => [$v], $consecutive))
+ ->willReturn(new QueryResult([$accountDataGenerator->buildAccount()]));
+ $this->configService->expects(self::exactly(count($accountsId)))->method('getByParam')
+ ->with('masterPwd')->willReturn(self::$faker->password);
+ $this->accountItemsService->expects(self::exactly(count($accountsId)))->method('updateItems')
+ ->withConsecutive(...array_map(fn($v) => [$v, true, $accounts[$v]], $accountsId));
+
+ $this->accountService->updateBulk($accountUpdateBulkDto);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testWithUsersById()
+ {
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $users = $accountDataGenerator->buildItemData();
+ $accountEnrichedDto = $accountDataGenerator->buildAccountEnrichedDto();
+
+ $this->accountToUserRepository->expects(self::once())->method('getUsersByAccountId')
+ ->with($accountEnrichedDto->getId())
+ ->willReturn(new QueryResult($users));
+
+ $out = $this->accountService->withUsers($accountEnrichedDto);
+
+ $this->assertEquals($users, $out->getUsers());
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testDelete()
+ {
+ $id = self::$faker->randomNumber();
+ $password = self::$faker->password;
+ $account = AccountDataGenerator::factory()->buildAccount();
+ $accountHistoryCreateDto = new AccountHistoryCreateDto($account, false, true, $password);
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn($password);
+
+ $this->accountRepository->expects(self::once())->method('getById')
+ ->with($id)->willReturn(new QueryResult([$account]));
+ $this->accountHistoryService->expects(self::once())->method('create')
+ ->with($accountHistoryCreateDto);
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(1);
+
+ $this->accountRepository->expects(self::once())->method('delete')
+ ->with($id)->willReturn($queryResult);
+
+ $this->accountService->delete($id);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testDeleteNotFound()
+ {
+ $id = self::$faker->randomNumber();
+ $password = self::$faker->password;
+ $account = AccountDataGenerator::factory()->buildAccount();
+ $accountHistoryCreateDto = new AccountHistoryCreateDto($account, false, true, $password);
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn($password);
+
+ $this->accountRepository->expects(self::once())->method('getById')
+ ->with($id)->willReturn(new QueryResult([$account]));
+ $this->accountHistoryService->expects(self::once())->method('create')
+ ->with($accountHistoryCreateDto);
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(0);
+
+ $this->accountRepository->expects(self::once())->method('delete')
+ ->with($id)->willReturn($queryResult);
+
+ $this->expectException(NoSuchItemException::class);
+ $this->expectExceptionMessage('Account not found');
+
+ $this->accountService->delete($id);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function testIncrementViewCounter()
+ {
+ $id = self::$faker->randomNumber();
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(1);
+
+ $this->accountRepository->expects(self::once())->method('incrementViewCounter')
+ ->with($id)->willReturn($queryResult);
+
+ $this->assertTrue($this->accountService->incrementViewCounter($id));
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function testIncrementViewCounterNoRows()
+ {
+ $id = self::$faker->randomNumber();
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(0);
+
+ $this->accountRepository->expects(self::once())->method('incrementViewCounter')
+ ->with($id)->willReturn($queryResult);
+
+ $this->assertFalse($this->accountService->incrementViewCounter($id));
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetAllBasic()
+ {
+ $this->accountRepository->expects(self::once())->method('getAll');
+
+ $this->accountService->getAllBasic();
+ }
+
+ /**
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetDataForLink()
+ {
+ $id = self::$faker->randomNumber();
+
+ $queryResult = new QueryResult([new Simple()]);
+
+ $this->accountRepository->expects(self::once())->method('getDataForLink')
+ ->with($id)->willReturn($queryResult);
+
+ $this->accountService->getDataForLink($id);
+ }
+
+ /**
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetDataForLinkNotFound()
+ {
+ $id = self::$faker->randomNumber();
+
+ $queryResult = new QueryResult();
+
+ $this->accountRepository->expects(self::once())->method('getDataForLink')
+ ->with($id)->willReturn($queryResult);
+
+ $this->expectException(NoSuchItemException::class);
+ $this->expectExceptionMessage('The account doesn\'t exist');
+
+ $this->accountService->getDataForLink($id);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testRestoreRemoved()
+ {
+ $accountHistoryDto = AccountDataGenerator::factory()->buildAccountHistoryDto();
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(1);
+
+ $this->accountRepository->expects(self::once())->method('createRemoved')
+ ->with(
+ Account::restoreRemoved($accountHistoryDto, $this->context->getUserData()->getId())
+ )
+ ->willReturn($queryResult);
+
+ $this->accountService->restoreRemoved($accountHistoryDto);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testRestoreRemovedError()
+ {
+ $accountHistoryDto = AccountDataGenerator::factory()->buildAccountHistoryDto();
+
+ $queryResult = new QueryResult();
+
+ $this->accountRepository->expects(self::once())->method('createRemoved')
+ ->with(
+ Account::restoreRemoved($accountHistoryDto, $this->context->getUserData()->getId())
+ )
+ ->willReturn($queryResult);
+
+ $this->expectException(ServiceException::class);
+ $this->expectExceptionMessage('Error on restoring the account');
+
+ $this->accountService->restoreRemoved($accountHistoryDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testEditPassword()
+ {
+ $id = self::$faker->randomNumber();
+ $account = AccountDataGenerator::factory()->buildAccount();
+ $accountUpdateDto = AccountUpdateDto::fromAccount($account);
+
+ $password = self::$faker->password;
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn($password);
+
+ $this->accountRepository->expects(self::once())->method('getById')
+ ->with($id)->willReturn(new QueryResult([$account]));
+
+ $accountHistoryCreateDto = new AccountHistoryCreateDto($account, true, false, $password);
+
+ $this->accountHistoryService->expects(self::once())->method('create')
+ ->with($accountHistoryCreateDto);
+
+ $this->accountCryptService->expects(self::once())->method('getPasswordEncrypted')
+ ->with($accountUpdateDto->getPass())
+ ->willReturn(
+ new EncryptedPassword($accountUpdateDto->getPass(), $accountUpdateDto->getKey())
+ );
+
+ $this->accountRepository->expects(self::once())->method('editPassword')
+ ->with($id, Account::updatePassword($accountUpdateDto));
+
+ $this->accountService->editPassword($id, $accountUpdateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testRestoreModified()
+ {
+ $password = self::$faker->password;
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn($password);
+
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $account = $accountDataGenerator->buildAccount();
+
+ $accountHistoryDto = $accountDataGenerator->buildAccountHistoryDto();
+
+ $this->accountRepository->expects(self::once())->method('getById')
+ ->with($accountHistoryDto->getAccountId())->willReturn(new QueryResult([$account]));
+
+ $accountHistoryCreateDto = new AccountHistoryCreateDto($account, true, false, $password);
+
+ $this->accountHistoryService->expects(self::once())->method('create')
+ ->with($accountHistoryCreateDto);
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(1);
+
+ $this->accountRepository->expects(self::once())->method('restoreModified')
+ ->with(
+ $accountHistoryDto->getAccountId(),
+ Account::restoreModified($accountHistoryDto, $this->context->getUserData()->getId())
+ )
+ ->willReturn($queryResult);
+
+ $this->accountService->restoreModified($accountHistoryDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testRestoreModifiedError()
+ {
+ $password = self::$faker->password;
+
+ $this->configService->expects(self::once())->method('getByParam')
+ ->with('masterPwd')->willReturn($password);
+
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $account = $accountDataGenerator->buildAccount();
+
+ $accountHistoryDto = $accountDataGenerator->buildAccountHistoryDto();
+
+ $this->accountRepository->expects(self::once())->method('getById')
+ ->with($accountHistoryDto->getAccountId())->willReturn(new QueryResult([$account]));
+
+ $accountHistoryCreateDto = new AccountHistoryCreateDto($account, true, false, $password);
+
+ $this->accountHistoryService->expects(self::once())->method('create')
+ ->with($accountHistoryCreateDto);
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(0);
+
+ $this->accountRepository->expects(self::once())->method('restoreModified')
+ ->with(
+ $accountHistoryDto->getAccountId(),
+ Account::restoreModified($accountHistoryDto, $this->context->getUserData()->getId())
+ )
+ ->willReturn($queryResult);
+
+ $this->expectException(ServiceException::class);
+ $this->expectExceptionMessage('Error on restoring the account');
+
+ $this->accountService->restoreModified($accountHistoryDto);
+ }
+
+ public function testSearch()
+ {
+ $itemSearch = ItemSearchDataGenerator::factory()->buildItemSearchData();
+
+ $this->accountRepository->expects(self::once())->method('search')->with($itemSearch);
+
+ $this->accountService->search($itemSearch);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testWithTagsById()
+ {
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $tags = $accountDataGenerator->buildItemData();
+ $accountEnrichedDto = $accountDataGenerator->buildAccountEnrichedDto();
+
+ $this->accountToTagRepository->expects(self::once())->method('getTagsByAccountId')
+ ->with($accountEnrichedDto->getId())
+ ->willReturn(new QueryResult($tags));
+
+ $out = $this->accountService->withTags($accountEnrichedDto);
+
+ $this->assertEquals($tags, $out->getTags());
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testCreate()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountCreateDto = $accountDataGenerator->buildAccountCreateDto();
+
+ $this->context->getUserData()->setIsAdminApp(true);
+
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password);
+
+ $this->accountCryptService->expects(self::once())->method('getPasswordEncrypted')
+ ->with($accountCreateDto->getPass())
+ ->willReturn($encryptedPassword);
+
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn(null);
+
+ $queryResult = new QueryResult();
+ $queryResult->setLastId($id);
+
+ $this->accountRepository->expects(self::once())->method('create')
+ ->with(Account::create($accountCreateDto))
+ ->willReturn($queryResult);
+
+ $this->accountItemsService->expects(self::once())->method('addItems')
+ ->with(true, $id, $accountCreateDto->withEncryptedPassword($encryptedPassword));
+
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->create($accountCreateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testCreateCannotChangePermissions()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $userData = $this->context->getUserData();
+ $accountCreateDto = $accountDataGenerator->buildAccountCreateDto()->withUserId($userData->getId())
+ ->withUserGroupId($userData->getUserGroupId());
+
+ $userData->setIsAdminApp(false);
+
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password);
+
+ $this->accountCryptService->expects(self::once())->method('getPasswordEncrypted')
+ ->with($accountCreateDto->getPass())
+ ->willReturn($encryptedPassword);
+
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn(null);
+
+ $queryResult = new QueryResult();
+ $queryResult->setLastId($id);
+
+ $this->accountRepository->expects(self::once())->method('create')
+ ->with(Account::create($accountCreateDto))
+ ->willReturn($queryResult);
+
+ $this->accountItemsService->expects(self::once())->method('addItems')
+ ->with(false, $id, $accountCreateDto->withEncryptedPassword($encryptedPassword));
+
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->create($accountCreateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testCreateWithPrivateForUser()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountCreateDto = $accountDataGenerator->buildAccountCreateDto();
+ $itemPreset = new ItemPreset([
+ 'id' => self::$faker->randomNumber(),
+ 'type' => self::$faker->colorName,
+ 'userId' => self::$faker->randomNumber(),
+ 'userGroupId' => self::$faker->randomNumber(),
+ 'userProfileId' => self::$faker->randomNumber(),
+ 'fixed' => 1,
+ 'priority' => self::$faker->randomNumber(),
+ 'data' => serialize(new AccountPrivate(true, true)),
+ ]);
+
+ $userData = $this->context->getUserData();
+ $userData->setIsAdminApp(true);
+ $userData->setId($accountCreateDto->getUserId());
+
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password);
+
+ $this->accountCryptService->expects(self::once())->method('getPasswordEncrypted')
+ ->with($accountCreateDto->getPass())
+ ->willReturn($encryptedPassword);
+
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn($itemPreset);
+
+ $queryResult = new QueryResult();
+ $queryResult->setLastId($id);
+
+ $this->accountRepository->expects(self::once())->method('create')
+ ->with(
+ new Callback(function (Account $account) {
+ return $account->getIsPrivate() === 1 && $account->getIsPrivateGroup() === 0;
+ }),
+ )
+ ->willReturn($queryResult);
+
+ $this->accountItemsService->expects(self::once())->method('addItems')
+ ->with(
+ true,
+ $id,
+ $accountCreateDto->withEncryptedPassword($encryptedPassword)
+ ->withPrivate(true)
+ ->withPrivateGroup(false)
+ );
+
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->create($accountCreateDto);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ */
+ public function testCreateWithPrivateForGroup()
+ {
+ $id = self::$faker->randomNumber();
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $accountCreateDto = $accountDataGenerator->buildAccountCreateDto();
+ $itemPreset = new ItemPreset([
+ 'id' => self::$faker->randomNumber(),
+ 'type' => self::$faker->colorName,
+ 'userId' => self::$faker->randomNumber(),
+ 'userGroupId' => self::$faker->randomNumber(),
+ 'userProfileId' => self::$faker->randomNumber(),
+ 'fixed' => 1,
+ 'priority' => self::$faker->randomNumber(),
+ 'data' => serialize(new AccountPrivate(true, true)),
+ ]);
+
+ $userData = $this->context->getUserData();
+ $userData->setIsAdminApp(true);
+ $userData->setUserGroupId($accountCreateDto->getUserGroupId());
+
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password);
+
+ $this->accountCryptService->expects(self::once())->method('getPasswordEncrypted')
+ ->with($accountCreateDto->getPass())
+ ->willReturn($encryptedPassword);
+
+ $this->itemPresetService->expects(self::once())->method('getForCurrentUser')
+ ->with(ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE)
+ ->willReturn($itemPreset);
+
+ $queryResult = new QueryResult();
+ $queryResult->setLastId($id);
+
+ $this->accountRepository->expects(self::once())->method('create')
+ ->with(
+ new Callback(function (Account $account) {
+ return $account->getIsPrivate() === 0 && $account->getIsPrivateGroup() === 1;
+ }),
+ )
+ ->willReturn($queryResult);
+
+ $this->accountItemsService->expects(self::once())->method('addItems')
+ ->with(
+ true,
+ $id,
+ $accountCreateDto->withEncryptedPassword($encryptedPassword)
+ ->withPrivate(false)
+ ->withPrivateGroup(true)
+ );
+
+ $this->accountPresetService->expects(self::once())->method('addPresetPermissions')->with($id);
+
+ $this->accountService->create($accountCreateDto);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetTotalNumAccounts()
+ {
+ $num = self::$faker->randomNumber();
+
+ $queryResult = new QueryResult([new Simple(['num' => $num])]);
+
+ $this->accountRepository->expects(self::once())->method('getTotalNumAccounts')
+ ->willReturn($queryResult);
+
+ $this->assertEquals($num, $this->accountService->getTotalNumAccounts());
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetPasswordHistoryForId()
+ {
+ $id = self::$faker->randomNumber();
+
+ $this->accountRepository->expects(self::once())->method('getPasswordHistoryForId')
+ ->with($id)->willReturn(new QueryResult([new Simple()]));
+
+ $this->accountService->getPasswordHistoryForId($id);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Infrastructure\Common\Repositories\NoSuchItemException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetPasswordHistoryForIdNotFound()
+ {
+ $id = self::$faker->randomNumber();
+
+ $this->accountRepository->expects(self::once())->method('getPasswordHistoryForId')
+ ->with($id)->willReturn(new QueryResult([]));
+
+ $this->expectException(NoSuchItemException::class);
+ $this->expectExceptionMessage('The account doesn\'t exist');
+
+ $this->accountService->getPasswordHistoryForId($id);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testGetAccountsPassData()
+ {
+ $this->accountRepository->expects(self::once())->method('getAccountsPassData')
+ ->willReturn(new QueryResult([new Simple()]));
+
+ $this->accountService->getAccountsPassData();
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testDeleteByIdBatch()
+ {
+ $ids = array_map(fn() => self::$faker->randomNumber(), range(0, 4));
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(1);
+
+ $this->accountRepository->expects(self::once())->method('deleteByIdBatch')
+ ->with($ids)->willReturn($queryResult);
+
+ $this->accountService->deleteByIdBatch($ids);
+ }
+
+ /**
+ * @throws \SP\Domain\Common\Services\ServiceException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testDeleteByIdBatchError()
+ {
+ $ids = array_map(fn() => self::$faker->randomNumber(), range(0, 4));
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(0);
+
+ $this->accountRepository->expects(self::once())->method('deleteByIdBatch')
+ ->with($ids)->willReturn($queryResult);
+
+ $this->expectException(ServiceException::class);
+ $this->expectExceptionMessage('Error while deleting the accounts');
+
+ $this->accountService->deleteByIdBatch($ids);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testWithUserGroupsById()
+ {
+ $accountDataGenerator = AccountDataGenerator::factory();
+ $userGroups = $accountDataGenerator->buildItemData();
+ $accountEnrichedDto = $accountDataGenerator->buildAccountEnrichedDto();
+
+ $this->accountToUserGroupRepository->expects(self::once())->method('getUserGroupsByAccountId')
+ ->with($accountEnrichedDto->getId())
+ ->willReturn(new QueryResult($userGroups));
+
+ $out = $this->accountService->withUserGroups($accountEnrichedDto);
+
+ $this->assertEquals($userGroups, $out->getUserGroups());
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function testIncrementDecryptCounter()
+ {
+ $id = self::$faker->randomNumber();
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(1);
+
+ $this->accountRepository->expects(self::once())->method('incrementDecryptCounter')
+ ->with($id)->willReturn($queryResult);
+
+ $this->assertTrue($this->accountService->incrementDecryptCounter($id));
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function testIncrementDecryptCounterNoRows()
+ {
+ $id = self::$faker->randomNumber();
+
+ $queryResult = new QueryResult();
+ $queryResult->setAffectedNumRows(0);
+
+ $this->accountRepository->expects(self::once())->method('incrementDecryptCounter')
+ ->with($id)->willReturn($queryResult);
+
+ $this->assertFalse($this->accountService->incrementDecryptCounter($id));
+ }
+
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ $methods = array_diff(get_class_methods(AccountRepositoryStub::class), ['transactionAware']);
+
+ $this->accountRepository = $this->createPartialMock(AccountRepositoryStub::class, $methods);
+ $this->accountToUserGroupRepository = $this->createMock(AccountToUserGroupRepositoryInterface::class);
+ $this->accountToUserRepository = $this->createMock(AccountToUserRepositoryInterface::class);
+ $this->accountToTagRepository = $this->createMock(AccountToTagRepositoryInterface::class);
+ $this->itemPresetService = $this->createMock(ItemPresetServiceInterface::class);
+ $this->accountHistoryService = $this->createMock(AccountHistoryServiceInterface::class);
+ $this->configService = $this->createMock(ConfigServiceInterface::class);
+ $this->accountCryptService = $this->createMock(AccountCryptServiceInterface::class);
+ $this->accountItemsService = $this->createMock(AccountItemsServiceInterface::class);
+ $this->accountPresetService = $this->createMock(AccountPresetServiceInterface::class);
+
+ $this->accountService = new AccountService(
+ $this->application,
+ $this->accountRepository,
+ $this->accountToUserGroupRepository,
+ $this->accountToUserRepository,
+ $this->accountToTagRepository,
+ $this->itemPresetService,
+ $this->accountHistoryService,
+ $this->accountItemsService,
+ $this->accountPresetService,
+ $this->configService,
+ $this->accountCryptService
+ );
+ }
+}
diff --git a/tests/SP/Generators/AccountDataGenerator.php b/tests/SP/Generators/AccountDataGenerator.php
index 94685d92..67e1416a 100644
--- a/tests/SP/Generators/AccountDataGenerator.php
+++ b/tests/SP/Generators/AccountDataGenerator.php
@@ -24,35 +24,39 @@
namespace SP\Tests\Generators;
-use SP\DataModel\AccountVData;
use SP\DataModel\ItemData;
+use SP\Domain\Account\Dtos\AccountCreateDto;
use SP\Domain\Account\Dtos\AccountEnrichedDto;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Account\Dtos\AccountHistoryDto;
+use SP\Domain\Account\Dtos\AccountUpdateDto;
+use SP\Domain\Account\Models\Account;
+use SP\Domain\Account\Models\AccountDataView;
+use SP\Domain\Account\Models\AccountSearchView;
+use SP\Domain\Common\Models\Simple;
/**
* Class AccountDataGenerator
*/
final class AccountDataGenerator extends DataGenerator
{
- public function buildAccountEnrichedData(): AccountEnrichedDto
+ public function buildAccountEnrichedDto(): AccountEnrichedDto
{
- $out = new AccountEnrichedDto(AccountVData::buildFromSimpleModel($this->buildAccountData()));
- $out->setUsers($this->buildItemData());
- $out->setTags($this->buildItemData());
- $out->setUserGroups($this->buildItemData());
+ $out = new AccountEnrichedDto($this->builAccountDataView());
+ $out = $out->withUsers($this->buildItemData());
+ $out = $out->withTags($this->buildItemData());
- return $out;
+ return $out->withUserGroups($this->buildItemData());
}
- public function buildAccountData(): SimpleModel
+ public function builAccountDataView(): AccountDataView
{
- return new SimpleModel($this->getAccountData());
+ return new AccountDataView($this->getAccountProperties());
}
/**
* @return array
*/
- private function getAccountData(): array
+ private function getAccountProperties(): array
{
return [
'id' => $this->faker->randomNumber(),
@@ -100,9 +104,28 @@ final class AccountDataGenerator extends DataGenerator
);
}
- public function buildAccountHistoryData(): SimpleModel
+ public function builAccountSearchView(): AccountSearchView
{
- return new SimpleModel([
+ return new AccountSearchView(
+ array_merge(
+ [
+ 'num_files' => $this->faker->randomNumber(),
+ 'publicLinkDateExpire' => $this->faker->unixTime,
+ 'publicLinkTotalCountViews' => $this->faker->randomNumber(),
+ ],
+ $this->getAccountProperties()
+ )
+ );
+ }
+
+ public function buildAccount(): Account
+ {
+ return new Account($this->getAccountProperties());
+ }
+
+ public function buildAccountHistoryData(): Simple
+ {
+ return new Simple([
'id' => $this->faker->randomNumber(),
'accountId' => $this->faker->randomNumber(),
'name' => $this->faker->name,
@@ -123,15 +146,89 @@ final class AccountDataGenerator extends DataGenerator
]);
}
- public function builAccountSearchVData(): SimpleModel
+ public function buildAccountUpdateDto(): AccountUpdateDto
{
- return new SimpleModel(array_merge(
- [
- 'num_files' => $this->faker->randomNumber(),
- 'publicLinkDateExpire' => $this->faker->unixTime,
- 'publicLinkTotalCountViews' => $this->faker->randomNumber(),
- ],
- $this->getAccountData()
- ));
+ return new AccountUpdateDto(
+ name : $this->faker->name,
+ login : $this->faker->userName,
+ clientId : $this->faker->randomNumber(),
+ categoryId : $this->faker->randomNumber(),
+ pass : $this->faker->password,
+ userId : $this->faker->randomNumber(),
+ key : $this->faker->password,
+ url : $this->faker->url,
+ notes : $this->faker->text,
+ userEditId : $this->faker->randomNumber(),
+ isPrivate : $this->faker->boolean,
+ isPrivateGroup : $this->faker->boolean,
+ passDateChange : $this->faker->unixTime,
+ parentId : $this->faker->randomNumber(),
+ userGroupId : $this->faker->randomNumber(),
+ otherUserEdit : $this->faker->boolean,
+ otherUserGroupEdit: $this->faker->boolean,
+ usersView : array_map(fn() => $this->faker->randomNumber(), range(0, 4)),
+ usersEdit : array_map(fn() => $this->faker->randomNumber(), range(0, 4)),
+ userGroupsView : array_map(fn() => $this->faker->randomNumber(), range(0, 4)),
+ userGroupsEdit : array_map(fn() => $this->faker->randomNumber(), range(0, 4)),
+ tags : array_map(fn() => $this->faker->randomNumber(), range(0, 4))
+ );
+ }
+
+ public function buildAccountCreateDto(): AccountCreateDto
+ {
+ return new AccountCreateDto(
+ name : $this->faker->name,
+ login : $this->faker->userName,
+ clientId : $this->faker->randomNumber(),
+ categoryId : $this->faker->randomNumber(),
+ pass : $this->faker->password,
+ userId : $this->faker->randomNumber(),
+ url : $this->faker->url,
+ notes : $this->faker->text,
+ userEditId : $this->faker->randomNumber(),
+ isPrivate : $this->faker->boolean,
+ isPrivateGroup : $this->faker->boolean,
+ passDateChange : $this->faker->unixTime,
+ parentId : $this->faker->randomNumber(),
+ userGroupId : $this->faker->randomNumber(),
+ otherUserEdit : $this->faker->boolean,
+ otherUserGroupEdit: $this->faker->boolean,
+ usersView : array_map(fn() => $this->faker->randomNumber(), range(0, 4)),
+ usersEdit : array_map(fn() => $this->faker->randomNumber(), range(0, 4)),
+ userGroupsView : array_map(fn() => $this->faker->randomNumber(), range(0, 4)),
+ userGroupsEdit : array_map(fn() => $this->faker->randomNumber(), range(0, 4)),
+ tags : array_map(fn() => $this->faker->randomNumber(), range(0, 4))
+ );
+ }
+
+ public function buildAccountHistoryDto(): AccountHistoryDto
+ {
+ return new AccountHistoryDto(
+ accountId : $this->faker->randomNumber(),
+ isDelete : $this->faker->boolean,
+ isModify : $this->faker->boolean,
+ dateAdd : $this->faker->unixTime,
+ dateEdit : $this->faker->unixTime,
+ passDate : $this->faker->unixTime,
+ countView : $this->faker->randomNumber(),
+ countDecrypt : $this->faker->randomNumber(),
+ name : $this->faker->name,
+ login : $this->faker->userName,
+ clientId : $this->faker->randomNumber(),
+ categoryId : $this->faker->randomNumber(),
+ pass : $this->faker->password,
+ userId : $this->faker->randomNumber(),
+ key : $this->faker->password,
+ url : $this->faker->url,
+ notes : $this->faker->text,
+ userEditId : $this->faker->randomNumber(),
+ isPrivate : $this->faker->boolean,
+ isPrivateGroup : $this->faker->boolean,
+ passDateChange : $this->faker->unixTime,
+ parentId : $this->faker->randomNumber(),
+ userGroupId : $this->faker->randomNumber(),
+ otherUserEdit : $this->faker->boolean,
+ otherUserGroupEdit: $this->faker->boolean,
+ );
}
}
diff --git a/tests/SP/Generators/CustomFieldGenerator.php b/tests/SP/Generators/CustomFieldGenerator.php
index 61f6ca6b..e0d9ae6e 100644
--- a/tests/SP/Generators/CustomFieldGenerator.php
+++ b/tests/SP/Generators/CustomFieldGenerator.php
@@ -24,14 +24,14 @@
namespace SP\Tests\Generators;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
/**
* Class CustomFieldGenerator
*/
final class CustomFieldGenerator extends DataGenerator
{
- public function buildSimpleModel(bool $useEncryption = false): SimpleModel
+ public function buildSimpleModel(bool $useEncryption = false): Simple
{
$data = null;
$key = null;
@@ -41,7 +41,7 @@ final class CustomFieldGenerator extends DataGenerator
$key = $this->faker->sha1;
}
- return new SimpleModel([
+ return new Simple([
'required' => $this->faker->boolean,
'showInList' => $this->faker->boolean,
'help' => $this->faker->text,
diff --git a/tests/SP/Generators/FileDataGenerator.php b/tests/SP/Generators/FileDataGenerator.php
index 5a8337d4..c97d54a6 100644
--- a/tests/SP/Generators/FileDataGenerator.php
+++ b/tests/SP/Generators/FileDataGenerator.php
@@ -24,30 +24,30 @@
namespace SP\Tests\Generators;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
/**
* Class FileDataGenerator
*/
final class FileDataGenerator extends DataGenerator
{
- public function buildFileExtData(): SimpleModel
+ public function buildFileExtData(): Simple
{
- return new SimpleModel(
+ return new Simple(
array_merge(
- $this->buildFileData()->toArray(),
+ $this->buildFileData()->toArray(null, null, true),
['clientName' => $this->faker->name, 'accountName' => $this->faker->name]
)
);
}
- public function buildFileData(): SimpleModel
+ public function buildFileData(): Simple
{
- return new SimpleModel([
+ return new Simple([
'id' => $this->faker->randomNumber(),
'accountId' => $this->faker->randomNumber(),
'name' => $this->faker->colorName,
- 'type' => $this->faker->mimeType,
+ 'type' => 'image/jpeg',
'content' => $this->faker->image(null, 32, 32),
'extension' => $this->faker->fileExtension,
'thumb' => $this->faker->image(null, 32, 32),
diff --git a/tests/SP/Generators/ItemPresetDataGenerator.php b/tests/SP/Generators/ItemPresetDataGenerator.php
index dd8376e6..890894e8 100644
--- a/tests/SP/Generators/ItemPresetDataGenerator.php
+++ b/tests/SP/Generators/ItemPresetDataGenerator.php
@@ -24,29 +24,30 @@
namespace SP\Tests\Generators;
+use SP\DataModel\ItemPreset\AccountPrivate;
use SP\DataModel\ItemPreset\Password;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Account\Models\ItemPreset;
/**
* Class ItemPresetDataGenerator
*/
final class ItemPresetDataGenerator extends DataGenerator
{
- public function buildItemPresetData(object $data): SimpleModel
+ public function buildItemPresetData(object $data): ItemPreset
{
- return new SimpleModel([
+ return new ItemPreset([
'id' => $this->faker->randomNumber(),
'type' => $this->faker->colorName,
'userId' => $this->faker->randomNumber(),
'userGroupId' => $this->faker->randomNumber(),
'userProfileId' => $this->faker->randomNumber(),
- 'fixed' => $this->faker->numberBetween(0, 1),
+ 'fixed' => (int)$this->faker->boolean,
'priority' => $this->faker->randomNumber(),
'data' => serialize($data),
]);
}
- public function buildPasswordPreset(): Password
+ public function buildPassword(): Password
{
return new Password(
$this->faker->numberBetween(1, 12),
@@ -61,4 +62,9 @@ final class ItemPresetDataGenerator extends DataGenerator
$this->faker->regexify('abc123')
);
}
+
+ public function buildAccountPrivate(): AccountPrivate
+ {
+ return new AccountPrivate($this->faker->boolean, $this->faker->boolean);
+ }
}
diff --git a/tests/SP/Infrastructure/Account/Repositories/AccountFileRepositoryTest.php b/tests/SP/Infrastructure/Account/Repositories/AccountFileRepositoryTest.php
index 5af5f0e4..89c94a12 100644
--- a/tests/SP/Infrastructure/Account/Repositories/AccountFileRepositoryTest.php
+++ b/tests/SP/Infrastructure/Account/Repositories/AccountFileRepositoryTest.php
@@ -29,7 +29,7 @@ use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\MockObject\MockObject;
use SP\DataModel\FileData;
use SP\DataModel\ItemSearchData;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
use SP\Infrastructure\Account\Repositories\AccountFileRepository;
use SP\Infrastructure\Database\DatabaseInterface;
use SP\Infrastructure\Database\QueryData;
@@ -62,7 +62,7 @@ class AccountFileRepositoryTest extends UnitaryTestCase
return array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -131,7 +131,7 @@ class AccountFileRepositoryTest extends UnitaryTestCase
$query = $arg->getQuery();
return $query->getBindValues()['accountId'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($query->getStatement());
}
);
@@ -181,7 +181,7 @@ class AccountFileRepositoryTest extends UnitaryTestCase
$query = $arg->getQuery();
return $query->getBindValues()['id'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($query->getStatement());
}
);
@@ -207,7 +207,7 @@ class AccountFileRepositoryTest extends UnitaryTestCase
&& $params['clientName'] === $searchStringLike
&& $params['accountName'] === $searchStringLike
&& $params['type'] === $searchStringLike
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
diff --git a/tests/SP/Infrastructure/Account/Repositories/AccountHistoryRepositoryTest.php b/tests/SP/Infrastructure/Account/Repositories/AccountHistoryRepositoryTest.php
index 7c66701f..fd032bba 100644
--- a/tests/SP/Infrastructure/Account/Repositories/AccountHistoryRepositoryTest.php
+++ b/tests/SP/Infrastructure/Account/Repositories/AccountHistoryRepositoryTest.php
@@ -28,11 +28,9 @@ use Aura\SqlQuery\QueryFactory;
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\MockObject\MockObject;
use SP\DataModel\ItemSearchData;
-use SP\Domain\Account\Adapters\AccountData;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
use SP\Domain\Account\Dtos\EncryptedPassword;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
use SP\Infrastructure\Account\Repositories\AccountHistoryRepository;
use SP\Infrastructure\Database\DatabaseInterface;
use SP\Infrastructure\Database\QueryData;
@@ -57,15 +55,15 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) use ($id) {
return $arg->getQuery()->getBindValues()['id'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
$this->database->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ ->method('doSelect')
+ ->with($callback)
+ ->willReturn(new QueryResult());
$this->accountHistoryRepository->getById($id);
}
@@ -77,15 +75,15 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) use ($id) {
return $arg->getQuery()->getBindValues()['id'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
$this->database->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ ->method('doSelect')
+ ->with($callback)
+ ->willReturn(new QueryResult());
$this->accountHistoryRepository->getHistoryForAccount($id);
}
@@ -105,15 +103,15 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
return array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
$this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn(new QueryResult());
+ ->method('doQuery')
+ ->with($callback)
+ ->willReturn(new QueryResult());
$this->accountHistoryRepository->deleteByIdBatch($ids);
}
@@ -125,7 +123,7 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
public function testDeleteByIdBatchWithoutIds(): void
{
$this->database->expects(self::never())
- ->method('doQuery');
+ ->method('doQuery');
$this->accountHistoryRepository->deleteByIdBatch([]);
}
@@ -136,33 +134,30 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
*/
public function testUpdatePassword(): void
{
- $accountPasswordRequest = new AccountPasswordRequest(
- self::$faker->randomNumber(),
- new EncryptedPassword(self::$faker->password, self::$faker->password),
- self::$faker->sha1
- );
+ $id = self::$faker->randomNumber();
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password, self::$faker->sha1);
$expected = new QueryResult();
$expected->setAffectedNumRows(1);
$callback = new Callback(
- static function (QueryData $arg) use ($accountPasswordRequest) {
+ static function (QueryData $arg) use ($id, $encryptedPassword) {
$params = $arg->getQuery()->getBindValues();
- return $params['pass'] === $accountPasswordRequest->getEncryptedPassword()->getPass()
- && $params['key'] === $accountPasswordRequest->getEncryptedPassword()->getKey()
- && $params['id'] === $accountPasswordRequest->getId()
- && $params['mPassHash'] === $accountPasswordRequest->getHash()
+ return $params['pass'] === $encryptedPassword->getPass()
+ && $params['key'] === $encryptedPassword->getKey()
+ && $params['mPassHash'] === $encryptedPassword->getHash()
+ && $params['id'] === $id
&& !empty($arg->getQuery()->getStatement());
}
);
$this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ ->method('doQuery')
+ ->with($callback)
+ ->willReturn($expected);
- $this->assertTrue($this->accountHistoryRepository->updatePassword($accountPasswordRequest));
+ $this->assertTrue($this->accountHistoryRepository->updatePassword($id, $encryptedPassword));
}
public function testSearch(): void
@@ -176,7 +171,7 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
return $params['name'] === $searchStringLike
&& $params['clientName'] === $searchStringLike
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -195,7 +190,7 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) {
return count($arg->getQuery()->getBindValues()) === 0
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -209,12 +204,11 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
$this->accountHistoryRepository->search(new ItemSearchData());
}
-
public function testGetAccountsPassData(): void
{
$callback = new Callback(
function (QueryData $arg) {
- return $arg->getMapClassName() === SimpleModel::class
+ return $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -242,7 +236,7 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) use ($dto) {
$params = $arg->getQuery()->getBindValues();
- $accountData = $dto->getAccountData();
+ $accountData = $dto->getAccount();
return $params['clientId'] === $accountData->getClientId()
&& $params['categoryId'] === $accountData->getCategoryId()
@@ -275,9 +269,9 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
);
$this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ ->method('doQuery')
+ ->with($callback)
+ ->willReturn($expected);
$this->assertEquals($expected->getLastId(), $this->accountHistoryRepository->create($dto));
}
@@ -285,7 +279,7 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
private function buildAccountHistoryCreateDto(): AccountHistoryCreateDto
{
return new AccountHistoryCreateDto(
- AccountData::buildFromSimpleModel(AccountDataGenerator::factory()->buildAccountData()),
+ AccountDataGenerator::factory()->buildAccount(),
self::$faker->boolean(),
self::$faker->boolean(),
self::$faker->sha1,
@@ -310,9 +304,9 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
);
$this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ ->method('doQuery')
+ ->with($callback)
+ ->willReturn($expected);
$this->assertTrue($this->accountHistoryRepository->delete($id));
}
@@ -335,9 +329,9 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
);
$this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ ->method('doQuery')
+ ->with($callback)
+ ->willReturn($expected);
$this->assertFalse($this->accountHistoryRepository->delete($id));
}
@@ -346,7 +340,7 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
{
$callback = new Callback(
static function (QueryData $arg) {
- return $arg->getMapClassName() === SimpleModel::class
+ return $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -375,15 +369,15 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
return array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
$this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn(new QueryResult());
+ ->method('doQuery')
+ ->with($callback)
+ ->willReturn(new QueryResult());
$this->accountHistoryRepository->deleteByAccountIdBatch($ids);
}
@@ -395,12 +389,11 @@ class AccountHistoryRepositoryTest extends UnitaryTestCase
public function testDeleteByAccountIdBatchWithoutIds(): void
{
$this->database->expects(self::never())
- ->method('doQuery');
+ ->method('doQuery');
$this->accountHistoryRepository->deleteByAccountIdBatch([]);
}
-
protected function setUp(): void
{
parent::setUp();
diff --git a/tests/SP/Infrastructure/Account/Repositories/AccountRepositoryTest.php b/tests/SP/Infrastructure/Account/Repositories/AccountRepositoryTest.php
index d4d90fb4..eb57c05e 100644
--- a/tests/SP/Infrastructure/Account/Repositories/AccountRepositoryTest.php
+++ b/tests/SP/Infrastructure/Account/Repositories/AccountRepositoryTest.php
@@ -27,17 +27,16 @@ namespace SP\Tests\Infrastructure\Account\Repositories;
use Aura\SqlQuery\QueryFactory;
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\MockObject\MockObject;
-use SP\DataModel\AccountHistoryData;
use SP\DataModel\ItemSearchData;
-use SP\Domain\Account\Dtos\AccountPasswordRequest;
-use SP\Domain\Account\Dtos\AccountRequest;
use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\Account;
+use SP\Domain\Account\Models\AccountDataView;
+use SP\Domain\Account\Models\AccountSearchView;
use SP\Domain\Account\Ports\AccountFilterUserInterface;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
use SP\Infrastructure\Account\Repositories\AccountRepository;
use SP\Infrastructure\Database\DatabaseInterface;
use SP\Infrastructure\Database\QueryData;
-use SP\Infrastructure\Database\QueryResult;
use SP\Tests\Generators\AccountDataGenerator;
use SP\Tests\UnitaryTestCase;
@@ -56,14 +55,11 @@ class AccountRepositoryTest extends UnitaryTestCase
{
$callback = new Callback(
static function (QueryData $arg) {
- return $arg->getMapClassName() === SimpleModel::class && !empty($arg->getQuery());
+ return $arg->getMapClassName() === Simple::class && !empty($arg->getQuery());
}
);
- $this->database->expects(self::once())
- ->method('doSelect')
- ->with($callback, false)
- ->willReturn(new QueryResult([new SimpleModel(['num' => 1])]));
+ $this->database->expects(self::once())->method('doSelect')->with($callback, false);
$this->accountRepository->getTotalNumAccounts();
}
@@ -73,11 +69,12 @@ class AccountRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) {
$query = $arg->getQuery();
+ $params = $query->getBindValues();
- return
- $query->getBindValues()['id'] === 1
- && $arg->getMapClassName() === SimpleModel::class
- && !empty($query->getStatement());
+ return count($params) === 1
+ && $params['id'] === 1
+ && $arg->getMapClassName() === Account::class
+ && !empty($query->getStatement());
}
);
@@ -85,10 +82,7 @@ class AccountRepositoryTest extends UnitaryTestCase
->expects(self::once())
->method('buildFilter');
- $this->database->expects(self::once())
- ->method('doSelect')
- ->with($callback, false)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback, false);
$this->accountRepository->getPasswordForId(1);
}
@@ -98,11 +92,12 @@ class AccountRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) {
$query = $arg->getQuery();
+ $params = $query->getBindValues();
- return
- $query->getBindValues()['id'] === 1
- && $arg->getMapClassName() === SimpleModel::class
- && !empty($query->getStatement());
+ return count($params) === 1
+ && $params['accountId'] === 1
+ && $arg->getMapClassName() === Simple::class
+ && !empty($query->getStatement());
}
);
@@ -110,10 +105,7 @@ class AccountRepositoryTest extends UnitaryTestCase
->expects(self::once())
->method('buildFilterHistory');
- $this->database->expects(self::once())
- ->method('doSelect')
- ->with($callback, false)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback, false);
$this->accountRepository->getPasswordHistoryForId(1);
}
@@ -126,21 +118,19 @@ class AccountRepositoryTest extends UnitaryTestCase
{
$id = 1;
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
-
$callback = new Callback(
static function (QueryData $arg) use ($id) {
- return $arg->getQuery()->getBindValues()['id'] === $id && !empty($arg->getQuery()->getStatement());
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 1
+ && $params['id'] === $id
+ && !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertTrue($this->accountRepository->incrementDecryptCounter($id));
+ $this->accountRepository->incrementDecryptCounter($id);
}
/**
@@ -151,21 +141,19 @@ class AccountRepositoryTest extends UnitaryTestCase
{
$id = 1;
- $expected = new QueryResult();
- $expected->setAffectedNumRows(0);
-
$callback = new Callback(
static function (QueryData $arg) use ($id) {
- return $arg->getQuery()->getBindValues()['id'] === $id && !empty($arg->getQuery());
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 1
+ && $params['id'] === $id
+ && !empty($arg->getQuery());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertFalse($this->accountRepository->incrementDecryptCounter($id));
+ $this->accountRepository->incrementDecryptCounter($id);
}
/**
@@ -174,62 +162,38 @@ class AccountRepositoryTest extends UnitaryTestCase
*/
public function testCreate(): void
{
- $accountRequest = $this->buildAccountRequest();
-
- $expected = new QueryResult();
- $expected->setLastId(1);
+ $account = AccountDataGenerator::factory()->buildAccount();
$callback = new Callback(
- static function (QueryData $arg) use ($accountRequest) {
+ static function (QueryData $arg) use ($account) {
$params = $arg->getQuery()->getBindValues();
- return $params['clientId'] === $accountRequest->clientId
- && $params['categoryId'] === $accountRequest->categoryId
- && $params['name'] === $accountRequest->name
- && $params['login'] === $accountRequest->login
- && $params['url'] === $accountRequest->url
- && $params['pass'] === $accountRequest->pass
- && $params['key'] === $accountRequest->key
- && $params['notes'] === $accountRequest->notes
- && $params['userId'] === $accountRequest->userId
- && $params['userGroupId'] === $accountRequest->userGroupId
- && $params['isPrivate'] === $accountRequest->isPrivate
- && $params['isPrivateGroup'] === $accountRequest->isPrivateGroup
- && $params['passDateChange'] === $accountRequest->passDateChange
- && $params['parentId'] === $accountRequest->parentId
+ return count($params) === 18
+ && $params['userId'] === $account->getUserId()
+ && $params['userGroupId'] === $account->getUserGroupId()
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['name'] === $account->getName()
+ && $params['clientId'] === $account->getClientId()
+ && $params['categoryId'] === $account->getCategoryId()
+ && $params['login'] === $account->getLogin()
+ && $params['url'] === $account->getUrl()
+ && $params['pass'] === $account->getPass()
+ && $params['key'] === $account->getKey()
+ && $params['notes'] === $account->getNotes()
+ && $params['isPrivate'] === $account->getIsPrivate()
+ && $params['isPrivateGroup'] === $account->getIsPrivateGroup()
+ && $params['passDate'] === $account->getPassDate()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['parentId'] === $account->getParentId()
+ && $params['otherUserEdit'] === $account->getOtherUserEdit()
+ && $params['otherUserGroupEdit'] === $account->getOtherUserGroupEdit()
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertEquals($expected->getLastId(), $this->accountRepository->create($accountRequest));
- }
-
- private function buildAccountRequest(): AccountRequest
- {
- $accountRequest = new AccountRequest();
- $accountRequest->id = self::$faker->randomNumber();
- $accountRequest->name = self::$faker->name;
- $accountRequest->login = self::$faker->userName;
- $accountRequest->url = self::$faker->url;
- $accountRequest->notes = self::$faker->text;
- $accountRequest->userEditId = self::$faker->randomNumber();
- $accountRequest->passDateChange = self::$faker->unixTime;
- $accountRequest->clientId = self::$faker->randomNumber();
- $accountRequest->categoryId = self::$faker->randomNumber();
- $accountRequest->isPrivate = self::$faker->numberBetween(0, 1);
- $accountRequest->isPrivateGroup = self::$faker->numberBetween(0, 1);
- $accountRequest->parentId = self::$faker->randomNumber();
- $accountRequest->userId = self::$faker->randomNumber();
- $accountRequest->userGroupId = self::$faker->randomNumber();
- $accountRequest->key = self::$faker->text;
- $accountRequest->pass = self::$faker->text;
-
- return $accountRequest;
+ $this->accountRepository->create($account);
}
/**
@@ -238,30 +202,25 @@ class AccountRepositoryTest extends UnitaryTestCase
*/
public function testEditPassword(): void
{
- $accountRequest = $this->buildAccountRequest();
-
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
+ $account = AccountDataGenerator::factory()->buildAccount();
$callback = new Callback(
- static function (QueryData $arg) use ($accountRequest) {
+ static function (QueryData $arg) use ($account) {
$params = $arg->getQuery()->getBindValues();
- return $params['pass'] === $accountRequest->pass
- && $params['key'] === $accountRequest->key
- && $params['userEditId'] === $accountRequest->userEditId
- && $params['passDateChange'] === $accountRequest->passDateChange
- && $params['id'] === $accountRequest->id
+ return count($params) === 5
+ && $params['pass'] === $account->getPass()
+ && $params['key'] === $account->getKey()
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['id'] === $account->getId()
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertEquals($expected->getAffectedNumRows(), $this->accountRepository->editPassword($accountRequest));
+ $this->accountRepository->editPassword($account->getId(), $account);
}
/**
@@ -270,32 +229,24 @@ class AccountRepositoryTest extends UnitaryTestCase
*/
public function testUpdatePassword(): void
{
- $accountPasswordRequest = new AccountPasswordRequest(
- self::$faker->randomNumber(),
- new EncryptedPassword(self::$faker->password, self::$faker->password),
- self::$faker->sha1
- );
-
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
+ $id = self::$faker->randomNumber();
+ $encryptedPassword = new EncryptedPassword(self::$faker->password, self::$faker->password);
$callback = new Callback(
- static function (QueryData $arg) use ($accountPasswordRequest) {
+ static function (QueryData $arg) use ($id, $encryptedPassword) {
$params = $arg->getQuery()->getBindValues();
- return $params['pass'] === $accountPasswordRequest->getEncryptedPassword()->getPass()
- && $params['key'] === $accountPasswordRequest->getEncryptedPassword()->getKey()
- && $params['id'] === $accountPasswordRequest->getId()
+ return count($params) === 3
+ && $params['pass'] === $encryptedPassword->getPass()
+ && $params['key'] === $encryptedPassword->getKey()
+ && $params['id'] === $id
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertTrue($this->accountRepository->updatePassword($accountPasswordRequest));
+ $this->accountRepository->updatePassword($id, $encryptedPassword);
}
/**
@@ -304,43 +255,38 @@ class AccountRepositoryTest extends UnitaryTestCase
*/
public function testEditRestore(): void
{
- $accountHistoryData =
- AccountHistoryData::buildFromSimpleModel(AccountDataGenerator::factory()->buildAccountHistoryData());
-
- $userId = 1;
-
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
+ $account = AccountDataGenerator::factory()->buildAccount();
$callback = new Callback(
- static function (QueryData $arg) use ($accountHistoryData, $userId) {
+ static function (QueryData $arg) use ($account) {
$params = $arg->getQuery()->getBindValues();
- return $params['id'] === $accountHistoryData->getAccountId()
- && $params['name'] === $accountHistoryData->getName()
- && $params['login'] === $accountHistoryData->getLogin()
- && $params['url'] === $accountHistoryData->getUrl()
- && $params['notes'] === $accountHistoryData->getNotes()
- && $params['userEditId'] === $userId
- && $params['passDateChange'] === $accountHistoryData->getPassDateChange()
- && $params['clientId'] === $accountHistoryData->getClientId()
- && $params['categoryId'] === $accountHistoryData->getCategoryId()
- && $params['isPrivate'] === $accountHistoryData->getIsPrivate()
- && $params['isPrivateGroup'] === $accountHistoryData->getIsPrivateGroup()
- && $params['parentId'] === $accountHistoryData->getParentId()
- && $params['userGroupId'] === $accountHistoryData->getUserGroupId()
- && $params['key'] === $accountHistoryData->getKey()
- && $params['pass'] === $accountHistoryData->getPass()
+ return count($params) === 18
+ && $params['id'] === $account->getId()
+ && $params['userId'] === $account->getUserId()
+ && $params['userGroupId'] === $account->getUserGroupId()
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['name'] === $account->getName()
+ && $params['clientId'] === $account->getClientId()
+ && $params['categoryId'] === $account->getCategoryId()
+ && $params['login'] === $account->getLogin()
+ && $params['url'] === $account->getUrl()
+ && $params['pass'] === $account->getPass()
+ && $params['key'] === $account->getKey()
+ && $params['notes'] === $account->getNotes()
+ && $params['isPrivate'] === $account->getIsPrivate()
+ && $params['isPrivateGroup'] === $account->getIsPrivateGroup()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['parentId'] === $account->getParentId()
+ && $params['otherUserGroupEdit'] === $account->getOtherUserGroupEdit()
+ && $params['otherUserEdit'] === $account->getOtherUserEdit()
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertTrue($this->accountRepository->editRestore($accountHistoryData, $userId));
+ $this->accountRepository->restoreModified($account->getId(), $account);
}
/**
@@ -350,8 +296,6 @@ class AccountRepositoryTest extends UnitaryTestCase
public function testDelete(): void
{
$id = 1;
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
$callback = new Callback(
static function (QueryData $arg) use ($id) {
@@ -360,12 +304,9 @@ class AccountRepositoryTest extends UnitaryTestCase
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertTrue($this->accountRepository->delete($id));
+ $this->accountRepository->delete($id);
}
/**
@@ -375,22 +316,20 @@ class AccountRepositoryTest extends UnitaryTestCase
public function testDeleteWithouResults(): void
{
$id = 1;
- $expected = new QueryResult();
- $expected->setAffectedNumRows(0);
$callback = new Callback(
static function (QueryData $arg) use ($id) {
- return $arg->getQuery()->getBindValues()['id'] === $id
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 1
+ && $params['id'] === $id
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertFalse($this->accountRepository->delete($id));
+ $this->accountRepository->delete($id);
}
/**
@@ -398,117 +337,110 @@ class AccountRepositoryTest extends UnitaryTestCase
*/
public function testUpdate(): void
{
- $accountRequest = $this->buildAccountRequest();
-
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
+ $account = AccountDataGenerator::factory()->buildAccount();
$callback = new Callback(
- static function (QueryData $arg) use ($accountRequest) {
+ static function (QueryData $arg) use ($account) {
$params = $arg->getQuery()->getBindValues();
- return $params['clientId'] === $accountRequest->clientId
- && $params['categoryId'] === $accountRequest->categoryId
- && $params['name'] === $accountRequest->name
- && $params['login'] === $accountRequest->login
- && $params['url'] === $accountRequest->url
- && $params['notes'] === $accountRequest->notes
- && $params['userEditId'] === $accountRequest->userEditId
- && $params['passDateChange'] === $accountRequest->passDateChange
- && $params['isPrivate'] === $accountRequest->isPrivate
- && $params['isPrivateGroup'] === $accountRequest->isPrivateGroup
- && $params['parentId'] === $accountRequest->parentId
- && $params['id'] === $accountRequest->id
+ return count($params) === 16
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['name'] === $account->getName()
+ && $params['clientId'] === $account->getClientId()
+ && $params['categoryId'] === $account->getCategoryId()
+ && $params['login'] === $account->getLogin()
+ && $params['url'] === $account->getUrl()
+ && $params['notes'] === $account->getNotes()
+ && $params['isPrivate'] === $account->getIsPrivate()
+ && $params['isPrivateGroup'] === $account->getIsPrivateGroup()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['parentId'] === $account->getParentId()
+ && $params['otherUserEdit'] === $account->getOtherUserEdit()
+ && $params['otherUserGroupEdit'] === $account->getOtherUserGroupEdit()
+ && $params['userGroupId'] === $account->getUserGroupId()
+ && $params['userId'] === $account->getUserId()
+ && $params['id'] === $account->getId()
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertEquals($expected->getAffectedNumRows(), $this->accountRepository->update($accountRequest));
+ $this->accountRepository->update($account->getId(), $account, true, true);
}
/**
* @throws \SP\Core\Exceptions\SPException
*/
- public function testUpdateWithChangeGroup(): void
+ public function testUpdateWithoutGroup(): void
{
- $accountRequest = $this->buildAccountRequest();
- $accountRequest->changeUserGroup = true;
-
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
+ $account = AccountDataGenerator::factory()->buildAccount();
$callback = new Callback(
- static function (QueryData $arg) use ($accountRequest) {
+ static function (QueryData $arg) use ($account) {
$params = $arg->getQuery()->getBindValues();
- return $params['clientId'] === $accountRequest->clientId
- && $params['categoryId'] === $accountRequest->categoryId
- && $params['name'] === $accountRequest->name
- && $params['login'] === $accountRequest->login
- && $params['url'] === $accountRequest->url
- && $params['notes'] === $accountRequest->notes
- && $params['userEditId'] === $accountRequest->userEditId
- && $params['passDateChange'] === $accountRequest->passDateChange
- && $params['isPrivate'] === $accountRequest->isPrivate
- && $params['isPrivateGroup'] === $accountRequest->isPrivateGroup
- && $params['parentId'] === $accountRequest->parentId
- && $params['userGroupId'] === $accountRequest->userGroupId
- && $params['id'] === $accountRequest->id
+ return count($params) === 15
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['name'] === $account->getName()
+ && $params['clientId'] === $account->getClientId()
+ && $params['categoryId'] === $account->getCategoryId()
+ && $params['login'] === $account->getLogin()
+ && $params['url'] === $account->getUrl()
+ && $params['notes'] === $account->getNotes()
+ && $params['isPrivate'] === $account->getIsPrivate()
+ && $params['isPrivateGroup'] === $account->getIsPrivateGroup()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['parentId'] === $account->getParentId()
+ && $params['otherUserEdit'] === $account->getOtherUserEdit()
+ && $params['otherUserGroupEdit'] === $account->getOtherUserGroupEdit()
+ && $params['userId'] === $account->getUserId()
+ && $params['id'] === $account->getId()
+ && !isset($params['userGroupId'])
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertEquals($expected->getAffectedNumRows(), $this->accountRepository->update($accountRequest));
+ $this->accountRepository->update($account->getId(), $account, true, false);
}
/**
* @throws \SP\Core\Exceptions\SPException
*/
- public function testUpdateWithChangeOwner(): void
+ public function testUpdateWithoutOwner(): void
{
- $accountRequest = $this->buildAccountRequest();
- $accountRequest->changeOwner = true;
-
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
+ $account = AccountDataGenerator::factory()->buildAccount();
$callback = new Callback(
- static function (QueryData $arg) use ($accountRequest) {
+ static function (QueryData $arg) use ($account) {
$params = $arg->getQuery()->getBindValues();
- return $params['clientId'] === $accountRequest->clientId
- && $params['categoryId'] === $accountRequest->categoryId
- && $params['name'] === $accountRequest->name
- && $params['login'] === $accountRequest->login
- && $params['url'] === $accountRequest->url
- && $params['notes'] === $accountRequest->notes
- && $params['userEditId'] === $accountRequest->userEditId
- && $params['passDateChange'] === $accountRequest->passDateChange
- && $params['isPrivate'] === $accountRequest->isPrivate
- && $params['isPrivateGroup'] === $accountRequest->isPrivateGroup
- && $params['parentId'] === $accountRequest->parentId
- && $params['userId'] === $accountRequest->userId
- && $params['id'] === $accountRequest->id
+ return count($params) === 15
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['name'] === $account->getName()
+ && $params['clientId'] === $account->getClientId()
+ && $params['categoryId'] === $account->getCategoryId()
+ && $params['login'] === $account->getLogin()
+ && $params['url'] === $account->getUrl()
+ && $params['notes'] === $account->getNotes()
+ && $params['isPrivate'] === $account->getIsPrivate()
+ && $params['isPrivateGroup'] === $account->getIsPrivateGroup()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['parentId'] === $account->getParentId()
+ && $params['otherUserEdit'] === $account->getOtherUserEdit()
+ && $params['otherUserGroupEdit'] === $account->getOtherUserGroupEdit()
+ && $params['userGroupId'] === $account->getUserGroupId()
+ && $params['id'] === $account->getId()
+ && !isset($params['userId'])
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertEquals($expected->getAffectedNumRows(), $this->accountRepository->update($accountRequest));
+ $this->accountRepository->update($account->getId(), $account, false, true);
}
/**
@@ -516,32 +448,89 @@ class AccountRepositoryTest extends UnitaryTestCase
*/
public function testUpdateBulk(): void
{
- $accountRequest = $this->buildAccountRequest();
-
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
+ $account = AccountDataGenerator::factory()->buildAccount();
$callback = new Callback(
- static function (QueryData $arg) use ($accountRequest) {
+ static function (QueryData $arg) use ($account) {
$params = $arg->getQuery()->getBindValues();
- return $params['userEditId'] === $accountRequest->userEditId
- && $params['clientId'] === $accountRequest->clientId
- && $params['categoryId'] === $accountRequest->categoryId
- && $params['userId'] === $accountRequest->userId
- && $params['userGroupId'] === $accountRequest->userGroupId
- && $params['passDateChange'] === $accountRequest->passDateChange
- && $params['id'] === $accountRequest->id
+ return count($params) === 7
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['clientId'] === $account->getClientId()
+ && $params['categoryId'] === $account->getCategoryId()
+ && $params['userId'] === $account->getUserId()
+ && $params['userGroupId'] === $account->getUserGroupId()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['id'] === $account->getId()
&& !empty($arg->getQuery()->getStatement());
}
);
$this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ ->method('doQuery')
+ ->with($callback);
- $this->assertEquals($expected->getAffectedNumRows(), $this->accountRepository->updateBulk($accountRequest));
+ $this->accountRepository->updateBulk($account->getId(), $account, true, true);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testUpdateBulkWithoutOwner(): void
+ {
+ $account = AccountDataGenerator::factory()->buildAccount();
+
+ $callback = new Callback(
+ static function (QueryData $arg) use ($account) {
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 6
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['clientId'] === $account->getClientId()
+ && $params['categoryId'] === $account->getCategoryId()
+ && !isset($params['userId'])
+ && $params['userGroupId'] === $account->getUserGroupId()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['id'] === $account->getId()
+ && !empty($arg->getQuery()->getStatement());
+ }
+ );
+
+ $this->database->expects(self::once())
+ ->method('doQuery')
+ ->with($callback);
+
+ $this->accountRepository->updateBulk($account->getId(), $account, false, true);
+ }
+
+ /**
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function testUpdateBulkWithoutGroup(): void
+ {
+ $account = AccountDataGenerator::factory()->buildAccount();
+
+ $callback = new Callback(
+ static function (QueryData $arg) use ($account) {
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 6
+ && $params['userEditId'] === $account->getUserEditId()
+ && $params['clientId'] === $account->getClientId()
+ && $params['categoryId'] === $account->getCategoryId()
+ && $params['userId'] === $account->getUserId()
+ && $params['passDateChange'] === $account->getPassDateChange()
+ && $params['id'] === $account->getId()
+ && !isset($params['userGroupId'])
+ && !empty($arg->getQuery()->getStatement());
+ }
+ );
+
+ $this->database->expects(self::once())
+ ->method('doQuery')
+ ->with($callback);
+
+ $this->accountRepository->updateBulk($account->getId(), $account, true, false);
}
/**
@@ -549,10 +538,9 @@ class AccountRepositoryTest extends UnitaryTestCase
*/
public function testUpdateBulkNoFieldsToUpdate(): void
{
- $this->database->expects(self::never())
- ->method('doQuery');
+ $this->database->expects(self::never())->method('doQuery');
- $this->assertEquals(0, $this->accountRepository->updateBulk(new AccountRequest()));
+ $this->accountRepository->updateBulk(0, new Account(), false, false);
}
public function testGetById(): void
@@ -561,34 +549,50 @@ class AccountRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) use ($id) {
- return $arg->getQuery()->getBindValues()['id'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 1
+ && $params['id'] === $id
+ && $arg->getMapClassName() === Account::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->getById($id);
}
+ public function testGetByIdEnriched(): void
+ {
+ $id = self::$faker->randomNumber();
+
+ $callback = new Callback(
+ static function (QueryData $arg) use ($id) {
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 1
+ && $params['id'] === $id
+ && $arg->getMapClassName() === AccountDataView::class
+ && !empty($arg->getQuery()->getStatement());
+ }
+ );
+
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
+
+ $this->accountRepository->getByIdEnriched($id);
+ }
+
public function testGetAll(): void
{
$callback = new Callback(
static function (QueryData $arg) {
- return $arg->getMapClassName() === SimpleModel::class
+ return $arg->getMapClassName() === Account::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database
- ->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->getAll();
}
@@ -605,18 +609,16 @@ class AccountRepositoryTest extends UnitaryTestCase
static function (QueryData $arg) use ($ids) {
$values = $arg->getQuery()->getBindValues();
- return array_shift($values) === array_shift($ids)
+ return count($values) === 3
&& array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
- && $arg->getMapClassName() === SimpleModel::class
+ && array_shift($values) === array_shift($ids)
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
$this->accountRepository->deleteByIdBatch($ids);
}
@@ -627,10 +629,9 @@ class AccountRepositoryTest extends UnitaryTestCase
*/
public function testDeleteByIdBatchWithNoIds(): void
{
- $this->database->expects(self::never())
- ->method('doQuery');
+ $this->database->expects(self::never())->method('doQuery');
- $this->assertEquals(0, $this->accountRepository->deleteByIdBatch([]));
+ $this->accountRepository->deleteByIdBatch([]);
}
public function testSearch(): void
@@ -642,21 +643,18 @@ class AccountRepositoryTest extends UnitaryTestCase
$params = $arg->getQuery()->getBindValues();
$searchStringLike = '%'.$item->getSeachString().'%';
- return $params['name'] === $searchStringLike
+ return count($params) === 5
+ && $params['name'] === $searchStringLike
&& $params['clientName'] === $searchStringLike
&& $params['categoryName'] === $searchStringLike
&& $params['userName'] === $searchStringLike
&& $params['userGroupName'] === $searchStringLike
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === AccountSearchView::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database
- ->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->search($item);
}
@@ -666,16 +664,12 @@ class AccountRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) {
return count($arg->getQuery()->getBindValues()) === 0
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === AccountSearchView::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database
- ->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->search(new ItemSearchData());
}
@@ -688,21 +682,20 @@ class AccountRepositoryTest extends UnitaryTestCase
{
$id = 1;
- $expected = new QueryResult();
- $expected->setAffectedNumRows(1);
-
$callback = new Callback(
static function (QueryData $arg) use ($id) {
- return $arg->getQuery()->getBindValues()['id'] === $id && !empty($arg->getQuery()->getStatement());
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 1
+ && $params['id'] === $id
+ && $arg->getMapClassName() === Simple::class
+ && !empty($arg->getQuery()->getStatement());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertTrue($this->accountRepository->incrementViewCounter($id));
+ $this->accountRepository->incrementViewCounter($id);
}
/**
@@ -713,21 +706,20 @@ class AccountRepositoryTest extends UnitaryTestCase
{
$id = 1;
- $expected = new QueryResult();
- $expected->setAffectedNumRows(0);
-
$callback = new Callback(
static function (QueryData $arg) use ($id) {
- return $arg->getQuery()->getBindValues()['id'] === $id && !empty($arg->getQuery());
+ $params = $arg->getQuery()->getBindValues();
+
+ return count($params) === 1
+ && $params['id'] === $id
+ && $arg->getMapClassName() === Simple::class
+ && !empty($arg->getQuery());
}
);
- $this->database->expects(self::once())
- ->method('doQuery')
- ->with($callback)
- ->willReturn($expected);
+ $this->database->expects(self::once())->method('doQuery')->with($callback);
- $this->assertFalse($this->accountRepository->incrementViewCounter($id));
+ $this->accountRepository->incrementViewCounter($id);
}
public function testGetDataForLink(): void
@@ -738,17 +730,14 @@ class AccountRepositoryTest extends UnitaryTestCase
static function (QueryData $arg) use ($id) {
$params = $arg->getQuery()->getBindValues();
- return $params['id'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ return count($params) === 1
+ && $params['id'] === $id
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database
- ->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->getDataForLink($id);
}
@@ -761,21 +750,16 @@ class AccountRepositoryTest extends UnitaryTestCase
function (QueryData $arg) use ($id) {
$params = $arg->getQuery()->getBindValues();
- return $params['id'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ return count($params) === 1
+ && $params['id'] === $id
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->accountFilterUser
- ->expects(self::once())
- ->method('buildFilter');
+ $this->accountFilterUser->expects(self::once())->method('buildFilter');
- $this->database
- ->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->getForUser($id);
}
@@ -787,20 +771,14 @@ class AccountRepositoryTest extends UnitaryTestCase
$params = $arg->getQuery()->getBindValues();
return count($params) === 0
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->accountFilterUser
- ->expects(self::once())
- ->method('buildFilter');
+ $this->accountFilterUser->expects(self::once())->method('buildFilter');
- $this->database
- ->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->getForUser();
}
@@ -813,21 +791,16 @@ class AccountRepositoryTest extends UnitaryTestCase
function (QueryData $arg) use ($id) {
$params = $arg->getQuery()->getBindValues();
- return $params['parentId'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ return count($params) === 1
+ && $params['parentId'] === $id
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->accountFilterUser
- ->expects(self::once())
- ->method('buildFilter');
+ $this->accountFilterUser->expects(self::once())->method('buildFilter');
- $this->database
- ->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->getLinked($id);
}
@@ -836,16 +809,12 @@ class AccountRepositoryTest extends UnitaryTestCase
{
$callback = new Callback(
function (QueryData $arg) {
- return $arg->getMapClassName() === SimpleModel::class
+ return $arg->getMapClassName() === Account::class
&& !empty($arg->getQuery()->getStatement());
}
);
- $this->database
- ->expects(self::once())
- ->method('doSelect')
- ->with($callback)
- ->willReturn(new QueryResult());
+ $this->database->expects(self::once())->method('doSelect')->with($callback);
$this->accountRepository->getAccountsPassData();
}
diff --git a/tests/SP/Infrastructure/Account/Repositories/AccountToFavoriteRepositoryTest.php b/tests/SP/Infrastructure/Account/Repositories/AccountToFavoriteRepositoryTest.php
index 220deb3d..8a3791c4 100644
--- a/tests/SP/Infrastructure/Account/Repositories/AccountToFavoriteRepositoryTest.php
+++ b/tests/SP/Infrastructure/Account/Repositories/AccountToFavoriteRepositoryTest.php
@@ -27,7 +27,7 @@ namespace SP\Tests\Infrastructure\Account\Repositories;
use Aura\SqlQuery\QueryFactory;
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\MockObject\MockObject;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
use SP\Infrastructure\Account\Repositories\AccountToFavoriteRepository;
use SP\Infrastructure\Database\DatabaseInterface;
use SP\Infrastructure\Database\QueryData;
@@ -53,7 +53,7 @@ class AccountToFavoriteRepositoryTest extends UnitaryTestCase
$query = $arg->getQuery();
return $query->getBindValues()['userId'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($query->getStatement());
}
);
diff --git a/tests/SP/Infrastructure/Account/Repositories/AccountToTagRepositoryTest.php b/tests/SP/Infrastructure/Account/Repositories/AccountToTagRepositoryTest.php
index c380b6f9..b06a4372 100644
--- a/tests/SP/Infrastructure/Account/Repositories/AccountToTagRepositoryTest.php
+++ b/tests/SP/Infrastructure/Account/Repositories/AccountToTagRepositoryTest.php
@@ -27,8 +27,7 @@ namespace SP\Tests\Infrastructure\Account\Repositories;
use Aura\SqlQuery\QueryFactory;
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\MockObject\MockObject;
-use SP\Domain\Account\Dtos\AccountRequest;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
use SP\Infrastructure\Account\Repositories\AccountToTagRepository;
use SP\Infrastructure\Database\DatabaseInterface;
use SP\Infrastructure\Database\QueryData;
@@ -54,7 +53,7 @@ class AccountToTagRepositoryTest extends UnitaryTestCase
$query = $arg->getQuery();
return $query->getBindValues()['accountId'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($query->getStatement());
}
);
@@ -104,34 +103,33 @@ class AccountToTagRepositoryTest extends UnitaryTestCase
*/
public function testAdd(): void
{
- $accountRequest = new AccountRequest();
- $accountRequest->id = self::$faker->randomNumber();
- $accountRequest->tags = self::getRandomNumbers(10);
+ $id = self::$faker->randomNumber();
+ $tags = self::getRandomNumbers(10);
$callbacks = array_map(
- static function ($tag) use ($accountRequest) {
+ static function ($tag) use ($id) {
return [
new Callback(
- static function (QueryData $arg) use ($accountRequest, $tag) {
+ static function (QueryData $arg) use ($id, $tag) {
$query = $arg->getQuery();
$params = $query->getBindValues();
- return $params['accountId'] === $accountRequest->id
+ return $params['accountId'] === $id
&& $params['tagId'] === $tag
&& !empty($query->getStatement());
}
),
];
},
- $accountRequest->tags
+ $tags
);
$this->database
- ->expects(self::exactly(count($accountRequest->tags)))
+ ->expects(self::exactly(count($tags)))
->method('doQuery')
->withConsecutive(...$callbacks);
- $this->accountToTagRepository->add($accountRequest);
+ $this->accountToTagRepository->add($id, $tags);
}
protected function setUp(): void
diff --git a/tests/SP/Infrastructure/Account/Repositories/PublicLinkRepositoryTest.php b/tests/SP/Infrastructure/Account/Repositories/PublicLinkRepositoryTest.php
index 0476c841..2121568e 100644
--- a/tests/SP/Infrastructure/Account/Repositories/PublicLinkRepositoryTest.php
+++ b/tests/SP/Infrastructure/Account/Repositories/PublicLinkRepositoryTest.php
@@ -29,7 +29,7 @@ use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\MockObject\MockObject;
use SP\DataModel\ItemSearchData;
use SP\DataModel\PublicLinkData;
-use SP\Domain\Common\Adapters\SimpleModel;
+use SP\Domain\Common\Models\Simple;
use SP\Infrastructure\Account\Repositories\PublicLinkRepository;
use SP\Infrastructure\Common\Repositories\DuplicatedItemException;
use SP\Infrastructure\Database\DatabaseInterface;
@@ -85,7 +85,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase
return $params['login'] === $searchStringLike
&& $params['accountName'] === $searchStringLike
&& $params['clientName'] === $searchStringLike
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -106,7 +106,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) use ($itemId) {
return $arg->getQuery()->getBindValues()['itemId'] === $itemId
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -126,7 +126,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) use ($id) {
return $arg->getQuery()->getBindValues()['id'] === $id
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -266,7 +266,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase
{
$callback = new Callback(
static function (QueryData $arg) {
- return $arg->getMapClassName() === SimpleModel::class
+ return $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -326,7 +326,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase
return array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
&& array_shift($values) === array_shift($ids)
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -358,7 +358,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase
$callback = new Callback(
static function (QueryData $arg) use ($hash) {
return $arg->getQuery()->getBindValues()['hash'] === $hash
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($arg->getQuery()->getStatement());
}
);
@@ -412,7 +412,7 @@ class PublicLinkRepositoryTest extends UnitaryTestCase
$query = $arg->getQuery();
return count($query->getBindValues()) === 0
- && $arg->getMapClassName() === SimpleModel::class
+ && $arg->getMapClassName() === Simple::class
&& !empty($query->getStatement());
}
);
diff --git a/tests/SP/Repositories/AccountHistoryRepositoryTest.php b/tests/SP/Repositories/AccountHistoryRepositoryTest.php
index fb814b69..74cb3440 100644
--- a/tests/SP/Repositories/AccountHistoryRepositoryTest.php
+++ b/tests/SP/Repositories/AccountHistoryRepositoryTest.php
@@ -31,10 +31,10 @@ use SP\Core\Context\ContextException;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountHistoryData;
use SP\DataModel\ItemSearchData;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
use SP\Domain\Account\Dtos\AccountPasswordRequest;
+use SP\Domain\Account\Models\AccountHistory;
use SP\Domain\Account\Ports\AccountHistoryRepositoryInterface;
use SP\Infrastructure\Account\Repositories\AccountHistoryRepository;
use SP\Tests\DatabaseTestCase;
@@ -201,11 +201,11 @@ class AccountHistoryRepositoryTest extends DatabaseTestCase
public function testGetById()
{
$result = self::$repository->getById(3);
- /** @var AccountHistoryData $data */
+ /** @var AccountHistory $data */
$data = $result->getData();
$this->assertEquals(1, $result->getNumRows());
- $this->assertInstanceOf(AccountHistoryData::class, $data);
+ $this->assertInstanceOf(AccountHistory::class, $data);
$this->assertEquals(3, $data->getId());
$this->assertEquals('2018-06-06 22:20:29', $data->getDateEdit());
$this->assertEquals('2018-06-05 22:49:34', $data->getDateAdd());
@@ -233,7 +233,7 @@ class AccountHistoryRepositoryTest extends DatabaseTestCase
$this->assertEquals(1, self::$repository->updatePassword($request));
$result = self::$repository->getById(3);
- /** @var AccountHistoryData $data */
+ /** @var AccountHistory $data */
$data = $result->getData();
$this->assertEquals($request->pass, $data->getPass());
diff --git a/tests/SP/Repositories/ItemPresetRepositoryTest.php b/tests/SP/Repositories/ItemPresetRepositoryTest.php
index f677f9dd..0ab491ab 100644
--- a/tests/SP/Repositories/ItemPresetRepositoryTest.php
+++ b/tests/SP/Repositories/ItemPresetRepositoryTest.php
@@ -29,9 +29,8 @@ use DI\NotFoundException;
use SP\Core\Context\ContextException;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
-use SP\DataModel\ItemPresetData;
use SP\DataModel\ItemSearchData;
-use SP\Domain\ItemPreset\Ports\ItemPresetRepositoryInterface;
+use SP\Domain\Account\Models\ItemPreset;
use SP\Infrastructure\ItemPreset\Repositories\ItemPresetRepository;
use SP\Tests\DatabaseTestCase;
use stdClass;
@@ -109,7 +108,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
*/
public function testUpdate()
{
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 1;
$data->userGroupId = 1;
$data->fixed = 1;
@@ -130,7 +129,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
{
$this->expectException(ConstraintException::class);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 1;
$data->userGroupId = 1;
$data->fixed = 1;
@@ -149,7 +148,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
{
$this->expectException(ConstraintException::class);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 2;
$data->userId = 10;
$data->fixed = 1;
@@ -168,7 +167,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
{
$this->expectException(ConstraintException::class);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 2;
$data->userGroupId = 10;
$data->fixed = 1;
@@ -187,7 +186,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
{
$this->expectException(ConstraintException::class);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 2;
$data->userProfileId = 10;
$data->fixed = 1;
@@ -204,7 +203,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
*/
public function testUpdateUnknownId()
{
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 10;
$data->userGroupId = 1;
$data->fixed = 1;
@@ -223,7 +222,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
*/
public function testGetById()
{
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 1;
$data->userId = 1;
$data->fixed = 0;
@@ -247,11 +246,11 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
$result = self::$repository->getAll();
$this->assertEquals($count, $result->getNumRows());
- /** @var ItemPresetData[] $data */
+ /** @var ItemPreset[] $data */
$data = $result->getDataAsArray();
$this->assertCount($count, $data);
- $this->assertInstanceOf(ItemPresetData::class, $data[0]);
+ $this->assertInstanceOf(ItemPreset::class, $data[0]);
$this->assertEquals(1, $data[0]->getId());
$this->assertEquals('permission', $data[0]->getType());
$this->assertEquals(1, $data[0]->getUserId());
@@ -261,11 +260,11 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
$this->assertEquals(0, $data[0]->getFixed());
$this->assertEquals(0, $data[0]->getPriority());
- $this->assertInstanceOf(ItemPresetData::class, $data[1]);
+ $this->assertInstanceOf(ItemPreset::class, $data[1]);
$this->assertEquals(2, $data[1]->getId());
$this->assertEquals('permission', $data[1]->getType());
- $this->assertInstanceOf(ItemPresetData::class, $data[2]);
+ $this->assertInstanceOf(ItemPreset::class, $data[2]);
$this->assertEquals(3, $data[2]->getId());
$this->assertEquals('permission', $data[2]->getType());
}
@@ -357,7 +356,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
*/
public function testCreate()
{
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 6;
$data->userGroupId = 1;
$data->fixed = 1;
@@ -379,7 +378,7 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
{
$this->expectException(ConstraintException::class);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->userGroupId = 1;
$data->fixed = 1;
$data->priority = 10;
@@ -406,10 +405,10 @@ class ItemPresetRepositoryTest extends DatabaseTestCase
$this->assertEquals(1, $result->getNumRows());
- /** @var ItemPresetData $data */
+ /** @var ItemPreset $data */
$data = $result->getData();
- $this->assertInstanceOf(ItemPresetData::class, $data);
+ $this->assertInstanceOf(ItemPreset::class, $data);
$this->assertEquals($expected, $data->getId());
}
diff --git a/tests/SP/Services/Account/AccountHistoryServiceTest.php b/tests/SP/Services/Account/AccountHistoryServiceTest.php
index ab61b0e3..63a0f5b8 100644
--- a/tests/SP/Services/Account/AccountHistoryServiceTest.php
+++ b/tests/SP/Services/Account/AccountHistoryServiceTest.php
@@ -31,10 +31,10 @@ use SP\Core\Context\ContextException;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\AccountHistoryData;
use SP\DataModel\ItemSearchData;
use SP\Domain\Account\Dtos\AccountHistoryCreateDto;
use SP\Domain\Account\Dtos\AccountPasswordRequest;
+use SP\Domain\Account\Models\AccountHistory;
use SP\Domain\Account\Ports\AccountHistoryServiceInterface;
use SP\Domain\Account\Services\AccountHistoryService;
use SP\Domain\Common\Services\ServiceException;
@@ -158,9 +158,9 @@ class AccountHistoryServiceTest extends DatabaseTestCase
public function testGetById()
{
$data = self::$service->getById(3);
- /** @var AccountHistoryData $data */
+ /** @var \SP\Domain\Account\Models\AccountHistory $data */
- $this->assertInstanceOf(AccountHistoryData::class, $data);
+ $this->assertInstanceOf(AccountHistory::class, $data);
$this->assertEquals(3, $data->getId());
$this->assertEquals('2018-06-06 22:20:29', $data->getDateEdit());
$this->assertEquals('2018-06-05 22:49:34', $data->getDateAdd());
diff --git a/tests/SP/Services/Account/AccountSearchServiceTest.php b/tests/SP/Services/Account/AccountSearchServiceTest.php
index 7b79354b..39e1da67 100644
--- a/tests/SP/Services/Account/AccountSearchServiceTest.php
+++ b/tests/SP/Services/Account/AccountSearchServiceTest.php
@@ -164,7 +164,7 @@ class AccountSearchServiceTest extends DatabaseTestCase
$i = 0;
foreach ($data as $searchItem) {
- $this->assertEquals($accountsId[$i], $searchItem->getAccountSearchVData()->getId());
+ $this->assertEquals($accountsId[$i], $searchItem->getAccountSearchView()->getId());
$i++;
}
}
@@ -214,7 +214,7 @@ class AccountSearchServiceTest extends DatabaseTestCase
$i = 0;
foreach ($data as $searchItem) {
- $this->assertEquals($accountsId[$i], $searchItem->getAccountSearchVData()->getId());
+ $this->assertEquals($accountsId[$i], $searchItem->getAccountSearchView()->getId());
$i++;
}
}
@@ -248,7 +248,7 @@ class AccountSearchServiceTest extends DatabaseTestCase
/** @var AccountSearchItem $item */
foreach ($result->getDataAsArray() as $item) {
- $this->assertEquals($accountsId[$i], $item->getAccountSearchVData()->getId());
+ $this->assertEquals($accountsId[$i], $item->getAccountSearchView()->getId());
$i++;
}
}
@@ -295,7 +295,7 @@ class AccountSearchServiceTest extends DatabaseTestCase
/** @var AccountSearchItem $item */
foreach ($result->getDataAsArray() as $item) {
- $this->assertEquals($accountsId[$i], $item->getAccountSearchVData()->getId());
+ $this->assertEquals($accountsId[$i], $item->getAccountSearchView()->getId());
$i++;
}
@@ -324,7 +324,7 @@ class AccountSearchServiceTest extends DatabaseTestCase
/** @var AccountSearchItem $item */
foreach ($result->getDataAsArray() as $item) {
- $this->assertEquals($accountsId[$i], $item->getAccountSearchVData()->getId());
+ $this->assertEquals($accountsId[$i], $item->getAccountSearchView()->getId());
$i++;
}
}
@@ -359,7 +359,7 @@ class AccountSearchServiceTest extends DatabaseTestCase
$i = 0;
foreach ($data as $item) {
- $this->assertEquals($accountsId[$i], $item->getAccountSearchVData()->getId());
+ $this->assertEquals($accountsId[$i], $item->getAccountSearchView()->getId());
$i++;
}
}
diff --git a/tests/SP/Services/Account/AccountServiceTest.php b/tests/SP/Services/Account/AccountServiceTest.php
index 36f3a34d..a7692e8b 100644
--- a/tests/SP/Services/Account/AccountServiceTest.php
+++ b/tests/SP/Services/Account/AccountServiceTest.php
@@ -40,7 +40,7 @@ use SP\DataModel\AccountVData;
use SP\DataModel\ItemSearchData;
use SP\DataModel\ProfileData;
use SP\Domain\Account\Adapters\AccountData;
-use SP\Domain\Account\Dtos\AccountBulkRequest;
+use SP\Domain\Account\Dtos\AccountUpdateBulkDto;
use SP\Domain\Account\Dtos\AccountPasswordRequest;
use SP\Domain\Account\Dtos\AccountRequest;
use SP\Domain\Account\Ports\AccountHistoryServiceInterface;
@@ -128,11 +128,11 @@ class AccountServiceTest extends DatabaseTestCase
$this->assertEquals($expectedId, self::$service->create($accountRequest));
- $result = self::$service->getById($expectedId);
+ $result = self::$service->getByIdEnriched($expectedId);
- self::$service->withTagsById($result);
- self::$service->withUsersById($result);
- self::$service->withUserGroupsById($result);
+ self::$service->withTags($result);
+ self::$service->withUsers($result);
+ self::$service->withUserGroups($result);
$data = $result->getAccountVData();
@@ -267,12 +267,12 @@ class AccountServiceTest extends DatabaseTestCase
*/
public function testEditRestore()
{
- self::$service->editRestore(3, 1);
+ self::$service->restoreModified(3, 1);
$this->expectException(ServiceException::class);
- self::$service->editRestore(1, 1);
- self::$service->editRestore(3, 10);
+ self::$service->restoreModified(1, 1);
+ self::$service->restoreModified(3, 10);
$this->assertEquals(6, self::getRowCount('AccountHistory'));
}
@@ -372,11 +372,11 @@ class AccountServiceTest extends DatabaseTestCase
self::$service->update($accountRequest);
- $result = self::$service->getById(1);
+ $result = self::$service->getByIdEnriched(1);
- self::$service->withTagsById($result);
- self::$service->withUsersById($result);
- self::$service->withUserGroupsById($result);
+ self::$service->withTags($result);
+ self::$service->withUsers($result);
+ self::$service->withUserGroups($result);
$data = $result->getAccountVData();
@@ -444,7 +444,7 @@ class AccountServiceTest extends DatabaseTestCase
self::$service->update($accountRequest);
- $result = self::$service->getById(1);
+ $result = self::$service->getByIdEnriched(1);
$data = $result->getAccountVData();
@@ -493,7 +493,7 @@ class AccountServiceTest extends DatabaseTestCase
self::$service->update($accountRequest);
- $result = self::$service->getById(1);
+ $result = self::$service->getByIdEnriched(1);
$data = $result->getAccountVData();
@@ -546,7 +546,7 @@ class AccountServiceTest extends DatabaseTestCase
self::$service->update($accountRequest);
- $result = self::$service->getById(1);
+ $result = self::$service->getByIdEnriched(1);
$data = $result->getAccountVData();
@@ -599,7 +599,7 @@ class AccountServiceTest extends DatabaseTestCase
self::$service->update($accountRequest);
- $result = self::$service->getById(1);
+ $result = self::$service->getByIdEnriched(1);
$data = $result->getAccountVData();
@@ -643,7 +643,7 @@ class AccountServiceTest extends DatabaseTestCase
{
$this->expectException(NoSuchItemException::class);
- self::$service->getById(10);
+ self::$service->getByIdEnriched(10);
}
/**
@@ -788,12 +788,12 @@ class AccountServiceTest extends DatabaseTestCase
public function testIncrementDecryptCounter()
{
/** @var AccountVData $accountBefore */
- $accountBefore = self::$service->getById(1)->getAccountVData();
+ $accountBefore = self::$service->getByIdEnriched(1)->getAccountVData();
$this->assertTrue(self::$service->incrementDecryptCounter(1));
/** @var AccountVData $accountAfter */
- $accountAfter = self::$service->getById(1)->getAccountVData();
+ $accountAfter = self::$service->getByIdEnriched(1)->getAccountVData();
$this->assertEquals($accountBefore->getCountDecrypt() + 1, $accountAfter->getCountDecrypt());
}
@@ -806,12 +806,12 @@ class AccountServiceTest extends DatabaseTestCase
public function testIncrementViewCounter()
{
/** @var AccountVData $accountBefore */
- $accountBefore = self::$service->getById(1)->getAccountVData();
+ $accountBefore = self::$service->getByIdEnriched(1)->getAccountVData();
$this->assertTrue(self::$service->incrementViewCounter(1));
/** @var AccountVData $accountAfter */
- $accountAfter = self::$service->getById(1)->getAccountVData();
+ $accountAfter = self::$service->getByIdEnriched(1)->getAccountVData();
$this->assertEquals($accountBefore->getCountView() + 1, $accountAfter->getCountView());
}
@@ -866,9 +866,9 @@ class AccountServiceTest extends DatabaseTestCase
$expectedId = 5;
- $this->assertEquals($expectedId, self::$service->createFromHistory($data));
+ $this->assertEquals($expectedId, self::$service->restoreRemoved($data));
- $result = self::$service->getById($expectedId);
+ $result = self::$service->getByIdEnriched($expectedId);
$resultData = $result->getAccountVData();
$this->assertEquals($data->getName(), $resultData->getName());
@@ -911,7 +911,7 @@ class AccountServiceTest extends DatabaseTestCase
$accountRequest->userGroupsView = [2, 3];
$accountRequest->userGroupsEdit = [2];
- $bulkRequest = new AccountBulkRequest([1, 2], $accountRequest);
+ $bulkRequest = new AccountUpdateBulkDto([1, 2], $accountRequest);
self::$service->updateBulk($bulkRequest);
@@ -929,11 +929,11 @@ class AccountServiceTest extends DatabaseTestCase
*/
private function checkBulkData(AccountRequest $accountRequest, $accountId)
{
- $result = self::$service->getById($accountId);
+ $result = self::$service->getByIdEnriched($accountId);
- self::$service->withTagsById($result);
- self::$service->withUsersById($result);
- self::$service->withUserGroupsById($result);
+ self::$service->withTags($result);
+ self::$service->withUsers($result);
+ self::$service->withUserGroups($result);
$data = $result->getAccountVData();
diff --git a/tests/SP/Services/Import/CsvImportTest.php b/tests/SP/Services/Import/CsvImportTest.php
index b55e0b61..a55c0ea2 100644
--- a/tests/SP/Services/Import/CsvImportTest.php
+++ b/tests/SP/Services/Import/CsvImportTest.php
@@ -1,10 +1,10 @@
.
+ * along with sysPass. If not, see .
*/
namespace SP\Tests\Services\Import;
@@ -115,7 +115,7 @@ class CsvImportTest extends DatabaseTestCase
// 1st account
$expectedId = 5;
- $data = $accountService->getById($expectedId)->getAccountVData();
+ $data = $accountService->getByIdEnriched($expectedId)->getAccountVData();
$this->assertEquals($expectedId, $data->getId());
$this->assertEquals('Test CSV 1', $data->getName());
@@ -131,7 +131,7 @@ class CsvImportTest extends DatabaseTestCase
// 2nd account
$expectedId = 6;
- $data = $accountService->getById($expectedId)->getAccountVData();
+ $data = $accountService->getByIdEnriched($expectedId)->getAccountVData();
$this->assertEquals($expectedId, $data->getId());
$this->assertEquals('Test CSV 2', $data->getName());
@@ -147,7 +147,7 @@ class CsvImportTest extends DatabaseTestCase
// 3rd account
$expectedId = 7;
- $data = $accountService->getById($expectedId)->getAccountVData();
+ $data = $accountService->getByIdEnriched($expectedId)->getAccountVData();
$this->assertEquals($expectedId, $data->getId());
$this->assertEquals('Test CSV 3', $data->getName());
diff --git a/tests/SP/Services/Import/SyspassImportTest.php b/tests/SP/Services/Import/SyspassImportTest.php
index 506a7fae..4723c3f1 100644
--- a/tests/SP/Services/Import/SyspassImportTest.php
+++ b/tests/SP/Services/Import/SyspassImportTest.php
@@ -1,10 +1,10 @@
.
+ * along with sysPass. If not, see .
*/
namespace SP\Tests\Services\Import;
@@ -116,7 +116,7 @@ class SyspassImportTest extends DatabaseTestCase
// 1st account
$expectedId = 5;
- $result = $accountService->getById($expectedId);
+ $result = $accountService->getByIdEnriched($expectedId);
$data = $result->getAccountVData();
$this->assertEquals($expectedId, $data->getId());
@@ -129,7 +129,7 @@ class SyspassImportTest extends DatabaseTestCase
$this->assertEmpty($data->getNotes());
$this->assertEquals('admin', $data->getLogin());
- $accountService->withTagsById($result);
+ $accountService->withTags($result);
$expectedTags = [7, 8, 9];
$i = 0;
@@ -145,7 +145,7 @@ class SyspassImportTest extends DatabaseTestCase
// 2nd account
$expectedId = 6;
- $result = $accountService->getById($expectedId);
+ $result = $accountService->getByIdEnriched($expectedId);
$data = $result->getAccountVData();
$this->assertEquals($expectedId, $data->getId());
@@ -158,7 +158,7 @@ class SyspassImportTest extends DatabaseTestCase
$this->assertEquals('blablacar', $data->getNotes());
$this->assertEquals('admin', $data->getLogin());
- $accountService->withTagsById($result);
+ $accountService->withTags($result);
$expectedTags = [8, 9, 1];
$i = 0;
@@ -174,7 +174,7 @@ class SyspassImportTest extends DatabaseTestCase
// 3rd account
$expectedId = 7;
- $result = $accountService->getById($expectedId);
+ $result = $accountService->getByIdEnriched($expectedId);
$data = $result->getAccountVData();
$this->assertEquals($expectedId, $data->getId());
@@ -193,7 +193,7 @@ class SyspassImportTest extends DatabaseTestCase
// 4th account
$expectedId = 8;
- $result = $accountService->getById($expectedId);
+ $result = $accountService->getByIdEnriched($expectedId);
$data = $result->getAccountVData();
$this->assertEquals($expectedId, $data->getId());
@@ -212,7 +212,7 @@ class SyspassImportTest extends DatabaseTestCase
// 5th account
$expectedId = 9;
- $result = $accountService->getById($expectedId);
+ $result = $accountService->getByIdEnriched($expectedId);
$data = $result->getAccountVData();
$this->assertEquals($expectedId, $data->getId());
diff --git a/tests/SP/Services/ItemPreset/ItemPresetServiceTest.php b/tests/SP/Services/ItemPreset/ItemPresetServiceTest.php
index 7f519021..d405776b 100644
--- a/tests/SP/Services/ItemPreset/ItemPresetServiceTest.php
+++ b/tests/SP/Services/ItemPreset/ItemPresetServiceTest.php
@@ -1,10 +1,10 @@
.
+ * along with sysPass. If not, see .
*/
namespace SP\Tests\Services\ItemPreset;
@@ -31,8 +31,8 @@ use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\NoSuchPropertyException;
use SP\Core\Exceptions\QueryException;
use SP\DataModel\ItemPreset\AccountPermission;
-use SP\DataModel\ItemPresetData;
use SP\DataModel\ItemSearchData;
+use SP\Domain\Account\Models\ItemPreset;
use SP\Domain\ItemPreset\Services\ItemPresetRequest;
use SP\Domain\ItemPreset\Services\ItemPresetService;
use SP\Infrastructure\Common\Repositories\NoSuchItemException;
@@ -82,7 +82,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
{
$result = self::$service->getForUser('permission', $userId, $userGroupId, $userProfileId);
- $this->assertInstanceOf(ItemPresetData::class, $result);
+ $this->assertInstanceOf(ItemPreset::class, $result);
$this->assertEquals($expected, $result->getId());
}
@@ -110,7 +110,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
*/
public function testGetById()
{
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 1;
$data->userId = 1;
$data->fixed = 0;
@@ -119,7 +119,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
$result = self::$service->getById(1);
- $this->assertInstanceOf(ItemPresetData::class, $result);
+ $this->assertInstanceOf(ItemPreset::class, $result);
$this->assertEquals($data, $result);
}
@@ -134,7 +134,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
$result = self::$service->getAll();
$this->assertCount($count, $result);
- $this->assertInstanceOf(ItemPresetData::class, $result[0]);
+ $this->assertInstanceOf(ItemPreset::class, $result[0]);
$this->assertEquals(1, $result[0]->getId());
$this->assertEquals('permission', $result[0]->getType());
$this->assertEquals(1, $result[0]->getUserId());
@@ -144,10 +144,10 @@ class ItemPresetServiceTest extends DatabaseTestCase
$this->assertEquals(0, $result[0]->getFixed());
$this->assertEquals(0, $result[0]->getPriority());
- $this->assertInstanceOf(ItemPresetData::class, $result[1]);
+ $this->assertInstanceOf(ItemPreset::class, $result[1]);
$this->assertEquals(2, $result[1]->getId());
- $this->assertInstanceOf(ItemPresetData::class, $result[2]);
+ $this->assertInstanceOf(ItemPreset::class, $result[2]);
$this->assertEquals(3, $result[2]->getId());
}
@@ -165,7 +165,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
$accountPermission->setUserGroupsView([2]);
$accountPermission->setUserGroupsEdit([1, 3]);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 1;
$data->userGroupId = 1;
$data->fixed = 1;
@@ -194,7 +194,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
$accountPermission->setUserGroupsView([2]);
$accountPermission->setUserGroupsEdit([1, 3]);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 10;
$data->userGroupId = 1;
$data->fixed = 1;
@@ -321,7 +321,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
{
$data = self::$service->getForCurrentUser('permission');
- $this->assertInstanceOf(ItemPresetData::class, $data);
+ $this->assertInstanceOf(ItemPreset::class, $data);
$this->assertEquals(2, $data->getId());
}
@@ -339,7 +339,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
$accountPermission->setUserGroupsView([2]);
$accountPermission->setUserGroupsEdit([1, 3]);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->id = 6;
$data->userGroupId = 1;
$data->fixed = 1;
@@ -369,7 +369,7 @@ class ItemPresetServiceTest extends DatabaseTestCase
$accountPermission->setUserGroupsView([2]);
$accountPermission->setUserGroupsEdit([1, 3]);
- $data = new ItemPresetData();
+ $data = new ItemPreset();
$data->userGroupId = 1;
$data->fixed = 1;
$data->priority = 10;
diff --git a/tests/SP/Stubs/AccountRepositoryStub.php b/tests/SP/Stubs/AccountRepositoryStub.php
new file mode 100644
index 00000000..16ea57f7
--- /dev/null
+++ b/tests/SP/Stubs/AccountRepositoryStub.php
@@ -0,0 +1,154 @@
+.
+ */
+
+namespace SP\Tests\Stubs;
+
+use Closure;
+use SP\DataModel\ItemSearchData;
+use SP\Domain\Account\Dtos\EncryptedPassword;
+use SP\Domain\Account\Models\Account;
+use SP\Domain\Account\Ports\AccountRepositoryInterface;
+use SP\Infrastructure\Database\QueryResult;
+
+/**
+ * Class AccountRepositoryStub
+ */
+class AccountRepositoryStub implements AccountRepositoryInterface
+{
+
+ public function getTotalNumAccounts(): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getPasswordForId(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getPasswordHistoryForId(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function incrementDecryptCounter(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function editPassword(int $accountId, Account $account): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function updatePassword(int $accountId, EncryptedPassword $encryptedPassword): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function restoreModified(int $accountId, Account $account): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function updateBulk(int $accountId, Account $account, bool $changeOwner, bool $changeUserGroup): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function incrementViewCounter(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getDataForLink(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getForUser(?int $accountId = null): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getLinked(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getAccountsPassData(): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function create(Account $account): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function delete(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function update(int $accountId, Account $account, bool $changeOwner, bool $changeUserGroup): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getByIdEnriched(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getById(int $accountId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function getAll(): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function deleteByIdBatch(array $accountsId): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function search(ItemSearchData $itemSearchData): QueryResult
+ {
+ return new QueryResult();
+ }
+
+ public function transactionAware(Closure $closure, object $newThis): mixed
+ {
+ return $closure->call($newThis);
+ }
+
+ public function createRemoved(Account $account): QueryResult
+ {
+ return new QueryResult();
+ }
+}
diff --git a/tests/SP/UnitaryTestCase.php b/tests/SP/UnitaryTestCase.php
index f2c1c9e4..5ebd53e1 100644
--- a/tests/SP/UnitaryTestCase.php
+++ b/tests/SP/UnitaryTestCase.php
@@ -79,8 +79,8 @@ abstract class UnitaryTestCase extends TestCase
$userLogin
->setLogin(self::$faker->userName)
->setName(self::$faker->userName)
- ->setId(self::$faker->randomNumber())
- ->setUserGroupId(self::$faker->randomNumber());
+ ->setId(self::$faker->randomNumber(2))
+ ->setUserGroupId(self::$faker->randomNumber(2));
$this->context = new StatelessContext();
$this->context->initialize();
diff --git a/tests/SP/Util/ChainableTest.php b/tests/SP/Util/ChainableTest.php
new file mode 100644
index 00000000..4c52ae8c
--- /dev/null
+++ b/tests/SP/Util/ChainableTest.php
@@ -0,0 +1,51 @@
+.
+ */
+
+namespace SP\Tests\Util;
+
+use PHPUnit\Framework\TestCase;
+use SP\Util\Chainable;
+
+/**
+ * Class ChainableTest
+ *
+ * @group unitary
+ */
+class ChainableTest extends TestCase
+{
+ public function testNext()
+ {
+ $chain = (new Chainable(fn($n) => $this->increment($n, 1), $this, 1))
+ ->next(fn($n) => $this->increment($n, 2))
+ ->next(fn($n) => $this->increment($n, 3))
+ ->resolve();
+
+ $this->assertEquals(7, $chain);
+ }
+
+ private function increment(int $a, int $b): int
+ {
+ return $a + $b;
+ }
+}